Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
class Program
{
/// <summary>
/// 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.
/// </summary>
static void Main()
{
// Sample inventory: SKU -> barcode value (Code128)
var inventory = new Dictionary<string, string>
{
{ "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}");
}
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -10,89 +11,95 @@
using Aspose.BarCode.Generation;

/// <summary>
/// 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.
/// </summary>
class Program
{
/// <summary>
/// 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.
/// </summary>
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:
// <Barcode>
// <Symbology>Code128</Symbology>
// <Value>123456</Value>
// </Barcode>
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}");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
class Program
{
/// <summary>
/// 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.
/// </summary>
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);
}
}
Loading
Loading