diff --git a/barcode-configuration-serialization/automate-generation-of-barcode-configuration-xml-for-each-product-sku-in-inventory-system.cs b/barcode-configuration-serialization/automate-generation-of-barcode-configuration-xml-for-each-product-sku-in-inventory-system.cs
index eab8719..587f7a6 100644
--- a/barcode-configuration-serialization/automate-generation-of-barcode-configuration-xml-for-each-product-sku-in-inventory-system.cs
+++ b/barcode-configuration-serialization/automate-generation-of-barcode-configuration-xml-for-each-product-sku-in-inventory-system.cs
@@ -1,73 +1,55 @@
-// Title: Generate Barcode Configuration XML for Inventory SKUs
-// Description: Creates Code128 barcode configuration XML files for each product SKU in an inventory, demonstrating how to automate barcode setup using Aspose.BarCode.
+// Title: Generate Code128 Barcodes and Export Configuration XML for Product SKUs
+// Description: This example creates Code128 barcode images for a list of product SKUs and saves the generation settings as XML files.
+// Category-Description: Demonstrates Aspose.BarCode generation and configuration export. It uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to produce barcode images and ExportToXml to persist settings. Ideal for inventory systems needing automated barcode creation and reusable configuration files. Suitable for developers working with barcode symbologies, image output, and XML configuration management.
// Prompt: Automate generation of barcode configuration XML for each product SKU in an inventory system.
-// Tags: barcode symbology, generation, xml, aspose.barcode, inventory
+// Tags: barcode symbology, generation, png, xml, aspose.barcode, code128
using System;
-using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates how to generate barcode configuration XML files for a set of product SKUs.
+/// Example program that generates Code128 barcode images for a set of product SKUs
+/// and exports the corresponding generation settings to XML configuration files.
///
class Program
{
///
- /// Entry point of the application. Iterates through a sample inventory and creates
- /// an XML configuration file for each SKU using the Aspose.BarCode library.
+ /// Entry point of the application. Iterates over sample SKUs, creates barcode images,
+ /// and writes XML configuration files for each.
///
static void Main()
{
- // Sample inventory: SKU -> barcode value (Code128)
- var inventory = new Dictionary
- {
- { "SKU001", "1234567890" },
- { "SKU002", "ABCDEF1234" },
- { "SKU003", "9876543210" },
- { "SKU004", "XYZ7890123" },
- { "SKU005", "0011223344" }
- };
+ // Define a sample collection of product SKUs to process
+ string[] skus = { "SKU001", "SKU002", "SKU003", "SKU004", "SKU005" };
- // Determine output folder for XML files
- string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "BarcodeConfigs");
- if (!Directory.Exists(outputFolder))
- {
- // Create the folder if it does not exist
- Directory.CreateDirectory(outputFolder);
- }
+ // Specify the output directory for both barcode images and XML configuration files
+ string outputDir = "Barcodes";
+ Directory.CreateDirectory(outputDir); // Ensure the directory exists
- // Process each inventory entry
- foreach (var kvp in inventory)
+ // Process each SKU individually
+ foreach (string sku in skus)
{
- string sku = kvp.Key;
- string codeText = kvp.Value;
+ // Build full file paths for the image and XML files
+ string imagePath = Path.Combine(outputDir, $"{sku}.png");
+ string xmlPath = Path.Combine(outputDir, $"{sku}.xml");
- // Validate SKU input
- if (string.IsNullOrWhiteSpace(sku))
+ // Initialize the barcode generator with Code128 symbology and the current SKU value
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, sku))
{
- Console.WriteLine("Warning: SKU is empty. Skipping entry.");
- continue;
- }
+ // Example of customizing a barcode parameter: set X-dimension (module width) to 2 points
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Create a Code128 barcode generator for the current SKU
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
- {
- // Optional: customize appearance
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Barcode.XDimension.Point = 2f; // Module size
- generator.Parameters.Barcode.BarHeight.Point = 40f; // Bar height
+ // Save the generated barcode as a PNG image
+ generator.Save(imagePath, BarCodeImageFormat.Png);
- // Export configuration to XML file named after the SKU
- string xmlPath = Path.Combine(outputFolder, $"{sku}.xml");
+ // Export the current generation settings to an XML configuration file
generator.ExportToXml(xmlPath);
- Console.WriteLine($"Exported barcode configuration for {sku} to {xmlPath}");
}
- }
- // Indicate successful completion
- Console.WriteLine("All barcode configurations have been generated.");
+ // Inform the user about the generated files
+ Console.WriteLine($"Generated barcode for {sku}: image={imagePath}, config={xmlPath}");
+ }
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/build-windows-service-that-watches-folder-for-new-xml-files-and-automatically-generates-barcodes.cs b/barcode-configuration-serialization/build-windows-service-that-watches-folder-for-new-xml-files-and-automatically-generates-barcodes.cs
index 58cbb4d..4ce8e6c 100644
--- a/barcode-configuration-serialization/build-windows-service-that-watches-folder-for-new-xml-files-and-automatically-generates-barcodes.cs
+++ b/barcode-configuration-serialization/build-windows-service-that-watches-folder-for-new-xml-files-and-automatically-generates-barcodes.cs
@@ -1,7 +1,8 @@
-// Title: Generate barcodes from XML files in a folder
-// Description: Demonstrates a console app that scans a directory for XML definitions and creates PNG barcodes using Aspose.BarCode.
+// Title: Windows Service Example – Generate Barcodes from XML Files
+// Description: Demonstrates watching a folder for XML files and creating barcode images using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode file‑processing and barcode generation category. It shows how to read XML input, map symbology names to EncodeTypes, and generate PNG images with BarcodeGenerator. Developers often need to automate barcode creation from data files, integrate with services, or batch‑process documents, and this snippet illustrates the core API usage for such scenarios.
// Prompt: Build a Windows service that watches a folder for new XML files and automatically generates barcodes.
-// Tags: barcode symbology, generation, png, aspose.barcode, xml, file-io
+// Tags: barcode, symbology, generation, png, aspose.barcode, barcodegenerator, encode types
using System;
using System.IO;
@@ -10,89 +11,95 @@
using Aspose.BarCode.Generation;
///
-/// Entry point for the barcode generation example.
+/// Demonstrates a simple console‑style implementation that could be adapted into a Windows Service to monitor a folder,
+/// read XML definitions, and generate barcode images using Aspose.BarCode.
///
class Program
{
///
- /// Scans the InputBarcodes folder for XML files, reads barcode specifications,
- /// generates corresponding PNG images, and saves them to the OutputBarcodes folder.
+ /// Entry point. Scans the Input folder for XML files, creates barcodes per definition, and saves PNG files to Output.
///
static void Main()
{
- // Define input and output directories (relative to the executable location)
- string inputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "InputBarcodes");
- string outputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OutputBarcodes");
+ // Define input and output directories relative to the current working directory.
+ string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Input");
+ string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Output");
- // Ensure the output directory exists
+ // Ensure the directories exist.
+ Directory.CreateDirectory(inputFolder);
Directory.CreateDirectory(outputFolder);
- // Verify the input directory exists
- if (!Directory.Exists(inputFolder))
- {
- Console.WriteLine($"Input folder not found: {inputFolder}");
- return;
- }
-
- // Get all XML files in the input folder
+ // Retrieve all XML files in the input folder.
string[] xmlFiles = Directory.GetFiles(inputFolder, "*.xml");
if (xmlFiles.Length == 0)
{
- Console.WriteLine("No XML files found to process.");
+ Console.WriteLine("No XML files found in the input folder.");
return;
}
- // Process each XML file individually
+ // Process each XML file individually.
foreach (string xmlPath in xmlFiles)
{
try
{
- // Load the XML document
+ // Load the XML document.
XDocument doc = XDocument.Load(xmlPath);
- XElement barcodeElement = doc.Root?.Element("Barcode");
- if (barcodeElement == null)
+ XElement root = doc.Root;
+ if (root == null)
{
- Console.WriteLine($"Invalid format in file: {Path.GetFileName(xmlPath)}");
+ Console.WriteLine($"Skipping '{Path.GetFileName(xmlPath)}': Empty XML.");
continue;
}
- // Extract symbology name and code text
- string symbologyName = barcodeElement.Element("Symbology")?.Value?.Trim();
- string codeText = barcodeElement.Element("CodeText")?.Value?.Trim();
+ // Expected XML format:
+ //
+ // Code128
+ // 123456
+ //
+ string symbologyName = root.Element("Symbology")?.Value?.Trim();
+ string codeText = root.Element("Value")?.Value?.Trim();
- // Validate required elements
+ // Validate required elements.
if (string.IsNullOrEmpty(symbologyName) || string.IsNullOrEmpty(codeText))
{
- Console.WriteLine($"Missing Symbology or CodeText in file: {Path.GetFileName(xmlPath)}");
+ Console.WriteLine($"Skipping '{Path.GetFileName(xmlPath)}': Missing Symbology or Value.");
continue;
}
- // Resolve symbology name to BaseEncodeType using reflection
+ // Resolve symbology name to BaseEncodeType using reflection.
var field = typeof(EncodeTypes).GetField(symbologyName);
if (field == null)
{
- Console.WriteLine($"Unknown symbology '{symbologyName}' in file: {Path.GetFileName(xmlPath)}");
+ Console.WriteLine($"Skipping '{Path.GetFileName(xmlPath)}': Unknown symbology '{symbologyName}'.");
continue;
}
BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
+ if (encodeType == null)
+ {
+ Console.WriteLine($"Skipping '{Path.GetFileName(xmlPath)}': Failed to obtain encode type.");
+ continue;
+ }
- // Prepare output file path (same name with .png extension)
- string outputFileName = Path.GetFileNameWithoutExtension(xmlPath) + ".png";
- string outputPath = Path.Combine(outputFolder, outputFileName);
-
- // Generate and save the barcode
+ // Create the barcode generator and configure optional parameters.
using (var generator = new BarcodeGenerator(encodeType, codeText))
{
+ // Example of setting a simple parameter (optional).
+ generator.Parameters.Barcode.XDimension.Point = 2f; // module size
+
+ // Build the output file path.
+ string outputFileName = Path.GetFileNameWithoutExtension(xmlPath) + ".png";
+ string outputPath = Path.Combine(outputFolder, outputFileName);
+
+ // Save the generated barcode image.
generator.Save(outputPath);
+ Console.WriteLine($"Generated barcode for '{Path.GetFileName(xmlPath)}' -> '{outputFileName}'.");
}
-
- Console.WriteLine($"Generated barcode for '{Path.GetFileName(xmlPath)}' -> {outputFileName}");
}
catch (Exception ex)
{
- // Handle any unexpected errors gracefully
- Console.WriteLine($"Error processing file '{Path.GetFileName(xmlPath)}': {ex.Message}");
+ // Log any unexpected errors for the current file.
+ Console.WriteLine($"Error processing '{Path.GetFileName(xmlPath)}': {ex.Message}");
}
}
diff --git a/barcode-configuration-serialization/chain-exporttoxml-and-importfromxml-calls-to-clone-barcodegenerator-configuration-into-new-object.cs b/barcode-configuration-serialization/chain-exporttoxml-and-importfromxml-calls-to-clone-barcodegenerator-configuration-into-new-object.cs
index 7c8aa6d..9c486c1 100644
--- a/barcode-configuration-serialization/chain-exporttoxml-and-importfromxml-calls-to-clone-barcodegenerator-configuration-into-new-object.cs
+++ b/barcode-configuration-serialization/chain-exporttoxml-and-importfromxml-calls-to-clone-barcodegenerator-configuration-into-new-object.cs
@@ -1,62 +1,60 @@
-// Title: Clone BarcodeGenerator configuration via XML export/import
-// Description: Demonstrates exporting a BarcodeGenerator's settings to XML and importing them into a new instance, effectively cloning the configuration.
+// Title: Clone BarcodeGenerator configuration using ExportToXml and ImportFromXml
+// Description: Demonstrates exporting a BarcodeGenerator's settings to XML and importing them to create an identical clone, useful for reusing configurations across objects.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showcasing how to serialize and deserialize barcode generator settings via XML. It highlights key API classes such as BarcodeGenerator, ExportToXml, and ImportFromXml, which developers commonly use to persist, share, or clone barcode configurations in enterprise applications.
// Prompt: Chain ExportToXml and ImportFromXml calls to clone a BarcodeGenerator configuration into a new object.
-// Tags: barcode symbology, configuration cloning, xml, export, import, aspose.barcodes, generation
+// Tags: barcode symbology, configuration cloning, xml serialization, exporttoxml, importfromxml, aspose.barcode
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
+using Aspose.BarCode;
///
-/// Example program that shows how to clone a BarcodeGenerator configuration
-/// by exporting it to XML and then importing it into a new generator instance.
+/// Demonstrates cloning a BarcodeGenerator configuration by exporting to XML and importing back.
///
class Program
{
///
- /// Entry point of the application. Performs the export, import, and image generation steps.
+ /// Entry point. Creates an original barcode, exports its configuration to XML, imports it to a new generator, and saves both images.
///
static void Main()
{
- // Define file paths for the temporary XML configuration and the output images
- string xmlPath = Path.Combine(Directory.GetCurrentDirectory(), "barcodeConfig.xml");
- string originalImagePath = Path.Combine(Directory.GetCurrentDirectory(), "original.png");
- string clonedImagePath = Path.Combine(Directory.GetCurrentDirectory(), "cloned.png");
-
- // Create and configure the original barcode generator
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
- {
- // Set some non-default parameters to demonstrate cloning
- generator.Parameters.Barcode.BarColor = Color.Blue;
- generator.Parameters.Barcode.XDimension.Point = 2f;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
- generator.Parameters.Resolution = 150;
-
- // Save the original barcode image to file
- generator.Save(originalImagePath);
-
- // Export the current configuration to an XML file for later import
- generator.ExportToXml(xmlPath);
- }
-
- // Import the configuration from the XML file into a new generator instance
- using (BarcodeGenerator clonedGenerator = BarcodeGenerator.ImportFromXml(xmlPath))
- {
- // Save the cloned barcode image (should be identical to the original)
- clonedGenerator.Save(clonedImagePath);
- }
-
- // Clean up the temporary XML file used for cloning
- if (File.Exists(xmlPath))
+ // Initialize the original barcode generator with Code128 symbology and sample text.
+ using (var original = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- File.Delete(xmlPath);
+ // Set various barcode appearance parameters.
+ original.Parameters.Barcode.XDimension.Point = 2f;
+ original.Parameters.Barcode.BarHeight.Point = 50f;
+ original.Parameters.Barcode.FilledBars = false;
+ original.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+ original.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica";
+ original.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f;
+
+ // Export the generator's configuration to an in‑memory XML stream.
+ using (var xmlStream = new MemoryStream())
+ {
+ bool exportSuccess = original.ExportToXml(xmlStream);
+ if (!exportSuccess)
+ {
+ Console.WriteLine("Failed to export barcode configuration to XML.");
+ return;
+ }
+
+ // Reset stream position to the beginning before reading.
+ xmlStream.Position = 0;
+
+ // Import the configuration from the XML stream to create a cloned generator.
+ using (var cloned = BarcodeGenerator.ImportFromXml(xmlStream))
+ {
+ // Save the original barcode image.
+ original.Save("original.png");
+
+ // Save the cloned barcode image.
+ cloned.Save("cloned.png");
+
+ Console.WriteLine("Original and cloned barcode images have been saved.");
+ }
+ }
}
-
- // Output the locations of the generated images for verification
- Console.WriteLine("Original barcode saved to: " + originalImagePath);
- Console.WriteLine("Cloned barcode saved to: " + clonedImagePath);
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/compare-memory-usage-of-exporttoxml-stream-versus-exporttoxml-string-for-identical-configurations.cs b/barcode-configuration-serialization/compare-memory-usage-of-exporttoxml-stream-versus-exporttoxml-string-for-identical-configurations.cs
index 759ff06..388d334 100644
--- a/barcode-configuration-serialization/compare-memory-usage-of-exporttoxml-stream-versus-exporttoxml-string-for-identical-configurations.cs
+++ b/barcode-configuration-serialization/compare-memory-usage-of-exporttoxml-stream-versus-exporttoxml-string-for-identical-configurations.cs
@@ -1,86 +1,74 @@
-// Title: Memory Usage Comparison of ExportToXml Overloads
-// Description: Demonstrates how to compare memory consumption when exporting barcode configuration to XML using a file path versus a stream.
+// Title: Compare memory usage of ExportToXml(Stream) vs ExportToXml(string)
+// Description: Demonstrates how to measure and compare the memory consumption of Aspose.BarCode's ExportToXml method when using a Stream versus a file path.
+// Category-Description: This example belongs to the Aspose.BarCode configuration export category, illustrating the use of BarcodeGenerator and its ExportToXml API. Developers often need to persist barcode settings to XML for later reuse, and choosing between stream or file output can impact memory usage. The snippet shows typical patterns for measuring memory impact in .NET applications.
// Prompt: Compare memory usage of ExportToXml(Stream) versus ExportToXml(string) for identical configurations.
-// Tags: barcode, export, xml, memory, aspose.barcode, stream, file
+// Tags: barcode symbology, export, xml, memory usage, aspose.barcode, barcodegenerator
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Sample program that measures and compares the memory allocation of
-/// BarcodeGenerator.ExportToXml when using a file path versus a stream.
+/// Example program that compares the memory usage of ExportToXml when writing to a
+/// versus writing directly to a file path, using identical barcode configurations.
///
class Program
{
///
- /// Entry point. Configures a barcode generator, exports its configuration
- /// to XML using both overloads, and reports the memory used by each operation.
+ /// Entry point of the example. Creates a barcode generator, exports its configuration to XML
+ /// using both a memory stream and a temporary file, and reports the memory consumption of each approach.
///
static void Main()
{
- // Initialize a barcode generator with a sample symbology and value.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Initialize a barcode generator with Code128 symbology and sample data.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Apply non‑default visual settings to make the configuration meaningful.
- generator.Parameters.Barcode.BarColor = Color.Blue;
+ // Adjust a non‑default parameter to ensure the configuration is not the default state.
generator.Parameters.Barcode.XDimension.Point = 2f;
- generator.Parameters.Barcode.BarHeight.Point = 40f;
- generator.Parameters.Resolution = 150;
- // Force a clean GC state before the first measurement.
+ // -------------------- Measure memory for ExportToXml(Stream) --------------------
+ // Force a full garbage collection to get a clean baseline.
GC.Collect();
GC.WaitForPendingFinalizers();
+ long memoryBeforeStream = GC.GetTotalMemory(true);
- // -------------------- ExportToXml(string) --------------------
- // Record memory before the export.
- long beforeString = GC.GetTotalMemory(true);
- // Export configuration to a physical XML file.
- bool resultString = generator.ExportToXml("barcode_config.xml");
- // Record memory after the export.
- long afterString = GC.GetTotalMemory(true);
- // Calculate the memory delta.
- long diffString = afterString - beforeString;
-
- // Output the result and memory usage for the string overload.
- Console.WriteLine($"ExportToXml(string) succeeded: {resultString}");
- Console.WriteLine($"Memory allocated (bytes) for ExportToXml(string): {diffString}");
-
- // -------------------- ExportToXml(Stream) --------------------
- // Use a memory stream to capture the XML output in memory.
+ // Export the configuration to a memory stream.
using (var memoryStream = new MemoryStream())
{
- // Clean up before the second measurement.
- GC.Collect();
- GC.WaitForPendingFinalizers();
+ bool streamResult = generator.ExportToXml(memoryStream);
+ Console.WriteLine($"ExportToXml(Stream) succeeded: {streamResult}");
+ }
- // Record memory before the stream export.
- long beforeStream = GC.GetTotalMemory(true);
- // Export configuration to the provided stream.
- bool resultStream = generator.ExportToXml(memoryStream);
- // Record memory after the export.
- long afterStream = GC.GetTotalMemory(true);
- // Calculate the memory delta.
- long diffStream = afterStream - beforeStream;
+ // Capture memory after the stream export.
+ long memoryAfterStream = GC.GetTotalMemory(true);
+ long memoryUsedStream = memoryAfterStream - memoryBeforeStream;
- // Output the result and memory usage for the stream overload.
- Console.WriteLine($"ExportToXml(Stream) succeeded: {resultStream}");
- Console.WriteLine($"Memory allocated (bytes) for ExportToXml(Stream): {diffStream}");
- }
+ // -------------------- Measure memory for ExportToXml(string) --------------------
+ // Force another garbage collection before the second measurement.
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ long memoryBeforeFile = GC.GetTotalMemory(true);
- // Clean up the temporary file created by ExportToXml(string).
- try
- {
- if (File.Exists("barcode_config.xml"))
- {
- File.Delete("barcode_config.xml");
- }
- }
- catch (Exception ex)
+ // Define a temporary file path for the XML output.
+ string tempFilePath = Path.Combine(Path.GetTempPath(), "barcode_config.xml");
+
+ // Export the configuration directly to a file.
+ bool fileResult = generator.ExportToXml(tempFilePath);
+ Console.WriteLine($"ExportToXml(string) succeeded: {fileResult}");
+
+ // Capture memory after the file export.
+ long memoryAfterFile = GC.GetTotalMemory(true);
+ long memoryUsedFile = memoryAfterFile - memoryBeforeFile;
+
+ // -------------------- Output comparison results --------------------
+ Console.WriteLine($"Memory used by ExportToXml(Stream): {memoryUsedStream} bytes");
+ Console.WriteLine($"Memory used by ExportToXml(string): {memoryUsedFile} bytes");
+
+ // Clean up the temporary XML file.
+ if (File.Exists(tempFilePath))
{
- Console.WriteLine($"Failed to delete temporary file: {ex.Message}");
+ File.Delete(tempFilePath);
}
}
}
diff --git a/barcode-configuration-serialization/convert-existing-barcode-image-generation-workflow-to-use-saved-xml-configurations-for-reproducible-output.cs b/barcode-configuration-serialization/convert-existing-barcode-image-generation-workflow-to-use-saved-xml-configurations-for-reproducible-output.cs
index 2df8821..54da962 100644
--- a/barcode-configuration-serialization/convert-existing-barcode-image-generation-workflow-to-use-saved-xml-configurations-for-reproducible-output.cs
+++ b/barcode-configuration-serialization/convert-existing-barcode-image-generation-workflow-to-use-saved-xml-configurations-for-reproducible-output.cs
@@ -1,7 +1,8 @@
-// Title: Barcode Generation with XML Configuration Export/Import
-// Description: Demonstrates creating a barcode, exporting its settings to XML, and reproducing the same barcode by importing the configuration.
+// Title: Generate barcode from saved XML configuration
+// Description: Demonstrates loading barcode settings from an XML file to produce a reproducible barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating how to export generator settings to XML and later import them for consistent barcode generation. It uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes, which are commonly employed when developers need repeatable barcode outputs across environments or deployments. Ideal for scenarios like automated testing, batch processing, or configuration‑driven applications.
// Prompt: Convert an existing barcode image generation workflow to use saved XML configurations for reproducible output.
-// Tags: barcode, code128, xml, export, import, image, aspose
+// Tags: barcode, xml, configuration, generation, code128, png, aspose.barcode
using System;
using System.IO;
@@ -10,69 +11,64 @@
using Aspose.Drawing;
///
-/// Example program that shows how to generate a barcode, export its configuration to XML,
-/// and then recreate the same barcode by importing the saved XML configuration.
+/// Demonstrates creating a barcode generator, exporting its configuration to XML,
+/// importing the configuration, and generating a barcode image.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Handles configuration file creation, import, and barcode image generation.
///
static void Main()
{
- // Define file paths for the generated images and the XML configuration
- string imagePath1 = "barcode1.png";
- string configPath = "barcode_config.xml";
- string imagePath2 = "barcode2.png";
+ const string configFile = "barcodeConfig.xml";
+ const string outputFile = "barcodeFromConfig.png";
- // -----------------------------------------------------------------
- // Step 1: Create a barcode generator, configure visual settings, and save the image
- // -----------------------------------------------------------------
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Ensure a configuration file exists. If not, create one with sample settings.
+ if (!File.Exists(configFile))
{
- // Set visual appearance of the barcode
- generator.Parameters.Barcode.BarColor = Color.Blue; // Barcode bars color
- generator.Parameters.BackColor = Color.White; // Background color
- generator.Parameters.Barcode.XDimension.Point = 2f; // Width of the smallest bar
- generator.Parameters.Barcode.BarHeight.Point = 40f; // Height of the barcode
- generator.Parameters.Barcode.Padding.Left.Point = 5f; // Left padding
- generator.Parameters.Barcode.Padding.Top.Point = 5f; // Top padding
- generator.Parameters.Barcode.Padding.Right.Point = 5f; // Right padding
- generator.Parameters.Barcode.Padding.Bottom.Point = 5f; // Bottom padding
-
- // Save the generated barcode image to a PNG file
- generator.Save(imagePath1, BarCodeImageFormat.Png);
+ // Create a barcode generator with sample settings.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ // Sample visual settings.
+ generator.Parameters.Barcode.BarColor = Color.Blue;
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.Barcode.BarHeight.Point = 50f;
+ generator.Parameters.Barcode.FilledBars = true;
+ generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica";
+ generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f;
+ generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
- // Export the current generator configuration to an XML file for later reuse
- bool exportSuccess = generator.ExportToXml(configPath);
- Console.WriteLine(exportSuccess
- ? $"Configuration exported to '{configPath}'."
- : $"Failed to export configuration to '{configPath}'.");
+ // Export the configuration to XML for later reuse.
+ generator.ExportToXml(configFile);
+ Console.WriteLine($"Configuration file created: {configFile}");
+ }
}
- // -----------------------------------------------------------------
- // Step 2: Load the saved configuration from XML and generate the same barcode
- // -----------------------------------------------------------------
- if (!File.Exists(configPath))
+ // Load the barcode generator from the saved XML configuration.
+ BarcodeGenerator loadedGenerator;
+ try
+ {
+ loadedGenerator = BarcodeGenerator.ImportFromXml(configFile);
+ }
+ catch (Exception ex)
{
- Console.WriteLine($"Configuration file '{configPath}' not found. Skipping import step.");
+ Console.WriteLine($"Failed to import configuration: {ex.Message}");
return;
}
- try
+ // Use the loaded generator to produce the barcode image.
+ using (loadedGenerator)
{
- // Import a new generator instance using the previously saved XML settings
- using (BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(configPath))
+ // The CodeText may be defined in the XML; if not, set a default.
+ if (string.IsNullOrEmpty(loadedGenerator.CodeText))
{
- // Save the barcode image generated from the imported configuration
- importedGenerator.Save(imagePath2, BarCodeImageFormat.Png);
- Console.WriteLine($"Barcode generated from XML configuration saved to '{imagePath2}'.");
+ loadedGenerator.CodeText = "Default123";
}
- }
- catch (Exception ex)
- {
- // Handle any errors that occur during the import process
- Console.WriteLine($"Error importing configuration: {ex.Message}");
+
+ // Save the generated barcode image.
+ loadedGenerator.Save(outputFile, BarCodeImageFormat.Png);
+ Console.WriteLine($"Barcode image generated from XML configuration: {outputFile}");
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/create-command-line-tool-that-reads-directory-of-xml-files-and-generates-corresponding-barcode-images.cs b/barcode-configuration-serialization/create-command-line-tool-that-reads-directory-of-xml-files-and-generates-corresponding-barcode-images.cs
index 369b6be..0e48dfc 100644
--- a/barcode-configuration-serialization/create-command-line-tool-that-reads-directory-of-xml-files-and-generates-corresponding-barcode-images.cs
+++ b/barcode-configuration-serialization/create-command-line-tool-that-reads-directory-of-xml-files-and-generates-corresponding-barcode-images.cs
@@ -1,71 +1,79 @@
-// Title: Generate Barcode Images from XML Definitions
-// Description: This example reads XML files that define barcode settings and creates PNG images for each, storing them in a subfolder.
+// Title: Command‑line XML‑to‑Barcode image generator
+// Description: Reads barcode configuration XML files from a directory and creates PNG barcode images using Aspose.BarCode.
+// Category-Description: Demonstrates Aspose.BarCode generation workflow where barcode settings are stored in XML. Shows how to import settings with BarcodeGenerator.ImportFromXml, generate images, and handle batch processing. Useful for developers automating barcode creation from configuration files or integrating barcode generation into CI pipelines.
// Prompt: Create a command‑line tool that reads a directory of XML files and generates corresponding barcode images.
-// Tags: barcode, xml, generation, png, command-line, aspose.barcode
+// Tags: barcode symbology, generation, png, aspose.barcode, barcodegenerator
using System;
using System.IO;
-using System.Collections.Generic;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Command‑line utility that imports barcode configurations from XML files
-/// and generates corresponding PNG images.
+/// Command‑line utility that converts barcode definition XML files into PNG images.
///
class Program
{
///
/// Entry point of the application.
- /// Accepts an optional directory path argument; processes up to five XML files
- /// and creates barcode images in a subfolder named "GeneratedImages".
+ /// Accepts optional input and output directory arguments, processes each XML file,
+ /// and generates a corresponding barcode image.
///
- /// Command‑line arguments; first argument may specify the input directory.
+ ///
+ /// args[0] – input directory (default: "InputXml").
+ /// args[1] – output directory (default: "OutputImages").
+ ///
static void Main(string[] args)
{
- // Determine the input directory: use first argument or fallback to a sample folder.
- string inputDir = args.Length > 0 ? args[0] : "BarcodesXml";
+ // Determine input and output directories (fallback to defaults)
+ string inputDir = args.Length > 0 ? args[0] : "InputXml";
+ string outputDir = args.Length > 1 ? args[1] : "OutputImages";
- // Verify that the input directory exists.
+ // Ensure output directory exists
+ Directory.CreateDirectory(outputDir);
+
+ // If input directory does not exist, create it and generate a sample XML file
if (!Directory.Exists(inputDir))
{
- Console.WriteLine($"Input directory does not exist: {inputDir}");
- return;
+ Directory.CreateDirectory(inputDir);
+ string sampleXmlPath = Path.Combine(inputDir, "sample.xml");
+ using (var sampleGenerator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ // Export generator settings to XML
+ sampleGenerator.ExportToXml(sampleXmlPath);
+ Console.WriteLine($"Created sample XML: {sampleXmlPath}");
+ }
}
- // Prepare output directory inside the input folder.
- string outputDir = Path.Combine(inputDir, "GeneratedImages");
- if (!Directory.Exists(outputDir))
+ // Get all XML files in the input directory
+ string[] xmlFiles = Directory.GetFiles(inputDir, "*.xml");
+ if (xmlFiles.Length == 0)
{
- Directory.CreateDirectory(outputDir);
+ Console.WriteLine("No XML files found to process.");
+ return;
}
- // Retrieve all XML files in the input directory (limit to 5 for safe batch processing).
- string[] xmlFiles = Directory.GetFiles(inputDir, "*.xml");
- int maxFiles = Math.Min(5, xmlFiles.Length);
-
- // Process each selected XML file.
- for (int i = 0; i < maxFiles; i++)
+ // Process each XML file and generate a PNG barcode image
+ foreach (string xmlPath in xmlFiles)
{
- string xmlPath = xmlFiles[i];
try
{
- // Import barcode settings from the XML file.
- using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath))
+ // Load barcode generator settings from XML
+ using (var generator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // Determine output image path (same name with .png extension).
+ // Determine output image path (same name, .png extension)
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(xmlPath);
string outputPath = Path.Combine(outputDir, fileNameWithoutExt + ".png");
- // Save the generated barcode image.
- generator.Save(outputPath);
+ // Save barcode image as PNG
+ generator.Save(outputPath, BarCodeImageFormat.Png);
Console.WriteLine($"Generated barcode image: {outputPath}");
}
}
catch (Exception ex)
{
- // Log the error and continue with the next file.
- Console.WriteLine($"Failed to process '{xmlPath}': {ex.Message}");
+ Console.WriteLine($"Error processing '{xmlPath}': {ex.Message}");
}
}
}
diff --git a/barcode-configuration-serialization/create-logging-wrapper-around-exporttoxml-and-importfromxml-to-record-timestamps-and-file-paths.cs b/barcode-configuration-serialization/create-logging-wrapper-around-exporttoxml-and-importfromxml-to-record-timestamps-and-file-paths.cs
index e1a700a..9f1b589 100644
--- a/barcode-configuration-serialization/create-logging-wrapper-around-exporttoxml-and-importfromxml-to-record-timestamps-and-file-paths.cs
+++ b/barcode-configuration-serialization/create-logging-wrapper-around-exporttoxml-and-importfromxml-to-record-timestamps-and-file-paths.cs
@@ -1,122 +1,105 @@
-// Title: Logging wrapper for barcode XML export/import
-// Description: Demonstrates how to log timestamps and file paths when exporting barcode settings to XML and importing them back, using Aspose.BarCode.
+// Title: Logging wrapper for Aspose.BarCode XML export/import operations
+// Description: Demonstrates how to wrap ExportToXml and ImportFromXml with logging that records timestamps and file paths.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showcasing how to persist and restore barcode generator settings using XML. It highlights key API classes such as BarcodeGenerator, EncodeTypes, and the ExportToXml/ImportFromXml methods. Developers often need to serialize settings for reuse, versioning, or deployment, and logging these actions aids troubleshooting and audit trails.
// Prompt: Create a logging wrapper around ExportToXml and ImportFromXml to record timestamps and file paths.
-// Tags: barcode symbology, export, import, xml, logging, aspose.barcode, csharp
+// Tags: barcode, code128, export, import, xml, logging, aspose.barcode, generation
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
-namespace BarcodeXmlLoggingDemo
+///
+/// Provides static methods that wrap Aspose.BarCode XML export and import operations
+/// with simple file-based logging of timestamps and file paths.
+///
+class BarcodeXmlLogger
{
+ // Log file name used for all logging entries.
+ private const string LogFile = "barcode_log.txt";
+
///
- /// Provides static methods that wrap Aspose.BarCode XML export/import operations with console logging.
+ /// Exports the specified settings to an XML file
+ /// while writing start and end timestamps to the log.
///
- public static class BarcodeXmlLogger
+ /// The barcode generator whose settings are to be exported.
+ /// The destination XML file path.
+ /// True if the export succeeded; otherwise, false.
+ public static bool ExportToXmlWithLog(BarcodeGenerator generator, string xmlPath)
{
- ///
- /// Exports the settings of a to an XML file and logs the operation.
- ///
- /// The barcode generator whose settings are to be exported.
- /// The full path of the XML file to write.
- /// True if the export succeeded; otherwise false.
- public static bool ExportToXmlWithLog(BarcodeGenerator generator, string xmlFilePath)
- {
- // Validate input arguments
- if (generator == null) throw new ArgumentNullException(nameof(generator));
- if (string.IsNullOrWhiteSpace(xmlFilePath)) throw new ArgumentException("XML file path must be provided.", nameof(xmlFilePath));
+ // Log the start of the export operation.
+ string startMessage = $"{DateTime.Now:o} - ExportToXml started. Path: {xmlPath}{Environment.NewLine}";
+ File.AppendAllText(LogFile, startMessage);
- // Log start of export
- Console.WriteLine($"[{DateTime.Now:O}] Exporting barcode settings to XML: {xmlFilePath}");
- bool result = false;
- try
- {
- // Perform the actual export
- result = generator.ExportToXml(xmlFilePath);
- // Log successful completion
- Console.WriteLine($"[{DateTime.Now:O}] Export completed. Success: {result}");
- }
- catch (Exception ex)
- {
- // Log any exception and rethrow
- Console.WriteLine($"[{DateTime.Now:O}] Export failed: {ex.Message}");
- throw;
- }
- return result;
- }
+ // Perform the actual export.
+ bool result = generator.ExportToXml(xmlPath);
- ///
- /// Imports barcode settings from an XML file, creates a , and logs the operation.
- ///
- /// The full path of the XML file to read.
- /// A new initialized with the imported settings.
- public static BarcodeGenerator ImportFromXmlWithLog(string xmlFilePath)
- {
- // Validate input arguments
- if (string.IsNullOrWhiteSpace(xmlFilePath)) throw new ArgumentException("XML file path must be provided.", nameof(xmlFilePath));
- if (!File.Exists(xmlFilePath))
- throw new FileNotFoundException("XML file not found.", xmlFilePath);
+ // Log the completion status of the export operation.
+ string endMessage = $"{DateTime.Now:o} - ExportToXml completed. Success: {result}{Environment.NewLine}";
+ File.AppendAllText(LogFile, endMessage);
- // Log start of import
- Console.WriteLine($"[{DateTime.Now:O}] Importing barcode settings from XML: {xmlFilePath}");
- BarcodeGenerator generator = null;
- try
- {
- // Perform the actual import
- generator = BarcodeGenerator.ImportFromXml(xmlFilePath);
- // Log successful creation with symbology info
- Console.WriteLine($"[{DateTime.Now:O}] Import completed. Generator created for symbology: {generator.BarcodeType.TypeName}");
- }
- catch (Exception ex)
- {
- // Log any exception and rethrow
- Console.WriteLine($"[{DateTime.Now:O}] Import failed: {ex.Message}");
- throw;
- }
- return generator;
- }
+ return result;
}
- class Program
+ ///
+ /// Imports a from an XML file while logging timestamps.
+ ///
+ /// The source XML file path.
+ /// A new instance created from the XML.
+ public static BarcodeGenerator ImportFromXmlWithLog(string xmlPath)
{
- ///
- /// Entry point of the demo. Exports barcode settings to XML, imports them back, generates an image, and cleans up temporary files.
- ///
- static void Main()
+ // Log the start of the import operation.
+ string startMessage = $"{DateTime.Now:o} - ImportFromXml started. Path: {xmlPath}{Environment.NewLine}";
+ File.AppendAllText(LogFile, startMessage);
+
+ // Perform the actual import.
+ BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath);
+
+ // Log the successful creation of the generator.
+ string endMessage = $"{DateTime.Now:o} - ImportFromXml completed. Generator created.{Environment.NewLine}";
+ File.AppendAllText(LogFile, endMessage);
+
+ return generator;
+ }
+}
+
+///
+/// Entry point of the example that demonstrates exporting, importing, and saving a barcode
+/// while using the logging wrapper defined in .
+///
+class Program
+{
+ ///
+ /// Main method that orchestrates the barcode generation, XML persistence, and image saving.
+ ///
+ static void Main()
+ {
+ // Ensure a clean log file for each run.
+ if (File.Exists("barcode_log.txt"))
{
- // Define temporary file paths for XML settings and barcode image
- string tempDir = Path.GetTempPath();
- string xmlPath = Path.Combine(tempDir, "barcode_settings.xml");
- string imagePath = Path.Combine(tempDir, "barcode_image.png");
+ File.Delete("barcode_log.txt");
+ }
- // Create a barcode generator, export its settings, then import them back
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
- {
- // Export settings to XML with logging
- BarcodeXmlLogger.ExportToXmlWithLog(generator, xmlPath);
- }
+ // Create a barcode generator for Code128 with sample data.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
+ {
+ // Export generator settings to XML with logging.
+ string xmlPath = "barcode_settings.xml";
+ BarcodeXmlLogger.ExportToXmlWithLog(generator, xmlPath);
+ }
- // Import settings from XML with logging and generate the barcode image
- using (var importedGenerator = BarcodeXmlLogger.ImportFromXmlWithLog(xmlPath))
- {
- // Save the generated barcode image to verify the imported settings
- importedGenerator.Save(imagePath);
- Console.WriteLine($"[{DateTime.Now:O}] Barcode image saved to: {imagePath}");
- }
+ // Import generator settings from XML with logging.
+ BarcodeGenerator importedGenerator = BarcodeXmlLogger.ImportFromXmlWithLog("barcode_settings.xml");
- // Optional cleanup of temporary files
- try
- {
- if (File.Exists(xmlPath)) File.Delete(xmlPath);
- if (File.Exists(imagePath)) File.Delete(imagePath);
- Console.WriteLine($"[{DateTime.Now:O}] Temporary files cleaned up.");
- }
- catch (Exception cleanupEx)
- {
- Console.WriteLine($"[{DateTime.Now:O}] Cleanup error: {cleanupEx.Message}");
- }
+ // Save the imported barcode as an image file.
+ using (importedGenerator)
+ {
+ string imagePath = "imported_barcode.png";
+ importedGenerator.Save(imagePath);
+ Console.WriteLine($"Barcode image saved to {Path.GetFullPath(imagePath)}");
}
+
+ // Indicate that processing has completed.
+ Console.WriteLine("Processing completed.");
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/create-utility-method-that-accepts-barcodegenerator-exports-its-state-to-xml-and-returns-xml-string.cs b/barcode-configuration-serialization/create-utility-method-that-accepts-barcodegenerator-exports-its-state-to-xml-and-returns-xml-string.cs
index 17c41e2..65f5ff2 100644
--- a/barcode-configuration-serialization/create-utility-method-that-accepts-barcodegenerator-exports-its-state-to-xml-and-returns-xml-string.cs
+++ b/barcode-configuration-serialization/create-utility-method-that-accepts-barcodegenerator-exports-its-state-to-xml-and-returns-xml-string.cs
@@ -1,60 +1,60 @@
// Title: Export BarcodeGenerator State to XML
-// Description: Demonstrates how to export the configuration of an Aspose.BarCode BarcodeGenerator to an XML string for persistence or inspection.
+// Description: Demonstrates how to export the configuration of a BarcodeGenerator to an XML string using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode configuration export category. It shows how to use the BarcodeGenerator class together with its Parameters property and the ExportToXml method to serialize the generator’s state. Developers often need to persist barcode settings for later reuse, debugging, or sharing across services, making XML export a common task in barcode automation workflows.
// Prompt: Create a utility method that accepts a BarcodeGenerator, exports its state to XML, and returns the XML string.
-// Tags: barcode symbology, export, xml, aspose.barcode, utility
+// Tags: barcode symbology, export, xml, configuration, aspose.barcode, barcodegenerator
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Example program that creates a barcode, modifies its appearance,
-/// and exports the generator's state to an XML string.
+/// Sample program that creates a barcode generator, configures it, and exports its state to an XML string.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the application. Demonstrates barcode generation and XML export.
///
static void Main()
{
- // Initialize a BarcodeGenerator for Code128 with sample data
+ // Initialize a BarcodeGenerator with Code128 symbology and sample text.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Set the barcode color to blue (demonstrates property modification)
- generator.Parameters.Barcode.BarColor = Color.Blue;
+ // Configure barcode appearance and behavior.
+ generator.Parameters.Barcode.XDimension.Point = 2f; // Width of the smallest bar.
+ generator.Parameters.Barcode.BarHeight.Point = 40f; // Height of the barcode.
+ generator.Parameters.Barcode.FilledBars = false; // Use unfilled bars.
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; // Suppress validation exceptions.
- // Export the current generator configuration to an XML string
+ // Export the generator's current configuration to an XML string.
string xml = ExportGeneratorToXml(generator);
-
- // Write the resulting XML to the console
Console.WriteLine(xml);
}
}
///
- /// Exports the state of the provided to an XML string.
+ /// Exports the provided instance to an XML string.
///
- /// The barcode generator whose configuration will be exported.
- /// An XML string representing the generator's current state.
+ /// The barcode generator whose state will be serialized.
+ /// XML representation of the generator's configuration.
/// Thrown when the export operation fails.
static string ExportGeneratorToXml(BarcodeGenerator generator)
{
- // Use a memory stream as the destination for the XML data
+ // Use a memory stream to capture the XML output.
using (var memoryStream = new MemoryStream())
{
- // Perform the export; the method returns true on success
+ // Perform the export; the method returns true on success.
bool exported = generator.ExportToXml(memoryStream);
if (!exported)
throw new InvalidOperationException("Failed to export barcode generator to XML.");
- // Reset the stream position to the beginning before reading
+ // Reset stream position to the beginning before reading.
memoryStream.Position = 0;
-
- // Read the entire XML content from the memory stream
using (var reader = new StreamReader(memoryStream))
{
+ // Read the entire XML content and return it.
return reader.ReadToEnd();
}
}
diff --git a/barcode-configuration-serialization/deserialize-barcode-settings-from-xml-stored-in-database-blob-field-using-memorystream.cs b/barcode-configuration-serialization/deserialize-barcode-settings-from-xml-stored-in-database-blob-field-using-memorystream.cs
index 1401fc1..b86b1ef 100644
--- a/barcode-configuration-serialization/deserialize-barcode-settings-from-xml-stored-in-database-blob-field-using-memorystream.cs
+++ b/barcode-configuration-serialization/deserialize-barcode-settings-from-xml-stored-in-database-blob-field-using-memorystream.cs
@@ -1,59 +1,49 @@
-// Title: Deserialize barcode settings from XML stored in a BLOB using MemoryStream
-// Description: Demonstrates loading barcode configuration XML from a database BLOB, importing it into Aspose.BarCode, and generating an image.
+// Title: Deserialize barcode settings from XML stored in a database BLOB using MemoryStream
+// Description: Demonstrates how to export barcode generator settings to XML, store them as a BLOB, and later import them back to recreate the barcode.
+// Category-Description: This example belongs to the Aspose.BarCode serialization and deserialization category, showcasing the use of BarcodeGenerator, ExportToXml, and ImportFromXml methods. Developers often need to persist barcode configurations in databases or files and restore them for consistent barcode generation across applications. The snippet illustrates typical workflow for storing settings as XML BLOBs and recreating generators without redefining parameters.
// Prompt: Deserialize barcode settings from XML stored in a database BLOB field using a MemoryStream.
-// Tags: barcode symbology, deserialization, xml, memorystream, aspose.barcode, code128, image generation
+// Tags: barcode symbology, serialization, deserialization, png, aspose.barcode, memorystream
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that imports barcode settings from XML stored in a BLOB and generates a barcode image.
+/// Program demonstrating deserialization of barcode settings from an XML BLOB.
///
class Program
{
///
- /// Entry point. Reads XML from a simulated BLOB, imports settings, and saves the barcode image.
+ /// Entry point. Exports a sample barcode configuration to XML, simulates storing it as a BLOB,
+ /// then imports the settings to generate a barcode image.
///
static void Main()
{
- // Sample XML that defines a Code128 barcode with codetext "12345".
- // In a real scenario this XML would be read from a database BLOB field.
- const string xmlContent = @"
-
- Code128
- 12345
-
-
-
- Below
- Center
-
- Arial
-
- 10
-
-
-
-
-
-";
-
- // Convert the XML string to a byte array as it would be stored in a BLOB.
- byte[] xmlBytes = System.Text.Encoding.UTF8.GetBytes(xmlContent);
-
- // Load the XML from a MemoryStream and import the barcode settings.
- using (var xmlStream = new MemoryStream(xmlBytes))
- using (var generator = BarcodeGenerator.ImportFromXml(xmlStream))
+ // Create a sample barcode generator with Code128 symbology and sample text.
+ using (var sampleGenerator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Verify that the generator was created successfully.
- Console.WriteLine($"Imported barcode type: {generator.BarcodeType.TypeName}");
- Console.WriteLine($"Imported codetext: {generator.CodeText}");
+ // Configure specific barcode parameters.
+ sampleGenerator.Parameters.Barcode.XDimension.Point = 2f;
+ sampleGenerator.Parameters.Barcode.BarHeight.Point = 40f;
+
+ // Export the generator's settings to a memory stream (simulating a BLOB in a database).
+ using (var exportStream = new MemoryStream())
+ {
+ sampleGenerator.ExportToXml(exportStream);
+ byte[] dbBlob = exportStream.ToArray(); // Simulated BLOB data.
- // Save the generated barcode image to a file.
- const string outputPath = "imported_barcode.png";
- generator.Save(outputPath);
- Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}");
+ // Deserialize the barcode settings from the XML BLOB using a new memory stream.
+ using (var importStream = new MemoryStream(dbBlob))
+ {
+ using (var importedGenerator = BarcodeGenerator.ImportFromXml(importStream))
+ {
+ // Generate and save the barcode image using the imported settings.
+ importedGenerator.Save("deserialized_barcode.png", BarCodeImageFormat.Png);
+ Console.WriteLine("Barcode image generated from deserialized settings.");
+ }
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/design-ui-component-that-loads-barcode-settings-from-xml-file-and-populates-property-editors.cs b/barcode-configuration-serialization/design-ui-component-that-loads-barcode-settings-from-xml-file-and-populates-property-editors.cs
index 56c6ecc..ab80aec 100644
--- a/barcode-configuration-serialization/design-ui-component-that-loads-barcode-settings-from-xml-file-and-populates-property-editors.cs
+++ b/barcode-configuration-serialization/design-ui-component-that-loads-barcode-settings-from-xml-file-and-populates-property-editors.cs
@@ -1,64 +1,74 @@
-// Title: Load Barcode Settings from XML and Display Properties
-// Description: Demonstrates loading barcode configuration from an XML file using Aspose.BarCode, then showing the settings and generating an image.
+// Title: Load barcode settings from XML and generate barcode image
+// Description: Demonstrates loading barcode configuration from an XML file, displaying key properties, and generating a barcode image using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating how to import and export barcode generator settings via XML. It showcases key API classes such as BarcodeGenerator, BarcodeParameters, and BarCodeImageFormat, which developers commonly use to persist settings, customize symbology, and produce barcode images in various formats.
// Prompt: Design a UI component that loads barcode settings from an XML file and populates property editors.
-// Tags: barcode symbology, import, xml, property editors, aspose.barcode
+// Tags: barcode, xml, configuration, generation, aspose.barcode, code128, png
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Example program that imports barcode settings from an XML file,
-/// displays key properties (simulating property editors), and generates an image.
+/// Example program that loads barcode settings from an XML file,
+/// displays selected properties (simulating UI editors), and generates a barcode image.
///
class Program
{
///
/// Entry point of the application.
- /// Loads barcode settings from an XML file, prints them, optionally modifies a property,
- /// and saves the resulting barcode image.
///
- /// Command‑line arguments; first argument can be the XML file path.
- static void Main(string[] args)
+ static void Main()
{
- // Determine XML file path (argument or default)
- string xmlPath = args.Length > 0 ? args[0] : "barcodeSettings.xml";
+ // Path to the XML file that stores barcode settings.
+ string xmlPath = "barcodeSettings.xml";
- // Verify that the XML file exists before attempting import
+ // Path for the generated barcode image.
+ string outputImage = "generatedBarcode.png";
+
+ // --------------------------------------------------------------------
+ // Create a sample XML settings file if it does not already exist.
+ // --------------------------------------------------------------------
if (!File.Exists(xmlPath))
{
- Console.WriteLine($"XML file not found: {xmlPath}");
- return;
+ // Initialize a BarcodeGenerator with Code128 symbology and sample text.
+ using (var sampleGenerator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ {
+ // Configure a few common barcode properties.
+ sampleGenerator.Parameters.Barcode.XDimension.Point = 2f; // Module size (points)
+ sampleGenerator.Parameters.Barcode.BarHeight.Point = 40f; // Bar height for 1D barcode (points)
+ sampleGenerator.Parameters.Barcode.BarColor = Color.Blue; // Foreground color
+ sampleGenerator.Parameters.BackColor = Color.White; // Background color
+ sampleGenerator.Parameters.Barcode.FilledBars = false; // No filled bars
+
+ // Export the configured settings to an XML file for later reuse.
+ sampleGenerator.ExportToXml(xmlPath);
+ Console.WriteLine($"Sample XML settings created at '{xmlPath}'.");
+ }
}
- // Load barcode settings from the specified XML file
+ // --------------------------------------------------------------------
+ // Load barcode settings from the XML file and display them.
+ // --------------------------------------------------------------------
using (var generator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // Display key properties (simulating property editors)
+ // Simulate property editors by writing key settings to the console.
Console.WriteLine("=== Loaded Barcode Settings ===");
- Console.WriteLine($"Symbology : {generator.BarcodeType.TypeName}");
- Console.WriteLine($"CodeText : {generator.CodeText}");
- Console.WriteLine($"Bar Color (ARGB) : {generator.Parameters.Barcode.BarColor.ToArgb()}");
- Console.WriteLine($"Background Color : {generator.Parameters.BackColor.ToArgb()}");
- Console.WriteLine($"Bar Height (pt) : {generator.Parameters.Barcode.BarHeight.Point} pt");
- Console.WriteLine($"X Dimension (pt) : {generator.Parameters.Barcode.XDimension.Point} pt");
- Console.WriteLine($"Image Width (pt) : {generator.Parameters.ImageWidth.Point} pt");
- Console.WriteLine($"Image Height (pt) : {generator.Parameters.ImageHeight.Point} pt");
- Console.WriteLine($"Resolution (dpi) : {generator.Parameters.Resolution}");
- Console.WriteLine($"AutoSizeMode : {generator.Parameters.AutoSizeMode}");
- Console.WriteLine($"CodeText Alignment : {generator.Parameters.Barcode.CodeTextParameters.Alignment}");
- Console.WriteLine($"CodeText Location : {generator.Parameters.Barcode.CodeTextParameters.Location}");
- Console.WriteLine($"Padding (pt) Left : {generator.Parameters.Barcode.Padding.Left.Point} pt");
- Console.WriteLine($"Padding (pt) Top : {generator.Parameters.Barcode.Padding.Top.Point} pt");
- Console.WriteLine($"Padding (pt) Right : {generator.Parameters.Barcode.Padding.Right.Point} pt");
- Console.WriteLine($"Padding (pt) Bottom: {generator.Parameters.Barcode.Padding.Bottom.Point} pt");
+ Console.WriteLine($"Symbology : {generator.BarcodeType.TypeName}");
+ Console.WriteLine($"CodeText : {generator.CodeText}");
+ Console.WriteLine($"XDimension (pt): {generator.Parameters.Barcode.XDimension.Point}");
+ Console.WriteLine($"BarHeight (pt) : {generator.Parameters.Barcode.BarHeight.Point}");
+ Console.WriteLine($"BarColor : {generator.Parameters.Barcode.BarColor}");
+ Console.WriteLine($"BackColor : {generator.Parameters.BackColor}");
+ Console.WriteLine($"FilledBars : {generator.Parameters.Barcode.FilledBars}");
+ Console.WriteLine();
- // Example: modify a property (bar color) and save to a new image (optional)
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue;
- string outputImage = "generated_from_xml.png";
- generator.Save(outputImage);
- Console.WriteLine($"Generated barcode saved to: {outputImage}");
+ // Generate the barcode image using the loaded settings.
+ generator.Save(outputImage, BarCodeImageFormat.Png);
+ Console.WriteLine($"Barcode image generated and saved as '{outputImage}'.");
}
+
+ // Program ends successfully.
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/develop-function-that-reads-xml-from-string-and-initializes-barcodegenerator-using-importfromxml-stream.cs b/barcode-configuration-serialization/develop-function-that-reads-xml-from-string-and-initializes-barcodegenerator-using-importfromxml-stream.cs
index ae884ce..3800a15 100644
--- a/barcode-configuration-serialization/develop-function-that-reads-xml-from-string-and-initializes-barcodegenerator-using-importfromxml-stream.cs
+++ b/barcode-configuration-serialization/develop-function-that-reads-xml-from-string-and-initializes-barcodegenerator-using-importfromxml-stream.cs
@@ -1,58 +1,64 @@
// Title: Initialize BarcodeGenerator from XML string
-// Description: Demonstrates reading barcode configuration XML from a string, converting it to a stream, and creating a BarcodeGenerator via ImportFromXml. Useful for dynamically configuring barcodes.
+// Description: Demonstrates reading barcode configuration XML from a string and creating a BarcodeGenerator via ImportFromXml.
+// Category-Description: This example belongs to the Aspose.BarCode XML configuration category, illustrating how to use the BarcodeGenerator.ImportFromXml(Stream) method. It shows developers how to define barcode settings (such as symbology and text) in XML, load it from memory, and generate a barcode image. Typical use cases include dynamic barcode creation from stored XML templates or configuration files.
// Prompt: Develop a function that reads XML from a string and initializes a BarcodeGenerator using ImportFromXml(Stream).
-// Tags: barcode symbology, import, xml, stream, aspose.barcodes, csharp
+// Tags: code128, barcode generation, xml import, importfromxml, aspose.barcode, png output
using System;
using System.IO;
using System.Text;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that creates a from XML configuration
-/// and saves the generated barcode image to a file.
+/// Example program that creates a BarcodeGenerator from an XML string using ImportFromXml.
///
class Program
{
///
- /// Reads XML from a string, creates a , and initializes a
- /// using .
+ /// Entry point of the example. Generates a barcode from XML and saves it as a PNG file.
///
- /// The XML string containing barcode configuration.
- /// A new instance of configured according to the XML.
- static BarcodeGenerator CreateGeneratorFromXml(string xmlContent)
+ static void Main()
{
- // Convert the XML string to UTF‑8 encoded bytes.
- byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlContent);
+ // XML definition for a Code128 barcode with sample text.
+ string xml = @"
+
+ Code128
+ 1234567890
+";
- // Wrap the byte array in a MemoryStream; the stream is disposed after ImportFromXml finishes.
- using (var xmlStream = new MemoryStream(xmlBytes))
+ try
+ {
+ // Create a BarcodeGenerator instance from the XML string.
+ using (var generator = CreateGeneratorFromXml(xml))
+ {
+ // Save the generated barcode image to verify successful creation.
+ generator.Save("generated_from_xml.png");
+ Console.WriteLine("Barcode generated and saved as generated_from_xml.png");
+ }
+ }
+ catch (Exception ex)
{
- // ImportFromXml reads the stream and returns a new BarcodeGenerator instance.
- BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlStream);
- return generator; // Caller is responsible for disposing the generator.
+ // Output any errors that occur during generation.
+ Console.WriteLine($"Error: {ex.Message}");
}
}
///
- /// Entry point of the program. Demonstrates creating a barcode from XML and saving it as an image file.
+ /// Reads XML content from a string, wraps it in a MemoryStream, and imports it into a new BarcodeGenerator.
///
- static void Main()
+ /// The XML string containing barcode configuration.
+ /// A BarcodeGenerator initialized with the settings defined in the XML.
+ static BarcodeGenerator CreateGeneratorFromXml(string xmlContent)
{
- // Sample XML that defines a Code128 barcode with the text "12345".
- string xml = @"
-
- Code128
- 12345
-";
+ // Convert the XML string to a UTF-8 byte array.
+ byte[] bytes = Encoding.UTF8.GetBytes(xmlContent);
- // Initialize the generator from the XML string.
- using (var generator = CreateGeneratorFromXml(xml))
+ // Use a MemoryStream to provide the XML data to ImportFromXml.
+ using (var stream = new MemoryStream(bytes))
{
- // Save the generated barcode image to a file.
- generator.Save("barcode_from_xml.png");
- Console.WriteLine("Barcode generated and saved as 'barcode_from_xml.png'.");
+ // ImportFromXml parses the XML and returns a configured BarcodeGenerator instance.
+ BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(stream);
+ return generator;
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/ensure-proper-disposal-of-filestream-objects-after-calling-exporttoxml-to-prevent-file-locks.cs b/barcode-configuration-serialization/ensure-proper-disposal-of-filestream-objects-after-calling-exporttoxml-to-prevent-file-locks.cs
index 005cdfa..ba79736 100644
--- a/barcode-configuration-serialization/ensure-proper-disposal-of-filestream-objects-after-calling-exporttoxml-to-prevent-file-locks.cs
+++ b/barcode-configuration-serialization/ensure-proper-disposal-of-filestream-objects-after-calling-exporttoxml-to-prevent-file-locks.cs
@@ -1,7 +1,8 @@
-// Title: Export and Import Barcode Generator Settings via XML
-// Description: Demonstrates exporting a BarcodeGenerator's configuration to an XML file and re-importing it to generate a barcode image.
+// Title: Export Barcode Generator Settings to XML with Proper Resource Disposal
+// Description: Demonstrates exporting Aspose.BarCode generator settings to an XML file while ensuring FileStream is correctly disposed to avoid file locks.
+// Category-Description: This example belongs to the Aspose.BarCode configuration export category, showcasing how to use BarcodeGenerator and its ExportToXml method. It highlights best practices for resource management with FileStream, a common requirement when persisting barcode settings for later reuse or analysis. Developers working with barcode generation often need to serialize settings for configuration sharing or debugging.
// Prompt: Ensure proper disposal of FileStream objects after calling ExportToXml to prevent file locks.
-// Tags: barcode, code128, export, xml, import, aspose.barcode, filestream
+// Tags: barcode symbology, export, xml, filestream disposal, aspose.barcode, generation
using System;
using System.IO;
@@ -9,36 +10,35 @@
using Aspose.BarCode.Generation;
///
-/// Example program that shows how to export a barcode generator's settings to XML,
-/// import them back, and create a barcode image.
+/// Demonstrates exporting barcode generator settings to XML and saving a barcode image.
///
class Program
{
///
- /// Entry point of the example. Executes the export/import workflow.
+ /// Entry point of the example. Creates a Code128 barcode, configures parameters,
+ /// exports settings to XML with proper disposal, and saves the barcode image.
///
static void Main()
{
- // Initialize a BarcodeGenerator with Code128 symbology and sample data.
+ // Initialize a BarcodeGenerator for Code128 symbology with sample text
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
+ // Optional: adjust visual parameters
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.Barcode.BarHeight.Point = 40f;
+
// Export the generator's configuration to an XML file.
// The FileStream is wrapped in a using block to guarantee disposal.
- using (var writeStream = new FileStream("barcode.xml", FileMode.Create, FileAccess.Write, FileShare.None))
+ using (var stream = new FileStream("barcode_settings.xml", FileMode.Create, FileAccess.Write, FileShare.None))
{
- generator.ExportToXml(writeStream);
- }
+ bool exported = generator.ExportToXml(stream);
+ Console.WriteLine($"Export to XML successful: {exported}");
+ } // FileStream disposed here, releasing any file lock.
- // Open the previously created XML file for reading.
- using (var readStream = new FileStream("barcode.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- // Import a new BarcodeGenerator instance from the XML configuration.
- using (var importedGenerator = BarcodeGenerator.ImportFromXml(readStream))
- {
- // Save the barcode generated from the imported settings as a PNG image.
- importedGenerator.Save("barcode.png");
- }
- }
- }
+ // Save the generated barcode image to verify the generator works.
+ generator.Save("barcode.png");
+ } // BarcodeGenerator disposed here.
+
+ Console.WriteLine("Operation completed.");
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/export-configured-barcodegenerator-state-to-xml-file-using-exporttoxml-string-overload.cs b/barcode-configuration-serialization/export-configured-barcodegenerator-state-to-xml-file-using-exporttoxml-string-overload.cs
index 7db09a5..a886412 100644
--- a/barcode-configuration-serialization/export-configured-barcodegenerator-state-to-xml-file-using-exporttoxml-string-overload.cs
+++ b/barcode-configuration-serialization/export-configured-barcodegenerator-state-to-xml-file-using-exporttoxml-string-overload.cs
@@ -1,37 +1,46 @@
-// Title: Export BarcodeGenerator Configuration to XML
-// Description: Demonstrates exporting a configured BarcodeGenerator's state to an XML file using the ExportToXml(string) overload. Useful for persisting barcode settings.
+// Title: Export BarcodeGenerator configuration to XML
+// Description: Demonstrates exporting a configured BarcodeGenerator's state to an XML file using the ExportToXml(string) overload.
+// Category-Description: This example belongs to the Aspose.BarCode generation and configuration category. It showcases how to set up barcode parameters with the BarcodeGenerator class, adjust visual properties, and persist the configuration to an XML file via ExportToXml. Developers often need to save and reuse barcode settings across applications or environments, making XML export a common practice for configuration management.
// Prompt: Export a configured BarcodeGenerator state to an XML file using ExportToXml(string) overload.
-// Tags: barcode, code128, export, xml, aspose.barcode, configuration
+// Tags: code128, export, xml, aspose.barcode, bargenerator, configuration
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Example program that configures a BarcodeGenerator and exports its settings to an XML file.
+/// Example program that configures a BarcodeGenerator and exports its state to an XML file.
///
class Program
{
///
- /// Entry point of the application. Configures a Code128 barcode and saves the generator state to XML.
+ /// Entry point of the example. Sets up barcode parameters and saves them to an XML configuration file.
///
static void Main()
{
- // Initialize a BarcodeGenerator with Code128 symbology and sample text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Define the output path for the exported XML configuration.
+ string xmlPath = "barcode_config.xml";
+
+ // Initialize a BarcodeGenerator for Code128 symbology with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
{
- // Set visual parameters for the barcode
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.DarkBlue; // Dark blue bars
- generator.Parameters.Barcode.XDimension.Point = 2f; // Width of the smallest bar unit
- generator.Parameters.Barcode.BarHeight.Point = 40f; // Height of the barcode
+ // ----- Configure barcode visual and functional parameters -----
+ generator.Parameters.Barcode.XDimension.Point = 2f; // Module size (width of the smallest bar)
+ generator.Parameters.Barcode.BarHeight.Point = 50f; // Height of the barcode bars
+ generator.Parameters.Barcode.FilledBars = true; // Use filled bars instead of outlines
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; // Suppress exceptions for invalid text
+ generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f; // Font size for human‑readable text
+ generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; // Position of the code text
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; // Color of the bars
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White; // Background color of the image
- // Export the current generator configuration to an XML file
- bool exported = generator.ExportToXml("barcodeConfig.xml");
+ // ----- Export the configured generator state to an XML file -----
+ bool success = generator.ExportToXml(xmlPath);
- // Inform the user whether the export succeeded
- Console.WriteLine(exported
- ? "Barcode configuration exported successfully."
- : "Failed to export barcode configuration.");
+ // Output the result of the export operation.
+ Console.WriteLine($"Export to XML {(success ? "succeeded" : "failed")}. File: {Path.GetFullPath(xmlPath)}");
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/implement-batch-processing-to-export-multiple-barcodegenerator-configurations-to-separate-xml-files-in-loop.cs b/barcode-configuration-serialization/implement-batch-processing-to-export-multiple-barcodegenerator-configurations-to-separate-xml-files-in-loop.cs
index ec0f7ca..810b8fb 100644
--- a/barcode-configuration-serialization/implement-batch-processing-to-export-multiple-barcodegenerator-configurations-to-separate-xml-files-in-loop.cs
+++ b/barcode-configuration-serialization/implement-batch-processing-to-export-multiple-barcodegenerator-configurations-to-separate-xml-files-in-loop.cs
@@ -1,49 +1,53 @@
-// Title: Batch Export of Barcode Configurations to XML
-// Description: Demonstrates how to loop through multiple barcode generator settings and export each configuration to a separate XML file.
+// Title: Batch export of multiple barcode configurations to XML
+// Description: Demonstrates how to generate several barcodes with different symbologies and export each generator's settings to separate XML files.
+// Category-Description: This example belongs to the Aspose.BarCode configuration export category, illustrating the use of BarcodeGenerator, its Parameters, and the ExportToXml method. Developers often need to persist barcode settings for later reuse, batch processing, or integration with other systems; this snippet shows a typical loop‑based approach for handling multiple configurations in one run.
// Prompt: Implement batch processing to export multiple BarcodeGenerator configurations to separate XML files in a loop.
-// Tags: barcode symbology, export, xml, batch processing, aspnet barcodes, generator
+// Tags: barcode symbology, export, xml, batch processing, aspnet, aspose.barcode, generator
using System;
-using System.Collections.Generic;
-using Aspose.BarCode.Generation;
+using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
///
-/// Example program that creates several barcode generators with different
-/// symbologies and exports each configuration to its own XML file.
+/// Provides an example of batch processing multiple barcode configurations
+/// and exporting each configuration to a separate XML file.
///
class Program
{
///
- /// Entry point of the application. Iterates over a collection of barcode
- /// configurations, generates each barcode, and saves the generator settings
- /// to an XML file.
+ /// Entry point of the application. Iterates over a set of barcode configurations,
+ /// creates a for each, and exports its settings to XML.
///
static void Main()
{
- // Define a list of barcode configurations (symbology, codetext, output XML file)
- var configs = new List<(BaseEncodeType type, string codeText, string xmlPath)>
+ // Define a collection of barcode configurations to be processed.
+ var configurations = new (BaseEncodeType EncodeType, string CodeText, string XmlFile)[]
{
(EncodeTypes.Code128, "ABC123", "code128.xml"),
(EncodeTypes.QR, "https://example.com", "qr.xml"),
(EncodeTypes.DataMatrix, "DM12345", "datamatrix.xml"),
(EncodeTypes.Pdf417, "PDF417 Sample Text", "pdf417.xml"),
- (EncodeTypes.Aztec, "AztecDemo", "aztec.xml")
+ (EncodeTypes.Aztec, "AztecSample", "aztec.xml")
};
- // Process each configuration in the list
- foreach (var (type, codeText, xmlPath) in configs)
+ // Process each configuration in the collection.
+ foreach (var config in configurations)
{
- // Create a BarcodeGenerator with the specified type and codetext
- using (var generator = new BarcodeGenerator(type, codeText))
+ // Create a barcode generator with the specified symbology and data.
+ using (var generator = new BarcodeGenerator(config.EncodeType, config.CodeText))
{
- // Set common visual parameters (optional)
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ // Set a common parameter (optional) – X dimension in points.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Export the generator configuration to an XML file
+ // Build the absolute path for the output XML file.
+ string xmlPath = Path.Combine(Directory.GetCurrentDirectory(), config.XmlFile);
+
+ // Export the generator's configuration to the XML file.
bool success = generator.ExportToXml(xmlPath);
- Console.WriteLine($"{xmlPath}: {(success ? "Exported" : "Failed")}");
+
+ // Output the result of the export operation.
+ Console.WriteLine($"Exported {config.EncodeType.TypeName} to '{xmlPath}': {(success ? "Success" : "Failed")}");
}
}
}
diff --git a/barcode-configuration-serialization/implement-error-handling-for-importfromxml-when-xml-file-is-missing-required-barcode-properties.cs b/barcode-configuration-serialization/implement-error-handling-for-importfromxml-when-xml-file-is-missing-required-barcode-properties.cs
index f33ff45..cde0d5b 100644
--- a/barcode-configuration-serialization/implement-error-handling-for-importfromxml-when-xml-file-is-missing-required-barcode-properties.cs
+++ b/barcode-configuration-serialization/implement-error-handling-for-importfromxml-when-xml-file-is-missing-required-barcode-properties.cs
@@ -1,105 +1,70 @@
-// Title: Import Barcode Generator from XML with Validation
-// Description: Demonstrates importing a barcode configuration from an XML file, validating required properties, and handling errors.
+// Title: Import barcode configuration from XML with validation
+// Description: Demonstrates importing barcode settings from an XML file, checking for missing required properties, and generating a barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator.ImportFromXml to load configuration, validate essential properties such as CodeText, and produce an image. Developers often need to load barcode definitions from external XML, ensure completeness, and handle errors gracefully. Typical use cases include batch processing, dynamic barcode creation, and integration with configuration management systems.
// Prompt: Implement error handling for ImportFromXml when the XML file is missing required barcode properties.
-// Tags: barcode symbology, import, xml, error handling, aspose.barcodes
+// Tags: barcode, import, xml, validation, code128, aspose.barcode, generation, png
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that imports a barcode generator configuration from an XML file,
+/// Example program that imports barcode settings from an XML file,
/// validates required properties, and generates a barcode image.
///
class Program
{
///
- /// Entry point of the program.
+ /// Entry point of the application.
///
static void Main()
{
// Path to the XML configuration file
string xmlPath = "barcodeConfig.xml";
- // Verify that the file exists before attempting to import
+ // Create a sample XML file that intentionally omits required properties (e.g., CodeText)
if (!File.Exists(xmlPath))
{
- Console.WriteLine($"Error: XML file '{xmlPath}' does not exist.");
- return;
+ string xmlContent = @"
+
+ Code128
+
+";
+ File.WriteAllText(xmlPath, xmlContent);
+ Console.WriteLine($"Sample XML created at '{xmlPath}'.");
}
- // Attempt to import the BarcodeGenerator from the XML file
- BarcodeGenerator generator = null;
try
{
- generator = BarcodeGenerator.ImportFromXml(xmlPath);
- }
- catch (BarCodeException ex)
- {
- // Handle known barcode-specific errors during import
- Console.WriteLine($"BarCodeException while importing XML: {ex.Message}");
- return;
- }
- catch (Exception ex)
- {
- // Handle any other unexpected errors during import
- Console.WriteLine($"Unexpected error while importing XML: {ex.Message}");
- return;
- }
-
- // Ensure the generator was created successfully
- if (generator == null)
- {
- Console.WriteLine("Error: ImportFromXml returned null.");
- return;
- }
-
- // Validate required barcode properties
- // For this example, EncodeType (BarcodeType) and CodeText are required
- bool hasError = false;
-
- // Check that the EncodeType (BarcodeType) is present
- if (generator.BarcodeType == null)
- {
- Console.WriteLine("Error: Encode type is missing in the XML configuration.");
- hasError = true;
- }
+ // Import barcode settings from the XML file
+ using (var generator = BarcodeGenerator.ImportFromXml(xmlPath))
+ {
+ // Ensure the import succeeded
+ if (generator == null)
+ {
+ Console.WriteLine("Import returned null. Cannot continue.");
+ return;
+ }
- // Check that the CodeText (data to encode) is present and not empty
- if (string.IsNullOrWhiteSpace(generator.CodeText))
- {
- Console.WriteLine("Error: CodeText (data to encode) is missing or empty in the XML configuration.");
- hasError = true;
- }
+ // Validate that required properties are present (e.g., CodeText)
+ if (string.IsNullOrWhiteSpace(generator.CodeText))
+ {
+ Console.WriteLine("Error: Imported configuration is missing required 'CodeText' property.");
+ return;
+ }
- // If any validation errors were found, clean up and exit
- if (hasError)
- {
- generator.Dispose();
- return;
- }
+ // Additional validation can be added here (e.g., check EncodeType, parameters, etc.)
- // Validation passed – generate and save the barcode image
- string outputPath = "generatedBarcode.png";
- try
- {
- // Use a using block to ensure proper disposal of the generator
- using (generator)
- {
+ // Generate and save the barcode image
+ string outputPath = "generatedBarcode.png";
generator.Save(outputPath);
- Console.WriteLine($"Barcode generated and saved to '{outputPath}'.");
+ Console.WriteLine($"Barcode generated successfully and saved to '{outputPath}'.");
}
}
- catch (BarCodeException ex)
- {
- // Handle barcode-specific errors during generation or saving
- Console.WriteLine($"BarCodeException while generating/saving barcode: {ex.Message}");
- }
catch (Exception ex)
{
- // Handle any other unexpected errors during generation or saving
- Console.WriteLine($"Unexpected error while generating/saving barcode: {ex.Message}");
+ // Handle any errors that occur during import or generation
+ Console.WriteLine($"Failed to import barcode from XML. Exception: {ex.Message}");
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/implement-fallback-mechanism-that-creates-default-barcode-configuration-if-importfromxml-fails.cs b/barcode-configuration-serialization/implement-fallback-mechanism-that-creates-default-barcode-configuration-if-importfromxml-fails.cs
index 7ecc133..d15b0cf 100644
--- a/barcode-configuration-serialization/implement-fallback-mechanism-that-creates-default-barcode-configuration-if-importfromxml-fails.cs
+++ b/barcode-configuration-serialization/implement-fallback-mechanism-that-creates-default-barcode-configuration-if-importfromxml-fails.cs
@@ -1,7 +1,8 @@
-// Title: Barcode Generation with XML Import and Fallback
-// Description: Demonstrates loading a barcode configuration from an XML file and falling back to a default configuration when the import fails.
+// Title: Barcode generation with XML import and fallback to default configuration
+// Description: Demonstrates loading barcode settings from an XML file and falling back to a default Code128 barcode when the import fails or the file is missing.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator.ImportFromXml, configure barcode parameters, and handle errors gracefully. Developers often need to load barcode configurations from external files for dynamic generation, and require a reliable fallback to ensure production continuity. The snippet showcases key classes like BarcodeGenerator, EncodeTypes, and AutoSizeMode, useful for creating 1D barcodes in PNG format.
// Prompt: Implement a fallback mechanism that creates a default barcode configuration if ImportFromXml fails.
-// Tags: barcode symbology, import, fallback, xml, aspose.barcode, c#
+// Tags: barcode symbology, generation, png, importfromxml, fallback, default configuration, aspose.barcode
using System;
using System.IO;
@@ -10,60 +11,66 @@
using Aspose.Drawing;
///
-/// Example program that tries to generate a barcode from an XML configuration file.
-/// If the import fails, it creates a default barcode configuration as a fallback.
+/// Example program that generates a barcode using configuration loaded from XML,
+/// with a fallback to a default configuration when loading fails.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the application. Attempts to import barcode settings from an XML file;
+ /// if unsuccessful, creates a default barcode generator and saves the image.
///
static void Main()
{
- // Path to the XML configuration file.
const string xmlPath = "barcodeConfig.xml";
+ const string outputPath = "barcode.png";
- // Check whether the XML file exists before attempting import.
+ BarcodeGenerator generator;
+
+ // Check if the XML configuration file exists
if (File.Exists(xmlPath))
{
try
{
- // ImportFromXml creates a BarcodeGenerator instance based on the XML settings.
- using (var generator = BarcodeGenerator.ImportFromXml(xmlPath))
- {
- // Save the generated barcode image to a file.
- generator.Save("imported.png");
- Console.WriteLine("Barcode generated from XML configuration.");
- }
-
- // Import succeeded; exit the method early.
- return;
+ // Attempt to import generator settings from the XML file
+ generator = BarcodeGenerator.ImportFromXml(xmlPath);
+ Console.WriteLine("Barcode configuration loaded from XML.");
}
catch (Exception ex)
{
- // Log the exception and continue to the fallback logic.
+ // Log the error and fall back to a default configuration
Console.WriteLine($"ImportFromXml failed: {ex.Message}");
+ Console.WriteLine("Falling back to default barcode configuration.");
+ generator = CreateDefaultGenerator();
}
}
else
{
- // XML file not found – inform the user and proceed with default settings.
- Console.WriteLine("XML configuration file not found. Using default settings.");
+ // XML file not found; use the default configuration
+ Console.WriteLine("XML configuration file not found. Using default barcode configuration.");
+ generator = CreateDefaultGenerator();
}
- // ---------- Fallback section ----------
- // Create a default barcode generator with a hard‑coded symbology and value.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Fallback123"))
+ // Save the generated barcode image to the specified path
+ using (generator)
{
- // Set a few default visual parameters.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue;
- generator.Parameters.Barcode.XDimension.Point = 2f;
- generator.Parameters.Barcode.BarHeight.Point = 40f;
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Save the fallback barcode image.
- generator.Save("fallback.png");
- Console.WriteLine("Default barcode generated as fallback.");
+ generator.Save(outputPath);
+ Console.WriteLine($"Barcode saved to '{outputPath}'.");
}
}
+
+ // Creates a simple default barcode (Code128) with basic settings
+ private static BarcodeGenerator CreateDefaultGenerator()
+ {
+ var gen = new BarcodeGenerator(EncodeTypes.Code128, "Default");
+ // Set common barcode parameters
+ gen.Parameters.Barcode.XDimension.Point = 2f; // Module size
+ gen.Parameters.Barcode.BarHeight.Point = 40f; // Bar height for 1D barcodes
+ gen.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ gen.Parameters.BackColor = Aspose.Drawing.Color.White;
+ gen.Parameters.AutoSizeMode = AutoSizeMode.None;
+ gen.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica";
+ gen.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f;
+ return gen;
+ }
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/import-barcode-generator-configuration-from-xml-file-path-using-importfromxml-string-overload.cs b/barcode-configuration-serialization/import-barcode-generator-configuration-from-xml-file-path-using-importfromxml-string-overload.cs
index b26934d..4e533ba 100644
--- a/barcode-configuration-serialization/import-barcode-generator-configuration-from-xml-file-path-using-importfromxml-string-overload.cs
+++ b/barcode-configuration-serialization/import-barcode-generator-configuration-from-xml-file-path-using-importfromxml-string-overload.cs
@@ -1,42 +1,50 @@
// Title: Import Barcode Generator Configuration from XML
-// Description: Demonstrates loading a barcode generator configuration from an XML file and saving the resulting barcode image to PNG.
+// Description: Demonstrates loading a barcode generator's settings from an XML file and creating a barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to import generator configuration using the ImportFromXml(string) overload. It highlights key API classes such as BarcodeGenerator and typical scenarios like reusing saved settings for consistent barcode output across applications. Developers often need to persist and restore barcode configurations for batch processing or deployment pipelines.
// Prompt: Import barcode generator configuration from an XML file path using ImportFromXml(string) overload.
-// Tags: barcode symbology, import, xml, aspose.barcode, csharp
+// Tags: barcode symbology, import, xml, generator, aspose.barcode
using System;
using System.IO;
using Aspose.BarCode.Generation;
///
-/// Example program that imports a barcode generator configuration from an XML file
-/// and saves the generated barcode image to a PNG file.
+/// Provides an example of importing a barcode generator configuration from an XML file
+/// and generating a barcode image using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Loads the XML configuration, creates a
+ /// instance via ImportFromXml, and saves the resulting barcode image.
///
static void Main()
{
- // Path to the XML configuration file.
+ // Path to the XML configuration file that contains barcode settings.
string xmlPath = "barcodeConfig.xml";
- // Verify that the XML file exists before attempting import.
+ // Ensure the specified XML file exists before attempting to import.
if (!File.Exists(xmlPath))
{
- Console.WriteLine($"Error: The file \"{xmlPath}\" does not exist.");
+ Console.WriteLine($"Error: The file '{xmlPath}' does not exist.");
return;
}
- // Import the BarcodeGenerator configuration from the XML file.
- // The ImportFromXml method returns a BarcodeGenerator instance that implements IDisposable.
+ // Import the barcode generator configuration from the XML file.
+ // The ImportFromXml method returns a fully configured BarcodeGenerator instance.
using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // Optional: modify the generator after import if needed.
- // Save the generated barcode image to a PNG file.
- string outputPath = "generatedBarcode.png";
- generator.Save(outputPath);
- Console.WriteLine($"Barcode image saved to \"{outputPath}\".");
+ // Verify that the import succeeded and a valid generator was returned.
+ if (generator == null)
+ {
+ Console.WriteLine("Error: Failed to import barcode configuration.");
+ return;
+ }
+
+ // Optional: Save the generated barcode image to verify the import succeeded.
+ string outputImage = "importedBarcode.png";
+ generator.Save(outputImage);
+ Console.WriteLine($"Barcode image saved to '{outputImage}'.");
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/integrate-xml-serialization-of-barcode-settings-into-web-api-that-accepts-configuration-json-and-returns-xml.cs b/barcode-configuration-serialization/integrate-xml-serialization-of-barcode-settings-into-web-api-that-accepts-configuration-json-and-returns-xml.cs
index 5370066..e980780 100644
--- a/barcode-configuration-serialization/integrate-xml-serialization-of-barcode-settings-into-web-api-that-accepts-configuration-json-and-returns-xml.cs
+++ b/barcode-configuration-serialization/integrate-xml-serialization-of-barcode-settings-into-web-api-that-accepts-configuration-json-and-returns-xml.cs
@@ -1,90 +1,102 @@
-// Title: XML serialization of barcode settings via a web‑API style console demo
-// Description: Demonstrates deserializing barcode configuration from JSON, generating a barcode, and exporting its settings to XML.
+// Title: XML Serialization of Barcode Settings via Web API
+// Description: Demonstrates converting barcode configuration JSON into Aspose.BarCode XML settings, suitable for returning from a web API.
+// Category-Description: This example belongs to the Aspose.BarCode configuration serialization category, illustrating how to use BarcodeGenerator, EncodeTypes, and ExportToXml to transform runtime barcode settings into XML. Developers building web services often need to accept JSON payloads, configure barcode generation, and expose the resulting configuration as XML for downstream processing or storage.
// Prompt: Integrate XML serialization of barcode settings into a web API that accepts configuration JSON and returns XML.
-// Tags: barcode, symbology, serialization, xml, json, aspose.barcode, webapi
+// Tags: barcode symbology serialization json xml aspose.barcode generation
using System;
using System.IO;
+using System.Text;
using System.Text.Json;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Simple DTO that represents the JSON payload received by the API.
-///
-class Config
-{
- ///
- /// The name of the barcode symbology (e.g., "Code128").
- ///
- public string Symbology { get; set; }
-
- ///
- /// The text to encode in the barcode.
- ///
- public string CodeText { get; set; }
-}
-
-///
-/// Console application that mimics the core logic of a web API endpoint.
+/// Demonstrates serialization of barcode generator settings to XML based on JSON configuration.
///
class Program
{
+ // Simple configuration model matching expected JSON structure
+ private class BarcodeConfig
+ {
+ public string Symbology { get; set; }
+ public string CodeText { get; set; }
+ public float? XDimension { get; set; }
+ public float? BarHeight { get; set; }
+ }
+
///
- /// Entry point that deserializes JSON, generates a barcode, and returns its settings as XML.
+ /// Entry point that parses JSON configuration, creates a BarcodeGenerator, applies settings, and outputs XML.
///
static void Main()
{
- // NOTE: The snippet runner is a console application. In a real web API this logic would be inside a controller action.
-
- // Sample JSON configuration (normally this would come from an HTTP request body)
- string jsonConfig = @"{ ""Symbology"": ""Code128"", ""CodeText"": ""Sample123"" }";
+ // Sample JSON configuration (in a real scenario this would come from an HTTP request)
+ string json = @"{
+ ""Symbology"": ""Code128"",
+ ""CodeText"": ""1234567890"",
+ ""XDimension"": 2.0,
+ ""BarHeight"": 40.0
+ }";
- // Deserialize JSON to a configuration object
- Config config = JsonSerializer.Deserialize(jsonConfig);
+ // Deserialize JSON into configuration object
+ BarcodeConfig config = JsonSerializer.Deserialize(json);
if (config == null)
{
- Console.WriteLine("Invalid configuration.");
+ Console.WriteLine("Failed to parse configuration.");
return;
}
- // Resolve the symbology name to a BaseEncodeType using reflection
- var field = typeof(EncodeTypes).GetField(config.Symbology);
- if (field == null)
+ // Resolve symbology name to BaseEncodeType using reflection
+ BaseEncodeType encodeType = ResolveEncodeType(config.Symbology);
+ if (encodeType == null)
{
Console.WriteLine($"Unknown symbology: {config.Symbology}");
return;
}
- BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
- // Create the barcode generator with the resolved type and codetext
- using (var generator = new BarcodeGenerator(encodeType, config.CodeText))
+ // Create barcode generator with provided codetext
+ using (var generator = new BarcodeGenerator(encodeType, config.CodeText ?? string.Empty))
{
- // Example of setting a barcode property (optional)
- generator.Parameters.Barcode.BarColor = Color.Black;
- generator.Parameters.BackColor = Color.White;
+ // Apply optional X dimension setting
+ if (config.XDimension.HasValue)
+ generator.Parameters.Barcode.XDimension.Point = config.XDimension.Value;
- // Export the barcode settings to XML (in-memory)
- using (var memoryStream = new MemoryStream())
+ // Apply optional bar height setting
+ if (config.BarHeight.HasValue)
+ generator.Parameters.Barcode.BarHeight.Point = config.BarHeight.Value;
+
+ // Export settings to XML using a memory stream
+ using (var ms = new MemoryStream())
{
- bool exported = generator.ExportToXml(memoryStream);
+ bool exported = generator.ExportToXml(ms);
if (!exported)
{
- Console.WriteLine("Failed to export barcode settings to XML.");
+ Console.WriteLine("Export to XML failed.");
return;
}
- // Reset stream position and read the XML content
- memoryStream.Position = 0;
- using (var reader = new StreamReader(memoryStream))
+ // Reset stream position and read XML content
+ ms.Position = 0;
+ using (var reader = new StreamReader(ms, Encoding.UTF8))
{
string xmlOutput = reader.ReadToEnd();
- Console.WriteLine("Exported XML:");
+ // Output XML (could be returned from an API endpoint)
Console.WriteLine(xmlOutput);
}
}
}
}
+
+ // Helper to map symbology string to EncodeTypes field via reflection
+ private static BaseEncodeType ResolveEncodeType(string symbologyName)
+ {
+ if (string.IsNullOrWhiteSpace(symbologyName))
+ return null;
+
+ var field = typeof(EncodeTypes).GetField(symbologyName);
+ if (field == null)
+ return null;
+
+ return field.GetValue(null) as BaseEncodeType;
+ }
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/measure-performance-differences-between-file-based-and-stream-based-xml-export-for-large-barcode-configurations.cs b/barcode-configuration-serialization/measure-performance-differences-between-file-based-and-stream-based-xml-export-for-large-barcode-configurations.cs
index b5076a8..e7d7208 100644
--- a/barcode-configuration-serialization/measure-performance-differences-between-file-based-and-stream-based-xml-export-for-large-barcode-configurations.cs
+++ b/barcode-configuration-serialization/measure-performance-differences-between-file-based-and-stream-based-xml-export-for-large-barcode-configurations.cs
@@ -1,75 +1,70 @@
-// Title: XML Export Performance Comparison for Barcode Configurations
-// Description: Demonstrates measuring and comparing the time taken to export a large barcode configuration to XML using file‑based and stream‑based approaches.
+// Title: Measure performance of file vs stream XML export for large barcode configurations
+// Description: Demonstrates how to export a complex barcode generator configuration to XML using both file‑based and stream‑based methods, and measures the time taken for each approach.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating the use of BarcodeGenerator, ExportToXml, and ImportFromXml APIs. Developers often need to persist and restore barcode settings for batch processing or configuration sharing, and comparing file and memory‑stream exports helps choose the most efficient method for large configurations.
// Prompt: Measure performance differences between file‑based and stream‑based XML export for large barcode configurations.
-// Tags: barcode symbology, export, xml, performance, file, stream, aspose.barcode
+// Tags: barcode symbology, export, xml, performance, file, stream, aspose.barcode, configuration
using System;
-using System.Diagnostics;
using System.IO;
+using System.Diagnostics;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Program that benchmarks file‑based vs stream‑based XML export of a barcode configuration.
+/// Demonstrates measuring performance differences between file‑based and stream‑based XML export for a large barcode configuration.
///
class Program
{
///
- /// Entry point. Creates a barcode generator with a complex configuration, exports it to XML via file and memory stream,
- /// measures execution time for each method, and outputs the results.
+ /// Entry point. Creates a complex barcode generator, exports its configuration to XML via file and memory stream,
+ /// measures execution time for each, and validates import from the stream.
///
- static void Main(string[] args)
+ static void Main()
{
- // Initialize a barcode generator with a relatively complex configuration
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample1234567890"))
+ // Initialize a barcode generator with a complex configuration to simulate a large setup
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123456"))
{
- // Configure various parameters to simulate a large configuration
+ // Set various barcode parameters
generator.Parameters.Barcode.XDimension.Point = 2f;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
- generator.Parameters.Resolution = 300;
- generator.Parameters.Barcode.BarColor = Color.Blue;
- generator.Parameters.BackColor = Color.White;
+ generator.Parameters.Barcode.BarHeight.Point = 50f;
+ generator.Parameters.Barcode.FilledBars = false;
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
+ generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica";
+ generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f;
+ generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
+ generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
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.Barcode.CodeTextParameters.Font.FamilyName = "Arial";
- generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f;
- generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
- generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ generator.Parameters.Resolution = 300f;
- // ------------------------------
- // Measure file‑based XML export
- // ------------------------------
+ // Measure file‑based XML export performance
var stopwatch = Stopwatch.StartNew();
bool fileExportSuccess = generator.ExportToXml("barcode_config.xml");
stopwatch.Stop();
- long fileExportMs = stopwatch.ElapsedMilliseconds;
+ long fileExportTimeMs = stopwatch.ElapsedMilliseconds;
- // -------------------------------
- // Measure stream‑based XML export
- // -------------------------------
- bool streamExportSuccess;
- long streamExportMs;
+ // Measure stream‑based XML export performance
using (var memoryStream = new MemoryStream())
{
stopwatch.Restart();
- streamExportSuccess = generator.ExportToXml(memoryStream);
+ bool streamExportSuccess = generator.ExportToXml(memoryStream);
stopwatch.Stop();
- streamExportMs = stopwatch.ElapsedMilliseconds;
+ long streamExportTimeMs = stopwatch.ElapsedMilliseconds;
- // Reset stream position and import back to verify correctness
+ // Verify that the exported stream can be imported back successfully
memoryStream.Position = 0;
- var importedGenerator = BarcodeGenerator.ImportFromXml(memoryStream);
- // Dispose imported generator (it implements IDisposable)
- importedGenerator.Dispose();
- }
+ using (var importedGenerator = BarcodeGenerator.ImportFromXml(memoryStream))
+ {
+ // Import validation only; no further actions required
+ }
- // Output the benchmark results
- Console.WriteLine($"File export: {(fileExportSuccess ? "Success" : "Failed")} in {fileExportMs} ms");
- Console.WriteLine($"Stream export: {(streamExportSuccess ? "Success" : "Failed")} in {streamExportMs} ms");
+ // Output the results
+ Console.WriteLine($"File export success: {fileExportSuccess}, time: {fileExportTimeMs} ms");
+ Console.WriteLine($"Stream export success: {streamExportSuccess}, time: {streamExportTimeMs} ms");
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/restore-barcodegenerator-instance-from-xml-data-stored-in-memorystream-via-importfromxml-stream.cs b/barcode-configuration-serialization/restore-barcodegenerator-instance-from-xml-data-stored-in-memorystream-via-importfromxml-stream.cs
index 993218f..2e82400 100644
--- a/barcode-configuration-serialization/restore-barcodegenerator-instance-from-xml-data-stored-in-memorystream-via-importfromxml-stream.cs
+++ b/barcode-configuration-serialization/restore-barcodegenerator-instance-from-xml-data-stored-in-memorystream-via-importfromxml-stream.cs
@@ -1,7 +1,8 @@
-// Title: Restore BarcodeGenerator from XML in MemoryStream
-// Description: Demonstrates exporting a BarcodeGenerator's settings to XML, storing it in a MemoryStream, and recreating the generator via ImportFromXml.
+// Title: Restore BarcodeGenerator from XML using ImportFromXml
+// Description: Demonstrates exporting a BarcodeGenerator's settings to XML stored in a MemoryStream and then restoring a new instance via ImportFromXml.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating how to serialize and deserialize barcode generator settings using XML. It showcases key API classes such as BarcodeGenerator, EncodeTypes, and BarCodeImageFormat, which developers use to persist barcode configurations, share them across services, or recreate barcodes without reapplying settings manually.
// Prompt: Restore a BarcodeGenerator instance from XML data stored in a MemoryStream via ImportFromXml(Stream).
-// Tags: barcode, symbology, code128, xml, import, export, memorystream, aspose.barcodes, generation
+// Tags: barcode, code128, xml, import, export, memorystream, aspose.barcode, generator, png
using System;
using System.IO;
@@ -9,40 +10,39 @@
using Aspose.BarCode.Generation;
///
-/// Example program that shows how to export a configuration to XML,
-/// store it in a , and then restore a new generator instance from that XML.
+/// Example program that exports a BarcodeGenerator's configuration to XML,
+/// then restores a new generator instance from that XML using a MemoryStream.
///
class Program
{
///
- /// Entry point of the example. Creates a barcode, exports its settings to XML,
- /// imports the settings back, and saves the resulting barcode image.
+ /// Entry point of the example. Performs export, import, and saves the restored barcode image.
///
static void Main()
{
- // Initialize a barcode generator with Code128 symbology and sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Initialize the original barcode generator with Code128 symbology and sample text.
+ using (BarcodeGenerator originalGenerator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
{
- // Optionally configure image dimensions.
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
-
- // Export the generator's configuration to an in‑memory XML stream.
- using (var xmlStream = new MemoryStream())
+ // Create a memory stream to hold the XML representation of the generator.
+ using (MemoryStream xmlStream = new MemoryStream())
{
- generator.ExportToXml(xmlStream);
+ // Export the generator's settings to the memory stream as XML.
+ originalGenerator.ExportToXml(xmlStream);
- // Rewind the stream so it can be read from the beginning.
+ // Reset the stream position to the beginning so it can be read.
xmlStream.Position = 0;
- // Create a new generator instance by importing the XML data.
- using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlStream))
- {
- // Save the barcode image generated from the imported settings.
- string outputPath = "imported_barcode.png";
- importedGenerator.Save(outputPath);
- Console.WriteLine($"Barcode image saved to: {outputPath}");
- }
+ // Import a new BarcodeGenerator instance from the XML data in the stream.
+ BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(xmlStream);
+
+ // Save the restored barcode image to a PNG file.
+ importedGenerator.Save("restored.png", BarCodeImageFormat.Png);
+
+ // Release resources used by the imported generator.
+ importedGenerator.Dispose();
+
+ // Inform the user that the process completed successfully.
+ Console.WriteLine("Barcode restored from XML and saved as 'restored.png'.");
}
}
}
diff --git a/barcode-configuration-serialization/serialize-barcode-generation-settings-to-memorystream-by-calling-exporttoxml-stream-method-directly.cs b/barcode-configuration-serialization/serialize-barcode-generation-settings-to-memorystream-by-calling-exporttoxml-stream-method-directly.cs
index 4716877..5d29924 100644
--- a/barcode-configuration-serialization/serialize-barcode-generation-settings-to-memorystream-by-calling-exporttoxml-stream-method-directly.cs
+++ b/barcode-configuration-serialization/serialize-barcode-generation-settings-to-memorystream-by-calling-exporttoxml-stream-method-directly.cs
@@ -1,43 +1,44 @@
// Title: Serialize barcode generation settings to XML in memory
-// Description: Demonstrates exporting Aspose.BarCode generator settings to a MemoryStream using ExportToXml.
+// Description: Demonstrates exporting Aspose.BarCode generation settings to a MemoryStream as XML, useful for persisting or transmitting configuration.
+// Category-Description: This example belongs to the Aspose.BarCode configuration serialization category, illustrating how to use BarcodeGenerator and its ExportToXml method to capture generation parameters. Developers often need to save or share barcode settings across services, and this pattern shows the typical API usage with MemoryStream for in‑memory handling.
// Prompt: Serialize barcode generation settings to a MemoryStream by calling ExportToXml(Stream) method directly.
-// Tags: barcode, serialization, xml, memorystream, aspose.barcode, export
+// Tags: barcode, serialization, xml, memorystream, aspnet, aspnetcore, aspose.barcode, code128, generation
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
-namespace BarcodeExportExample
+///
+/// Demonstrates exporting barcode generation settings to an in‑memory XML representation.
+///
+class Program
{
///
- /// Provides an example of exporting barcode generation settings to a MemoryStream as XML.
+ /// Entry point that creates a Code128 barcode generator, configures parameters, and exports its settings to XML via a MemoryStream.
///
- class Program
+ static void Main()
{
- ///
- /// Entry point of the example. Creates a barcode generator, customizes settings,
- /// and serializes those settings to a memory stream using ExportToXml.
- ///
- static void Main()
+ // Initialize a barcode generator for Code128 with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Initialize a barcode generator for Code128 symbology with sample data.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Set specific generation parameters (X dimension and bar height).
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.Barcode.BarHeight.Point = 40f;
+
+ // Export the generator's configuration to a MemoryStream as XML.
+ using (var memoryStream = new MemoryStream())
{
- // Customize generation parameters (e.g., bar color and module size).
- generator.Parameters.Barcode.BarColor = Color.Blue; // Set the barcode bars to blue.
- generator.Parameters.Barcode.XDimension.Point = 2f; // Define the X-dimension (module width) in points.
+ bool success = generator.ExportToXml(memoryStream);
+ Console.WriteLine($"Export to XML successful: {success}");
- // Prepare a memory stream to hold the exported XML.
- using (var memoryStream = new MemoryStream())
+ // Rewind the stream to the beginning to read the XML content.
+ memoryStream.Position = 0;
+ using (var reader = new StreamReader(memoryStream))
{
- // Export the current generator settings to the memory stream as XML.
- bool exportResult = generator.ExportToXml(memoryStream);
-
- // Output the result of the export operation and the size of the generated XML.
- Console.WriteLine($"Export successful: {exportResult}");
- Console.WriteLine($"XML size in bytes: {memoryStream.Length}");
+ string xmlContent = reader.ReadToEnd();
+ Console.WriteLine("Exported XML:");
+ Console.WriteLine(xmlContent);
}
}
}
diff --git a/barcode-configuration-serialization/serialize-barcodegenerator-with-multi-line-text-and-verify-line-breaks-are-preserved-after-import.cs b/barcode-configuration-serialization/serialize-barcodegenerator-with-multi-line-text-and-verify-line-breaks-are-preserved-after-import.cs
index c5fc9c4..bcc918f 100644
--- a/barcode-configuration-serialization/serialize-barcodegenerator-with-multi-line-text-and-verify-line-breaks-are-preserved-after-import.cs
+++ b/barcode-configuration-serialization/serialize-barcodegenerator-with-multi-line-text-and-verify-line-breaks-are-preserved-after-import.cs
@@ -1,7 +1,8 @@
-// Title: Serialize BarcodeGenerator with Multi-line Text
-// Description: Demonstrates exporting a BarcodeGenerator containing multi-line CodeText to XML and verifying that line breaks are retained after importing.
+// Title: Serialize BarcodeGenerator with multi-line text and verify line breaks
+// Description: Demonstrates how to serialize a BarcodeGenerator containing multi‑line text to XML and ensures that line‑break characters are retained after deserialization.
+// Category-Description: This example belongs to the Aspose.BarCode serialization category, illustrating the use of BarcodeGenerator, ExportToXml, and ImportFromXml for persisting barcode settings. Developers often need to store barcode configurations, share them across services, or archive them, and must guarantee that text data, including line breaks, remains unchanged during the process. The snippet shows best practices for handling multi‑line CodeText and validating integrity after import.
// Prompt: Serialize a BarcodeGenerator with multi‑line text and verify line breaks are preserved after import.
-// Tags: barcode, code128, serialization, xml, multiline, aspnet.barcode
+// Tags: barcode symbology, serialization, xml, code128, barcodelibrary
using System;
using System.IO;
@@ -9,54 +10,52 @@
using Aspose.BarCode.Generation;
///
-/// Example program that shows how to serialize a with multi‑line text,
-/// export its settings to XML, and confirm that line breaks are preserved after re‑importing.
+/// Example program that serializes a with multi‑line text to XML,
+/// then imports it back to verify that line‑break characters are preserved.
///
class Program
{
///
- /// Entry point of the example. Performs the export/import cycle and validates line‑break preservation.
+ /// Entry point of the example. Performs serialization, deserialization, and validation.
///
static void Main()
{
- // Define temporary file paths for the XML settings and the optional PNG image.
- string xmlPath = "barcode.xml";
- string imagePath = "barcode.png";
+ // Define a multi‑line text containing different line‑break characters.
+ string originalText = "Line1\r\nLine2\nLine3\rLine4";
- // Original multi‑line text to be encoded in the barcode.
- string originalText = "Line1\r\nLine2\r\nLine3";
+ // Determine the full path for the temporary XML file used for serialization.
+ string xmlPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.xml");
- // Create a BarcodeGenerator for Code128 and assign the multi‑line CodeText.
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128))
+ // Create a BarcodeGenerator, assign the multi‑line text, and export its settings to XML.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
generator.CodeText = originalText;
-
- // Save a visual representation of the barcode (optional, for verification).
- generator.Save(imagePath);
-
- // Export the generator's configuration, including the CodeText, to an XML file.
generator.ExportToXml(xmlPath);
}
- // Ensure the XML file was created before attempting to import it.
+ // Ensure the XML file was successfully created before proceeding.
if (!File.Exists(xmlPath))
{
- Console.WriteLine("Error: XML file was not created.");
+ Console.WriteLine("Failed to create the XML file.");
return;
}
- // Import the generator settings from the XML file.
- using (BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath))
+ // Import the barcode generator from the previously saved XML file.
+ using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- // Retrieve the CodeText from the imported generator.
- string importedText = importedGenerator.CodeText;
-
- // Verify that the line breaks in the imported text match the original.
- bool isPreserved = importedText == originalText;
+ // Compare the imported CodeText with the original to verify line‑break preservation.
+ bool isPreserved = importedGenerator.CodeText == originalText;
+ Console.WriteLine($"Line breaks preserved after import: {isPreserved}");
+ }
- Console.WriteLine("Line breaks preserved: " + isPreserved);
- Console.WriteLine("Imported CodeText:");
- Console.WriteLine(importedText);
+ // Attempt to delete the temporary XML file; ignore any errors during cleanup.
+ try
+ {
+ File.Delete(xmlPath);
+ }
+ catch
+ {
+ // Cleanup failure is non‑critical; no action required.
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/test-that-importfromxml-correctly-interprets-xml-namespaces-when-file-includes-additional-metadata.cs b/barcode-configuration-serialization/test-that-importfromxml-correctly-interprets-xml-namespaces-when-file-includes-additional-metadata.cs
index c4e0eec..759e78f 100644
--- a/barcode-configuration-serialization/test-that-importfromxml-correctly-interprets-xml-namespaces-when-file-includes-additional-metadata.cs
+++ b/barcode-configuration-serialization/test-that-importfromxml-correctly-interprets-xml-namespaces-when-file-includes-additional-metadata.cs
@@ -1,95 +1,69 @@
-// Title: ImportFromXml with XML namespaces handling demonstration
-// Description: Shows how to export a barcode generator to XML, inject extra namespaced metadata, and import it back, verifying that namespaces are correctly interpreted.
+// Title: Import barcode settings from XML with namespace handling
+// Description: Demonstrates using Aspose.BarCode's ImportFromXml to generate a barcode from an XML configuration that includes namespaces and extra metadata.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to load barcode settings from an XML file using the BarcodeGenerator class. Typical use cases involve configuring barcodes via external XML files, handling namespaces, and integrating metadata. Developers often need to import settings, generate images, and verify readability in automated workflows.
// Prompt: Test that ImportFromXml correctly interprets XML namespaces when the file includes additional metadata.
-// Tags: barcode, import, xml, namespaces, code128, aspose.barcodes
+// Tags: barcode symbology, generation, png, importfromxml, aspose.barcode
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates exporting a barcode to XML, adding extra namespaced metadata, and importing it back using Aspose.BarCode.
+/// Example program that imports barcode generation settings from an XML file,
+/// creates a barcode image, and verifies that the barcode can be read back.
///
class Program
{
///
- /// Entry point of the example. Performs export, modification, import, and validation steps.
+ /// Entry point of the example. Writes an XML configuration, imports it,
+ /// generates a barcode image, and reads the barcode to confirm correctness.
///
static void Main()
{
- // Paths for temporary files
- string xmlPath = "barcode.xml";
- string modifiedXmlPath = "barcode_modified.xml";
+ // Define XML configuration with a namespace and extra metadata
+ string xmlContent = @"
+
+ Code128
+ Test123
+
+ TestUser
+ Sample barcode generated from XML
+
+";
- // Step 1: Create a barcode generator and set a property
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
- {
- // Set the barcode color to blue
- generator.Parameters.Barcode.BarColor = Color.Blue;
-
- // Export the generator settings to XML
- generator.ExportToXml(xmlPath);
- }
-
- // Verify the original XML file exists
- if (!File.Exists(xmlPath))
- {
- Console.WriteLine("Failed to create the original XML file.");
- return;
- }
+ // Paths for the temporary XML file and the resulting barcode image
+ string xmlPath = "barcode_config.xml";
+ string imagePath = "imported_barcode.png";
- // Step 2: Load the XML and insert additional metadata with its own namespace
- string xmlContent = File.ReadAllText(xmlPath);
+ // Write the XML configuration to a file on disk
+ File.WriteAllText(xmlPath, xmlContent);
- // Find the position before the closing root element to insert extra data
- int insertPos = xmlContent.LastIndexOf("", StringComparison.Ordinal);
- if (insertPos == -1)
+ // Import barcode generator settings from the XML file
+ using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath))
{
- Console.WriteLine("Unexpected XML format.");
- return;
+ // Save the generated barcode image in PNG format
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Define extra metadata using a custom namespace
- string extraMetadata = @"
-
- Sample metadata
-
-";
-
- // Insert the extra metadata into the original XML content
- string modifiedXml = xmlContent.Insert(insertPos, extraMetadata);
- File.WriteAllText(modifiedXmlPath, modifiedXml);
-
- // Verify the modified XML file exists
- if (!File.Exists(modifiedXmlPath))
- {
- Console.WriteLine("Failed to create the modified XML file.");
- return;
- }
-
- // Step 3: Import the barcode generator from the modified XML
- BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(modifiedXmlPath);
- if (importedGenerator == null)
- {
- Console.WriteLine("ImportFromXml returned null.");
- return;
- }
-
- // Output key properties to confirm successful import
- Console.WriteLine("Imported CodeText: " + importedGenerator.CodeText);
- Console.WriteLine("Imported BarColor: " + importedGenerator.Parameters.Barcode.BarColor.Name);
-
- // Clean up temporary files (optional)
- try
+ // Verify that the barcode image was created and can be decoded
+ if (File.Exists(imagePath))
{
- File.Delete(xmlPath);
- File.Delete(modifiedXmlPath);
+ // Initialize a reader for Code128 barcodes
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ {
+ // Iterate through all detected barcodes and output their decoded text
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ Console.WriteLine("Decoded CodeText: " + result.CodeText);
+ }
+ }
}
- catch
+ else
{
- // Ignored - cleanup not critical for the test
+ Console.WriteLine("Failed to generate barcode image.");
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/use-exporttoxml-to-generate-configuration-files-for-different-barcode-standards-and-store-them-in-version-control.cs b/barcode-configuration-serialization/use-exporttoxml-to-generate-configuration-files-for-different-barcode-standards-and-store-them-in-version-control.cs
index fbc55b3..5ab3b30 100644
--- a/barcode-configuration-serialization/use-exporttoxml-to-generate-configuration-files-for-different-barcode-standards-and-store-them-in-version-control.cs
+++ b/barcode-configuration-serialization/use-exporttoxml-to-generate-configuration-files-for-different-barcode-standards-and-store-them-in-version-control.cs
@@ -1,71 +1,79 @@
-// Title: Export barcode configurations to XML files
-// Description: Demonstrates using ExportToXml to create XML configuration files for various barcode symbologies, useful for version‑controlled settings.
+// Title: Export barcode generator configurations to XML files
+// Description: Demonstrates how to use Aspose.BarCode's ExportToXml method to create XML configuration files for various barcode symbologies, useful for version‑controlled settings.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showcasing the use of BarcodeGenerator and its Parameters API to define visual and encoding options, then persisting them with ExportToXml. Developers often need to store barcode settings in source control to ensure consistent generation across environments and CI pipelines.
// Prompt: Use ExportToXml to generate configuration files for different barcode standards and store them in version control.
-// Tags: barcode symbology, export, xml, configuration, aspose.barcode
+// Tags: barcode symbology, export, xml, configuration, aspose.barcode, generator, version control
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode;
using Aspose.Drawing;
///
-/// Generates XML configuration files for multiple barcode symbologies using Aspose.BarCode.
+/// Generates barcode configuration XML files for multiple symbologies using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Creates a folder, iterates over barcode definitions, applies specific settings, and exports each configuration to XML.
+ /// Entry point of the example. Creates an output folder, defines barcode configurations,
+ /// exports each configuration to XML, and reports the result.
///
static void Main()
{
- // Define the directory where XML configuration files will be saved
- string configDir = Path.Combine(Directory.GetCurrentDirectory(), "Configs");
- if (!Directory.Exists(configDir))
+ // Ensure the output directory exists
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "BarcodeConfigs");
+ if (!Directory.Exists(outputDir))
{
- // Create the directory if it does not already exist
- Directory.CreateDirectory(configDir);
+ Directory.CreateDirectory(outputDir);
}
- // List of barcode specifications: symbology type, sample code text, and target XML file name
- var barcodeInfos = new (BaseEncodeType type, string codeText, string fileName)[]
+ // Define a set of barcode configurations to export
+ var configs = new (BaseEncodeType EncodeType, string CodeText, string FileName)[]
{
- (EncodeTypes.Code128, "1234567890", "Code128Config.xml"),
- (EncodeTypes.QR, "Hello QR", "QRConfig.xml"),
- (EncodeTypes.DataMatrix, "DMTest", "DataMatrixConfig.xml"),
- (EncodeTypes.AustraliaPost, "5912345678ABCde", "AustraliaPostConfig.xml")
+ (EncodeTypes.Code128, "ABC123456", "Code128Config.xml"),
+ (EncodeTypes.QR, "https://example.com", "QRConfig.xml"),
+ (EncodeTypes.DataMatrix, "DataMatrixSample", "DataMatrixConfig.xml"),
+ (EncodeTypes.AustraliaPost, "1100000000", "AustraliaPostConfig.xml"),
+ (EncodeTypes.OneCode, "12345678901234567890", "OneCodeConfig.xml")
};
- // Process each barcode definition
- foreach (var info in barcodeInfos)
+ // Export each configuration to an XML file
+ foreach (var cfg in configs)
{
- // Initialize a generator for the specified symbology and code text
- using (var generator = new BarcodeGenerator(info.type, info.codeText))
- {
- // Apply symbology‑specific parameters when required
- if (info.type == EncodeTypes.QR)
- {
- // Set a high error correction level for QR codes
- generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
- }
- else if (info.type == EncodeTypes.AustraliaPost)
- {
- // Use CTable encoding for Australian Post barcodes (customer information)
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
- }
+ ExportBarcodeConfiguration(cfg.EncodeType, cfg.CodeText, Path.Combine(outputDir, cfg.FileName));
+ }
- // Build the full path for the XML output file
- string xmlPath = Path.Combine(configDir, info.fileName);
+ Console.WriteLine("Barcode configuration XML files have been generated in: " + outputDir);
+ }
- // Export the generator's configuration to an XML file
- bool success = generator.ExportToXml(xmlPath);
+ ///
+ /// Creates a with the specified encoding type and text,
+ /// applies optional visual settings, and exports the configuration to an XML file.
+ ///
+ /// The barcode symbology to use.
+ /// The data to encode.
+ /// The full path where the XML configuration will be saved.
+ static void ExportBarcodeConfiguration(BaseEncodeType encodeType, string codeText, string xmlPath)
+ {
+ // Initialize the generator with the desired symbology and data
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
+ // Optional visual settings
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ generator.Parameters.Barcode.XDimension.Point = 2f; // module size
+ 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;
- // Report the result of the export operation
- Console.WriteLine($"{info.fileName}: Export {(success ? "succeeded" : "failed")}");
+ // Export the generator's settings to an XML file
+ bool success = generator.ExportToXml(xmlPath);
+ if (!success)
+ {
+ Console.WriteLine($"Failed to export configuration for {encodeType.TypeName} to {xmlPath}");
}
}
-
- // Indicate that all exports have completed
- Console.WriteLine("Barcode configuration export completed.");
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/use-exporttoxml-with-filestream-opened-in-append-mode-to-concatenate-multiple-configuration-snapshots.cs b/barcode-configuration-serialization/use-exporttoxml-with-filestream-opened-in-append-mode-to-concatenate-multiple-configuration-snapshots.cs
index a98f186..1653865 100644
--- a/barcode-configuration-serialization/use-exporttoxml-with-filestream-opened-in-append-mode-to-concatenate-multiple-configuration-snapshots.cs
+++ b/barcode-configuration-serialization/use-exporttoxml-with-filestream-opened-in-append-mode-to-concatenate-multiple-configuration-snapshots.cs
@@ -1,62 +1,69 @@
-// Title: Export Multiple Barcode Configurations to a Single XML File
-// Description: Demonstrates using ExportToXml with a FileStream opened in Append mode to concatenate several barcode configuration snapshots into one XML document.
+// Title: Export barcode configurations to XML using Append mode
+// Description: Demonstrates how to export multiple Aspose.BarCode generator configurations to a single XML file by appending each snapshot, and then import the first configuration back.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating the use of BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml for persisting and reusing barcode settings. Developers often need to store generator parameters, share them across services, or version‑control configurations; the key API classes involved are BarcodeGenerator, its Parameters property, and the XML import/export methods.
// Prompt: Use ExportToXml with a FileStream opened in Append mode to concatenate multiple configuration snapshots.
-// Tags: barcode, export, xml, configuration, append, aspose.barcode, c#
+// Tags: barcode symbology, export, xml, configuration, aspose.barcode, fileio
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that creates several barcode generators,
-/// modifies a property, and appends each generator's configuration
-/// to a single XML file using ExportToXml.
+/// Shows how to concatenate multiple barcode generator configurations into a single XML file
+/// and later import a configuration to generate a barcode image.
///
class Program
{
///
- /// Entry point. Generates barcode configurations and concatenates
- /// their XML representations into config.xml.
+ /// Entry point of the example. Exports two barcode configurations to an XML file,
+ /// then imports the first configuration and saves the resulting barcode image.
///
static void Main()
{
- // Path of the XML file that will hold all concatenated configuration snapshots
- const string xmlFilePath = "config.xml";
-
- // Ensure the file exists; create an empty file if it does not
- if (!File.Exists(xmlFilePath))
+ // ------------------------------------------------------------
+ // Create the first barcode generator (Code128) and modify a setting
+ // ------------------------------------------------------------
+ using (var generator1 = new BarcodeGenerator(EncodeTypes.Code128, "FirstSample"))
{
- using (var createStream = new FileStream(xmlFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
+ // Change the X-dimension (module width) to 2 points
+ generator1.Parameters.Barcode.XDimension.Point = 2f;
+
+ // Append the generator's configuration to the XML file
+ using (var appendStream = new FileStream("barcodeConfigs.xml", FileMode.Append, FileAccess.Write, FileShare.Read))
{
- // Empty file created – no content needed at this point
+ generator1.ExportToXml(appendStream);
}
}
- // Sample barcode texts to be used for generating configurations
- string[] codeTexts = { "ABC123", "DEF456", "GHI789" };
-
- // Iterate over each sample text, generate a barcode, and export its configuration
- foreach (string text in codeTexts)
+ // ------------------------------------------------------------
+ // Create the second barcode generator (QR) and set error correction level
+ // ------------------------------------------------------------
+ using (var generator2 = new BarcodeGenerator(EncodeTypes.QR, "SecondSample"))
{
- // Initialize a barcode generator with Code128 symbology and the current text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text))
- {
- // Example of customizing a generator property (set barcode bar color to blue)
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue;
+ // Set QR error correction to the highest level (Level H)
+ generator2.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
- // Open the XML file in Append mode so each configuration is added sequentially
- using (var stream = new FileStream(xmlFilePath, FileMode.Append, FileAccess.Write, FileShare.None))
- {
- // Export the current generator's configuration to the XML stream
- bool exported = generator.ExportToXml(stream);
- Console.WriteLine($"Exported configuration for '{text}': {exported}");
- }
+ // Append the second configuration to the same XML file
+ using (var appendStream = new FileStream("barcodeConfigs.xml", FileMode.Append, FileAccess.Write, FileShare.Read))
+ {
+ generator2.ExportToXml(appendStream);
}
}
- // Inform the user that all configurations have been successfully concatenated
- Console.WriteLine("All configurations have been concatenated to " + xmlFilePath);
+ // ------------------------------------------------------------
+ // Load the first configuration from the concatenated XML file
+ // ------------------------------------------------------------
+ using (var readStream = new FileStream("barcodeConfigs.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
+ {
+ // ImportFromXml reads the first XML document found in the stream
+ using (var importedGenerator = BarcodeGenerator.ImportFromXml(readStream))
+ {
+ // Generate and save the barcode image based on the imported settings
+ importedGenerator.Save("importedBarcode.png");
+ Console.WriteLine("Imported barcode saved as importedBarcode.png");
+ }
+ }
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/use-single-xml-file-to-store-array-of-barcode-configurations-and-load-them-sequentially.cs b/barcode-configuration-serialization/use-single-xml-file-to-store-array-of-barcode-configurations-and-load-them-sequentially.cs
index c940322..3a6a6f6 100644
--- a/barcode-configuration-serialization/use-single-xml-file-to-store-array-of-barcode-configurations-and-load-them-sequentially.cs
+++ b/barcode-configuration-serialization/use-single-xml-file-to-store-array-of-barcode-configurations-and-load-them-sequentially.cs
@@ -1,91 +1,72 @@
-// Title: Generate Multiple Barcodes from XML Configuration
-// Description: Loads barcode settings from a single XML file and generates corresponding barcode images sequentially.
+// Title: Generate Barcodes from XML Configurations
+// Description: Demonstrates creating barcode configuration XML files, then loading them to generate barcode images.
+// Category-Description: This example belongs to the Aspose.BarCode generation and configuration management category. It showcases the use of BarcodeGenerator for encoding, exporting settings to XML via ExportToXml, and re‑importing those settings with ImportFromXml to produce images. Developers often need to store barcode definitions centrally (e.g., in XML) for batch processing or dynamic generation scenarios.
// Prompt: Use a single XML file to store an array of barcode configurations and load them sequentially.
-// Tags: barcode, symbology, xml, generation, aspose.barcode, image output
+// Tags: barcode symbology, generation, xml configuration, aspose.barcode, image output
using System;
+using System.Collections.Generic;
using System.IO;
-using System.Xml.Linq;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates loading barcode configurations from an XML file and generating barcode images.
+/// Example program that creates barcode configuration XML files,
+/// then reads each configuration to generate corresponding barcode images.
///
class Program
{
///
- /// Entry point. Reads the XML, creates barcodes, and saves them as PNG files.
+ /// Entry point of the application.
///
static void Main()
{
- // Path to the XML file that contains barcode configurations
- const string xmlPath = "barcodes.xml";
-
- // Verify that the XML file exists before proceeding
- if (!File.Exists(xmlPath))
+ // Define the output directory for generated images and XML configuration files.
+ string outputDir = "Barcodes";
+ if (!Directory.Exists(outputDir))
{
- Console.WriteLine($"XML file not found: {Path.GetFullPath(xmlPath)}");
- return;
+ Directory.CreateDirectory(outputDir);
}
- // Load the XML document into memory
- XDocument doc = XDocument.Load(xmlPath);
-
- // Expect a root element with multiple child elements
- var barcodeElements = doc.Root?.Elements("Barcode");
- if (barcodeElements == null)
+ // List of barcode configurations: type, text, XML file path, and image file path.
+ var configs = new List<(BaseEncodeType type, string text, string xmlFile, string imageFile)>
{
- Console.WriteLine("No elements found in the XML.");
- return;
- }
+ (EncodeTypes.Code128, "ABC123", Path.Combine(outputDir, "config1.xml"), Path.Combine(outputDir, "code128.png")),
+ (EncodeTypes.QR, "https://example.com", Path.Combine(outputDir, "config2.xml"), Path.Combine(outputDir, "qr.png")),
+ (EncodeTypes.DataMatrix, "DataMatrixSample", Path.Combine(outputDir, "config3.xml"), Path.Combine(outputDir, "datamatrix.png"))
+ };
- // Ensure the output directory exists (creates it if missing)
- string outputDir = "GeneratedBarcodes";
- Directory.CreateDirectory(outputDir);
-
- int index = 1;
- // Iterate over each element and generate the corresponding image
- foreach (var elem in barcodeElements)
+ // --------------------------------------------------------------------
+ // Step 1: Create XML configuration files for each barcode definition.
+ // --------------------------------------------------------------------
+ foreach (var cfg in configs)
{
- // Extract the symbology name (EncodeType) and the text to encode (CodeText)
- string symbologyName = (string)elem.Element("EncodeType");
- string codeText = (string)elem.Element("CodeText");
-
- // Validate required fields
- if (string.IsNullOrWhiteSpace(symbologyName) || string.IsNullOrWhiteSpace(codeText))
+ using (var generator = new BarcodeGenerator(cfg.type, cfg.text))
{
- Console.WriteLine($"Skipping entry #{index}: missing EncodeType or CodeText.");
- index++;
- continue;
- }
-
- // Resolve the symbology name to a BaseEncodeType value using reflection
- var field = typeof(EncodeTypes).GetField(symbologyName);
- if (field == null)
- {
- Console.WriteLine($"Unknown symbology '{symbologyName}' in entry #{index}.");
- index++;
- continue;
- }
-
- BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
-
- // Create the barcode generator with the resolved type and text
- using (var generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Set common visual parameters (optional)
+ // Optional: set visual parameters for the barcode.
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Resolution = 300; // DPI
- // Build the output file path and save the barcode as PNG
- string outputPath = Path.Combine(outputDir, $"barcode_{index}.png");
- generator.Save(outputPath);
- Console.WriteLine($"Generated barcode #{index}: {outputPath}");
+ // Export the current generator settings to an XML file.
+ generator.ExportToXml(cfg.xmlFile);
}
+ }
- index++;
+ // ---------------------------------------------------------------
+ // Step 2: Load each configuration from XML and generate the image.
+ // ---------------------------------------------------------------
+ foreach (var cfg in configs)
+ {
+ // Import a BarcodeGenerator instance from the previously saved XML.
+ using (var generator = BarcodeGenerator.ImportFromXml(cfg.xmlFile))
+ {
+ // Save the generated barcode image to the specified file.
+ generator.Save(cfg.imageFile);
+ Console.WriteLine($"Generated barcode saved to: {cfg.imageFile}");
+ }
}
+
+ Console.WriteLine("All barcodes have been processed.");
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/validate-that-exporttoxml-includes-custom-symbology-options-such-as-checksum-mode-and-encoding-type.cs b/barcode-configuration-serialization/validate-that-exporttoxml-includes-custom-symbology-options-such-as-checksum-mode-and-encoding-type.cs
index 5f34e72..83b28f7 100644
--- a/barcode-configuration-serialization/validate-that-exporttoxml-includes-custom-symbology-options-such-as-checksum-mode-and-encoding-type.cs
+++ b/barcode-configuration-serialization/validate-that-exporttoxml-includes-custom-symbology-options-such-as-checksum-mode-and-encoding-type.cs
@@ -1,80 +1,55 @@
-// Title: ExportToXml with custom symbology options demonstration
-// Description: Shows how to export barcode generator settings, including checksum mode and encoding type, to XML and then import them back.
+// Title: Export QR barcode settings to XML and verify custom symbology options
+// Description: Demonstrates exporting a QR barcode generator's configuration, including checksum and encoding settings, to XML and re-importing it to confirm the options are preserved.
+// Category-Description: This example belongs to the Aspose.BarCode generation and serialization category, showcasing how to use BarcodeGenerator, its Parameters, and the ExportToXml/ImportFromXml APIs. Developers often need to persist barcode settings for later reuse, configuration files, or cross‑application sharing. The snippet illustrates setting custom symbology options, exporting them to an XML stream, and validating that they survive a round‑trip.
// Prompt: Validate that ExportToXml includes custom symbology options such as checksum mode and encoding type.
-// Tags: barcode symbology, export, xml, checksum, encoding, aspose.barcode
+// Tags: barcode symbology, export, xml, checksum, encoding, aspose.barcode, generation
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates exporting barcode generation settings (including custom symbology options)
-/// to XML and importing them back to verify that the options are preserved.
+/// Example program that creates a QR barcode, configures custom symbology options,
+/// exports the generator settings to XML, and verifies that the options are retained
+/// after importing the XML back into a new generator instance.
///
class Program
{
///
- /// Entry point of the example. Executes export/import validation for Codabar and QR symbologies.
+ /// Entry point of the example. Performs the export‑import validation of custom QR barcode options.
///
static void Main()
{
- // Prepare a temporary directory for XML files
- string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo");
- Directory.CreateDirectory(tempDir);
-
- // ---------- Codabar with checksum mode ----------
- string codabarXml = Path.Combine(tempDir, "codabar.xml");
- using (var codabarGen = new BarcodeGenerator(EncodeTypes.Codabar, "A123B"))
- {
- // Set custom checksum mode (Mod10) for Codabar
- codabarGen.Parameters.Barcode.Codabar.ChecksumMode = CodabarChecksumMode.Mod10;
-
- // Export the generator settings to an XML file
- bool exported = codabarGen.ExportToXml(codabarXml);
- Console.WriteLine($"Codabar ExportToXml success: {exported}");
- }
-
- // Import the Codabar settings from XML and validate the checksum mode
- using (var importedCodabar = BarcodeGenerator.ImportFromXml(codabarXml))
- {
- var mode = importedCodabar.Parameters.Barcode.Codabar.ChecksumMode;
- Console.WriteLine($"Imported Codabar ChecksumMode: {mode}");
- }
-
- // ---------- QR with ECI encoding ----------
- string qrXml = Path.Combine(tempDir, "qr.xml");
- using (var qrGen = new BarcodeGenerator(EncodeTypes.QR, "Sample QR"))
- {
- // Set QR encoding mode to ECI and specify UTF-8 as the ECI encoding
- qrGen.Parameters.Barcode.QR.EncodeMode = QREncodeMode.ECIEncoding;
- qrGen.Parameters.Barcode.QR.ECIEncoding = ECIEncodings.UTF8;
-
- // Export the QR generator settings to an XML file
- bool exported = qrGen.ExportToXml(qrXml);
- Console.WriteLine($"QR ExportToXml success: {exported}");
- }
-
- // Import the QR settings from XML and validate the encoding options
- using (var importedQr = BarcodeGenerator.ImportFromXml(qrXml))
- {
- var encodeMode = importedQr.Parameters.Barcode.QR.EncodeMode;
- var eci = importedQr.Parameters.Barcode.QR.ECIEncoding;
- Console.WriteLine($"Imported QR EncodeMode: {encodeMode}");
- Console.WriteLine($"Imported QR ECIEncoding: {eci}");
- }
-
- // Cleanup temporary files (optional)
- try
- {
- File.Delete(codabarXml);
- File.Delete(qrXml);
- Directory.Delete(tempDir);
- }
- catch
+ // Initialize a QR barcode generator with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Test123"))
{
- // Ignore any errors during cleanup
+ // Configure custom symbology options.
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; // Enable checksum calculation.
+ generator.Parameters.Barcode.QR.ECIEncoding = ECIEncodings.UTF8; // Set UTF‑8 encoding for QR data.
+
+ // Export the generator's configuration to an in‑memory XML stream.
+ using (var xmlStream = new MemoryStream())
+ {
+ bool exportResult = generator.ExportToXml(xmlStream);
+ Console.WriteLine($"ExportToXml succeeded: {exportResult}");
+
+ // Reset the stream position to the beginning for reading.
+ xmlStream.Position = 0;
+
+ // Import the settings from the XML stream into a new generator instance.
+ using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlStream))
+ {
+ // Verify that the checksum option was preserved.
+ bool checksumRestored = importedGenerator.Parameters.Barcode.IsChecksumEnabled == EnableChecksum.Yes;
+ // Verify that the encoding type was preserved.
+ bool eciRestored = importedGenerator.Parameters.Barcode.QR.ECIEncoding == ECIEncodings.UTF8;
+
+ Console.WriteLine($"Checksum option restored: {checksumRestored}");
+ Console.WriteLine($"Encoding type restored: {eciRestored}");
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/verify-that-all-visual-properties-such-as-size-color-and-text-persist-after-xml-deserialization.cs b/barcode-configuration-serialization/verify-that-all-visual-properties-such-as-size-color-and-text-persist-after-xml-deserialization.cs
index 09011b0..f5b1059 100644
--- a/barcode-configuration-serialization/verify-that-all-visual-properties-such-as-size-color-and-text-persist-after-xml-deserialization.cs
+++ b/barcode-configuration-serialization/verify-that-all-visual-properties-such-as-size-color-and-text-persist-after-xml-deserialization.cs
@@ -1,105 +1,70 @@
-// Title: Barcode visual properties persistence after XML deserialization
-// Description: Demonstrates creating a barcode with specific visual settings, exporting to XML, importing back, and verifying that size, colors, text, and padding remain unchanged.
+// Title: Verify visual property persistence after XML deserialization
+// Description: Demonstrates creating a barcode, customizing visual properties, exporting to XML, importing back, and confirming that size, color, and text settings remain unchanged.
+// Category-Description: This example belongs to the Aspose.BarCode serialization category, illustrating how to use BarcodeGenerator, ExportToXml, and ImportFromXml for persisting barcode configuration. Developers often need to store barcode settings in XML for later reuse, configuration files, or cross‑application sharing. The snippet shows typical use cases such as saving visual appearance, dimensions, and text attributes.
// Prompt: Verify that all visual properties such as size, color, and text persist after XML deserialization.
-// Tags: barcode, code128, xml, serialization, visual properties, aspose.barcode, c#
+// Tags: barcode symbology, serialization, xml, visual properties, aspose.barcode, code128, generation
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program that creates a barcode, saves its configuration to XML,
-/// reloads it, and checks that visual properties are preserved.
+/// Example program that creates a barcode, customizes its visual appearance,
+/// serializes the settings to XML, deserializes them, and verifies that all
+/// visual properties persist correctly.
///
class Program
{
///
- /// Entry point. Executes the barcode creation, XML export/import, and verification steps.
+ /// Entry point of the example. Executes the barcode generation,
+ /// XML export/import, and property verification steps.
///
static void Main()
{
- // Define file paths for the XML configuration and optional PNG image.
- string xmlPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.xml");
- string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png");
-
- // --------------------------------------------------------------------
- // Create a barcode generator and configure its visual appearance.
- // --------------------------------------------------------------------
+ // Initialize a barcode generator with Code128 symbology and sample text.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
{
- // Set foreground (barcode) and background colors.
+ // Configure visual properties: colors, dimensions, and text formatting.
generator.Parameters.Barcode.BarColor = Color.Blue;
generator.Parameters.BackColor = Color.Yellow;
-
- // Configure image size. AutoSizeMode.Interpolation uses the explicit dimensions.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
generator.Parameters.ImageWidth.Point = 300f;
generator.Parameters.ImageHeight.Point = 150f;
-
- // Define human‑readable text (code text) appearance.
generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial";
generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f;
generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
- // Apply uniform padding around the barcode.
- 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;
-
- // Save the barcode image (optional, provides a visual reference).
- generator.Save(imagePath, BarCodeImageFormat.Png);
-
- // Export the complete generator configuration to an XML file.
- generator.ExportToXml(xmlPath);
- }
-
- // --------------------------------------------------------------------
- // Import the generator configuration from the previously saved XML.
- // --------------------------------------------------------------------
- using (var imported = BarcodeGenerator.ImportFromXml(xmlPath))
- {
- // Verify that colors persisted correctly.
- bool colorsMatch = imported.Parameters.Barcode.BarColor.Equals(Color.Blue) &&
- imported.Parameters.BackColor.Equals(Color.Yellow);
+ // Export the current generator settings to an in‑memory XML stream.
+ using (var xmlStream = new MemoryStream())
+ {
+ generator.ExportToXml(xmlStream);
+ xmlStream.Position = 0; // Reset stream position for reading.
- // Verify that size and auto‑size mode persisted.
- bool sizeMatch = imported.Parameters.ImageWidth.Point == 300f &&
- imported.Parameters.ImageHeight.Point == 150f &&
- imported.Parameters.AutoSizeMode == AutoSizeMode.Interpolation;
+ // Import a new generator instance from the XML data.
+ using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlStream))
+ {
+ // Compare each visual property between the original and imported generators.
+ bool barColorMatch = importedGenerator.Parameters.Barcode.BarColor.ToArgb() == generator.Parameters.Barcode.BarColor.ToArgb();
+ bool backColorMatch = importedGenerator.Parameters.BackColor.ToArgb() == generator.Parameters.BackColor.ToArgb();
+ bool widthMatch = Math.Abs(importedGenerator.Parameters.ImageWidth.Point - generator.Parameters.ImageWidth.Point) < 0.001f;
+ bool heightMatch = Math.Abs(importedGenerator.Parameters.ImageHeight.Point - generator.Parameters.ImageHeight.Point) < 0.001f;
+ bool fontFamilyMatch = importedGenerator.Parameters.Barcode.CodeTextParameters.Font.FamilyName == generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName;
+ bool fontSizeMatch = Math.Abs(importedGenerator.Parameters.Barcode.CodeTextParameters.Font.Size.Point - generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point) < 0.001f;
+ bool alignmentMatch = importedGenerator.Parameters.Barcode.CodeTextParameters.Alignment == generator.Parameters.Barcode.CodeTextParameters.Alignment;
+ bool codeTextMatch = importedGenerator.CodeText == generator.CodeText;
- // Verify that code‑text font settings persisted.
- bool textFontMatch = imported.Parameters.Barcode.CodeTextParameters.Font.FamilyName == "Arial" &&
- imported.Parameters.Barcode.CodeTextParameters.Font.Size.Point == 12f &&
- imported.Parameters.Barcode.CodeTextParameters.Alignment == TextAlignment.Center;
-
- // Verify that padding values persisted.
- bool paddingMatch = imported.Parameters.Barcode.Padding.Left.Point == 5f &&
- imported.Parameters.Barcode.Padding.Top.Point == 5f &&
- imported.Parameters.Barcode.Padding.Right.Point == 5f &&
- imported.Parameters.Barcode.Padding.Bottom.Point == 5f;
-
- // Output verification results to the console.
- Console.WriteLine($"Colors persisted: {colorsMatch}");
- Console.WriteLine($"Size persisted: {sizeMatch}");
- Console.WriteLine($"Text font persisted: {textFontMatch}");
- Console.WriteLine($"Padding persisted: {paddingMatch}");
- }
-
- // --------------------------------------------------------------------
- // Clean up generated files (optional).
- // --------------------------------------------------------------------
- try
- {
- if (File.Exists(xmlPath)) File.Delete(xmlPath);
- if (File.Exists(imagePath)) File.Delete(imagePath);
- }
- catch
- {
- // Suppress any exceptions that occur during cleanup.
+ // Output verification results to the console.
+ Console.WriteLine($"BarColor persisted: {barColorMatch}");
+ Console.WriteLine($"BackColor persisted: {backColorMatch}");
+ Console.WriteLine($"ImageWidth persisted: {widthMatch}");
+ Console.WriteLine($"ImageHeight persisted: {heightMatch}");
+ Console.WriteLine($"FontFamily persisted: {fontFamilyMatch}");
+ Console.WriteLine($"FontSize persisted: {fontSizeMatch}");
+ Console.WriteLine($"TextAlignment persisted: {alignmentMatch}");
+ Console.WriteLine($"CodeText persisted: {codeTextMatch}");
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/write-script-that-loads-barcode-configurations-from-xml-modifies-foreground-color-and-re-exports-them.cs b/barcode-configuration-serialization/write-script-that-loads-barcode-configurations-from-xml-modifies-foreground-color-and-re-exports-them.cs
index af83db0..29bf6b3 100644
--- a/barcode-configuration-serialization/write-script-that-loads-barcode-configurations-from-xml-modifies-foreground-color-and-re-exports-them.cs
+++ b/barcode-configuration-serialization/write-script-that-loads-barcode-configurations-from-xml-modifies-foreground-color-and-re-exports-them.cs
@@ -1,7 +1,8 @@
-// Title: Load and modify barcode configuration XML
-// Description: Demonstrates loading a barcode configuration from an XML file, changing its foreground color, and exporting the modified configuration.
+// Title: Modify barcode configuration XML by changing foreground color
+// Description: Demonstrates loading a barcode configuration from an XML file, updating the bar color, and exporting the modified configuration.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showcasing how to import and export barcode settings using BarcodeGenerator. It highlights common tasks such as adjusting visual properties (e.g., colors) of barcodes programmatically, which developers often need when customizing barcode appearance for different branding or design requirements. Ideal for developers looking to automate barcode style changes across multiple configurations.
// Prompt: Write a script that loads barcode configurations from XML, modifies the foreground color, and re‑exports them.
-// Tags: barcode symbology, configuration, xml, color modification, aspose.barcode, aspose.drawing
+// Tags: barcode, xml, configuration, color, aspose.barcodes, aspose.drawing
using System;
using System.IO;
@@ -9,39 +10,42 @@
using Aspose.Drawing;
///
-/// Example program that imports a barcode configuration from XML,
-/// changes the barcode's foreground color, and exports the updated configuration.
+/// Loads a barcode configuration from an XML file, changes the foreground color,
+/// and saves the modified configuration to a new XML file.
///
class Program
{
///
/// Entry point of the application.
- /// Loads the XML configuration, modifies the bar color, and saves the result.
+ /// Accepts optional command‑line arguments for input and output file paths.
///
- static void Main()
+ /// [0] Input XML path, [1] Output XML path (optional).
+ static void Main(string[] args)
{
- // Input and output XML file paths
- const string inputXmlPath = "barcode_config.xml";
- const string outputXmlPath = "barcode_config_modified.xml";
+ // Determine input XML path: first argument or default filename
+ string inputPath = args.Length > 0 ? args[0] : "barcodeConfig.xml";
- // Verify that the input XML file exists before proceeding
- if (!File.Exists(inputXmlPath))
+ // Determine output XML path: second argument or default filename
+ string outputPath = args.Length > 1 ? args[1] : "barcodeConfig_modified.xml";
+
+ // Verify that the input file exists before proceeding
+ if (!File.Exists(inputPath))
{
- Console.WriteLine($"Input XML file not found: {inputXmlPath}");
+ Console.WriteLine($"Input file not found: {inputPath}");
return;
}
- // Load barcode configuration from XML, modify the foreground color, and save back to XML
- using (var generator = BarcodeGenerator.ImportFromXml(inputXmlPath))
+ // Import barcode configuration from the specified XML file
+ using (var generator = BarcodeGenerator.ImportFromXml(inputPath))
{
- // Change the barcode foreground (bar) color to Red
+ // Update the barcode's foreground (bar) color to red
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Red;
- // Export the modified configuration to a new XML file
- generator.ExportToXml(outputXmlPath);
+ // Export the updated configuration to the designated output XML file
+ generator.ExportToXml(outputPath);
}
- // Inform the user that the modified configuration has been saved
- Console.WriteLine($"Modified barcode configuration saved to: {outputXmlPath}");
+ // Inform the user that the operation completed successfully
+ Console.WriteLine($"Modified barcode configuration saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/barcode-configuration-serialization/write-unit-tests-that-compare-generated-barcode-images-before-and-after-xml-serialization-round-trip.cs b/barcode-configuration-serialization/write-unit-tests-that-compare-generated-barcode-images-before-and-after-xml-serialization-round-trip.cs
index 317e031..8d7b0ac 100644
--- a/barcode-configuration-serialization/write-unit-tests-that-compare-generated-barcode-images-before-and-after-xml-serialization-round-trip.cs
+++ b/barcode-configuration-serialization/write-unit-tests-that-compare-generated-barcode-images-before-and-after-xml-serialization-round-trip.cs
@@ -1,130 +1,107 @@
-// Title: Barcode XML serialization round‑trip verification
-// Description: Demonstrates generating barcodes, exporting settings to XML, re‑importing, and comparing the resulting images to ensure fidelity.
+// Title: Barcode XML Serialization Round‑Trip Image Comparison
+// Description: Demonstrates generating barcodes, exporting settings to XML, re‑importing, and verifying that the resulting images are identical.
+// Category-Description: This example belongs to the Aspose.BarCode serialization category, showcasing how to use BarcodeGenerator, ExportToXml, and ImportFromXml for persisting barcode configurations. Typical use cases include saving barcode settings, transferring them between services, and ensuring visual consistency after deserialization. Developers often need to validate that serialization does not alter the generated output.
// Prompt: Write unit tests that compare generated barcode images before and after XML serialization round‑trip.
-// Tags: barcode, xml serialization, roundtrip, image comparison, unit test, aspose.barcode
+// Tags: barcode, xml serialization, round-trip, image comparison, code128, qr, datamatrix, aspose.barcode, generation
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Linq;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Example program that creates barcodes, serializes their settings to XML,
-/// deserializes them back, and verifies that the generated images are identical.
+/// Example program that generates barcodes, serializes the generator settings to XML,
+/// deserializes them back, and compares the original and round‑trip images for equality.
///
class Program
{
///
- /// Entry point. Executes a series of round‑trip tests for different barcode symbologies.
+ /// Entry point of the example. Iterates over a set of barcode types, performs an XML
+ /// round‑trip of the generator settings, and prints the comparison result.
///
static void Main()
{
- // Define test cases: each tuple contains a symbology type and the text to encode.
- var tests = new (BaseEncodeType type, string text)[]
+ // Define a list of barcode symbologies and sample texts to test.
+ var tests = new List<(BaseEncodeType type, string text)>
{
(EncodeTypes.Code128, "Test123"),
(EncodeTypes.QR, "https://example.com"),
(EncodeTypes.DataMatrix, "DataMatrixSample")
};
- // Run each test and report the result.
+ // Process each test case.
foreach (var (type, text) in tests)
{
- Console.WriteLine($"Testing {type.TypeName} with text \"{text}\"");
- bool result = RunRoundTripTest(type, text);
- Console.WriteLine(result ? "PASS" : "FAIL");
- Console.WriteLine();
- }
- }
-
- ///
- /// Generates a barcode, saves its image, exports its settings to XML,
- /// re‑imports the settings, generates a second image, and compares the two.
- ///
- /// The barcode symbology to use.
- /// The text to encode in the barcode.
- /// True if the two generated images are pixel‑identical; otherwise false.
- static bool RunRoundTripTest(BaseEncodeType encodeType, string codeText)
- {
- // Create a temporary folder for all intermediate files.
- string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeRoundTrip");
- if (!Directory.Exists(tempDir))
- {
- Directory.CreateDirectory(tempDir);
- }
-
- // Build unique file paths for XML and PNG images.
- string xmlPath = Path.Combine(tempDir, $"barcode_{Guid.NewGuid()}.xml");
- string imgPath1 = Path.Combine(tempDir, $"barcode_original_{Guid.NewGuid()}.png");
- string imgPath2 = Path.Combine(tempDir, $"barcode_roundtrip_{Guid.NewGuid()}.png");
-
- // --------------------------------------------------------------------
- // Generate the original barcode and save its image.
- // --------------------------------------------------------------------
- using (var generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Use deterministic size to avoid variations caused by auto‑sizing.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
-
- // Save the first image (optional visual reference).
- generator.Save(imgPath1, BarCodeImageFormat.Png);
-
- // Export the generator's configuration to an XML file.
- generator.ExportToXml(xmlPath);
- }
+ // ------------------------------------------------------------
+ // Generate the original barcode image.
+ // ------------------------------------------------------------
+ byte[] originalImage;
+ using (var generator = new BarcodeGenerator(type, text))
+ {
+ // Set a deterministic parameter to ensure repeatable output.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ originalImage = GetImageBytes(generator);
+ }
- // --------------------------------------------------------------------
- // Import the configuration from XML and generate a second image.
- // --------------------------------------------------------------------
- using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath))
- {
- importedGenerator.Save(imgPath2, BarCodeImageFormat.Png);
- }
+ // ------------------------------------------------------------
+ // Export the generator settings to XML (in‑memory).
+ // ------------------------------------------------------------
+ byte[] xmlData;
+ using (var generator = new BarcodeGenerator(type, text))
+ {
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ using (var xmlStream = new MemoryStream())
+ {
+ generator.ExportToXml(xmlStream);
+ xmlData = xmlStream.ToArray();
+ }
+ }
- // --------------------------------------------------------------------
- // Load both images and compare them pixel by pixel.
- // --------------------------------------------------------------------
- using (var bmp1 = new Bitmap(imgPath1))
- using (var bmp2 = new Bitmap(imgPath2))
- {
- bool identical = CompareBitmaps(bmp1, bmp2);
+ // ------------------------------------------------------------
+ // Import the generator settings from the XML data.
+ // ------------------------------------------------------------
+ BarcodeGenerator importedGenerator;
+ using (var xmlStream = new MemoryStream(xmlData))
+ {
+ importedGenerator = BarcodeGenerator.ImportFromXml(xmlStream);
+ }
- // Clean up temporary files regardless of the comparison outcome.
- try { File.Delete(xmlPath); } catch { }
- try { File.Delete(imgPath1); } catch { }
- try { File.Delete(imgPath2); } catch { }
+ // ------------------------------------------------------------
+ // Generate the barcode image after the XML round‑trip.
+ // ------------------------------------------------------------
+ byte[] roundTripImage;
+ using (importedGenerator)
+ {
+ roundTripImage = GetImageBytes(importedGenerator);
+ }
- return identical;
+ // ------------------------------------------------------------
+ // Compare the two images byte‑by‑byte and output the result.
+ // ------------------------------------------------------------
+ bool imagesEqual = originalImage.SequenceEqual(roundTripImage);
+ Console.WriteLine($"{type.TypeName} round‑trip test: {(imagesEqual ? "PASS" : "FAIL")}");
}
}
///
- /// Compares two bitmaps for exact pixel equality.
+ /// Generates a barcode image using the provided
+ /// and returns the image data as a PNG byte array.
///
- /// First bitmap.
- /// Second bitmap.
- /// True if both bitmaps have identical dimensions and pixel data; otherwise false.
- static bool CompareBitmaps(Bitmap bmp1, Bitmap bmp2)
+ /// Configured barcode generator.
+ /// PNG image bytes.
+ private static byte[] GetImageBytes(BarcodeGenerator generator)
{
- // Quick size check before per‑pixel comparison.
- if (bmp1.Width != bmp2.Width || bmp1.Height != bmp2.Height)
- return false;
-
- // Compare each pixel.
- for (int y = 0; y < bmp1.Height; y++)
+ using (var bitmap = generator.GenerateBarCodeImage())
{
- for (int x = 0; x < bmp1.Width; x++)
+ using (var ms = new MemoryStream())
{
- if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
- return false;
+ bitmap.Save(ms, ImageFormat.Png);
+ return ms.ToArray();
}
}
-
- return true;
}
}
\ No newline at end of file