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 15b0906..c8f8f2a 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,81 +1,99 @@
+// 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.
+// 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
+
using System;
+using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates performance measurement of Aspose.BarCode ExportToXml using file path and stream overloads.
+/// 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.
///
class Program
{
///
- /// Entry point of the application. Generates a set of barcode samples and measures the time taken
- /// to export them to XML via file path and memory stream overloads.
+ /// 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.
///
- /// Command‑line arguments (not used).
- static void Main(string[] args)
+ static void Main()
{
- // Number of barcode samples (small safe size for the runner)
- const int sampleCount = 5;
-
- // Temporary directory for XML files
- string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeExport");
- Directory.CreateDirectory(tempDir);
-
- // ------------------------------------------------------------
- // Measure ExportToXml using the file‑path overload
- // ------------------------------------------------------------
- Stopwatch fileTimer = Stopwatch.StartNew();
- for (int i = 0; i < sampleCount; i++)
+ // Prepare a temporary directory for XML files
+ string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeExportDemo");
+ if (!Directory.Exists(tempDir))
{
- // Create a barcode generator for each sample.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
- {
- // Build the full path for the XML file
- string xmlPath = Path.Combine(tempDir, $"barcode{i}.xml");
- // Export the barcode definition to the specified file
- generator.ExportToXml(xmlPath);
- }
+ Directory.CreateDirectory(tempDir);
}
- fileTimer.Stop();
- // ------------------------------------------------------------
- // Measure ExportToXml using the stream overload
- // ------------------------------------------------------------
- Stopwatch streamTimer = Stopwatch.StartNew();
- for (int i = 0; i < sampleCount; i++)
+ // Sample barcode texts (small batch for safe execution)
+ List sampleTexts = new List
{
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
+ "ABC123456",
+ "9876543210",
+ "TestCode128",
+ "12345ABCDE",
+ "ZXCVBNM123"
+ };
+
+ // 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++)
+ {
+ string codeText = sampleTexts[i];
+
+ // Create a BarcodeGenerator instance for the current text
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Export to a memory stream (no file system I/O)
- using (var ms = new MemoryStream())
+ // 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);
+
+ // Export to XML stream and measure time
+ using (MemoryStream ms = new MemoryStream())
{
- generator.ExportToXml(ms);
+ 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}.");
}
}
}
- streamTimer.Stop();
- // Output timing results
- Console.WriteLine($"Export to file path total time: {fileTimer.ElapsedMilliseconds} ms");
- Console.WriteLine($"Export to stream total time: {streamTimer.ElapsedMilliseconds} ms");
+ // Output timing comparison
+ Console.WriteLine("Performance comparison of ExportToXml (file path vs stream):");
+ for (int i = 0; i < sampleTexts.Count; i++)
+ {
+ Console.WriteLine($"Item {i + 1}: File = {fileTimes[i].TotalMilliseconds} ms, Stream = {streamTimes[i].TotalMilliseconds} ms");
+ }
- // ------------------------------------------------------------
- // Cleanup temporary files and directory
- // ------------------------------------------------------------
+ // Clean up temporary XML files
try
{
- // Delete each generated XML file
- foreach (var file in Directory.GetFiles(tempDir, "*.xml"))
+ foreach (string file in Directory.GetFiles(tempDir, "*.xml"))
+ {
File.Delete(file);
-
- // Remove the temporary directory itself
+ }
Directory.Delete(tempDir);
}
catch
{
- // Ignored - cleanup is best effort.
+ // If cleanup fails, ignore – not critical for the demo
}
}
-}
+}
\ 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 8877a0e..5de4370 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,93 +1,82 @@
+// 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.
+// 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
+
using System;
-using System.Globalization;
using System.IO;
using System.Xml;
-using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates reading barcodes from images and exporting the results to XML files.
+/// 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.
///
class Program
{
///
- /// Entry point of the application. Processes a set of sample images,
- /// extracts barcode information, and writes the data to XML files.
+ /// 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.
///
static void Main()
{
- // Define sample image file paths (replace with actual paths as needed)
- string[] imagePaths = new string[]
+ // Define the list of image files to be processed.
+ // Adjust the file paths as needed for your environment.
+ string[] imageFiles = new string[]
{
- "sample1.png",
- "sample2.png",
- "sample3.png"
+ "image1.png",
+ "image2.png",
+ "image3.png",
+ "image4.png",
+ "image5.png"
};
- // Ensure the output directory exists; create it if it does not
- string outputDir = "output";
- if (!Directory.Exists(outputDir))
- {
- Directory.CreateDirectory(outputDir);
- }
-
- // Process each image file individually
- foreach (string imagePath in imagePaths)
+ // Process each image file in the list.
+ foreach (string imagePath in imageFiles)
{
- // Skip processing if the file cannot be found
+ // 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, supporting all barcode types
+ // Initialize a barcode reader for the current image,
+ // configured to detect all supported barcode types.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Read all barcodes present in the image
- var results = reader.ReadBarCodes();
+ int barcodeIndex = 0; // Counter for naming XML files uniquely per image.
- // Determine the XML output file name based on the image name
- string xmlFileName = Path.GetFileNameWithoutExtension(imagePath) + ".xml";
- string xmlPath = Path.Combine(outputDir, xmlFileName);
-
- // Write the barcode data to an XML file with indentation for readability
- using (var writer = XmlWriter.Create(xmlPath, new XmlWriterSettings { Indent = true }))
+ // Iterate over all detected barcodes in the image.
+ foreach (var result in reader.ReadBarCodes())
{
- writer.WriteStartDocument(); // XML declaration
- writer.WriteStartElement("Barcodes"); // Root element
- writer.WriteAttributeString("SourceImage", Path.GetFileName(imagePath));
+ // Construct the XML file name using the image name and barcode index.
+ string xmlFileName = $"{Path.GetFileNameWithoutExtension(imagePath)}_{barcodeIndex}.xml";
- // Iterate over each detected barcode and write its details
- foreach (var result in results)
+ // Create an XML writer with indentation for readability.
+ using (var writer = XmlWriter.Create(xmlFileName, new XmlWriterSettings { Indent = true }))
{
+ writer.WriteStartDocument();
writer.WriteStartElement("BarCode");
+ // Write barcode type and text elements, handling possible null values.
writer.WriteElementString("Type", result.CodeTypeName ?? string.Empty);
writer.WriteElementString("CodeText", result.CodeText ?? string.Empty);
- writer.WriteElementString("Confidence", result.Confidence.ToString());
- writer.WriteElementString(
- "ReadingQuality",
- result.ReadingQuality.ToString(CultureInfo.InvariantCulture));
-
- // Write the region (bounding rectangle) of the barcode
- var rect = result.Region.Rectangle;
- writer.WriteStartElement("Region");
- writer.WriteElementString("X", rect.X.ToString(CultureInfo.InvariantCulture));
- writer.WriteElementString("Y", rect.Y.ToString(CultureInfo.InvariantCulture));
- writer.WriteElementString("Width", rect.Width.ToString(CultureInfo.InvariantCulture));
- writer.WriteElementString("Height", rect.Height.ToString(CultureInfo.InvariantCulture));
- writer.WriteEndElement(); //
writer.WriteEndElement(); //
+ writer.WriteEndDocument();
}
- writer.WriteEndElement(); //
- writer.WriteEndDocument(); // End of XML document
+ Console.WriteLine($"Processed barcode {barcodeIndex} from '{imagePath}' -> '{xmlFileName}'");
+ barcodeIndex++;
}
- // Inform the user that processing for the current image is complete
- Console.WriteLine($"Processed '{imagePath}' -> '{xmlPath}'");
+ // If no barcodes were detected, inform the user.
+ if (barcodeIndex == 0)
+ {
+ Console.WriteLine($"No barcodes detected in '{imagePath}'.");
+ }
}
}
}
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 51c5773..1c26eb8 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,61 +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.
+// 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
+
using System;
using System.IO;
using System.Xml;
-using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Reads barcodes from an image file and writes the detection results to an XML document.
+/// Demonstrates how to read barcodes from an image and export the results to an XML file.
///
class Program
{
///
- /// Application entry point.
+ /// Entry point of the console application.
+ /// Accepts an optional image path argument, detects barcodes, and writes the results to an XML file.
///
- /// Command‑line arguments; the first argument may specify the image file path.
+ /// Command‑line arguments; the first argument may be the image file path.
static void Main(string[] args)
{
- // Determine the image path: use the first command‑line argument if supplied,
- // otherwise fall back to a default sample image.
+ // Determine image path from command‑line or use a default sample.
string imagePath = args.Length > 0 ? args[0] : "sample.png";
- // Verify that the specified image file exists before proceeding.
+ // Verify that the image file exists before proceeding.
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
+ Console.WriteLine($"Image file not found: {imagePath}");
return;
}
- // Define the output XML file path where barcode information will be saved.
- string xmlPath = "Barcodes.xml";
+ // Prepare the output XML file path by changing the image extension to .xml.
+ string xmlPath = Path.ChangeExtension(imagePath, ".xml");
- // Create a BarCodeReader that attempts to decode all supported barcode types.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Configure the XML writer to produce indented, human‑readable output.
+ XmlWriterSettings settings = new XmlWriterSettings
{
- // Perform the barcode recognition and obtain an array of results.
- BarCodeResult[] results = reader.ReadBarCodes();
+ Indent = true,
+ IndentChars = " "
+ };
- // Write the detection results to an XML file with indentation for readability.
- using (var writer = XmlWriter.Create(xmlPath, new XmlWriterSettings { Indent = true }))
- {
- writer.WriteStartDocument(); // Begin the XML document.
- writer.WriteStartElement("Barcodes"); // Root element.
+ // Open the XML writer within a using block to ensure proper disposal.
+ using (XmlWriter writer = XmlWriter.Create(xmlPath, settings))
+ {
+ writer.WriteStartDocument();
+ writer.WriteStartElement("Barcodes");
- // Iterate over each detected barcode and write its details as an element.
- foreach (var result in results)
+ // Initialize the barcode reader to detect all supported barcode types.
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ {
+ // Iterate through each detected barcode in the image.
+ foreach (var result in reader.ReadBarCodes())
{
writer.WriteStartElement("BarCode");
- writer.WriteAttributeString("Type", result.CodeTypeName ?? string.Empty);
- writer.WriteAttributeString("CodeText", result.CodeText ?? string.Empty);
+
+ // 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);
+
+ // 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
+
writer.WriteEndElement(); // BarCode
}
-
- writer.WriteEndElement(); // Barcodes
- writer.WriteEndDocument(); // End of XML document.
}
- // Inform the user about the number of barcodes detected and the output location.
- Console.WriteLine($"Detected {results.Length} barcode(s). Results written to {xmlPath}.");
+ 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}");
}
}
\ 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 1998898..a716301 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,73 +1,77 @@
+// Title: Barcode checkpoint/restart demo
+// Description: Demonstrates exporting a reader's state to XML, closing the reader, reopening it, and continuing barcode detection.
+// 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
+
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates generating a Code128 barcode, reading it,
-/// exporting the reader state to XML, and restoring the reader
-/// from the saved state.
+/// Demonstrates checkpoint/restart functionality for barcode detection using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
+ /// 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.
///
- /// Command‑line arguments (not used).
- static void Main(string[] args)
+ static void Main()
{
- // Path for the generated barcode image
- const string imagePath = "barcode.png";
+ // Paths for the barcode image and the checkpoint file
+ string imagePath = "sample.png";
+ string checkpointPath = "reader_state.xml";
- // -------------------------------------------------
- // 1. Generate a simple Code128 barcode and save it
- // -------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Demo123"))
+ // Ensure a barcode image exists; create one if missing
+ if (!File.Exists(imagePath))
{
- // Save the generated barcode image to the specified path
- generator.Save(imagePath);
+ // 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}");
+ }
}
- // -------------------------------------------------
- // 2. First reading session – read the barcode,
- // then export the reader state to an XML stream
- // -------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // First detection pass – read the barcode and export reader state
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Read all barcodes from the image
- var firstResults = reader.ReadBarCodes();
- Console.WriteLine("First read results:");
- foreach (var result in firstResults)
+ // Perform detection and process the first result
+ foreach (var result in reader.ReadBarCodes())
{
- // Output each detected barcode type and its text
- Console.WriteLine($"{result.CodeTypeName}: {result.CodeText}");
+ Console.WriteLine($"First read – Type: {result.CodeTypeName}, Text: {result.CodeText}");
+
+ // Export current reader settings to XML (checkpoint)
+ reader.ExportToXml(checkpointPath);
+ Console.WriteLine($"Reader state exported to: {checkpointPath}");
+ break; // Demonstrate checkpoint after first result
}
+ }
- // Export the current reader configuration/state to XML
- using (var stateStream = new MemoryStream())
+ // Simulate application restart: import settings, set image again, continue detection
+ using (var reader = BarCodeReader.ImportFromXml(checkpointPath))
+ {
+ if (reader == null)
{
- reader.ExportToXml(stateStream);
- stateStream.Position = 0; // Rewind the stream for subsequent reading
+ Console.WriteLine("Failed to import reader state.");
+ return;
+ }
- // -------------------------------------------------
- // 3. Simulate closing the reader and creating a new one
- // -------------------------------------------------
- // Import the previously saved state into a new reader instance
- var restoredReader = BarCodeReader.ImportFromXml(stateStream);
- using (restoredReader)
- {
- // The image must be set again after import
- restoredReader.SetBarCodeImage(imagePath);
+ // 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);
- // Continue detection with the restored reader
- var secondResults = restoredReader.ReadBarCodes();
- Console.WriteLine("After restart read results:");
- foreach (var result in secondResults)
- {
- // Output each detected barcode type and its text after restoration
- Console.WriteLine($"{result.CodeTypeName}: {result.CodeText}");
- }
- }
+ // Continue detection from the imported state
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Second read – Type: {result.CodeTypeName}, 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 c74d161..929c6e3 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,11 +1,19 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates barcode generation, recognition, and exporting the reader's state as XML.
+/// Sample program that generates a barcode, recognizes it from a stream,
+/// and outputs the reader's XML state.
///
class Program
{
@@ -13,58 +21,54 @@ class Program
/// Recognizes barcodes from an image stream and returns the reader's XML state.
///
/// Stream containing the barcode image.
- /// XML representation of the reader's state after recognition.
+ /// XML string representing the reader's configuration and results.
static string RecognizeAndExportXml(Stream imageStream)
{
if (imageStream == null)
- throw new ArgumentException("Image stream cannot be null.");
-
- // Ensure the stream is positioned at the beginning before reading.
- imageStream.Position = 0;
+ throw new ArgumentNullException(nameof(imageStream));
- // Create a reader that checks all supported symbologies.
+ // Initialize the reader with all supported decode types.
using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
{
- // Perform recognition (optional, but ensures results are populated).
+ // Perform the actual recognition.
reader.ReadBarCodes();
- // Export the reader's state to an in‑memory XML stream.
+ // Export the reader's configuration/state to XML.
using (var xmlStream = new MemoryStream())
{
reader.ExportToXml(xmlStream);
- xmlStream.Position = 0; // Reset to beginning for reading.
+ xmlStream.Position = 0; // Reset stream position for reading.
- // Read the XML content as a string.
- using (var readerStream = new StreamReader(xmlStream))
+ using (var sr = new StreamReader(xmlStream))
{
- return readerStream.ReadToEnd();
+ // Return the entire XML content as a string.
+ return sr.ReadToEnd();
}
}
}
}
///
- /// Entry point of the program. Generates a sample barcode, recognizes it, and prints the XML state.
+ /// Entry point that generates a sample barcode, runs recognition, and prints the XML state.
///
static void Main()
{
- // Generate a sample barcode image in memory.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Create a sample barcode image in memory.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- using (var imageStream = new MemoryStream())
+ using (var bitmap = generator.GenerateBarCodeImage())
{
- // Save the barcode as PNG into the stream.
- generator.Save(imageStream, BarCodeImageFormat.Png);
-
- // Reset stream position before recognition.
- imageStream.Position = 0;
-
- // Recognize the barcode and obtain the XML state.
- string xmlState = RecognizeAndExportXml(imageStream);
+ 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.
- // Output the XML state to the console.
- Console.WriteLine("Reader XML State:");
- Console.WriteLine(xmlState);
+ // Recognize and obtain XML state.
+ string xml = RecognizeAndExportXml(imageStream);
+ Console.WriteLine("Reader XML State:");
+ Console.WriteLine(xml);
+ }
}
}
}
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 6eeaeb7..6be6487 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,107 +1,118 @@
+// 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.
+// 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
+
using System;
-using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates benchmarking of Aspose.BarCode ExportToXml and ImportFromXml methods.
+/// Demonstrates a performance benchmark for exporting and importing barcode definitions using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a set of barcodes, exports them to XML,
- /// imports them back, measures execution time, and cleans up temporary files.
+ /// Entry point. Generates a set of barcodes, exports them to XML, measures export time,
+ /// then imports them back and measures import time.
///
static void Main()
{
- // Number of barcode samples to process (kept small for quick execution)
- const int sampleCount = 5;
-
- // List of barcode symbologies to be used for the samples
- var symbologies = new List
- {
- EncodeTypes.Code128,
- EncodeTypes.QR,
- EncodeTypes.DataMatrix,
- EncodeTypes.Pdf417,
- EncodeTypes.Aztec
- };
-
- // If the requested sample count exceeds the predefined symbologies,
- // repeat the first symbology to fill the list.
- while (symbologies.Count < sampleCount)
- {
- symbologies.Add(EncodeTypes.Code128);
- }
+ // Number of barcodes to process (kept small for safe execution)
+ const int barcodeCount = 5;
- // Create a temporary directory to store generated XML files
- string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeXmlBenchmark");
- Directory.CreateDirectory(tempDir);
+ // Prepare temporary folder for XML files
+ string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeBenchmark");
+ Directory.CreateDirectory(tempFolder);
- // Keep track of the generated XML file paths for later import and cleanup
- var xmlFiles = new List();
+ // Arrays to hold file paths for later import
+ string[] xmlFiles = new string[barcodeCount];
- // -------------------- Export to XML benchmark --------------------
- var exportStopwatch = Stopwatch.StartNew(); // Start timing export operations
+ // ------------------- Export to XML Benchmark -------------------
+ // Start timing the export operation
+ Stopwatch exportStopwatch = Stopwatch.StartNew();
- for (int i = 0; i < sampleCount; i++)
+ for (int i = 0; i < barcodeCount; i++)
{
- // Generate a unique text value for each barcode
+ // Create a unique code text for each barcode
string codeText = $"Sample{i + 1}";
- BaseEncodeType type = symbologies[i];
+ // Determine the XML file path for this barcode
+ string xmlPath = Path.Combine(tempFolder, $"barcode_{i + 1}.xml");
+ xmlFiles[i] = xmlPath;
- // Create a barcode generator, export its definition to XML, and store the file path
- using (var generator = new BarcodeGenerator(type, codeText))
+ // Generate the barcode and export its definition to XML
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- string xmlPath = Path.Combine(tempDir, $"barcode_{i + 1}.xml");
- generator.ExportToXml(xmlPath);
- xmlFiles.Add(xmlPath);
+ // Export properties to XML file
+ bool exported = generator.ExportToXml(xmlPath);
+ if (!exported)
+ {
+ Console.WriteLine($"Export failed for barcode {i + 1}");
+ }
}
}
- exportStopwatch.Stop(); // Stop timing export operations
+ // Stop timing and report export duration
+ exportStopwatch.Stop();
+ Console.WriteLine($"ExportToXml: Processed {barcodeCount} barcodes in {exportStopwatch.ElapsedMilliseconds} ms");
- // -------------------- Import from XML benchmark --------------------
- var importStopwatch = Stopwatch.StartNew(); // Start timing import operations
+ // ------------------- Import from XML Benchmark -------------------
+ // Start timing the import operation
+ Stopwatch importStopwatch = Stopwatch.StartNew();
- foreach (var xmlPath in xmlFiles)
+ for (int i = 0; i < barcodeCount; i++)
{
- // Import the barcode definition from the XML file.
- // No further processing is required for the benchmark.
- using (var generator = BarcodeGenerator.ImportFromXml(xmlPath))
+ string xmlPath = xmlFiles[i];
+ // Verify the XML file exists before attempting import
+ if (!File.Exists(xmlPath))
{
- // Intentionally left blank.
+ Console.WriteLine($"XML file missing for barcode {i + 1}");
+ continue;
}
- }
- importStopwatch.Stop(); // Stop timing import operations
+ // Import creates a new BarcodeGenerator instance from the XML definition
+ using (var importedGenerator = 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}");
+ }
+ }
- // Output benchmark results to the console
- Console.WriteLine($"ExportToXml time for {sampleCount} items: {exportStopwatch.ElapsedMilliseconds} ms");
- Console.WriteLine($"ImportFromXml time for {sampleCount} items: {importStopwatch.ElapsedMilliseconds} ms");
+ // Stop timing and report import duration
+ importStopwatch.Stop();
+ Console.WriteLine($"ImportFromXml: Processed {barcodeCount} barcodes in {importStopwatch.ElapsedMilliseconds} ms");
- // -------------------- Cleanup temporary files --------------------
+ // Cleanup temporary XML files
foreach (var file in xmlFiles)
{
try
{
- File.Delete(file);
+ if (File.Exists(file))
+ {
+ File.Delete(file);
+ }
}
catch
{
- // Suppress any exceptions during file deletion
+ // Ignore any cleanup errors
}
}
+ // Remove the temporary folder
try
{
- Directory.Delete(tempDir);
+ if (Directory.Exists(tempFolder))
+ {
+ Directory.Delete(tempFolder, true);
+ }
}
catch
{
- // Suppress any exceptions during directory deletion
+ // 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 ce4cde0..384fe87 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,80 +1,73 @@
+// 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.
+// 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
+
using System;
-using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating barcodes, reading them, and exporting the reader state to XML.
+/// 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.
///
class Program
{
///
- /// Application entry point.
- /// Generates sample barcodes, reads them, and logs detection results and reader state.
+ /// Entry point of the console application.
+ /// Generates barcodes, reads them, and writes the reader state to XML files.
///
static void Main()
{
- // Define a collection of sample barcodes (symbology type and associated text)
- var samples = new List<(BaseEncodeType type, string text)>
+ // 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.EAN13, "1234567890128")
+ (EncodeTypes.DatabarStacked, "(01)01234567890123")
};
- int index = 0; // Used to differentiate output files for each sample
-
- // Process each sample barcode definition
- foreach (var sample in samples)
+ // Iterate over each sample barcode definition.
+ for (int i = 0; i < samples.Length; i++)
{
- // Create a memory stream to hold the generated barcode image
- using (var ms = new MemoryStream())
- {
- // Generate the barcode image and write it to the memory stream
- using (var generator = new BarcodeGenerator(sample.type, sample.text))
- {
- // Save the barcode as a PNG image
- generator.Save(ms, BarCodeImageFormat.Png);
- }
+ var (encodeType, codeText) = samples[i];
- // Reset stream position to the beginning for reading
- ms.Position = 0;
+ // Generate a barcode image and store it in a memory stream.
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ using (var imageStream = new MemoryStream())
+ {
+ // 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.
- // Initialize a barcode reader that supports all available symbologies
- using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
+ // Initialize a barcode reader to decode all supported types from the image stream.
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
{
- // Iterate over all detected barcodes in the image
+ Console.WriteLine($"Reading barcode {i + 1}: {encodeType.TypeName}");
+
+ // Enumerate and display each detected barcode result.
foreach (var result in reader.ReadBarCodes())
{
- // Output detection details to the console
- Console.WriteLine($"[{index}] Detected Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ Console.WriteLine($" Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
}
- // Build a unique file name for exporting the reader's internal state
- string xmlPath = $"ReaderState_{index}.xml";
-
- // Attempt to export the reader state (settings and results) to an XML file
- try
- {
- reader.ExportToXml(xmlPath);
- Console.WriteLine($"Reader state exported to: {xmlPath}");
- }
- catch (Exception ex)
- {
- // Log any errors that occur during export
- Console.WriteLine($"Failed to export reader state: {ex.Message}");
- }
+ // 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}");
}
}
- index++; // Increment index for the next sample
+ Console.WriteLine(); // Add a blank line as a visual separator between samples.
}
- // Indicate that all processing is complete
- Console.WriteLine("Processing completed.");
+ // 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.
}
}
\ 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 5ebfb91..5b55273 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,61 +1,70 @@
+// 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.
+// 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
+
using System;
using System.IO;
-using Aspose.BarCode.Generation;
using Aspose.BarCode;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates importing a barcode generator from XML and handling expected exceptions.
+/// Contains the entry point demonstrating a unit‑test‑like verification that
+/// throws when no barcode image has been set.
///
class Program
{
///
- /// Entry point of the application. Executes the test for XML import exception handling.
+ /// 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.
///
static void Main()
{
- TestImportFromXmlThrows();
- }
-
- ///
- /// Tests that importing a from XML without image data throws an exception.
- ///
- static void TestImportFromXmlThrows()
- {
- // Create a minimal XML that does not contain any barcode image data.
- string xmlContent = @"
-
- 12345
- Code128
-";
+ // Create a temporary XML file with minimal content.
+ string tempXmlPath = Path.GetTempFileName();
- // Write the XML to a memory stream so it can be read by the ImportFromXml method.
- using (var memoryStream = new MemoryStream())
+ try
{
- // Use a StreamWriter with UTF-8 encoding to write the XML string into the stream.
- using (var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8, 1024, true))
- {
- writer.Write(xmlContent);
- writer.Flush(); // Ensure all data is written to the underlying stream.
- memoryStream.Position = 0; // Reset position to the beginning for reading.
- }
+ // Write a simple, empty element to the temp file.
+ File.WriteAllText(tempXmlPath, "");
+
+ bool exceptionThrown = false;
try
{
- // Attempt to import from XML without having set a barcode image.
- // According to the requirement, this should throw an exception.
- BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(memoryStream);
-
- // If no exception is thrown, the test fails.
- Console.WriteLine("Test Failed: No exception was thrown.");
+ // 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);
- // Dispose the generator if it was created to release resources.
- generator?.Dispose();
+ // 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.
- Console.WriteLine("Test Passed: Caught expected exception.");
- Console.WriteLine("Exception Message: " + ex.Message);
+ 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)
+ {
+ Console.WriteLine("Test passed: ImportFromXml threw an exception as expected.");
+ }
+ else
+ {
+ Console.WriteLine("Test failed: ImportFromXml did not throw an exception.");
+ }
+ }
+ finally
+ {
+ // Clean up the temporary file.
+ if (File.Exists(tempXmlPath))
+ {
+ File.Delete(tempXmlPath);
}
}
}
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 8615b13..4255558 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,86 +1,83 @@
+// 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.
+// Prompt: Demonstrate how to use ExportToXml(Stream) to send barcode recognition state over a network socket.
+// Tags: barcode, recognition, export, xml, network, socket, aspose
+
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
-using Aspose.BarCode;
+using System.Threading.Tasks;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing.Imaging;
+using Aspose.Drawing;
///
-/// Demonstrates barcode generation, recognition, and transmission of recognition data over a TCP socket.
+/// Demonstrates generating a barcode, recognizing it, exporting the recognition state to XML,
+/// and sending that XML over a TCP socket.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Code128 barcode, reads it, exports the recognition result to XML,
- /// and simulates sending that XML over a network socket.
+ /// Entry point of the example. Executes the barcode generation, recognition, export, and network transmission.
///
static void Main()
{
- // Generate a simple Code128 barcode and keep it in a memory stream.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Generate a simple Code128 barcode image in memory.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
{
- using (var imageStream = new MemoryStream())
+ using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
{
- // Save the generated barcode image as PNG into the memory stream.
- generator.Save(imageStream, BarCodeImageFormat.Png);
- // Reset stream position to the beginning for reading.
- imageStream.Position = 0;
-
- // Recognize the barcode from the image stream.
- using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
+ // Create a reader for the generated image and perform recognition of all supported types.
+ using (var reader = new BarCodeReader(barcodeImage, DecodeType.AllSupportedTypes))
{
- // Iterate through all detected barcodes and output their type and text.
+ // Output each detected barcode to the console.
foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}");
}
- // Export the recognition state to an XML stream.
- using (var xmlStream = new MemoryStream())
+ // Export the recognition state to a memory stream in XML format.
+ using (var stateStream = new MemoryStream())
{
- reader.ExportToXml(xmlStream);
- // Reset stream position to the beginning for transmission.
- xmlStream.Position = 0;
+ bool exported = reader.ExportToXml(stateStream);
+ Console.WriteLine($"Exported to XML: {exported}");
- // ----- Simulate sending the XML over a network socket -----
- const int port = 5000;
- // Set up a TCP listener on the loopback address.
- var listener = new TcpListener(IPAddress.Loopback, port);
- listener.Start();
+ // 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();
- // Begin accepting an incoming client connection asynchronously.
- var acceptTask = listener.AcceptTcpClientAsync();
+ // 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.");
+ }
+ });
- // Client side: connect to the listener and send the XML data.
- using (var client = new TcpClient())
- {
- client.Connect(IPAddress.Loopback, port);
- using (var netStream = client.GetStream())
+ // Connect as a client and send the XML data over the socket.
+ using (var client = new TcpClient())
{
- // Copy the XML bytes to the network stream.
- xmlStream.CopyTo(netStream);
+ client.Connect(IPAddress.Loopback, 5000);
+ using (NetworkStream clientStream = 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.");
+ }
}
- }
- // Server side: receive the XML data from the client.
- using (var serverClient = acceptTask.Result)
- using (var serverStream = serverClient.GetStream())
- using (var receivedMs = new MemoryStream())
- {
- // Copy received bytes into a memory stream.
- serverStream.CopyTo(receivedMs);
- // Convert the received bytes to a UTF-8 string.
- string receivedXml = System.Text.Encoding.UTF8.GetString(receivedMs.ToArray());
- Console.WriteLine("Received XML:");
- Console.WriteLine(receivedXml);
+ // Wait for the server side to finish processing the received data.
+ acceptTask.Wait();
+ listener.Stop();
}
-
- // Stop listening for further connections.
- listener.Stop();
- // ---------------------------------------------------------
}
}
}
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 1f7e27a..8abcddf 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,59 +1,56 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a Code128 barcode, exporting and importing reader settings via XML, and recognizing the barcode.
+/// 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.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point. Generates a barcode, exports reader settings to XML,
+ /// imports them into a new reader, and reads the barcode again.
///
static void Main()
{
- // Generate a simple Code128 barcode and keep it in a memory stream
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Generate a sample barcode image (Code128)
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Enable checksum (required for Code128)
- generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
-
- // Stream to hold the generated barcode image
- using (var imageStream = new MemoryStream())
+ using (var barcodeImage = generator.GenerateBarCodeImage())
{
- // Save barcode image to the stream in PNG format
- generator.Save(imageStream, BarCodeImageFormat.Png);
- // Reset stream position for reading
- imageStream.Position = 0;
-
// Create a reader for the generated image
- using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
+ using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128))
{
- // Enable checksum validation to demonstrate state persistence
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
-
- // Export the reader's current state to an XML stream
- using (var xmlStream = new MemoryStream())
+ // Export the reader's state to an XML stream
+ using (var exportStream = new MemoryStream())
{
- reader.ExportToXml(xmlStream);
- // Reset XML stream position for import
- xmlStream.Position = 0;
+ reader.ExportToXml(exportStream);
+ exportStream.Position = 0; // Reset stream position for reading
- // Import the previously saved state into a new reader instance
- BarCodeReader importedReader = BarCodeReader.ImportFromXml(xmlStream);
+ // 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);
- // Reapply the same barcode image to the imported reader
- imageStream.Position = 0;
- importedReader.SetBarCodeImage(imageStream);
+ // Apply the same barcode image to the new reader
+ newReader.SetBarCodeImage(barcodeImage);
- // Perform recognition using the imported settings
- foreach (var result in importedReader.ReadBarCodes())
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ // Perform recognition using the imported settings
+ foreach (var result in newReader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Detected Text: {result.CodeText}");
+ }
}
}
}
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 cead22d..6fb7b67 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,100 +1,88 @@
+// 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.
+// 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
+
using System;
using System.IO;
using System.Text.Json;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-///
-/// Represents application configuration settings.
-///
-class Config
-{
- ///
- /// Gets or sets the directory where exported files will be saved.
- ///
- public string ExportDirectory { get; set; } = "Export";
-}
-
-///
-/// Main program class.
-///
-class Program
+namespace BarcodeExportConfigExample
{
///
- /// Application entry point. Handles configuration loading/creation,
- /// ensures the export directory exists, generates a barcode, and
- /// exports its configuration to an XML file.
+ /// Simple configuration class matching the JSON structure.
+ /// Contains the default directory where exported XML files are saved.
///
- static void Main()
+ public class AppConfig
{
- const string configPath = "config.json";
-
- Config config;
+ public string ExportDirectory { get; set; } = "Export";
+ }
- // Load existing configuration or create a default one.
- if (File.Exists(configPath))
+ 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()
{
- try
+ // Load configuration from "config.json" if it exists; otherwise use defaults.
+ var config = LoadConfiguration("config.json");
+
+ // Ensure the export directory exists; create it if necessary.
+ if (!Directory.Exists(config.ExportDirectory))
{
- string json = File.ReadAllText(configPath);
- config = JsonSerializer.Deserialize(json) ?? new Config();
+ Directory.CreateDirectory(config.ExportDirectory);
}
- catch (Exception ex)
+
+ // Create a barcode generator for Code128 with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- Console.WriteLine($"Failed to read config: {ex.Message}");
- config = new Config();
+ // 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}");
}
}
- else
+
+ ///
+ /// 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)
{
- config = new Config();
- try
+ // If the config file does not exist, return a new instance with default values.
+ if (!File.Exists(filePath))
{
- string json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
- File.WriteAllText(configPath, json);
- Console.WriteLine($"Created default config at '{configPath}'.");
+ return new AppConfig();
}
- catch (Exception ex)
- {
- Console.WriteLine($"Failed to write default config: {ex.Message}");
- }
- }
- // Ensure the export directory exists.
- if (!Directory.Exists(config.ExportDirectory))
- {
try
{
- Directory.CreateDirectory(config.ExportDirectory);
- Console.WriteLine($"Created export directory '{config.ExportDirectory}'.");
+ // 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)
{
- Console.WriteLine($"Failed to create export directory: {ex.Message}");
- return;
+ // Log any errors and revert to default configuration.
+ Console.WriteLine($"Error loading configuration: {ex.Message}");
+ return new AppConfig();
}
}
-
- // Define barcode parameters.
- BaseEncodeType encodeType = EncodeTypes.Code128;
- string codeText = "1234567890";
-
- // Generate the barcode and export its configuration.
- using (var generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Optional barcode visual settings.
- generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
-
- // Build the full path for the XML export file.
- string xmlFilePath = Path.Combine(config.ExportDirectory, "barcode.xml");
-
- // Export the barcode configuration to XML.
- bool exported = generator.ExportToXml(xmlFilePath);
- Console.WriteLine(exported
- ? $"Barcode configuration exported to '{xmlFilePath}'."
- : $"Failed to export barcode configuration to '{xmlFilePath}'.");
- }
}
}
\ No newline at end of file
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 ad3a99d..df80b3f 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,50 +1,69 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates creating a Code128 barcode, exporting its state to XML,
-/// and logging the generated file paths.
+/// Example program that generates a barcode, exports its configuration to XML,
+/// and logs the image path used when reading the barcode.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Performs barcode generation, XML export,
+ /// and reads the barcode while logging relevant information.
///
static void Main()
{
- // Define a temporary output directory for all generated files.
- string outputDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo");
- Directory.CreateDirectory(outputDir); // Ensure the directory exists.
-
- // Build full file paths for the barcode image, XML state, and log file.
- string imagePath = Path.Combine(outputDir, "barcode.png");
- string xmlPath = Path.Combine(outputDir, "barcode_state.xml");
- string logPath = Path.Combine(outputDir, "log.txt");
+ // Define file paths for the barcode image and the exported XML
+ string imagePath = "barcode.png";
+ string xmlPath = "barcode.xml";
- // Create a simple Code128 barcode with the specified data.
+ // Generate a Code128 barcode, save the image, and export generator settings to XML
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Enable checksum calculation for the barcode.
- generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
-
- // Save the generated barcode as a PNG image.
+ // Save the generated barcode image to the specified path
generator.Save(imagePath);
- // Export the generator's internal state to an XML file.
+ // Export the generator's current state (settings) to an XML file
generator.ExportToXml(xmlPath);
}
- // Prepare a log message containing the locations of the generated files.
- string logContent = $"Barcode image saved to: {imagePath}{Environment.NewLine}" +
- $"Generator state exported to XML: {xmlPath}{Environment.NewLine}" +
- $"Log generated at: {logPath}{Environment.NewLine}";
+ // Retrieve the exported XML content if the file was created successfully
+ string xmlContent = File.Exists(xmlPath) ? File.ReadAllText(xmlPath) : "XML file not found.";
- // Output the log message to the console for immediate feedback.
- Console.WriteLine(logContent);
+ // Initialize a BarCodeReader to read barcodes from the saved image
+ using (var reader = new BarCodeReader())
+ {
+ // 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
+ {
+ // Inform the user that the expected image file could not be found
+ Console.WriteLine($"Image file not found: {imagePath}");
+ }
+
+ // Log the previously exported XML state for diagnostic purposes
+ Console.WriteLine("Exported XML state:");
+ Console.WriteLine(xmlContent);
- // Persist the log message to a text file.
- File.WriteAllText(logPath, logContent);
+ // 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}");
+ }
+ }
}
}
\ 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 b5380da..738d6cc 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,96 +1,133 @@
+// 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.
+// 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
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates exporting a barcode generator's configuration to XML,
-/// importing it back, and verifying that the settings are preserved.
+/// Example program that exports a barcode generator configuration to XML,
+/// imports it back, and validates that the restored settings produce the same barcode.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Executes the export, import, and verification steps.
///
static void Main()
{
- // Prepare a temporary file path with an .xml extension for storing the exported settings.
- string tempXmlPath = Path.ChangeExtension(Path.GetTempFileName(), ".xml");
+ // ------------------------------------------------------------
+ // 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");
- // Create a barcode generator, configure its parameters, and export the configuration to XML.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
+ // ------------------------------------------------------------
+ // Create original barcode generator with custom visual settings
+ // ------------------------------------------------------------
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
{
- // Disable automatic sizing.
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Set the X-dimension (module width) to 2 points.
+ // 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 the barcode height to 40 points.
- generator.Parameters.Barcode.BarHeight.Point = 40f;
+ // Export the generator's configuration to an XML file
+ bool exportSuccess = generator.ExportToXml(xmlPath);
+ if (!exportSuccess)
+ {
+ Console.WriteLine("FAILED: ExportToXml returned false.");
+ return;
+ }
- // Write the current configuration to the temporary XML file.
- generator.ExportToXml(tempXmlPath);
+ // Save the generated barcode image (used later for visual verification)
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Attempt to import a barcode generator from the previously saved XML file.
- BarcodeGenerator importedGenerator = null;
- try
- {
- importedGenerator = BarcodeGenerator.ImportFromXml(tempXmlPath);
- }
- catch (Exception ex)
+ // ------------------------------------------------------------
+ // Import the configuration from XML into a new generator instance
+ // ------------------------------------------------------------
+ using (BarcodeGenerator imported = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // Report any import errors and clean up the temporary file before exiting.
- Console.WriteLine("ImportFromXml threw an exception: " + ex.Message);
- Cleanup(tempXmlPath);
- return;
- }
+ // 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;
- // Verify that the imported generator's settings match the original configuration.
- bool isCodeTextEqual = importedGenerator.CodeText == "Test123";
- bool isSymbologyEqual = importedGenerator.BarcodeType.TypeName == EncodeTypes.Code128.TypeName;
- bool isXDimensionEqual = Math.Abs(importedGenerator.Parameters.Barcode.XDimension.Point - 2f) < 0.001f;
- bool isBarHeightEqual = Math.Abs(importedGenerator.Parameters.Barcode.BarHeight.Point - 40f) < 0.001f;
- bool isAutoSizeModeEqual = importedGenerator.Parameters.AutoSizeMode == AutoSizeMode.None;
+ if (!settingsMatch)
+ {
+ Console.WriteLine("FAILED: Imported settings do not match original.");
+ return;
+ }
- if (isCodeTextEqual && isSymbologyEqual && isXDimensionEqual && isBarHeightEqual && isAutoSizeModeEqual)
- {
- Console.WriteLine("Test Passed: Imported settings match the exported ones.");
- }
- else
- {
- // Output detailed mismatch information for debugging.
- Console.WriteLine("Test Failed: Mismatch in imported settings.");
- Console.WriteLine($"CodeText: Expected 'Test123', Actual '{importedGenerator.CodeText}'");
- Console.WriteLine($"Symbology: Expected '{EncodeTypes.Code128.TypeName}', Actual '{importedGenerator.BarcodeType.TypeName}'");
- Console.WriteLine($"XDimension: Expected 2, Actual {importedGenerator.Parameters.Barcode.XDimension.Point}");
- Console.WriteLine($"BarHeight: Expected 40, Actual {importedGenerator.Parameters.Barcode.BarHeight.Point}");
- Console.WriteLine($"AutoSizeMode: Expected None, Actual {importedGenerator.Parameters.AutoSizeMode}");
- }
+ // ------------------------------------------------------------
+ // Generate a barcode image from the imported settings into memory
+ // ------------------------------------------------------------
+ using (MemoryStream ms = new MemoryStream())
+ {
+ imported.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading
- // Release resources used by the imported generator and delete the temporary XML file.
- importedGenerator?.Dispose();
- Cleanup(tempXmlPath);
- }
+ // ------------------------------------------------------------
+ // Decode the barcode from the generated image to verify content
+ // ------------------------------------------------------------
+ using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
+ {
+ var results = reader.ReadBarCodes();
+ if (results.Length == 0)
+ {
+ Console.WriteLine("FAILED: No barcode detected in the generated image.");
+ return;
+ }
- ///
- /// Deletes the specified file if it exists, suppressing any exceptions.
- ///
- /// The full path of the file to delete.
- static void Cleanup(string filePath)
- {
+ // Ensure the decoded text matches the original code text
+ bool decodeMatch = true;
+ foreach (var result in results)
+ {
+ if (string.IsNullOrEmpty(result.CodeText) || result.CodeText != "Test123")
+ {
+ decodeMatch = false;
+ break;
+ }
+ }
+
+ if (!decodeMatch)
+ {
+ Console.WriteLine("FAILED: Decoded CodeText does not match original.");
+ return;
+ }
+
+ // 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(filePath))
- {
- File.Delete(filePath);
- }
+ if (File.Exists(xmlPath)) File.Delete(xmlPath);
+ if (File.Exists(imagePath)) File.Delete(imagePath);
}
catch
{
- // Intentionally ignore any errors that occur during cleanup.
+ // Cleanup failures are non‑critical for the test outcome
}
}
}
\ 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 f84a65c..4f93508 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,50 +1,49 @@
+// 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.
+// 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
+
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Console application that processes XML files to generate barcode images.
-/// It reads each XML file, creates a barcode using Aspose.BarCode, saves the image,
-/// and moves the processed XML to a separate folder.
+/// Entry point for the barcode generation service.
///
class Program
{
///
- /// Entry point of the application.
- /// Scans the Input folder for XML files, generates barcode images,
- /// and moves processed XML files to the Processed folder.
+ /// Main method processes XML barcode definitions, generates images, and moves processed files.
///
- static void Main()
+ /// Command‑line arguments: [0] input folder, [1] output folder.
+ static void Main(string[] args)
{
- // Define folder paths relative to the current directory
- string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Input");
- string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Output");
- string processedFolder = Path.Combine(Directory.GetCurrentDirectory(), "Processed");
+ // Determine input folder (first argument) or use default "Input"
+ string inputFolder = args.Length > 0 ? args[0] : "Input";
- // Ensure the Output folder exists
- if (!Directory.Exists(outputFolder))
- {
- Directory.CreateDirectory(outputFolder);
- }
+ // Determine output folder for generated images (second argument) or use default "Output"
+ string outputFolder = args.Length > 1 ? args[1] : "Output";
- // Ensure the Processed folder exists
- if (!Directory.Exists(processedFolder))
- {
- Directory.CreateDirectory(processedFolder);
- }
+ // Folder where processed XML files will be moved after successful handling
+ string processedFolder = Path.Combine(inputFolder, "Processed");
- // Verify that the Input folder exists; abort if it does not
+ // Validate that the input folder exists; abort if it does not
if (!Directory.Exists(inputFolder))
{
- Console.WriteLine($"Input folder not found: {inputFolder}");
+ Console.WriteLine($"Input directory '{inputFolder}' does not exist.");
return;
}
- // Retrieve all XML files in the Input folder
+ // Ensure the output and processed folders exist (create if necessary)
+ Directory.CreateDirectory(outputFolder);
+ Directory.CreateDirectory(processedFolder);
+
+ // Retrieve all XML files in the input folder
string[] xmlFiles = Directory.GetFiles(inputFolder, "*.xml");
if (xmlFiles.Length == 0)
{
- Console.WriteLine("No XML files to process.");
+ Console.WriteLine("No XML files found to process.");
return;
}
@@ -53,39 +52,34 @@ static void Main()
{
try
{
- // Import barcode generator settings from the XML file
+ // Import barcode settings from the XML file using Aspose.BarCode
using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // Build the output image path (same name with .png extension)
- string fileNameWithoutExt = Path.GetFileNameWithoutExtension(xmlPath);
- string outputPath = Path.Combine(outputFolder, fileNameWithoutExt + ".png");
+ // If import fails, log and continue with next file
+ if (generator == null)
+ {
+ Console.WriteLine($"Failed to import barcode from '{xmlPath}'.");
+ continue;
+ }
- // Save the generated barcode image to the Output folder
- generator.Save(outputPath);
- Console.WriteLine($"Generated barcode saved to: {outputPath}");
- }
-
- // Move the processed XML file to the Processed folder
- string destXmlPath = Path.Combine(processedFolder, Path.GetFileName(xmlPath));
+ // 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);
- // If a file with the same name already exists in Processed, delete it first
- if (File.Exists(destXmlPath))
- {
- File.Delete(destXmlPath);
+ // Save the generated barcode image to the output folder
+ generator.Save(imagePath);
+ Console.WriteLine($"Generated barcode saved to '{imagePath}'.");
}
- // Move the XML file
+ // After successful generation, move the processed XML to the "Processed" subfolder
+ string destXmlPath = Path.Combine(processedFolder, Path.GetFileName(xmlPath));
File.Move(xmlPath, destXmlPath);
- Console.WriteLine($"Moved processed XML to: {destXmlPath}");
}
catch (Exception ex)
{
- // Log any errors and continue processing remaining files
+ // Log any errors that occur during processing of the current XML file
Console.WriteLine($"Error processing '{xmlPath}': {ex.Message}");
}
}
-
- // Indicate that all processing is complete
- Console.WriteLine("Processing completed.");
}
}
\ 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 3010c8a..e705c85 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,96 +1,129 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates exporting a configuration to XML,
-/// importing it back, generating barcode images, and comparing the original and
-/// imported results.
+/// Entry point for the barcode XML import integrity diagnostic example.
///
class Program
{
///
- /// Application entry point.
- /// Creates a QR barcode, exports its settings to an XML stream,
- /// imports the settings into a new generator, generates images from both,
- /// and outputs a diagnostic comparison of key properties.
+ /// Generates a barcode, exports its configuration to XML, re‑imports it, and compares the original and imported results.
///
static void Main()
{
- // Initialize the original barcode generator with sample settings.
- using (var originalGenerator = new BarcodeGenerator(EncodeTypes.QR, "Test123"))
+ // --------------------------------------------------------------------
+ // 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";
+
+ // --------------------------------------------------------------------
+ // Sample barcode data: code text and symbology type.
+ // --------------------------------------------------------------------
+ const string codeText = "1234567890";
+ BaseEncodeType encodeType = EncodeTypes.Code128;
+
+ // --------------------------------------------------------------------
+ // 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))
+ {
+ // 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;
+ }
+
+ // --------------------------------------------------------------------
+ // Import a new barcode generator from the previously saved XML.
+ // --------------------------------------------------------------------
+ BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath);
+ if (importedGenerator == null)
{
- // Configure QR-specific parameters.
- originalGenerator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
- // Set the module (X) dimension in points.
- originalGenerator.Parameters.Barcode.XDimension.Point = 2f;
- // Define image resolution (dpi) and rotation.
- originalGenerator.Parameters.Resolution = 300f;
- originalGenerator.Parameters.RotationAngle = 0f;
-
- // Generate the original barcode image and store it in a byte array.
- byte[] originalImageBytes;
- using (var originalBitmap = originalGenerator.GenerateBarCodeImage())
- using (var originalMs = new MemoryStream())
- {
- originalBitmap.Save(originalMs, ImageFormat.Png);
- originalImageBytes = originalMs.ToArray();
- }
-
- // Export the generator's configuration to an in‑memory XML stream.
- using (var xmlMs = new MemoryStream())
- {
- originalGenerator.ExportToXml(xmlMs);
- // Reset stream position for reading.
- xmlMs.Position = 0;
-
- // Import the settings from XML into a new generator instance.
- using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlMs))
- {
- // Generate a barcode image from the imported generator.
- byte[] importedImageBytes;
- using (var importedBitmap = importedGenerator.GenerateBarCodeImage())
- using (var importedMs = new MemoryStream())
- {
- importedBitmap.Save(importedMs, ImageFormat.Png);
- importedImageBytes = importedMs.ToArray();
- }
-
- // Compare core properties between original and imported generators.
- bool codeTextMatch = originalGenerator.CodeText == importedGenerator.CodeText;
- bool symbologyMatch = originalGenerator.BarcodeType.TypeName == importedGenerator.BarcodeType.TypeName;
- bool imageMatch = AreByteArraysEqual(originalImageBytes, importedImageBytes);
-
- // Output diagnostic results to the console.
- Console.WriteLine("Diagnostic Comparison Results:");
- Console.WriteLine($"CodeText match: {codeTextMatch}");
- Console.WriteLine($"Symbology match: {symbologyMatch}");
- Console.WriteLine($"Generated image match: {imageMatch}");
- }
- }
+ Console.WriteLine("Failed to import generator from XML. Exiting.");
+ return;
}
+
+ // --------------------------------------------------------------------
+ // Save an image using the imported generator 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))
+ {
+ 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")}");
+ }
+
+ // --------------------------------------------------------------------
+ // Clean up temporary files (optional). Uncomment to delete files.
+ // --------------------------------------------------------------------
+ // File.Delete(originalImagePath);
+ // File.Delete(importedImagePath);
+ // File.Delete(xmlPath);
}
- ///
- /// Compares two byte arrays for equality.
- ///
- /// First byte array.
- /// Second byte array.
- /// True if both arrays are non‑null, have the same length, and contain identical bytes; otherwise, false.
- static bool AreByteArraysEqual(byte[] a, byte[] b)
+ // ------------------------------------------------------------------------
+ // 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 (a == null || b == null) return false;
- if (a.Length != b.Length) return false;
+ if (!File.Exists(path1) || !File.Exists(path2))
+ return false;
+
+ byte[] file1 = File.ReadAllBytes(path1);
+ byte[] file2 = File.ReadAllBytes(path2);
- for (int i = 0; i < a.Length; i++)
+ if (file1.Length != file2.Length)
+ return false;
+
+ for (int i = 0; i < file1.Length; i++)
{
- if (a[i] != b[i]) return false;
+ if (file1[i] != file2[i])
+ return false;
}
-
return true;
}
}
\ 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 ba32756..aaf7eb6 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,102 +1,99 @@
+// 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.
+// 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
+
using System;
using System.IO;
-using System.Linq;
-using System.Xml.Linq;
using Aspose.BarCode;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.Generation;
///
-/// Entry point for the barcode processing application.
-/// Scans a directory for image files, reads any barcodes present,
-/// and writes the results to XML files alongside the images.
+/// Example program that processes barcode images, creates generators, and exports their state to XML files.
///
class Program
{
///
- /// Application start method.
- /// Determines the target directory (from arguments or default) and initiates processing.
+ /// Entry point of the application. Sets up input/output directories and starts processing.
///
- /// Command‑line arguments; first argument may specify a directory path.
- static void Main(string[] args)
+ static void Main()
{
- // Determine the directory to process. Use a default sample if not provided.
- string directoryPath = args.Length > 0
- ? args[0]
- : Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ // 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");
- // Verify that the directory exists before proceeding.
- if (!Directory.Exists(directoryPath))
+ // Ensure the output directory exists; create it if it does not
+ if (!Directory.Exists(outputDirectory))
{
- Console.WriteLine($"Directory does not exist: {directoryPath}");
- return;
+ Directory.CreateDirectory(outputDirectory);
}
- // Process all supported image files in the directory.
- ProcessBarcodesInDirectory(directoryPath);
+ // Process each barcode image and export its generator state to XML
+ ProcessBarcodes(inputDirectory, outputDirectory);
}
///
- /// Scans the specified directory for image files, reads any barcodes,
- /// and writes detection results to XML files.
+ /// Loops through image files in , creates a for each,
+ /// exports its configuration to an XML file in , and logs the outcome.
///
- /// Path of the directory containing image files.
- static void ProcessBarcodesInDirectory(string directoryPath)
+ /// Directory containing barcode image files.
+ /// Directory where XML files will be saved.
+ static void ProcessBarcodes(string inputDir, string outputDir)
{
- // Supported image extensions (lower‑case for comparison).
- string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".gif" };
+ // Verify that the input directory exists before proceeding
+ if (!Directory.Exists(inputDir))
+ {
+ Console.WriteLine($"Input directory does not exist: {inputDir}");
+ return;
+ }
- // Retrieve all files in the directory (filtering occurs later).
- var files = Directory.GetFiles(directoryPath);
+ // 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);
- foreach (var filePath in files)
+ // Iterate over the selected image files
+ for (int i = 0; i < maxItems; i++)
{
- // Skip files that do not have a supported image extension.
- if (Array.IndexOf(extensions, Path.GetExtension(filePath).ToLowerInvariant()) < 0)
- continue;
+ string imagePath = imageFiles[i];
- Console.WriteLine($"Processing file: {Path.GetFileName(filePath)}");
+ // Skip the file if it cannot be found (defensive check)
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"File not found, skipping: {imagePath}");
+ continue;
+ }
- // Use BarCodeReader to read all supported barcode types from the image.
- using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
+ try
{
- // Perform the barcode detection.
- var results = reader.ReadBarCodes();
+ // Use the file name (without extension) as the barcode's codetext for demonstration purposes
+ string codeText = Path.GetFileNameWithoutExtension(imagePath);
- // Build an XML document containing the detection results.
- var doc = new XDocument(
- new XElement("BarCodeResults",
- new XElement("SourceFile", Path.GetFileName(filePath)),
- new XElement("DetectedBarCodes",
- // Create an element for each detected barcode.
- from result in results
- select new XElement("BarCode",
- new XElement("CodeText", result.CodeText),
- new XElement("Symbology", result.CodeTypeName),
- new XElement("Confidence", (int)result.Confidence))
- )
- )
- );
+ // Create a barcode generator with Code128 symbology and the derived codetext
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ // Optional: customize appearance (example sets the barcode color to blue)
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue;
- // Save the XML document alongside the image (same name with .xml extension).
- string xmlPath = Path.ChangeExtension(filePath, ".xml");
- doc.Save(xmlPath);
- Console.WriteLine($"Saved XML: {Path.GetFileName(xmlPath)}");
+ // Build the full path for the XML output file
+ string xmlFileName = Path.Combine(outputDir, $"{codeText}.xml");
- // Log detection results to the console.
- if (results.Length == 0)
- {
- Console.WriteLine(" No barcodes detected.");
- }
- else
- {
- foreach (var result in results)
- {
- Console.WriteLine($" Detected: {result.CodeTypeName} - {result.CodeText} (Confidence: {result.Confidence})");
- }
+ // Export the generator's current state to the XML file
+ generator.ExportToXml(xmlFileName);
+
+ // Log successful processing
+ Console.WriteLine($"Processed '{imagePath}' -> XML saved as '{xmlFileName}'.");
}
}
+ catch (Exception ex)
+ {
+ // Log any errors that occur during processing of the current file
+ Console.WriteLine($"Error processing '{imagePath}': {ex.Message}");
+ }
}
+ // Indicate that all processing is complete
Console.WriteLine("Processing completed.");
}
}
\ 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 21ff25d..9a3df3b 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,71 +1,55 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates loading barcode reader settings from an XML file,
-/// processing an image, and outputting detected barcode information.
+/// 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.
///
class Program
{
///
- /// Application entry point.
- /// Accepts optional command‑line arguments for the XML state file and image file.
+ /// Entry point of the application.
+ /// Loads the XML configuration, validates input files, performs barcode detection,
+ /// and outputs each detected barcode's type and value.
///
- ///
- /// args[0] – path to the XML state file (default: "state.xml").
- /// args[1] – path to the image file (default: "sample.png").
- ///
- static void Main(string[] args)
+ static void Main()
{
- // Resolve the XML state file path; use default if not supplied.
- string xmlPath = args.Length > 0 ? args[0] : "state.xml";
-
- // Resolve the image file path; use default if not supplied.
- string imagePath = args.Length > 1 ? args[1] : "sample.png";
+ // Default file names – replace with your own paths or pass as arguments.
+ string xmlPath = "state.xml";
+ string imagePath = "barcode.png";
- // Verify that the XML state file exists before proceeding.
+ // Validate XML file existence.
if (!File.Exists(xmlPath))
{
Console.WriteLine($"XML state file not found: {xmlPath}");
return;
}
- // Verify that the image file exists before proceeding.
+ // Validate image file existence.
if (!File.Exists(imagePath))
{
Console.WriteLine($"Image file not found: {imagePath}");
return;
}
- // Initialize the barcode reader within a using block to ensure proper disposal.
- using (var reader = new BarCodeReader())
+ // Load reader settings from the XML file.
+ // ImportFromXml returns a BarCodeReader instance with the imported configuration.
+ using (BarCodeReader reader = BarCodeReader.ImportFromXml(xmlPath))
{
- // Load reader configuration from the specified XML file.
- BarCodeReader.ImportFromXml(xmlPath);
-
- // Assign the image that will be processed for barcode detection.
+ // Assign the image to be processed.
reader.SetBarCodeImage(imagePath);
- // Ensure the reader scans for all supported barcode symbologies.
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
-
- // Execute the barcode recognition process.
- var results = reader.ReadBarCodes();
-
- // Check if any barcodes were detected and output appropriate messages.
- if (results.Length == 0)
- {
- Console.WriteLine("No barcodes detected.");
- }
- else
+ // Perform barcode detection.
+ foreach (var result in reader.ReadBarCodes())
{
- // Iterate through each detected barcode and display its type and text.
- foreach (var result in results)
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- }
+ // Output detected barcode type and value.
+ Console.WriteLine($"Type: {result.CodeTypeName}, Value: {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 fa4a75e..b0a42e9 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,56 +1,51 @@
+// 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.
+// Prompt: Export the recognition state to an XML file after processing a single barcode image.
+// Tags: barcode, recognition, xml, export, aspose.barcode, c#
+
using System;
using System.IO;
using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Demonstrates barcode generation, recognition, and exporting the recognition state to XML.
+/// Sample program that reads a barcode image, prints detection results,
+/// and saves the complete recognition state to an XML file.
///
class Program
{
///
- /// Entry point. Handles barcode generation (if needed), reads the barcode, prints details,
- /// and exports the full recognition state to an XML file.
+ /// Entry point of the application.
///
static void Main()
{
- // Define file paths for the barcode image and the exported XML.
- string imagePath = "barcode.png";
- string xmlPath = "recognition_state.xml";
+ // Path to the barcode image to be processed.
+ const string imagePath = "barcode.png";
+
+ // Path where the recognition state XML will be saved.
+ const string xmlOutputPath = "recognition_state.xml";
- // If the barcode image does not exist, generate a sample Code128 barcode.
+ // Verify that the image file exists before attempting to read it.
if (!File.Exists(imagePath))
{
- // Create a BarcodeGenerator with the desired encoding and data.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
- {
- // Save the generated barcode image to the specified path.
- generator.Save(imagePath);
- Console.WriteLine($"Sample barcode image created at '{imagePath}'.");
- }
+ Console.WriteLine($"Error: Image file \"{imagePath}\" not found.");
+ return;
}
- // Initialize a BarCodeReader to detect all supported barcode types in the image.
+ // Create a BarCodeReader for the image, detecting all supported symbologies.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Perform the recognition and retrieve all detected barcodes.
- var results = reader.ReadBarCodes();
-
- // Iterate through each recognition result and output its details.
- foreach (var result in results)
+ // Iterate through all detected barcodes.
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Type: {result.CodeTypeName}");
- Console.WriteLine($"CodeText: {result.CodeText}");
- Console.WriteLine($"Confidence: {result.Confidence}");
- Console.WriteLine($"ReadingQuality: {result.ReadingQuality}");
- Console.WriteLine();
+ // Output basic information about each detected barcode.
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
}
- // Export the complete recognition state (including all detected barcodes) to an XML file.
- reader.ExportToXml(xmlPath);
- Console.WriteLine($"Recognition state exported to '{xmlPath}'.");
+ // Export the full recognition state (detected barcodes, settings, metadata) to an XML file.
+ reader.ExportToXml(xmlOutputPath);
+ Console.WriteLine($"Recognition state exported to \"{xmlOutputPath}\".");
}
}
}
\ 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 138b012..3c492b9 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,84 +1,68 @@
+// Title: Barcode Generation, Detection, and Checkpoint Export
+// Description: Generates a Code128 barcode image, reads it, and exports a checkpoint XML after each detection.
+// Prompt: Implement checkpoint functionality by exporting the state to XML after each successful barcode detection.
+// Tags: barcode, code128, generation, detection, xml, checkpoint, aspose.barcode
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating barcodes, saving them as images,
-/// recognizing them, and exporting recognition checkpoints using Aspose.BarCode.
+/// Demonstrates creating a barcode, reading it, and saving a checkpoint XML after each detection.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates sample barcodes, saves them, reads them back,
- /// and writes XML checkpoints for each detection.
+ /// Entry point of the application. Generates a barcode image, reads it, and exports checkpoints.
///
static void Main()
{
- // Define the output directory for generated images and checkpoint files.
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
+ // Define the file path for the generated barcode image
+ string imagePath = "barcode.png";
- // Ensure the output directory exists.
- if (!Directory.Exists(outputDir))
+ // ------------------------------------------------------------
+ // Generate a Code128 barcode and save it to the specified file
+ // ------------------------------------------------------------
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- Directory.CreateDirectory(outputDir);
+ generator.Save(imagePath);
}
- // Define a collection of sample barcodes to generate.
- // Each tuple contains the barcode symbology type and the text to encode.
- var samples = new (BaseEncodeType type, string text)[]
+ // Verify that the barcode image file was successfully created
+ if (!File.Exists(imagePath))
{
- (EncodeTypes.Code128, "ABC123456"),
- (EncodeTypes.QR, "https://example.com"),
- (EncodeTypes.EAN13, "5901234123457")
- };
+ Console.WriteLine($"Error: Barcode image not found at '{imagePath}'.");
+ return;
+ }
- // Iterate over each sample, generate the barcode image, and then recognize it.
- for (int i = 0; i < samples.Length; i++)
+ // ------------------------------------------------------------
+ // Initialize a barcode reader that supports all barcode types
+ // ------------------------------------------------------------
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Deconstruct the tuple into symbology and text.
- var (symbology, codeText) = samples[i];
-
- // Build the file path for the barcode image.
- string imagePath = Path.Combine(outputDir, $"barcode_{i}.png");
+ int index = 0; // Counter for detected barcodes
- // -------------------------
- // Generate barcode image
- // -------------------------
- using (BarcodeGenerator generator = new BarcodeGenerator(symbology, codeText))
+ // Iterate through each detected barcode in the image
+ foreach (var result in reader.ReadBarCodes())
{
- // Save the generated barcode as a PNG file.
- generator.Save(imagePath, BarCodeImageFormat.Png);
- }
+ // Output detection details to the console
+ Console.WriteLine($"Detected [{index}]: Type = {result.CodeTypeName}, Text = {result.CodeText}");
- // -------------------------
- // Recognize barcode and export checkpoint after each detection
- // -------------------------
- using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
- {
- // Read all barcodes detected in the image.
- BarCodeResult[] results = reader.ReadBarCodes();
+ // 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}'.");
- // Process each detection result.
- for (int j = 0; j < results.Length; j++)
- {
- BarCodeResult result = results[j];
-
- // Output detection details to the console.
- Console.WriteLine($"Image {i}, Detection {j}: Type={result.CodeTypeName}, Text={result.CodeText}");
+ index++;
+ }
- // Export the reader's internal state to an XML file as a checkpoint.
- string checkpointPath = Path.Combine(outputDir, $"checkpoint_{i}_{j}.xml");
- reader.ExportToXml(checkpointPath);
- }
+ // If no barcodes were found, inform the user
+ if (index == 0)
+ {
+ Console.WriteLine("No barcodes were detected in the image.");
}
}
-
- // Indicate that processing has finished.
- 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 0aad9ee..1c5b9b4 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,74 +1,85 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates usage of Aspose.BarCode's BarCodeReader and BarcodeGenerator,
-/// including error handling when exporting XML without initializing the reader,
-/// and proper export after setting a barcode image.
+/// Demonstrates error handling for ExportToXml when the BarCodeReader is not initialized with an image.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Attempt to export XML without initializing the reader with an image.
- // This should raise an exception because the reader has no source image.
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader())
+ // Define the path for the sample barcode image
+ string imagePath = "sample.png";
+
+ // Generate a simple Code128 barcode and save it to a file
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ {
+ generator.Save(imagePath);
+ }
+
+ // Verify that the image file was created successfully
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine("Failed to create the sample barcode image.");
+ return;
+ }
+
+ // 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
{
- using (var xmlStream = new MemoryStream())
- {
- // ExportToXml is expected to fail here.
- reader.ExportToXml(xmlStream);
- Console.WriteLine("Exported XML without image (unexpected).");
- }
+ reader.ExportToXml("reader_without_image.xml");
+ Console.WriteLine("Export succeeded unexpectedly (no image was set).");
}
catch (Exception ex)
{
- // Expected error handling: display the exception message.
- Console.WriteLine($"Expected error when exporting without image: {ex.Message}");
+ // Expected exception handling
+ Console.WriteLine("Caught expected exception when exporting without image:");
+ Console.WriteLine(ex.Message);
}
- }
-
- // ------------------------------------------------------------
- // 2. Proper usage: generate a barcode, load it into the reader,
- // then export the reader's data to XML.
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
- {
- using (var imageStream = new MemoryStream())
- {
- // Save the generated barcode image to a memory stream in PNG format.
- generator.Save(imageStream, BarCodeImageFormat.Png);
- // Reset stream position to the beginning for reading.
- imageStream.Position = 0;
- using (var reader = new BarCodeReader())
- {
- // Initialize the reader with the generated barcode image.
- reader.SetBarCodeImage(imageStream);
+ // Initialize the reader with the generated barcode image
+ reader.SetBarCodeImage(imagePath);
- using (var xmlStream = new MemoryStream())
- {
- // Export the reader's settings and detected barcodes to XML.
- reader.ExportToXml(xmlStream);
- // Reset stream position to read the XML content.
- xmlStream.Position = 0;
- string xml = new StreamReader(xmlStream).ReadToEnd();
-
- // Output the exported XML to the console.
- Console.WriteLine("Exported XML after initializing reader:");
- Console.WriteLine(xml);
- }
- }
+ // 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)
+ {
+ // Unexpected exception handling
+ Console.WriteLine("Unexpected exception after initializing the reader:");
+ Console.WriteLine(ex.Message);
}
}
+
+ // Clean up generated files (optional)
+ try
+ {
+ 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);
+ }
+ catch
+ {
+ // Ignore any cleanup errors
+ }
}
}
\ 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 eb80708..d955e21 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,3 +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.
+// 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
+
using System;
using System.IO;
using System.Security.Cryptography;
@@ -5,64 +10,64 @@
using Aspose.BarCode.Generation;
///
-/// Demonstrates exporting a barcode generator state to XML and encrypting the XML file using AES.
+/// 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.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Code128 barcode, exports its state to an XML file, and encrypts that file.
+ /// Entry point of the application. Performs barcode generation, XML export,
+ /// AES encryption of the exported file, and cleanup of the plain XML.
///
static void Main()
{
- // Define file paths for the XML state and the encrypted output
+ // Define file paths for the intermediate XML state and the final encrypted output
string xmlPath = "barcode_state.xml";
string encryptedPath = "barcode_state.enc";
- // Create a barcode generator for Code128 with sample data
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Create a barcode generator for Code128 with sample data and export its state to XML
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Export the generator's state to an XML file
+ // Export the barcode properties to an XML file; ExportToXml returns true on success
bool exported = generator.ExportToXml(xmlPath);
- Console.WriteLine(exported
- ? $"Exported XML to '{xmlPath}'."
- : $"Failed to export XML to '{xmlPath}'.");
- }
-
- // Ensure the XML file was created before attempting encryption
- if (!File.Exists(xmlPath))
- {
- Console.WriteLine("XML file not found. Encryption aborted.");
- return;
+ if (!exported)
+ {
+ Console.WriteLine("Failed to export barcode state to XML.");
+ return;
+ }
}
- // Prepare a deterministic 256‑bit key and 128‑bit IV for demonstration purposes
- byte[] key = new byte[32]; // 256-bit key
- byte[] iv = new byte[16]; // 128-bit IV
+ // Prepare static AES key and IV for demonstration (do NOT use static 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);
- // Perform AES encryption of the XML file
- using (var aes = Aes.Create())
+ // Encrypt the XML file using AES and write the ciphertext to a new file
+ using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
- aes.Mode = CipherMode.CBC;
- aes.Padding = PaddingMode.PKCS7;
- // Open the source XML file for reading
- using (var inputFile = new FileStream(xmlPath, FileMode.Open, FileAccess.Read))
- // Create the destination file for the encrypted data
- using (var outputFile = new FileStream(encryptedPath, FileMode.Create, FileAccess.Write))
- // Set up a CryptoStream to handle encryption while writing
- using (var cryptoStream = new CryptoStream(outputFile, aes.CreateEncryptor(), CryptoStreamMode.Write))
+ 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))
{
- // Copy the entire XML content into the CryptoStream, which encrypts it on the fly
+ // Copy the plaintext XML data into the CryptoStream, which encrypts it on the fly
inputFile.CopyTo(cryptoStream);
}
}
- // Inform the user that encryption succeeded
- Console.WriteLine($"Encrypted XML saved to '{encryptedPath}'.");
+ // Attempt to delete the original plain XML file, leaving only the encrypted version
+ try
+ {
+ File.Delete(xmlPath);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Could not delete original XML file: {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 552d83f..1b0da7d 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,141 +1,82 @@
+// 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.
+// 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
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
-using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.Generation;
///
-/// Demonstrates merging barcode information from multiple XML state files
-/// and writing a summary text file.
+/// Program that merges barcode detection results from multiple Aspose.BarCode state XML files into a single summary XML document.
///
class Program
{
///
- /// Simple model to hold barcode information extracted from XML state files.
- ///
- class BarcodeInfo
- {
- public string SourceFile { get; set; }
- public string Type { get; set; }
- public string CodeText { get; set; }
- }
-
- ///
- /// Entry point of the application. Creates sample XML files, merges their
- /// barcode data, and writes a summary file.
+ /// Entry point. Reads each XML state file, extracts barcode type and text, and writes a consolidated summary.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Prepare a folder with sample XML state files (in a real scenario
- // these would already exist)
- // --------------------------------------------------------------------
- string stateFolder = Path.Combine(Directory.GetCurrentDirectory(), "StateFiles");
- if (!Directory.Exists(stateFolder))
- {
- Directory.CreateDirectory(stateFolder);
- }
+ // Define the paths to the XML state files (replace with actual file locations as needed)
+ string[] xmlFiles = { "state1.xml", "state2.xml", "state3.xml" };
- // --------------------------------------------------------------------
- // Create a few sample XML files for demonstration purposes
- // --------------------------------------------------------------------
- CreateSampleStateFile(Path.Combine(stateFolder, "state1.xml"), new[]
- {
- new BarcodeInfo { Type = "Code128", CodeText = "ABC123" },
- new BarcodeInfo { Type = "QR", CodeText = "https://example.com" }
- });
+ // List that will hold the combined barcode type and text pairs from all files
+ var mergedBarcodes = new List<(string Type, string CodeText)>();
- CreateSampleStateFile(Path.Combine(stateFolder, "state2.xml"), new[]
+ // Iterate over each XML file to import its BarCodeReader state
+ foreach (string xmlPath in xmlFiles)
{
- new BarcodeInfo { Type = "EAN13", CodeText = "5901234123457" }
- });
-
- CreateSampleStateFile(Path.Combine(stateFolder, "state3.xml"), new[]
- {
- new BarcodeInfo { Type = "Code39", CodeText = "CODE39" },
- new BarcodeInfo { Type = "DataMatrix", CodeText = "DM12345" }
- });
-
- // --------------------------------------------------------------------
- // Merge all XML state files into a single collection
- // --------------------------------------------------------------------
- List mergedBarcodes = new List();
- foreach (string xmlPath in Directory.GetFiles(stateFolder, "*.xml"))
- {
- // Verify the file exists before attempting to load it
+ // Verify that the file exists before attempting to import
if (!File.Exists(xmlPath))
{
Console.WriteLine($"Warning: File not found - {xmlPath}");
continue;
}
- XDocument doc;
- try
+ // Import the BarCodeReader state from the XML file
+ using (BarCodeReader reader = BarCodeReader.ImportFromXml(xmlPath))
{
- // Load the XML document; handle any parsing errors gracefully
- doc = XDocument.Load(xmlPath);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Failed to load XML file '{xmlPath}': {ex.Message}");
- continue;
- }
-
- // Iterate over each element and extract its attributes
- foreach (XElement barcodeElem in doc.Root?.Elements("Barcode") ?? new List())
- {
- string type = (string)barcodeElem.Attribute("Type") ?? "Unknown";
- string codeText = (string)barcodeElem.Attribute("CodeText") ?? string.Empty;
-
- mergedBarcodes.Add(new BarcodeInfo
+ // If the import fails, report and skip to the next file
+ if (reader == null)
{
- SourceFile = Path.GetFileName(xmlPath),
- Type = type,
- CodeText = codeText
- });
- }
- }
+ Console.WriteLine($"Warning: Failed to import {xmlPath}");
+ continue;
+ }
- // --------------------------------------------------------------------
- // Output a summary of merged barcode entries to a text file
- // --------------------------------------------------------------------
- string summaryPath = Path.Combine(Directory.GetCurrentDirectory(), "MergedBarcodes.txt");
- using (var writer = new StreamWriter(summaryPath, false))
- {
- writer.WriteLine("SourceFile\tBarcodeType\tCodeText");
- foreach (var info in mergedBarcodes)
- {
- writer.WriteLine($"{info.SourceFile}\t{info.Type}\t{info.CodeText}");
+ // Read barcodes from the imported state; this populates FoundBarCodes if needed
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // 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));
+ }
+ }
}
}
- Console.WriteLine($"Merged {mergedBarcodes.Count} barcode entries into '{summaryPath}'.");
- }
+ // Build a summary XML document containing all collected barcode information
+ var summaryDoc = 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)))))));
- ///
- /// Helper method to create a simple XML state file with the given barcode entries.
- ///
- /// Full path where the XML file will be saved.
- /// Array of barcode information to include in the file.
- static void CreateSampleStateFile(string filePath, BarcodeInfo[] barcodes)
- {
- // Build the root element
- var root = new XElement("Barcodes");
- foreach (var b in barcodes)
- {
- // Create a element with Type and CodeText attributes
- var elem = new XElement("Barcode");
- elem.SetAttributeValue("Type", b.Type);
- elem.SetAttributeValue("CodeText", b.CodeText);
- root.Add(elem);
- }
+ // Define the output path for the merged summary XML
+ string outputPath = "merged_summary.xml";
- // Save the constructed XML document to the specified file
- var doc = new XDocument(root);
- using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
- {
- doc.Save(stream);
- }
+ // Save the summary document to disk
+ summaryDoc.Save(outputPath);
+ Console.WriteLine($"Merged summary saved to {outputPath}");
}
}
\ 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 36893da..a33d50f 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,82 +1,94 @@
+// Title: Aggregate barcode results from multiple XML states
+// Description: Demonstrates importing barcode generator XML, generating images, recognizing barcodes, and aggregating results for reporting.
+// 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
+
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing.Imaging;
+using Aspose.Drawing;
///
-/// Demonstrates importing barcode generator settings from XML files,
-/// generating barcode images, reading them, and aggregating the results.
+/// Sample program that creates barcode generators, exports them to XML,
+/// imports the XML back, reads the generated barcodes, and aggregates the results.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the application. Prepares sample XML states, aggregates barcode results,
+ /// and writes a simple report to the console.
///
static void Main()
{
- // Define sample XML state files (replace with real paths as needed)
- var xmlFiles = new List
+ // 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"))
{
- "state1.xml",
- "state2.xml",
- "state3.xml"
- };
+ // 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);
+ }
- // Process each XML file and collect all detected barcode results
- var aggregatedResults = AggregateBarcodeResults(xmlFiles);
+ // ----- Second barcode: QR with text "Hello World" -----
+ using (var gen2 = new BarcodeGenerator(EncodeTypes.QR, "Hello World"))
+ {
+ // 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);
+ }
- // Output the total number of barcodes detected
- Console.WriteLine($"Total barcodes detected: {aggregatedResults.Count}");
+ // Aggregate barcode results from the imported XML states.
+ List aggregatedResults = AggregateBarcodeResults(xmlStreams);
- // List each detected barcode's type and text
+ // Report the aggregated results to the console.
+ Console.WriteLine("Aggregated Barcode Results:");
foreach (var result in aggregatedResults)
{
- Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ Console.WriteLine($"Type: {result.CodeTypeName}, CodeText: {result.CodeText}");
+ }
+
+ // Clean up streams to release resources.
+ foreach (var stream in xmlStreams)
+ {
+ stream.Dispose();
}
}
///
- /// Imports barcode generators from the given XML files, generates images,
- /// reads barcodes from those images and aggregates all results.
+ /// Imports barcode generators from XML streams, generates barcode images,
+ /// recognizes the barcodes, and aggregates all objects into a single collection.
///
- /// Paths to XML files containing barcode generator settings.
- /// List of all detected objects.
- static List AggregateBarcodeResults(IEnumerable xmlPaths)
+ /// Collection of streams containing exported barcode generator XML.
+ /// List of objects from all imported states.
+ static List AggregateBarcodeResults(IEnumerable xmlStreams)
{
- // Collection to hold all barcode results from all files
var allResults = new List();
- // Iterate over each provided XML path
- foreach (var path in xmlPaths)
+ // Process each XML stream individually.
+ foreach (var xmlStream in xmlStreams)
{
- // Verify the XML file exists before attempting to import
- if (!File.Exists(path))
- {
- Console.WriteLine($"Warning: XML file not found – skipping '{path}'.");
- continue;
- }
-
- // Import generator settings from the XML file
- using (var generator = BarcodeGenerator.ImportFromXml(path))
+ // Import the BarcodeGenerator from its XML representation.
+ using (var generator = BarcodeGenerator.ImportFromXml(xmlStream))
{
- // Create a memory stream to hold the generated barcode image
- using (var imageStream = new MemoryStream())
+ // Generate the barcode image in memory.
+ using (var image = generator.GenerateBarCodeImage())
{
- // Save the barcode image as PNG into the memory stream
- generator.Save(imageStream, BarCodeImageFormat.Png);
- // Reset stream position to the beginning for reading
- imageStream.Position = 0;
-
- // Initialize a barcode reader to decode all supported types
- using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
+ // Recognize the barcode(s) from the generated image.
+ using (var reader = new BarCodeReader(image, DecodeType.AllSupportedTypes))
{
- // Read all barcodes present in the image
- var results = reader.ReadBarCodes();
+ // Read all barcodes found in the image.
+ BarCodeResult[] results = reader.ReadBarCodes();
- // If any barcodes were detected, add them to the aggregate list
+ // Add the results to the aggregated collection, if any were found.
if (results != null)
{
allResults.AddRange(results);
@@ -86,7 +98,6 @@ static List AggregateBarcodeResults(IEnumerable xmlPaths)
}
}
- // Return the complete list of detected barcode results
return allResults;
}
}
\ 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 3bea1e6..9b7fd8c 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,119 +1,95 @@
+// 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.
+// 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
+
using System;
using System.Collections.Generic;
using System.IO;
-using System.Xml.Serialization;
+using System.Linq;
+using System.Xml.Linq;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
-
-///
-/// Represents a scanned barcode result with its text, type, and region coordinates.
-///
-public class ScanResult
-{
- public string CodeText { get; set; }
- public string CodeTypeName { get; set; }
- public float RegionX { get; set; }
- public float RegionY { get; set; }
- public float RegionWidth { get; set; }
- public float RegionHeight { get; set; }
-}
///
-/// Provides methods to persist and retrieve scanning results to/from an XML file.
+/// Example program that generates barcodes, reads them back, and persists processing state to allow restart after a failure.
///
-public static class StatePersistence
+class Program
{
///
- /// Serializes a list of objects to the specified file path.
+ /// Entry point of the application. Executes the barcode processing loop and manages state persistence.
///
- /// The file path where the XML will be saved.
- /// The list of scan results to serialize.
- public static void Save(string filePath, List results)
+ static void Main()
{
- var serializer = new XmlSerializer(typeof(List));
- using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
+ const string stateFile = "state.xml";
+
+ // Load previously processed indices from the state file (if it exists).
+ var processed = new HashSet();
+ if (File.Exists(stateFile))
{
- serializer.Serialize(stream, results);
+ 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())
+ {
+ if (int.TryParse(elem.Value, out int idx))
+ processed.Add(idx);
+ }
+ }
+ catch
+ {
+ // If the state file is corrupted, discard its contents and start fresh.
+ processed.Clear();
+ }
}
- }
- ///
- /// Deserializes a list of objects from the specified file path.
- ///
- /// The file path of the XML to read.
- /// A list of scan results; empty if the file does not exist.
- public static List Load(string filePath)
- {
- if (!File.Exists(filePath))
+ // Sample list of barcode texts to be generated and processed.
+ var codes = new List
{
- Console.WriteLine($"State file not found: {filePath}");
- return new List();
- }
+ "ABC123",
+ "XYZ789",
+ "123456",
+ "HELLO",
+ "WORLD"
+ };
- var serializer = new XmlSerializer(typeof(List));
- using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
+ // Iterate over each barcode text, skipping those already processed.
+ for (int i = 0; i < codes.Count; i++)
{
- return (List)serializer.Deserialize(stream);
- }
- }
-}
+ if (processed.Contains(i))
+ continue; // Skip index already handled in a previous run.
-///
-/// Demonstrates barcode generation, scanning, state persistence, and restoration.
-///
-class Program
-{
- ///
- /// Entry point of the application. Generates a barcode, scans it, saves state, clears memory, and restores state.
- ///
- static void Main()
- {
- const string imagePath = "barcode.png";
- const string statePath = "state.xml";
+ string imagePath = $"barcode_{i}.png";
- // Step 1: Generate a sample barcode image.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
- {
- generator.Save(imagePath);
- }
+ // Generate a barcode image for the current text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codes[i]))
+ {
+ generator.Save(imagePath);
+ }
- // Step 2: Scan the barcode and collect results.
- var scannedResults = new List();
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
- {
- foreach (var result in reader.ReadBarCodes())
+ // Read the generated barcode image and output its details.
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- var region = result.Region.Rectangle;
- scannedResults.Add(new ScanResult
+ foreach (var result in reader.ReadBarCodes())
{
- CodeText = result.CodeText,
- CodeTypeName = result.CodeTypeName,
- RegionX = (float)region.X,
- RegionY = (float)region.Y,
- RegionWidth = (float)region.Width,
- RegionHeight = (float)region.Height
- });
- Console.WriteLine($"Scanned: {result.CodeTypeName} - {result.CodeText}");
+ Console.WriteLine($"Index {i}: Type={result.CodeTypeName}, Text={result.CodeText}");
+ }
}
- }
-
- // Step 3: Persist the scanning state to XML.
- StatePersistence.Save(statePath, scannedResults);
- Console.WriteLine($"State saved to {statePath}");
- // Simulate a crash by clearing the in‑memory list.
- scannedResults.Clear();
-
- // Step 4: Restore the state from XML after "restart".
- var restoredResults = StatePersistence.Load(statePath);
- Console.WriteLine($"State restored from {statePath}");
-
- // Step 5: Display restored results.
- foreach (var res in restoredResults)
- {
- Console.WriteLine($"Restored: {res.CodeTypeName} - {res.CodeText} (Region: {res.RegionX},{res.RegionY},{res.RegionWidth},{res.RegionHeight})");
+ // 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))
+ )
+ )
+ );
+ stateDoc.Save(stateFile);
}
+
+ // All barcode items have been processed successfully.
}
}
\ 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 dd83921..72dcf0f 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,108 +1,131 @@
+// 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.
+// 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
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating two different barcodes, combining them into a single image,
-/// reading the combined image with custom reader options, and exporting those options to XML.
+/// Example program showing how to generate barcodes, combine them, read with custom options,
+/// and serialize/deserialize reader settings to XML.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point. Generates sample barcodes, combines them, reads using custom options,
+ /// exports/imports settings to XML, and displays results.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Define file paths for the combined image and the exported XML file.
- // --------------------------------------------------------------------
- string combinedImagePath = Path.Combine(Directory.GetCurrentDirectory(), "combined.png");
- string readerOptionsXmlPath = Path.Combine(Directory.GetCurrentDirectory(), "readerOptions.xml");
-
- // --------------------------------------------------------------------
- // Generate the first barcode (Code128) and store it in a bitmap.
- // --------------------------------------------------------------------
- Bitmap bmpCode128;
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
+ // Prepare temporary paths for output files
+ string outputDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo");
+ 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"))
{
- using (var ms = new MemoryStream())
- {
- // Save the barcode image to a memory stream in PNG format.
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
- bmpCode128 = new Bitmap(ms);
- }
+ generator1.Save(barcode1Stream, BarCodeImageFormat.Png);
+ }
+ using (var generator2 = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ generator2.Save(barcode2Stream, BarCodeImageFormat.Png);
}
- // --------------------------------------------------------------------
- // Generate the second barcode (QR) and store it in a bitmap.
- // --------------------------------------------------------------------
- Bitmap bmpQr;
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ // 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))
{
- using (var ms = new MemoryStream())
+ int combinedWidth = bmp1.Width + bmp2.Width;
+ int combinedHeight = Math.Max(bmp1.Height, bmp2.Height);
+
+ using (var combinedBmp = new Bitmap(combinedWidth, combinedHeight))
{
- // Save the QR code image to a memory stream in PNG format.
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
- bmpQr = new Bitmap(ms);
+ 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);
}
}
- // --------------------------------------------------------------------
- // Combine the two barcode bitmaps side by side into a single image.
- // --------------------------------------------------------------------
- int combinedWidth = bmpCode128.Width + bmpQr.Width;
- int combinedHeight = Math.Max(bmpCode128.Height, bmpQr.Height);
- using (var combinedBitmap = new Bitmap(combinedWidth, combinedHeight))
+ // Verify that the combined image was created successfully
+ if (!File.Exists(combinedImagePath))
+ {
+ Console.WriteLine("Failed to create combined barcode image.");
+ return;
+ }
+
+ // ---------- Read multiple barcodes with custom options ----------
+ using (var reader = new BarCodeReader())
{
- using (var graphics = Graphics.FromImage(combinedBitmap))
+ // 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
+ reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast;
+
+ // Assign the combined image as the source for reading
+ reader.SetBarCodeImage(combinedImagePath);
+
+ // Perform the reading operation and output results
+ Console.WriteLine("Reading barcodes with custom options:");
+ foreach (var result in reader.ReadBarCodes())
{
- // Fill background with white.
- graphics.Clear(Color.White);
- // Draw the first barcode on the left.
- graphics.DrawImage(bmpCode128, 0, 0, bmpCode128.Width, bmpCode128.Height);
- // Draw the second barcode on the right.
- graphics.DrawImage(bmpQr, bmpCode128.Width, 0, bmpQr.Width, bmpQr.Height);
+ Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
}
- // Save the combined image to disk as PNG.
- combinedBitmap.Save(combinedImagePath, ImageFormat.Png);
+ // Export the current reader settings to an XML file
+ reader.ExportToXml(xmlSettingsPath);
+ }
+
+ // Verify that the XML settings file was created
+ if (!File.Exists(xmlSettingsPath))
+ {
+ Console.WriteLine("Failed to export reader settings to XML.");
+ return;
}
- // --------------------------------------------------------------------
- // Release the temporary bitmap resources.
- // --------------------------------------------------------------------
- bmpCode128.Dispose();
- bmpQr.Dispose();
+ // ---------- Import settings from XML and read again ----------
+ var importedReader = BarCodeReader.ImportFromXml(xmlSettingsPath);
+ if (importedReader == null)
+ {
+ Console.WriteLine("Failed to import reader settings from XML.");
+ return;
+ }
- // --------------------------------------------------------------------
- // Create a BarCodeReader for the combined image with all supported types.
- // --------------------------------------------------------------------
- using (var reader = new BarCodeReader(combinedImagePath, DecodeType.AllSupportedTypes))
+ using (importedReader)
{
- // Configure custom reader options for higher quality and specific settings.
- reader.QualitySettings = QualitySettings.HighQuality; // Use high‑quality preset.
- reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; // Fast deconvolution mode.
- reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension;
- reader.QualitySettings.MinimalXDimension = 2f; // Minimal X dimension in pixels.
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; // Enforce checksum validation.
-
- // Read all barcodes present in the combined image.
- var results = reader.ReadBarCodes();
- Console.WriteLine($"Detected {results.Length} barcode(s):");
- foreach (var result in results)
+ // 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}");
}
-
- // Export the configured reader options to an XML file.
- reader.ExportToXml(readerOptionsXmlPath);
- Console.WriteLine($"Reader options exported to: {readerOptionsXmlPath}");
}
+
+ // Cleanup temporary files (optional)
+ // File.Delete(combinedImagePath);
+ // File.Delete(xmlSettingsPath);
+ // Directory.Delete(outputDir, true);
}
}
\ 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 b57c57c..6202125 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,65 +1,61 @@
+// 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.
+// Prompt: Import a saved XML state file into a new reader instance before setting the image.
+// Tags: barcode, import, xml, reader, decode, aspose, barcoderecognition
+
using System;
using System.IO;
-using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates creating a barcode image, exporting its settings to XML,
-/// and then importing those settings to read the barcode from the image.
+/// Example program that imports a saved BarCodeReader state from XML and decodes a barcode image.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point. Loads XML state, configures the reader, and reads barcodes from an image.
///
static void Main()
{
- // Paths for the barcode image and the XML settings file.
- string xmlPath = "readerSettings.xml";
+ // Paths to the XML state file and the barcode image.
+ string xmlPath = "readerState.xml";
string imagePath = "barcode.png";
- // If either the barcode image or the XML settings file is missing,
- // generate a sample barcode and export its configuration.
- if (!File.Exists(imagePath) || !File.Exists(xmlPath))
+ // Verify that the XML file exists.
+ if (!File.Exists(xmlPath))
{
- // Create a barcode generator for Code128 with sample data.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
- {
- // Save the generated barcode image to the specified path.
- generator.Save(imagePath);
-
- // Export the generator's configuration to an XML file for later import.
- generator.ExportToXml(xmlPath);
- }
+ Console.WriteLine($"XML state file not found: {xmlPath}");
+ return;
}
- // Ensure the XML settings file exists before attempting to import it.
- if (!File.Exists(xmlPath))
+ // Verify that the image file exists.
+ if (!File.Exists(imagePath))
{
- Console.WriteLine($"XML settings file not found: {xmlPath}");
+ Console.WriteLine($"Barcode image file not found: {imagePath}");
return;
}
- // Import reader settings from the XML file.
- using (var reader = BarCodeReader.ImportFromXml(xmlPath))
+ // Create a new BarCodeReader instance.
+ using (var reader = new BarCodeReader())
{
- // Assign the barcode image to the reader.
- if (File.Exists(imagePath))
- {
- reader.SetBarCodeImage(imagePath);
- }
- else
- {
- Console.WriteLine($"Barcode image file not found: {imagePath}");
- return;
- }
+ // 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);
- // Iterate through all recognized barcodes and display their details.
+ // Perform recognition and output results.
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ Console.WriteLine($"Type: {result.CodeTypeName}");
+ Console.WriteLine($"Text: {result.CodeText}");
+ Console.WriteLine($"Confidence: {result.Confidence}");
+ Console.WriteLine($"Region: {result.Region.Rectangle}");
+ Console.WriteLine();
}
}
}
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 1c05187..e7474a9 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,60 +1,61 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a barcode, reading it, and exporting the reader's state to XML.
+/// Example program that generates a Code128 barcode, exports the reader state to XML,
+/// and then imports the state to verify that recognition still works.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Code128 barcode, reads it, and exports the reader configuration to an XML stream.
+ /// Entry point of the example. Performs barcode generation, state export, and import.
///
static void Main()
{
- // Create a memory stream to hold the generated barcode image.
- using (var barcodeStream = new MemoryStream())
+ // Create a simple Code128 barcode and generate its image.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Initialize the barcode generator with the desired symbology and data.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ using (var barcodeImage = generator.GenerateBarCodeImage())
{
- // Save the generated barcode as a PNG image into the memory stream.
- generator.Save(barcodeStream, BarCodeImageFormat.Png);
- }
-
- // Reset the stream position to the beginning so it can be read.
- barcodeStream.Position = 0;
+ // 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}");
+ }
- // Create a barcode reader that can decode all supported barcode types.
- using (var reader = new BarCodeReader(barcodeStream, DecodeType.AllSupportedTypes))
- {
- // Perform an initial read to verify that the barcode can be detected.
- var initialResults = reader.ReadBarCodes();
- Console.WriteLine($"Initial read: {initialResults.Length} barcode(s) detected.");
+ // Save the reader's state to a memory stream in XML format.
+ using (var xmlStream = new MemoryStream())
+ {
+ reader.ExportToXml(xmlStream);
+ Console.WriteLine($"Reader state exported to XML (size: {xmlStream.Length} bytes).");
- // Export the reader's current state (settings, quality, etc.) to an XML representation.
- using (var xmlStream = new MemoryStream())
- {
- reader.ExportToXml(xmlStream);
- Console.WriteLine($"Exported reader state to XML (size: {xmlStream.Length} bytes).");
+ // Reset the stream position before deserialization.
+ xmlStream.Position = 0;
- // Rewind the XML stream to the beginning for reading its contents.
- xmlStream.Position = 0;
+ // Deserialize the reader state from the XML stream.
+ using (var importedReader = BarCodeReader.ImportFromXml(xmlStream))
+ {
+ // The imported reader needs the image to perform recognition.
+ importedReader.SetBarCodeImage(barcodeImage);
- // Read the XML data as a string for display or further processing.
- using (var sr = new StreamReader(xmlStream, leaveOpen: true))
- {
- string xml = sr.ReadToEnd();
- Console.WriteLine("Reader state XML:");
- Console.WriteLine(xml);
+ // Verify that the imported reader works by reading the barcode again.
+ foreach (var importedResult in importedReader.ReadBarCodes())
+ {
+ Console.WriteLine($"Imported read: {importedResult.CodeText}");
+ }
+ }
}
-
- // At this point, xmlStream contains the serialized reader state.
- // It can be saved, transmitted, or later restored using BarCodeReader.ImportFromXml(xmlStream).
}
}
}
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 be5df7e..d3f1866 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,83 +1,89 @@
+// 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.
+// 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
+
using System;
using System.IO;
-using System.Linq;
using System.Xml.Linq;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode;
+using Aspose.Drawing;
///
-/// Demonstrates generating a barcode, reading it, and exporting recognition parameters and results to XML.
+/// Example program that creates a barcode, reads it, and serializes
+/// the recognition parameters and results into an XML document.
///
class Program
{
///
/// Entry point of the application.
- /// Generates a Code128 barcode, reads it, and writes recognition data to an XML file.
+ /// Generates a barcode image, reads it, and writes recognition data to XML.
///
static void Main()
{
- // Create a barcode generator for Code128 with the value "12345"
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
+ // Paths for the generated barcode image and the output XML
+ string imagePath = "barcode.png";
+ string xmlPath = "barcode_results.xml";
+
+ // ------------------------------------------------------------
+ // Generate a sample barcode image using Code128 symbology
+ // ------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Store the generated barcode image in a memory stream
- using (var imageStream = new MemoryStream())
- {
- // Save the barcode as a PNG image into the stream
- generator.Save(imageStream, BarCodeImageFormat.Png);
- // Reset stream position to the beginning for reading
- imageStream.Position = 0;
+ generator.Save(imagePath);
+ }
- // Initialize a barcode reader that can decode all supported symbologies
- using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
- {
- // Configure reader settings
- reader.Timeout = 2000; // 2‑second timeout
- reader.QualitySettings = QualitySettings.HighPerformance;
- reader.QualitySettings.AllowIncorrectBarcodes = true;
+ // Verify that the image was created successfully
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
+ return;
+ }
- // Export the current recognition parameters to an XML document
- XDocument parametersXml;
- using (var paramStream = new MemoryStream())
- {
- reader.ExportToXml(paramStream);
- paramStream.Position = 0;
- parametersXml = XDocument.Load(paramStream);
- }
+ // ------------------------------------------------------------
+ // Create a BarCodeReader to recognize the barcode from the image
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ {
+ // Set recognition parameters
+ reader.Timeout = 5000; // timeout in milliseconds
+ reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast;
- // Perform barcode recognition and obtain results
- var results = reader.ReadBarCodes();
+ // Perform recognition and obtain all detected barcodes
+ BarCodeResult[] results = reader.ReadBarCodes();
- // Build a combined XML document containing both parameters and recognition results
- var finalDoc = new XDocument(
- new XElement("RecognitionResult",
- // Include the exported parameters
- new XElement("Parameters", parametersXml.Root.Elements()),
- // Include each recognized barcode as a separate element
- new XElement("Barcodes",
- results.Select(r => new XElement("Barcode",
- new XElement("Type", r.CodeTypeName),
- new XElement("CodeText", r.CodeText),
- new XElement("Confidence", r.Confidence),
- new XElement("ReadingQuality", r.ReadingQuality),
- new XElement("Angle", r.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)
- )
- ))
+ // --------------------------------------------------------
+ // Build XML document containing both parameters and results
+ // --------------------------------------------------------
+ var doc = new XDocument(
+ new XElement("BarCodeRecognition",
+ new XElement("Parameters",
+ new XElement("Timeout", reader.Timeout),
+ new XElement("Deconvolution", reader.QualitySettings.Deconvolution.ToString())
+ ),
+ new XElement("Results",
+ from r 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("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)
)
)
- );
+ )
+ )
+ );
- // Save the final XML document to a file
- const string outputPath = "RecognitionResult.xml";
- finalDoc.Save(outputPath);
- Console.WriteLine($"Recognition data saved to '{outputPath}'.");
- }
- }
+ // Save the XML document to the specified file
+ doc.Save(xmlPath);
}
+
+ 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 5026d33..4d40615 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,68 +1,66 @@
+// 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.
+// 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
+
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a barcode, exporting reader settings to XML,
-/// importing those settings, and recognizing the barcode from a memory stream.
+/// Example program that generates a QR code, exports the reader state to XML,
+/// imports it back, and continues processing without reloading the image file.
///
class Program
{
///
- /// Entry point of the application.
+ /// 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.
///
static void Main()
{
- // 1. Generate a barcode and keep it in a memory stream.
- using (var imageStream = new MemoryStream())
+ // Generate a QR barcode and keep it in a memory stream
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello World"))
{
- // Create a barcode generator for Code128 with the text "Sample123".
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
- {
- // Save the generated barcode as a PNG image into the memory stream.
- generator.Save(imageStream, BarCodeImageFormat.Png);
- }
-
- // Reset the stream position to the beginning so it can be read.
- imageStream.Position = 0;
-
- // 2. Create a BarCodeReader, assign the image, and configure it.
- using (var reader = new BarCodeReader())
+ using (var imgStream = new MemoryStream())
{
- // Restrict decoding to Code128 type only.
- reader.SetBarCodeReadType(DecodeType.Code128);
- // Assign the barcode image stream to the reader.
- reader.SetBarCodeImage(imageStream);
+ // 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
- // Export current reader settings (including decode type) to XML in a memory stream.
- using (var xmlStream = new MemoryStream())
+ // Load the image from the memory stream into a bitmap
+ using (var bitmap = new Bitmap(imgStream))
{
- reader.ExportToXml(xmlStream);
- // Reset XML stream position for subsequent import.
- xmlStream.Position = 0;
-
- // 3. Import the reader state from the XML stream.
- var importedReader = BarCodeReader.ImportFromXml(xmlStream);
- if (importedReader == null)
+ // First recognition pass using a BarCodeReader
+ using (var reader = new BarCodeReader(bitmap, DecodeType.QR))
{
- Console.WriteLine("Failed to import reader state from XML.");
- return;
- }
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"First read: {result.CodeText}");
+ }
- // The image is not stored in the XML, so reassign it.
- // Reset the image stream position before reuse.
- imageStream.Position = 0;
- importedReader.SetBarCodeImage(imageStream);
+ // Export the reader's internal state to XML stored in a memory stream
+ using (var xmlStream = new MemoryStream())
+ {
+ reader.ExportToXml(xmlStream);
+ xmlStream.Position = 0; // Reset for reading the XML
- // 4. Perform barcode recognition using the imported reader.
- foreach (var result in importedReader.ReadBarCodes())
- {
- // Output detected barcode type and text.
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
+ // Import a new BarCodeReader instance from the XML state
+ var importedReader = BarCodeReader.ImportFromXml(xmlStream);
+ using (importedReader)
+ {
+ // Reassign the same bitmap (the image itself is not stored in the XML)
+ importedReader.SetBarCodeImage(bitmap);
+
+ // Continue processing without reloading the image file
+ foreach (var result in importedReader.ReadBarCodes())
+ {
+ Console.WriteLine($"After import read: {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 ff7cf67..82398b4 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,74 +1,125 @@
+// 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.
+// 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
+
using System;
using System.IO;
+using System.Security.Cryptography;
+using System.Text;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates how to import a barcode reader configuration from an XML file
-/// and use it to read barcodes from an image.
+/// Example program that decrypts an encrypted XML state file and restores barcode recognition settings using Aspose.BarCode.
///
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 of the application.
+ /// Entry point. Ensures an encrypted state file exists, decrypts it, imports settings, generates a matching barcode, and reads it.
///
static void Main()
{
- // Paths to the required input files.
- const string xmlPath = "encrypted_state.xml";
- const string barcodeImagePath = "barcode.png";
+ const string encryptedFilePath = "encrypted_state.bin";
- // Verify that the XML configuration file exists.
- if (!File.Exists(xmlPath))
+ // Ensure an encrypted state file exists. If not, create one from a sample barcode.
+ if (!File.Exists(encryptedFilePath))
{
- Console.WriteLine($"XML file not found: {xmlPath}");
- return;
+ CreateEncryptedStateFile(encryptedFilePath);
}
- // Verify that the barcode image file exists.
- if (!File.Exists(barcodeImagePath))
+ // Decrypt the XML state.
+ byte[] decryptedXml = DecryptFile(encryptedFilePath, AesKey, AesIv);
+
+ // Import the settings into a BarCodeReader instance.
+ using (var xmlStream = new MemoryStream(decryptedXml))
+ using (var reader = BarCodeReader.ImportFromXml(xmlStream))
{
- Console.WriteLine($"Barcode image file not found: {barcodeImagePath}");
- return;
- }
+ if (reader == null)
+ {
+ Console.WriteLine("Failed to import settings from XML.");
+ return;
+ }
- BarCodeReader reader;
+ // Generate a barcode image that matches the imported settings.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ using (var barcodeImage = generator.GenerateBarCodeImage())
+ {
+ // 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}");
+ }
+ }
+ }
+ }
- // Load the XML configuration into a memory stream and create the reader.
- using (FileStream fs = File.OpenRead(xmlPath))
- using (MemoryStream xmlStream = new MemoryStream())
+ // Creates an encrypted XML state file from a sample barcode's settings.
+ private static void CreateEncryptedStateFile(string filePath)
+ {
+ // Generate a sample barcode and export its settings to XML.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ using (var xmlMemory = new MemoryStream())
{
- // Copy file contents to the memory stream.
- fs.CopyTo(xmlStream);
- // Reset stream position to the beginning before importing.
- xmlStream.Position = 0;
- // Import the barcode reader configuration from the XML stream.
- reader = BarCodeReader.ImportFromXml(xmlStream);
+ generator.ExportToXml(xmlMemory);
+ byte[] xmlBytes = xmlMemory.ToArray();
+
+ // Encrypt the XML bytes.
+ byte[] encryptedBytes = Encrypt(xmlBytes, AesKey, AesIv);
+
+ // Write encrypted data to file.
+ File.WriteAllBytes(filePath, encryptedBytes);
}
+ }
- // Open the barcode image and associate it with the reader.
- using (Bitmap bitmap = new Bitmap(barcodeImagePath))
- using (reader)
+ // Encrypts plain data using AES-CBC with PKCS7 padding.
+ private static byte[] Encrypt(byte[] plainData, byte[] key, byte[] iv)
+ {
+ using (Aes aes = Aes.Create())
{
- // Set the image that the reader will process.
- reader.SetBarCodeImage(bitmap);
- // Perform barcode detection.
- var results = reader.ReadBarCodes();
+ aes.Key = key;
+ aes.IV = iv;
+ aes.Mode = CipherMode.CBC;
+ aes.Padding = PaddingMode.PKCS7;
- // Check if any barcodes were detected.
- if (results.Length == 0)
+ using (ICryptoTransform encryptor = aes.CreateEncryptor())
+ using (var ms = new MemoryStream())
+ using (var cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
- Console.WriteLine("No barcodes detected.");
+ cryptoStream.Write(plainData, 0, plainData.Length);
+ cryptoStream.FlushFinalBlock();
+ return ms.ToArray();
}
- else
+ }
+ }
+
+ // 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())
+ {
+ aes.Key = key;
+ aes.IV = iv;
+ aes.Mode = CipherMode.CBC;
+ aes.Padding = PaddingMode.PKCS7;
+
+ 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())
{
- // Output details for each detected barcode.
- foreach (var result in results)
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine($"Confidence: {result.Confidence}");
- }
+ cryptoStream.CopyTo(resultStream);
+ return resultStream.ToArray();
}
}
}
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 8ae0f48..2a6f671 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,75 +1,69 @@
+// 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.
+// 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
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates importing barcode settings from an XML configuration file and generating a barcode image.
+/// Example program that imports barcode settings from an XML file and handles
+/// errors related to missing barcode images required by the configuration.
///
class Program
{
///
- /// Entry point of the application. Handles XML configuration loading, barcode generation, and error fallback.
+ /// 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.
///
static void Main()
{
- // Paths for configuration and output
- string xmlPath = "barcodeConfig.xml";
- string outputPath = "output.png";
+ // Path to the XML configuration file.
+ const string xmlPath = "barcodeConfig.xml";
- // Verify that the XML configuration file exists; create a sample if missing
+ // Verify that the XML file exists before attempting import.
if (!File.Exists(xmlPath))
{
Console.WriteLine($"XML configuration file not found: {xmlPath}");
-
- // Sample XML content with basic barcode settings
- string sampleXml = @"
-
- Code128
- 123456
-";
-
- // Write the sample XML to disk
- File.WriteAllText(xmlPath, sampleXml);
- Console.WriteLine($"Sample XML created at {xmlPath}");
+ return;
}
try
{
- // Import barcode settings from the XML file
+ // Import barcode generator settings from the XML file.
using (var generator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // Save the generated barcode image to the specified path
- generator.Save(outputPath);
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // 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");
}
}
- catch (Exception ex)
+ catch (BarCodeException ex)
{
- // Specific handling when the XML expects an image set via SetBarCodeImage
- if (ex.Message.Contains("SetBarCodeImage", StringComparison.OrdinalIgnoreCase))
+ // 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))
{
- Console.WriteLine("Error: The XML configuration expects a barcode image but none was provided via SetBarCodeImage.");
-
- // Attempt to generate a simple fallback barcode
- try
- {
- using (var fallbackGen = new BarcodeGenerator(EncodeTypes.Code128, "Fallback123"))
- {
- fallbackGen.Save(outputPath);
- Console.WriteLine($"Fallback barcode saved to {outputPath}");
- }
- }
- catch (Exception fallbackEx)
- {
- Console.WriteLine($"Fallback generation failed: {fallbackEx.Message}");
- }
+ 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.");
}
else
{
- // General import failure
- Console.WriteLine($"ImportFromXml failed: {ex.Message}");
+ // General barcode-related errors.
+ Console.WriteLine($"BarCodeException: {ex.Message}");
}
}
+ catch (Exception ex)
+ {
+ // Fallback for any other unexpected errors.
+ Console.WriteLine($"Unexpected error: {ex.Message}");
+ }
}
}
\ 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 4c2dcc7..3cb9c3f 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,96 +1,53 @@
+// 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.
+// 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
+
using System;
using System.IO;
-using System.Xml.Linq;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates loading barcode symbology from an XML file,
-/// validating it against an expected value, and generating a barcode image.
+/// Example program that validates the barcode symbology defined in an imported XML state before generating the barcode image.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the program. Performs validation of the barcode symbology and generates an image if the validation passes.
///
static void Main()
{
- // Define the expected barcode symbology (Code128 in this case)
- BaseEncodeType expectedSymbology = EncodeTypes.Code128;
+ // Expected symbology name (e.g., "Code128")
+ const string expectedSymbology = "Code128";
- // Path to the optional XML state file that may contain the symbology name
- string xmlPath = "state.xml";
+ // Path to the XML file that contains the barcode state
+ const string xmlPath = "barcode_state.xml";
- // Load the XML document: either from file or use a sample XML string if the file is missing
- XDocument doc;
- if (File.Exists(xmlPath))
+ // Verify that the XML file exists before attempting import
+ if (!File.Exists(xmlPath))
{
- try
- {
- doc = XDocument.Load(xmlPath);
- }
- catch (Exception ex)
- {
- // Report any errors that occur while loading the XML file and exit
- Console.WriteLine($"Failed to load XML file: {ex.Message}");
- return;
- }
- }
- else
- {
- // Sample XML used when the state file does not exist
- string sampleXml = @"Code128";
- doc = XDocument.Parse(sampleXml);
- }
-
- // Retrieve the symbology name from the XML document
- string symbologyName = doc.Root?.Element("BarcodeSymbology")?.Value?.Trim();
- if (string.IsNullOrEmpty(symbologyName))
- {
- // If the element is missing or empty, inform the user and exit
- Console.WriteLine("Symbology element not found in XML.");
+ Console.WriteLine($"Error: XML file not found at '{xmlPath}'.");
return;
}
- // Use reflection to map the string name to the corresponding EncodeTypes field
- var fieldInfo = typeof(EncodeTypes).GetField(symbologyName);
- if (fieldInfo == null)
+ // Import the barcode generator from the XML state
+ using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // If the name does not correspond to a known symbology, report and exit
- Console.WriteLine($"Unknown symbology name in XML: {symbologyName}");
- return;
- }
+ // Retrieve the actual symbology type name from the imported generator
+ string actualSymbology = generator.BarcodeType.TypeName;
- // Cast the reflected value to BaseEncodeType
- BaseEncodeType xmlSymbology = (BaseEncodeType)fieldInfo.GetValue(null);
-
- // Compare the symbology from XML with the expected symbology
- if (xmlSymbology.TypeName != expectedSymbology.TypeName)
- {
- // Mismatch detected – report details and exit
- Console.WriteLine($"Symbology mismatch. Expected: {expectedSymbology.TypeName}, Found: {xmlSymbology.TypeName}");
- return;
- }
-
- // Symbology matches the expectation
- Console.WriteLine($"Symbology validated: {xmlSymbology.TypeName}");
-
- // Example barcode generation using the validated symbology
- string codeText = "1234567890"; // Data to encode in the barcode
- string outputPath = "validated_barcode.png"; // Destination file for the generated image
-
- // Create a BarcodeGenerator with the validated symbology and data
- using (var generator = new BarcodeGenerator(xmlSymbology, codeText))
- {
- // Optional: set image resolution (dots per inch)
- generator.Parameters.Resolution = 300f;
+ // Compare with the expected symbology (case‑insensitive)
+ if (!string.Equals(actualSymbology, expectedSymbology, StringComparison.OrdinalIgnoreCase))
+ {
+ Console.WriteLine($"Warning: Expected symbology '{expectedSymbology}' but found '{actualSymbology}'. Processing aborted.");
+ return;
+ }
- // Save the generated barcode image to the specified path
- generator.Save(outputPath);
+ // 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}'.");
}
-
- // Inform the user that the barcode has been successfully generated
- Console.WriteLine($"Barcode generated and saved to '{outputPath}'.");
}
}
\ 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 8c2f793..429274e 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,3 +1,8 @@
+// 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.
+// 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
+
using System;
using System.Collections.Generic;
using System.IO;
@@ -7,96 +12,98 @@
using Aspose.Drawing;
///
-/// Demonstrates generating a barcode, reading it, exporting/importing reader state,
-/// and serializing the results to JSON.
+/// 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.
///
class Program
{
- // Simple DTO for JSON serialization of barcode results
- class BarcodeResultInfo
- {
- public string CodeTypeName { get; set; }
- public string CodeText { get; set; }
- public int Confidence { get; set; }
- public double ReadingQuality { get; set; }
- public RegionInfo Region { get; set; }
- }
-
- // DTO representing the region of a detected barcode
- class RegionInfo
- {
- public float X { get; set; }
- public float Y { get; set; }
- public float Width { get; set; }
- public float Height { get; set; }
- public double Angle { get; set; }
- }
-
///
/// Entry point of the application.
- /// Generates a sample barcode if needed, reads it, exports/imports reader state,
- /// and prints the detection results as formatted JSON.
///
static void Main()
{
- const string imagePath = "barcode.png";
- const string xmlPath = "reader.xml";
+ // Define temporary file paths for the barcode image and the exported XML state
+ string imagePath = "barcode.png";
+ string xmlPath = "reader_state.xml";
- // Ensure a sample barcode image exists; generate one if missing
- if (!File.Exists(imagePath))
+ // ------------------------------------------------------------
+ // Generate a sample Code128 barcode and save it to a PNG file
+ // ------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello World"))
- {
- generator.Save(imagePath);
- }
+ generator.Save(imagePath);
}
- // Create a reader, assign the image, and export its state to XML
- using (var bitmap = new Bitmap(imagePath))
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ // ------------------------------------------------------------
+ // Create a BarCodeReader, export its internal state to XML, then dispose it
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Export the current reader configuration and state to an XML file
reader.ExportToXml(xmlPath);
}
- // Import the reader state from the previously saved XML
- using (var importedReader = BarCodeReader.ImportFromXml(xmlPath))
+ // ------------------------------------------------------------
+ // Import the previously saved reader state from the XML file
+ // ------------------------------------------------------------
+ BarCodeReader importedReader = BarCodeReader.ImportFromXml(xmlPath);
+ if (importedReader == null)
{
- // Reassign the image after import (required for further reading)
- importedReader.SetBarCodeImage(imagePath);
+ Console.WriteLine("Failed to import BarCodeReader from XML.");
+ return;
+ }
+
+ // Assign the image source to the imported reader (required after import)
+ importedReader.SetBarCodeImage(imagePath);
- // Perform barcode detection on the image
- var results = importedReader.ReadBarCodes();
+ // ------------------------------------------------------------
+ // Read barcodes from the image using the imported reader
+ // ------------------------------------------------------------
+ BarCodeResult[] results = importedReader.ReadBarCodes();
- // Convert detection results into a list of DTOs for serialization
- var resultList = new List();
- foreach (var result in results)
+ // ------------------------------------------------------------
+ // Convert each BarCodeResult into an anonymous object suitable for JSON serialization
+ // ------------------------------------------------------------
+ var jsonItems = new List