diff --git a/swiss-qr-code/access-creditor-name-iban-amount-and-currency-properties-from-decoded-swissqrcodetext-instance.cs b/swiss-qr-code/access-creditor-name-iban-amount-and-currency-properties-from-decoded-swissqrcodetext-instance.cs
index 9b66d1d..38937e4 100644
--- a/swiss-qr-code/access-creditor-name-iban-amount-and-currency-properties-from-decoded-swissqrcodetext-instance.cs
+++ b/swiss-qr-code/access-creditor-name-iban-amount-and-currency-properties-from-decoded-swissqrcodetext-instance.cs
@@ -1,68 +1,83 @@
+// Title: Decode Swiss QR Bill and extract creditor details
+// Description: Demonstrates generating a Swiss QR code, decoding it, and accessing creditor name, IBAN, amount, and currency from the decoded SwissQRCodetext.
+// Category-Description: This example belongs to the Aspose.BarCode Swiss QR Bill processing category. It showcases the use of BarcodeGenerator, BarCodeReader, and ComplexCodetextReader to create, read, and parse Swiss QR codes. Developers working with financial QR codes can learn how to encode bill data, generate PNG images, and retrieve structured payment information programmatically.
+// Prompt: Access creditor name, IBAN, amount, and currency properties from the decoded SwissQRCodetext instance.
+// Tags: swissqr, qr, barcode generation, barcode recognition, png, aspose.barcode, financial, payment
+
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.BarCode;
///
-/// Demonstrates creation, encoding, and decoding of a Swiss QR bill using Aspose.BarCode.
+/// Example program that creates a Swiss QR code, decodes it, and extracts key payment fields.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Swiss QR code, saves it to a memory stream, then reads and decodes it.
+ /// Entry point. Generates a Swiss QR barcode, reads it back, and prints creditor details.
///
static void Main()
{
// ------------------------------------------------------------
- // 1. Build the Swiss QR bill codetext with required fields.
+ // 1. Build the Swiss QR bill data model with required fields.
// ------------------------------------------------------------
var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe"; // Creditor's name
- swissQr.Bill.Creditor.CountryCode = "CH"; // Creditor's country (Switzerland)
- swissQr.Bill.Account = "CH9300762011623852957"; // IBAN account number
- swissQr.Bill.Amount = 199.95m; // Payment amount
- swissQr.Bill.Currency = "CHF"; // Currency (mandatory)
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // QR bill version
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Currency = "CHF";
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+
+ // ------------------------------------------------------------
+ // 2. Construct the encoded text that will be embedded in the QR code.
+ // ------------------------------------------------------------
+ string encodedText = swissQr.GetConstructedCodetext();
// ------------------------------------------------------------
- // 2. Encode the codetext into a QR barcode image stored in memory.
+ // 3. Generate a QR barcode image (PNG) containing the Swiss QR text.
// ------------------------------------------------------------
- using (var ms = new MemoryStream())
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, encodedText))
{
- // Generate the QR code and write it as PNG into the memory stream.
- using (var generator = new ComplexBarcodeGenerator(swissQr))
+ using (var ms = new MemoryStream())
{
generator.Save(ms, BarCodeImageFormat.Png);
- }
-
- // Reset stream position to the beginning for reading.
- ms.Position = 0;
+ ms.Position = 0; // Reset stream position for reading.
- // ------------------------------------------------------------
- // 3. Decode the QR barcode from the memory stream.
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(ms, DecodeType.QR))
- {
- // Iterate over all detected barcodes (should be only one).
- foreach (var result in reader.ReadBarCodes())
+ // ------------------------------------------------------------
+ // 4. Read and decode the barcode image from the memory stream.
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
{
- // Attempt to parse the complex Swiss QR codetext.
- var decoded = ComplexCodetextReader.TryDecodeSwissQR(result.CodeText);
- if (decoded != null)
- {
- // Output decoded bill details to the console.
- Console.WriteLine("Creditor Name: " + decoded.Bill.Creditor.Name);
- Console.WriteLine("IBAN: " + decoded.Bill.Account);
- Console.WriteLine("Amount: " + decoded.Bill.Amount);
- Console.WriteLine("Currency: " + decoded.Bill.Currency);
- }
- else
+ var results = reader.ReadBarCodes();
+
+ // ------------------------------------------------------------
+ // 5. Iterate over decoded results and extract Swiss QR bill fields.
+ // ------------------------------------------------------------
+ foreach (var result in results)
{
- // Inform the user if decoding failed.
- Console.WriteLine("Failed to decode SwissQR codetext.");
+ // Attempt to parse the raw code text as a Swiss QR bill.
+ var decodedSwiss = ComplexCodetextReader.TryDecodeSwissQR(result.CodeText);
+ if (decodedSwiss != null)
+ {
+ // Access required properties from the decoded object.
+ string creditorName = decodedSwiss.Bill.Creditor.Name;
+ string iban = decodedSwiss.Bill.Account;
+ decimal amount = decodedSwiss.Bill.Amount;
+ string currency = decodedSwiss.Bill.Currency;
+
+ // Output the extracted values.
+ Console.WriteLine($"Creditor Name: {creditorName}");
+ Console.WriteLine($"IBAN: {iban}");
+ Console.WriteLine($"Amount: {amount}");
+ Console.WriteLine($"Currency: {currency}");
+ }
+ else
+ {
+ Console.WriteLine("Failed to decode Swiss QR codetext.");
+ }
}
}
}
diff --git a/swiss-qr-code/benchmark-time-required-to-decode-swiss-qr-code-images-of-varying-resolutions-using-barcodereader.cs b/swiss-qr-code/benchmark-time-required-to-decode-swiss-qr-code-images-of-varying-resolutions-using-barcodereader.cs
index 429822e..5d5931f 100644
--- a/swiss-qr-code/benchmark-time-required-to-decode-swiss-qr-code-images-of-varying-resolutions-using-barcodereader.cs
+++ b/swiss-qr-code/benchmark-time-required-to-decode-swiss-qr-code-images-of-varying-resolutions-using-barcodereader.cs
@@ -1,3 +1,9 @@
+// Title: Benchmark decoding time for Swiss QR Code images at various resolutions
+// Description: Demonstrates how to generate Swiss QR Code barcodes of different sizes and measure the time required to decode them using Aspose.BarCode's BarCodeReader.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode types such as Swiss QR Code. It showcases the use of ComplexBarcodeGenerator for creating QR bills and BarCodeReader for decoding, a common task for developers building payment processing or QR‑code scanning solutions. The snippet helps compare performance across image resolutions.
+// Prompt: Benchmark the time required to decode Swiss QR Code images of varying resolutions using BarCodeReader.
+// Tags: swiss qr code, barcode generation, barcode decoding, performance benchmark, aspnet.barcode, complexbarcodegenerator, barcodereader
+
using System;
using System.Diagnostics;
using System.IO;
@@ -6,22 +12,47 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates benchmarking of QR code decoding at various image resolutions
-/// using Aspose.BarCode library. Generates a Swiss QR bill barcode, decodes it,
-/// and reports the decoding time for each DPI setting.
+/// Generates Swiss QR Code images at different resolutions and benchmarks the decoding time using BarCodeReader.
///
class Program
{
///
- /// Entry point of the application. Generates a Swiss QR barcode at multiple
- /// resolutions, decodes it, and prints timing and content information.
+ /// Entry point of the example. Iterates over predefined resolutions, creates a Swiss QR Code for each,
+ /// decodes it, and prints the elapsed time.
///
static void Main()
{
- // Define different image resolutions (dots per inch) to benchmark.
- int[] resolutions = { 72, 150, 300, 600 };
+ // Define a set of image resolutions to test (width x height in points)
+ var resolutions = new (int width, int height)[]
+ {
+ (100, 100),
+ (200, 200),
+ (400, 400)
+ };
+
+ // Process each resolution
+ foreach (var res in resolutions)
+ {
+ // Generate a Swiss QR Code image at the specified resolution
+ byte[] imageData = GenerateSwissQrImage(res.width, res.height);
+
+ // Decode the image and measure the time taken
+ double elapsedMs = DecodeImageAndMeasure(imageData);
+
+ // Output the benchmark result
+ Console.WriteLine($"Resolution: {res.width}x{res.height} points - Decode time: {elapsedMs:F2} ms");
+ }
+ }
- // Prepare sample Swiss QR bill data (must be valid for generation).
+ ///
+ /// Generates a Swiss QR Code image with the given width and height (points) and returns the PNG bytes.
+ ///
+ /// Image width in points.
+ /// Image height in points.
+ /// Byte array containing the PNG image.
+ static byte[] GenerateSwissQrImage(int width, int height)
+ {
+ // Prepare Swiss QR Code codetext with required fields
var swissQr = new SwissQRCodetext();
swissQr.Bill.Creditor.Name = "John Doe";
swissQr.Bill.Creditor.CountryCode = "CH";
@@ -29,52 +60,51 @@ static void Main()
swissQr.Bill.Amount = 199.95m;
swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Iterate over each resolution, generate, decode, and report results.
- foreach (int dpi in resolutions)
+ // Create the generator for the complex barcode
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- // Generate Swiss QR barcode image at the specified resolution.
- using (var generator = new ComplexBarcodeGenerator(swissQr))
- {
- generator.Parameters.Resolution = (float)dpi;
-
- // Store the generated image in a memory stream.
- using (var ms = new MemoryStream())
- {
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
+ // Set image size in points
+ generator.Parameters.ImageWidth.Point = (float)width;
+ generator.Parameters.ImageHeight.Point = (float)height;
- // Start timing the decoding process.
- var stopwatch = Stopwatch.StartNew();
-
- // Decode the barcode from the memory stream.
- using (var reader = new BarCodeReader(ms, DecodeType.QR))
- {
- var results = reader.ReadBarCodes();
-
- // Stop timing after decoding completes.
- stopwatch.Stop();
+ // Save to a memory stream in PNG format and return the byte array
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ return ms.ToArray();
+ }
+ }
+ }
- // Output resolution and decoding duration.
- Console.WriteLine($"Resolution: {dpi} DPI");
- Console.WriteLine($"Decoding time: {stopwatch.ElapsedMilliseconds} ms");
+ ///
+ /// Decodes the provided image bytes and returns the elapsed time in milliseconds.
+ ///
+ /// Byte array containing the barcode image.
+ /// Decoding duration in milliseconds.
+ static double DecodeImageAndMeasure(byte[] imageBytes)
+ {
+ using (var ms = new MemoryStream(imageBytes))
+ {
+ // Initialize the reader for all supported barcode types
+ using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
+ {
+ // Start timing
+ var stopwatch = Stopwatch.StartNew();
- // Iterate over all detected barcodes (should be one in this case).
- foreach (var result in results)
- {
- Console.WriteLine($" Detected type: {result.CodeTypeName}");
- Console.WriteLine($" CodeText: {result.CodeText}");
+ // Perform the decoding operation
+ var results = reader.ReadBarCodes();
- // Decode the complex codetext to verify Swiss QR content.
- var decoded = ComplexCodetextReader.TryDecodeSwissQR(result.CodeText);
- if (decoded != null)
- {
- Console.WriteLine($" Decoded Bill Amount: {decoded.Bill.Amount}");
- }
- }
+ // Stop timing
+ stopwatch.Stop();
- Console.WriteLine(); // Blank line for readability between resolutions.
- }
+ // Optionally output decoded text (if any)
+ foreach (var result in results)
+ {
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
}
+
+ // Return elapsed time in milliseconds
+ return stopwatch.Elapsed.TotalMilliseconds;
}
}
}
diff --git a/swiss-qr-code/compare-swiss-qr-code-image-dimensions-and-file-size-using-different-margin-and-module-size-configurations.cs b/swiss-qr-code/compare-swiss-qr-code-image-dimensions-and-file-size-using-different-margin-and-module-size-configurations.cs
index 2e5e556..14e76d7 100644
--- a/swiss-qr-code/compare-swiss-qr-code-image-dimensions-and-file-size-using-different-margin-and-module-size-configurations.cs
+++ b/swiss-qr-code/compare-swiss-qr-code-image-dimensions-and-file-size-using-different-margin-and-module-size-configurations.cs
@@ -1,113 +1,94 @@
+// Title: Compare Swiss QR Code image dimensions and file size with varying margins and module sizes
+// Description: Demonstrates how different margin and module size settings affect the generated Swiss QR Code image dimensions and PNG file size.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on Swiss QR Code creation using ComplexBarcodeGenerator. It shows how to configure padding and XDimension (module size) to control image size, a common requirement for developers generating payment QR codes for Swiss QR‑bill standards.
+// Prompt: Compare Swiss QR Code image dimensions and file size using different margin and module size configurations.
+// Tags: swiss qr code, barcode generation, image dimensions, file size, margin, module size, aspnet.barcode, complexbarcodegenerator, png
+
using System;
-using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of Swiss QR Code images with varying margins and module sizes,
-/// and reports their dimensions and file sizes.
+/// Demonstrates how margin and module size affect Swiss QR Code image dimensions and file size.
///
class Program
{
///
- /// Generates a Swiss QR Code image with the specified margin (padding) and module size (XDimension).
- /// The image is saved to and the same path is returned.
+ /// Entry point. Generates Swiss QR Codes with default and custom configurations and prints their dimensions and file sizes.
///
- /// Full path where the PNG image will be saved.
- /// Margin (padding) to apply on all sides, expressed in points.
- /// Size of a single QR module (XDimension), expressed in points.
- /// The file path of the saved image.
- static string GenerateSwissQr(string filePath, float marginPoints, float moduleSizePoints)
+ static void Main()
{
- // Prepare Swiss QR bill data (valid sample values)
- var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe";
- swissQr.Bill.Creditor.CountryCode = "CH";
- swissQr.Bill.Account = "CH9300762011623852957";
- swissQr.Bill.Amount = 199.95m;
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
-
- // Create a ComplexBarcodeGenerator for the Swiss QR data
- using (var generator = new ComplexBarcodeGenerator(swissQr))
+ // Define two configurations: a default setting and a custom one with larger margin and module size.
+ var configs = new (string Name, float Margin, float ModuleSize)[]
{
- // Apply uniform margin (padding) on all four sides
- generator.Parameters.Barcode.Padding.Left.Point = marginPoints;
- generator.Parameters.Barcode.Padding.Top.Point = marginPoints;
- generator.Parameters.Barcode.Padding.Right.Point = marginPoints;
- generator.Parameters.Barcode.Padding.Bottom.Point = marginPoints;
-
- // Set the module size (XDimension) for the QR code
- generator.Parameters.Barcode.XDimension.Point = moduleSizePoints;
-
- // Save the generated barcode as a PNG file
- generator.Save(filePath, BarCodeImageFormat.Png);
- }
-
- return filePath;
- }
+ ("Default", 5f, 2f), // small margin, default module size
+ ("Custom", 20f, 5f) // larger margin and larger modules
+ };
- ///
- /// Retrieves the width and height (in pixels) of an image file.
- ///
- /// Path to the image file.
- /// A tuple containing the width and height.
- static (int width, int height) GetImageDimensions(string imagePath)
- {
- using (var img = Image.FromFile(imagePath))
+ // Iterate over each configuration, generate the barcode, and display results.
+ foreach (var cfg in configs)
{
- return (img.Width, img.Height);
+ try
+ {
+ var result = GenerateSwissQR(cfg.Name, cfg.Margin, cfg.ModuleSize);
+ Console.WriteLine($"{cfg.Name} Configuration:");
+ Console.WriteLine($" Image Width : {result.Width} px");
+ Console.WriteLine($" Image Height: {result.Height} px");
+ Console.WriteLine($" File Size : {result.FileSize} bytes");
+ Console.WriteLine();
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error generating {cfg.Name} configuration: {ex.Message}");
+ }
}
}
///
- /// Entry point of the application. Generates Swiss QR Code images with different
- /// margin and module size configurations, then prints their dimensions and file sizes.
+ /// Generates a Swiss QR Code using the specified margin and module size, then returns its dimensions and PNG file size.
///
- static void Main()
+ /// Name of the configuration (used for logging only).
+ /// Padding (margin) to apply on all sides, in points.
+ /// Size of a single QR module (XDimension), in points.
+ /// Tuple containing image width, height, and file size in bytes.
+ private static (int Width, int Height, long FileSize) GenerateSwissQR(string configName, float margin, float moduleSize)
{
- // Define configurations: (margin in points, module size in points)
- var configurations = new List<(float margin, float module)>
- {
- (5f, 2f),
- (5f, 3f),
- (10f, 2f),
- (10f, 3f)
- };
-
- // Create a temporary directory to store the generated images
- string outputDir = Path.Combine(Path.GetTempPath(), "SwissQrDemo");
- Directory.CreateDirectory(outputDir);
-
- // Header for console output
- Console.WriteLine("Swiss QR Code dimension and file size comparison:");
- Console.WriteLine("-------------------------------------------------");
- Console.WriteLine("{0,8} {1,8} | {2,6} {3,6} | {4,10}", "Margin", "Module", "Width", "Height", "FileSize");
+ // Prepare Swiss QR code text with mandatory bill fields.
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Process each configuration
- foreach (var cfg in configurations)
+ // Create a ComplexBarcodeGenerator for the Swiss QR code.
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- // Build a descriptive file name based on the current configuration
- string fileName = $"SwissQR_M{cfg.margin}_X{cfg.module}.png";
- string filePath = Path.Combine(outputDir, fileName);
+ // Apply uniform padding (margin) on all sides.
+ generator.Parameters.Barcode.Padding.Left.Point = margin;
+ generator.Parameters.Barcode.Padding.Top.Point = margin;
+ generator.Parameters.Barcode.Padding.Right.Point = margin;
+ generator.Parameters.Barcode.Padding.Bottom.Point = margin;
- // Generate the QR code image
- GenerateSwissQr(filePath, cfg.margin, cfg.module);
+ // Set the module size (XDimension) for the QR code.
+ generator.Parameters.Barcode.XDimension.Point = moduleSize;
- // Retrieve image dimensions
- var (width, height) = GetImageDimensions(filePath);
+ // Generate the barcode image.
+ using (Image image = generator.GenerateBarCodeImage())
+ {
+ // Save the image to a memory stream to determine the PNG file size.
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ long fileSize = ms.Length;
- // Determine file size in bytes
- long fileSize = new FileInfo(filePath).Length;
-
- // Output the results for this configuration
- Console.WriteLine("{0,8} {1,8} | {2,6} {3,6} | {4,10} bytes", cfg.margin, cfg.module, width, height, fileSize);
+ // Return the image dimensions and file size.
+ return (image.Width, image.Height, fileSize);
+ }
+ }
}
-
- // Inform the user where the images have been saved
- Console.WriteLine("\nImages saved to: " + outputDir);
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/configure-complexbarcodegenerator-to-output-barcode-image-with-transparent-background-for-ui-component-overlay.cs b/swiss-qr-code/configure-complexbarcodegenerator-to-output-barcode-image-with-transparent-background-for-ui-component-overlay.cs
index 80c8bec..08fde6e 100644
--- a/swiss-qr-code/configure-complexbarcodegenerator-to-output-barcode-image-with-transparent-background-for-ui-component-overlay.cs
+++ b/swiss-qr-code/configure-complexbarcodegenerator-to-output-barcode-image-with-transparent-background-for-ui-component-overlay.cs
@@ -1,45 +1,51 @@
+// Title: Generate Swiss QR barcode with transparent background
+// Description: Demonstrates configuring ComplexBarcodeGenerator to produce a PNG barcode image with a transparent background, suitable for overlay in UI components.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use ComplexBarcodeGenerator with Swiss QR codetext, set visual parameters like background transparency, and save to PNG. Developers working with QR codes for payment standards or UI overlays often need to customize colors and output formats using the Aspose.BarCode.Generation and Aspose.BarCode.ComplexBarcode APIs.
+// Prompt: Configure ComplexBarcodeGenerator to output a barcode image with transparent background for UI component overlay.
+// Tags: swissqr, qr, transparent background, png, complexbarcodegenerator, aspnet, aspnetcore, barcode generation
+
using System;
using System.IO;
using Aspose.BarCode;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a Swiss QR code barcode with a transparent background
-/// and saving it as a PNG image.
+/// Example program that creates a Swiss QR barcode with a transparent background using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates the barcode and writes the output file path to the console.
+ /// Entry point. Generates the barcode image and saves it as a PNG with transparency.
///
static void Main()
{
- // Define the output file path for the generated barcode image.
- string outputPath = "transparent_barcode.png";
-
- // Create and configure the Swiss QR code text with required bill details.
+ // Prepare SwissQR codetext with required fields
var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe"; // Creditor's name
- swissQr.Bill.Creditor.CountryCode = "CH"; // Creditor's country code (Switzerland)
- swissQr.Bill.Account = "CH9300762011623852957"; // IBAN account number
- swissQr.Bill.Amount = 199.95m; // Invoice amount
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // QR bill version
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Generate the barcode using the configured Swiss QR code text.
+ // Create ComplexBarcodeGenerator with the codetext
using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- // Set the background color of the barcode to transparent.
+ // Set transparent background for the image
generator.Parameters.BackColor = Color.Transparent;
- // Save the barcode as a PNG file with the specified output path.
+ // Optionally set the barcode (foreground) color
+ generator.Parameters.Barcode.BarColor = Color.Black;
+
+ // Define the output file path (current directory)
+ string outputPath = Path.Combine(Environment.CurrentDirectory, "transparent_qr.png");
+
+ // Save the barcode as PNG, which supports transparency
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"Barcode image saved to: {outputPath}");
+ Console.WriteLine("Barcode image generated with transparent background.");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/create-batch-process-to-generate-swiss-qr-code-images-for-invoices-listed-in-csv-file.cs b/swiss-qr-code/create-batch-process-to-generate-swiss-qr-code-images-for-invoices-listed-in-csv-file.cs
index d08719c..7de9d41 100644
--- a/swiss-qr-code/create-batch-process-to-generate-swiss-qr-code-images-for-invoices-listed-in-csv-file.cs
+++ b/swiss-qr-code/create-batch-process-to-generate-swiss-qr-code-images-for-invoices-listed-in-csv-file.cs
@@ -1,127 +1,116 @@
+// Title: Generate Swiss QR Code Images from CSV Invoices
+// Description: Demonstrates batch creation of Swiss QR Code barcodes for invoice data read from a CSV file and saves them as PNG images.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Swiss QR Bill. It showcases using the SwissQRCodetext class and ComplexBarcodeGenerator to encode payment information into QR codes, a common requirement for financial applications and invoicing systems. Developers often need to automate QR code creation for multiple records, handling CSV input and image output.
+// Prompt: Create a batch process to generate Swiss QR Code images for invoices listed in a CSV file.
+// Tags: swiss qr code, batch processing, png, aspose.barcode, complexbarcodegenerator, csv
+
using System;
using System.IO;
using System.Collections.Generic;
+using Aspose.BarCode;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates reading invoice data from a CSV file and generating Swiss QR Code images for each invoice.
+/// Batch processor that reads invoice data from a CSV file and generates Swiss QR Code images.
///
class Program
{
///
- /// Simple invoice data model.
- ///
- class Invoice
- {
- public string InvoiceNumber { get; set; }
- public string Account { get; set; }
- public decimal Amount { get; set; }
- public string CreditorName { get; set; }
- }
-
- ///
- /// Application entry point. Reads invoices, creates output folder, and generates QR code images.
+ /// Entry point of the application. Reads invoices, creates QR codes, and saves them as PNG files.
///
static void Main()
{
- // Input CSV file containing invoice data
- string inputCsv = "invoices.csv";
+ // Path to the input CSV file containing invoice records
+ string csvPath = "invoices.csv";
- // Folder where generated QR code images will be saved
- string outputFolder = "SwissQRImages";
+ // Directory where generated QR code images will be stored
+ string outputFolder = "output";
- // Ensure the output directory exists; create it if missing
+ // Ensure the output directory exists; create it if necessary
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
- // If the CSV file does not exist, create a small sample file for demonstration purposes
- if (!File.Exists(inputCsv))
+ // If the CSV file is missing, create a sample file with example invoices
+ if (!File.Exists(csvPath))
{
- var sampleLines = new[]
+ var sampleLines = new List
{
- "InvoiceNumber,Account,Amount,CreditorName",
- "INV001,CH9300762011623852957,199.95,John Doe",
- "INV002,CH9300762011623852958,250.00,Acme Corp",
- "INV003,CH9300762011623852959,75.50,Global Ltd"
+ "Account,CreditorName,CountryCode,Amount,BillInformation",
+ "CH9300762011623852957,John Doe,CH,199.95,Invoice 001",
+ "CH9300762011623852957,Acme Corp,CH,350.00,Invoice 002",
+ "CH9300762011623852957,Global Ltd,CH,1200.50,Invoice 003"
};
- File.WriteAllLines(inputCsv, sampleLines);
- Console.WriteLine($"Sample CSV created at '{inputCsv}'.");
+ File.WriteAllLines(csvPath, sampleLines);
}
- // Read invoices from the CSV file into a list
- List invoices = new List();
- try
+ // Read all lines from the CSV file
+ string[] lines = File.ReadAllLines(csvPath);
+ if (lines.Length <= 1)
{
- using (var reader = new StreamReader(inputCsv))
- {
- bool isHeader = true; // Skip the first line (header)
- while (!reader.EndOfStream)
- {
- string line = reader.ReadLine();
- if (string.IsNullOrWhiteSpace(line))
- continue; // Ignore empty lines
-
- if (isHeader)
- {
- isHeader = false;
- continue; // Skip header line
- }
-
- // Split CSV line into fields
- string[] parts = line.Split(',');
- if (parts.Length < 4)
- continue; // Skip malformed lines
-
- // Create an Invoice object from the parsed fields
- invoices.Add(new Invoice
- {
- InvoiceNumber = parts[0].Trim(),
- Account = parts[1].Trim(),
- Amount = decimal.Parse(parts[2].Trim()),
- CreditorName = parts[3].Trim()
- });
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error reading CSV: {ex.Message}");
+ Console.WriteLine("No invoice data found in the CSV file.");
return;
}
- // Process each invoice and generate a Swiss QR Code image
- foreach (var inv in invoices)
+ // Process each invoice line, skipping the header row.
+ // Limit processing to a maximum of 5 items for safety in this example.
+ int maxItems = Math.Min(lines.Length - 1, 5);
+ for (int i = 1; i <= maxItems; i++)
{
- try
+ string line = lines[i];
+
+ // Simple CSV split (assumes no commas inside fields)
+ string[] parts = line.Split(',');
+
+ // Validate that the line contains all required columns
+ if (parts.Length < 5)
{
- // Build Swiss QR code data structure
- var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = inv.CreditorName;
- swissQr.Bill.Creditor.CountryCode = "CH";
- swissQr.Bill.Account = inv.Account;
- swissQr.Bill.Amount = inv.Amount;
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
-
- // Determine output file path for the QR code image
- string outputPath = Path.Combine(outputFolder, $"{inv.InvoiceNumber}.png");
-
- // Generate and save the QR code image
- using (var generator = new ComplexBarcodeGenerator(swissQr))
- {
- generator.Save(outputPath, BarCodeImageFormat.Png);
- }
-
- Console.WriteLine($"Generated QR for invoice {inv.InvoiceNumber} -> {outputPath}");
+ Console.WriteLine($"Skipping line {i + 1}: insufficient columns.");
+ continue;
}
- catch (Exception ex)
+
+ // Map CSV columns to local variables
+ string account = parts[0].Trim();
+ string creditorName = parts[1].Trim();
+ string countryCode = parts[2].Trim();
+
+ // Parse the amount; skip the line if parsing fails
+ if (!decimal.TryParse(parts[3].Trim(), out decimal amount))
{
- Console.WriteLine($"Failed to generate QR for invoice {inv.InvoiceNumber}: {ex.Message}");
+ Console.WriteLine($"Skipping line {i + 1}: invalid amount.");
+ continue;
}
+
+ string billInfo = parts[4].Trim();
+
+ // Build the Swiss QR bill data structure
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Account = account;
+ swissQr.Bill.Creditor.Name = creditorName;
+ swissQr.Bill.Creditor.CountryCode = countryCode;
+ swissQr.Bill.Amount = amount;
+ swissQr.Bill.BillInformation = billInfo;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+
+ // Define the output file path for the generated QR code image
+ string outputPath = Path.Combine(outputFolder, $"invoice_{i}.png");
+
+ // Generate and save the QR code image using ComplexBarcodeGenerator
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
+ {
+ // Set barcode and background colors (optional)
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+
+ // Save the QR code as a PNG file
+ generator.Save(outputPath);
+ }
+
+ Console.WriteLine($"Generated QR code for invoice {i} at: {outputPath}");
}
- Console.WriteLine("Processing completed.");
+ Console.WriteLine("Batch processing completed.");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/create-console-app-that-reads-qr-code-images-from-folder-and-writes-payment-details-to-json.cs b/swiss-qr-code/create-console-app-that-reads-qr-code-images-from-folder-and-writes-payment-details-to-json.cs
index 7a62b52..5c457c9 100644
--- a/swiss-qr-code/create-console-app-that-reads-qr-code-images-from-folder-and-writes-payment-details-to-json.cs
+++ b/swiss-qr-code/create-console-app-that-reads-qr-code-images-from-folder-and-writes-payment-details-to-json.cs
@@ -1,109 +1,106 @@
+// Title: QR Code Batch Reader to JSON Export
+// Description: Reads QR code images from a folder, extracts barcode data, and writes payment details to a JSON file.
+// Category-Description: Demonstrates Aspose.BarCode barcode recognition for QR codes, covering image file enumeration, barcode extraction using BarCodeReader, and JSON serialization with System.Text.Json. This example belongs to the “Barcode Recognition and Data Export” category, useful for developers automating payment processing or inventory tracking by converting scanned QR codes into structured data.
+// Prompt: Create a console app that reads QR code images from a folder and writes payment details to JSON.
+// Tags: qr, barcode, recognition, json, aspose.barcode, system.text.json
+
using System;
-using System.IO;
using System.Collections.Generic;
+using System.IO;
using System.Text.Json;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Entry point for the QR code extraction utility.
-/// Scans a folder for image files, extracts QR code text, and writes results to a JSON file.
+/// Represents extracted payment information from a QR code image.
///
-class Program
+class PaymentInfo
{
- ///
- /// Simple DTO to hold extracted QR code data.
- ///
- private class PaymentInfo
- {
- public string FileName { get; set; }
- public string CodeText { get; set; }
- }
+ public string FileName { get; set; }
+ public string CodeText { get; set; }
+ public string CodeTypeName { get; set; }
+ public int X { get; set; }
+ public int Y { get; set; }
+ public int Width { get; set; }
+ public int Height { get; set; }
+}
+///
+/// Entry point of the console application that processes QR code images and outputs JSON.
+///
+class Program
+{
///
- /// Main method processes command‑line arguments, reads images, extracts QR codes, and writes JSON output.
+ /// Main method parses optional input folder argument, reads QR codes, and writes results to JSON.
///
- ///
- /// args[0] – optional input folder path (default: "QRCodes").
- /// args[1] – optional output JSON file path (default: "paymentDetails.json").
- ///
+ /// Command‑line arguments; first argument can specify the input folder.
static void Main(string[] args)
{
- // Resolve input folder: use first argument if provided, otherwise default.
- string inputFolder = args.Length > 0 && !string.IsNullOrWhiteSpace(args[0])
- ? args[0]
- : "QRCodes";
-
- // Resolve output JSON file path: use second argument if provided, otherwise default.
- string outputJsonPath = args.Length > 1 && !string.IsNullOrWhiteSpace(args[1])
- ? args[1]
- : "paymentDetails.json";
+ // Determine the folder containing QR code images; allow override via command‑line argument.
+ string inputFolder = "QrImages";
+ if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0]))
+ {
+ inputFolder = args[0];
+ }
- // Verify that the input folder exists before proceeding.
+ // Verify that the input folder exists.
if (!Directory.Exists(inputFolder))
{
- Console.WriteLine($"Input folder does not exist: {inputFolder}");
+ Console.WriteLine($"Folder not found: {inputFolder}");
return;
}
- // Define supported image file extensions.
- string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif" };
+ // Define supported image extensions.
+ string[] imageExtensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif" };
+ var files = Directory.GetFiles(inputFolder);
var paymentList = new List();
- // Enumerate all files in the input folder.
- foreach (string filePath in Directory.GetFiles(inputFolder))
+ // Iterate over each file in the folder.
+ foreach (var file in files)
{
// Skip files that do not have a supported image extension.
- if (Array.IndexOf(extensions, Path.GetExtension(filePath).ToLowerInvariant()) < 0)
+ string ext = Path.GetExtension(file).ToLowerInvariant();
+ if (Array.IndexOf(imageExtensions, ext) < 0)
continue;
- // Defensive check: ensure the file still exists.
- if (!File.Exists(filePath))
- {
- Console.WriteLine($"File not found (skipped): {filePath}");
+ // Ensure the file still exists before processing.
+ if (!File.Exists(file))
continue;
- }
- try
+ // Open the image with BarCodeReader configured for QR codes.
+ using (var reader = new BarCodeReader(file, DecodeType.QR))
{
- // Load the image using Aspose.Drawing.Bitmap (IDisposable).
- using (var bitmap = new Bitmap(filePath))
+ // Read all barcodes found in the image.
+ var results = reader.ReadBarCodes();
+ foreach (var result in results)
{
- // Initialize a barcode reader configured for QR codes only.
- using (var reader = new BarCodeReader(bitmap, DecodeType.QR))
+ // Extract the bounding rectangle of the detected barcode.
+ var rect = result.Region.Rectangle;
+
+ // Populate a PaymentInfo instance with extracted data.
+ var info = new PaymentInfo
{
- // Iterate over all detected QR codes in the image.
- foreach (var result in reader.ReadBarCodes())
- {
- // Add a new record containing the file name and extracted QR code text.
- paymentList.Add(new PaymentInfo
- {
- FileName = Path.GetFileName(filePath),
- CodeText = result.CodeText
- });
- }
- }
+ FileName = Path.GetFileName(file),
+ CodeText = result.CodeText,
+ CodeTypeName = result.CodeTypeName,
+ X = rect.X,
+ Y = rect.Y,
+ Width = rect.Width,
+ Height = rect.Height
+ };
+
+ // Add the info to the collection.
+ paymentList.Add(info);
}
}
- catch (Exception ex)
- {
- // Log any errors encountered while processing the current file.
- Console.WriteLine($"Error processing '{filePath}': {ex.Message}");
- }
}
- // Serialize the collected payment information to a formatted JSON string.
- try
- {
- var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
- string json = JsonSerializer.Serialize(paymentList, jsonOptions);
- File.WriteAllText(outputJsonPath, json);
- Console.WriteLine($"Successfully wrote {paymentList.Count} record(s) to '{outputJsonPath}'.");
- }
- catch (Exception ex)
- {
- // Log any errors that occur during JSON serialization or file writing.
- Console.WriteLine($"Failed to write JSON output: {ex.Message}");
- }
+ // Serialize the collected payment details to a formatted JSON string.
+ string outputPath = Path.Combine(inputFolder, "payment_details.json");
+ var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
+ string json = JsonSerializer.Serialize(paymentList, jsonOptions);
+ File.WriteAllText(outputPath, json);
+
+ // Inform the user of the processing result.
+ Console.WriteLine($"Processed {paymentList.Count} barcode(s). Output written to {outputPath}");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/create-net-method-that-accepts-parameters-and-returns-byte-array-of-swiss-qr-code-png.cs b/swiss-qr-code/create-net-method-that-accepts-parameters-and-returns-byte-array-of-swiss-qr-code-png.cs
index 7159c03..49a07e2 100644
--- a/swiss-qr-code/create-net-method-that-accepts-parameters-and-returns-byte-array-of-swiss-qr-code-png.cs
+++ b/swiss-qr-code/create-net-method-that-accepts-parameters-and-returns-byte-array-of-swiss-qr-code-png.cs
@@ -1,74 +1,66 @@
+// Title: Generate Swiss QR Code PNG as byte array
+// Description: Demonstrates creating a Swiss QR Code barcode and returning the PNG image as a byte array.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Swiss QR Code. It showcases the use of ComplexBarcodeGenerator, SwissQRCodetext, and BarCodeImageFormat to produce PNG output, a common requirement for payment QR codes in financial applications.
+// Prompt: Create a .NET method that accepts parameters and returns a byte array of the Swiss QR Code PNG.
+// Tags: swiss qr code, barcode generation, png output, aspose.barcode, complexbarcodegenerator
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
-namespace BarcodeDemo
+///
+/// Demonstrates generation of a Swiss QR Code barcode and returns the PNG image as a byte array.
+///
+class Program
{
///
- /// Demonstrates generation of a Swiss QR Code barcode and saving it as a PNG file.
+ /// Generates a Swiss QR Code PNG and returns it as a byte array.
///
- class Program
+ /// Name of the creditor (mandatory).
+ /// ISO country code of the creditor (e.g., "CH").
+ /// IBAN account number (must be a valid Swiss IBAN).
+ /// Invoice amount.
+ /// Byte array containing the PNG image of the generated Swiss QR Code.
+ public static byte[] GenerateSwissQrCode(string creditorName, string creditorCountryCode, string account, decimal amount)
{
- ///
- /// Entry point of the application. Generates a Swiss QR Code PNG byte array,
- /// displays its length, and optionally writes it to a file.
- ///
- static void Main()
- {
- // Sample data for Swiss QR Code
- string account = "CH9300762011623852957";
- decimal amount = 199.95m;
- string creditorName = "John Doe";
-
- // Generate PNG bytes using the helper method
- byte[] pngBytes = GenerateSwissQrCode(account, amount, creditorName);
-
- // Output the size of the generated byte array for verification
- Console.WriteLine($"Generated Swiss QR Code PNG byte array length: {pngBytes.Length}");
+ // Prepare the Swiss QR Code data structure.
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Creditor.Name = creditorName;
+ swissQr.Bill.Creditor.CountryCode = creditorCountryCode;
+ swissQr.Bill.Account = account;
+ swissQr.Bill.Amount = amount;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Save the PNG to disk for manual inspection (optional)
- string outputPath = "SwissQR.png";
- using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
+ // Generate the barcode image into a memory stream.
+ using (var memoryStream = new MemoryStream())
+ {
+ // ComplexBarcodeGenerator creates the QR code based on the provided data.
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- fileStream.Write(pngBytes, 0, pngBytes.Length);
+ // Save the generated barcode as PNG into the memory stream.
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
}
- Console.WriteLine($"Saved PNG to {outputPath}");
+ // Return the PNG bytes from the memory stream.
+ return memoryStream.ToArray();
}
+ }
- // Generates a Swiss QR Code PNG and returns it as a byte array.
- public static byte[] GenerateSwissQrCode(
- string account,
- decimal amount,
- string creditorName,
- string creditorCountryCode = "CH",
- SwissQRBill.QrBillStandardVersion version = SwissQRBill.QrBillStandardVersion.V2_0)
- {
- // Validate required parameters
- if (string.IsNullOrWhiteSpace(account))
- throw new ArgumentException("Account is required.", nameof(account));
- if (string.IsNullOrWhiteSpace(creditorName))
- throw new ArgumentException("Creditor name is required.", nameof(creditorName));
-
- // Populate Swiss QR codetext with mandatory fields
- var swissQr = new SwissQRCodetext();
- swissQr.Bill.Account = account;
- swissQr.Bill.Amount = amount;
- swissQr.Bill.Creditor.Name = creditorName;
- swissQr.Bill.Creditor.CountryCode = creditorCountryCode;
- swissQr.Bill.Version = version;
+ ///
+ /// Entry point that calls with sample data and writes the result length to console.
+ ///
+ static void Main()
+ {
+ // Sample data for demonstration purposes.
+ var pngBytes = GenerateSwissQrCode(
+ creditorName: "John Doe",
+ creditorCountryCode: "CH",
+ account: "CH9300762011623852957",
+ amount: 199.95m);
- // Generate barcode image into a memory stream and return the bytes
- using (var generator = new ComplexBarcodeGenerator(swissQr))
- {
- using (var ms = new MemoryStream())
- {
- generator.Save(ms, BarCodeImageFormat.Png);
- return ms.ToArray();
- }
- }
- }
+ // Output the size of the generated PNG byte array.
+ Console.WriteLine($"Generated Swiss QR Code PNG byte array length: {pngBytes.Length}");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/customize-barcode-foreground-and-background-colors-via-complexbarcodegenerator-properties-before-generating-image.cs b/swiss-qr-code/customize-barcode-foreground-and-background-colors-via-complexbarcodegenerator-properties-before-generating-image.cs
index a8fc93f..0580164 100644
--- a/swiss-qr-code/customize-barcode-foreground-and-background-colors-via-complexbarcodegenerator-properties-before-generating-image.cs
+++ b/swiss-qr-code/customize-barcode-foreground-and-background-colors-via-complexbarcodegenerator-properties-before-generating-image.cs
@@ -1,54 +1,51 @@
+// Title: Customize SwissQR barcode colors with ComplexBarcodeGenerator
+// Description: Demonstrates how to set foreground and background colors for a SwissQR barcode before generating a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of ComplexBarcodeGenerator and its Parameters to customize visual appearance such as bar and background colors. Developers often need to tailor barcode colors to match branding or UI themes while generating QR codes for payments or data exchange. The snippet illustrates typical steps: creating codetext, configuring colors, and saving the image.
+// Prompt: Customize barcode foreground and background colors via ComplexBarcodeGenerator properties before generating the image.
+// Tags: swissqr, complexbarcode, color, png, generation, aspose.barcode, aspose.drawing
+
using System;
+using System.IO;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
///
-/// Demonstrates generating a Swiss QR code barcode with custom colors using Aspose.BarCode.
+/// Example program that creates a SwissQR barcode, customizes its colors,
+/// and saves the result as a PNG image.
///
class Program
{
///
- /// Entry point of the application. Creates a Swiss QR code, configures barcode colors,
- /// and saves the generated image to a file.
+ /// Entry point of the application.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Prepare a Swiss QR codetext with required fields
- // ------------------------------------------------------------
+ // Prepare a SwissQR codetext with required mandatory fields
var swissQr = new SwissQRCodetext();
-
- // Set creditor (payee) details
swissQr.Bill.Creditor.Name = "John Doe";
swissQr.Bill.Creditor.CountryCode = "CH";
-
- // Set account number (IBAN) and payment amount
swissQr.Bill.Account = "CH9300762011623852957";
swissQr.Bill.Amount = 199.95m;
-
- // Specify the QR bill version to use
swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // ------------------------------------------------------------
- // 2. Generate the barcode with custom colors
- // ------------------------------------------------------------
+ // Define the output file path for the generated barcode image
+ string outputPath = "SwissQR.png";
+
+ // Create a ComplexBarcodeGenerator instance using the prepared codetext
using (var generator = new ComplexBarcodeGenerator(swissQr))
{
// Set the foreground (bars) color to blue
- generator.Parameters.Barcode.BarColor = Color.Blue;
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue;
// Set the background color to yellow
- generator.Parameters.BackColor = Color.Yellow;
-
- // Define the output file path
- string outputPath = "complex_barcode.png";
+ generator.Parameters.BackColor = Aspose.Drawing.Color.Yellow;
- // Save the barcode image as PNG
+ // Save the barcode image as a PNG file
generator.Save(outputPath, BarCodeImageFormat.Png);
-
- // Inform the user where the image was saved
- Console.WriteLine($"Barcode image saved to {outputPath}");
}
+
+ // Inform the user where the image has been saved
+ Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/deserialize-xml-of-swissqrcodetext-back-into-object-to-regenerate-qr-code-barcode.cs b/swiss-qr-code/deserialize-xml-of-swissqrcodetext-back-into-object-to-regenerate-qr-code-barcode.cs
index 5ef0518..bde23c6 100644
--- a/swiss-qr-code/deserialize-xml-of-swissqrcodetext-back-into-object-to-regenerate-qr-code-barcode.cs
+++ b/swiss-qr-code/deserialize-xml-of-swissqrcodetext-back-into-object-to-regenerate-qr-code-barcode.cs
@@ -1,49 +1,82 @@
+// Title: Deserialize SwissQR XML to Regenerate QR Code
+// Description: Demonstrates how to serialize a SwissQR barcode configuration to XML, deserialize it back, and regenerate the QR code image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode operations collection. It showcases the use of BarcodeGenerator, ComplexBarcodeGenerator, and SwissQRCodetext classes for QR code creation, XML export/import, and object reconstruction. Developers working with SwissQR (QR-bill) payments often need to persist barcode settings, transfer them between systems, or recreate barcodes from stored data.
+// Prompt: Deserialize XML of SwissQRCodetext back into an object to regenerate the QR code barcode.
+// Tags: qr code, swissqr, xml serialization, barcode generation, complex barcode, aspnet bar code
+
using System;
using System.IO;
-using System.Xml.Linq;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
+///
+/// Example program that creates a SwissQR barcode, exports its configuration to XML,
+/// imports the configuration back, decodes it into a SwissQRCodetext object,
+/// and finally regenerates the QR code image.
+///
class Program
{
+ ///
+ /// Entry point of the example. Executes the full round‑trip of SwissQR barcode creation,
+ /// XML persistence, and regeneration.
+ ///
static void Main()
{
- // Step 1: Create a sample SwissQR codetext object and fill required fields.
- var originalCodetext = new SwissQRCodetext();
- originalCodetext.Bill.Account = "CH9300762011623852957";
- originalCodetext.Bill.Creditor.CountryCode = "CH";
- originalCodetext.Bill.Creditor.Name = "John Doe";
- originalCodetext.Bill.Creditor.Street = "Main Street 1";
- originalCodetext.Bill.Creditor.PostalCode = "8000";
- originalCodetext.Bill.Creditor.Town = "Zurich";
- originalCodetext.Bill.Amount = 199.95m;
- originalCodetext.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
-
- // Construct the encoded string from the object.
- string constructed = originalCodetext.GetConstructedCodetext();
-
- // Step 2: Serialize the constructed codetext into a simple XML string.
- string xmlContent = $"{constructed}";
-
- // Step 3: Parse the XML and extract the codetext.
- XDocument doc = XDocument.Parse(xmlContent);
- string extractedCodeText = doc.Root.Element("CodeText")?.Value;
- if (string.IsNullOrEmpty(extractedCodeText))
+ // ------------------------------------------------------------
+ // 1. Build a SwissQR codetext object with required payment data
+ // ------------------------------------------------------------
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+
+ // ------------------------------------------------------------
+ // 2. Generate the plain QR code text from the object
+ // ------------------------------------------------------------
+ string plainCodeText = swissQr.GetConstructedCodetext();
+
+ // ------------------------------------------------------------
+ // 3. Create a QR barcode generator and export its configuration to XML
+ // ------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, plainCodeText))
{
- Console.WriteLine("Failed to extract codetext from XML.");
+ string xmlPath = "SwissQR.xml";
+ generator.ExportToXml(xmlPath);
+ }
+
+ // ------------------------------------------------------------
+ // 4. Import the generator configuration from the previously saved XML
+ // ------------------------------------------------------------
+ if (!File.Exists("SwissQR.xml"))
+ {
+ Console.WriteLine("XML file not found.");
return;
}
- // Step 4: Initialize a new SwissQRCodetext object from the extracted string.
- var deserializedCodetext = new SwissQRCodetext();
- deserializedCodetext.InitFromString(extractedCodeText);
+ var importedGenerator = BarcodeGenerator.ImportFromXml("SwissQR.xml");
+ string importedCodeText = importedGenerator.CodeText;
+
+ // ------------------------------------------------------------
+ // 5. Decode the plain codetext back into a SwissQRCodetext object
+ // ------------------------------------------------------------
+ SwissQRCodetext decodedSwissQr = ComplexCodetextReader.TryDecodeSwissQR(importedCodeText);
+ if (decodedSwissQr == null)
+ {
+ Console.WriteLine("Failed to decode SwissQR codetext.");
+ return;
+ }
- // Step 5: Generate the Swiss QR barcode image using ComplexBarcodeGenerator.
- using (ComplexBarcodeGenerator generator = new ComplexBarcodeGenerator(deserializedCodetext))
+ // ------------------------------------------------------------
+ // 6. Regenerate the QR barcode image from the decoded object
+ // ------------------------------------------------------------
+ using (var complexGenerator = new ComplexBarcodeGenerator(decodedSwissQr))
{
- string outputPath = "SwissQR.png";
- generator.Save(outputPath);
- Console.WriteLine($"Swiss QR barcode saved to '{Path.GetFullPath(outputPath)}'.");
+ complexGenerator.Save("SwissQR_fromXml.png");
}
+
+ Console.WriteLine("QR code regenerated successfully.");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/export-generated-swiss-qr-code-as-jpeg-image-with-adjustable-quality-settings-for-web-usage.cs b/swiss-qr-code/export-generated-swiss-qr-code-as-jpeg-image-with-adjustable-quality-settings-for-web-usage.cs
index 07061de..2c962cb 100644
--- a/swiss-qr-code/export-generated-swiss-qr-code-as-jpeg-image-with-adjustable-quality-settings-for-web-usage.cs
+++ b/swiss-qr-code/export-generated-swiss-qr-code-as-jpeg-image-with-adjustable-quality-settings-for-web-usage.cs
@@ -1,39 +1,63 @@
+// Title: Export Swiss QR Code to JPEG with Adjustable Quality
+// Description: Demonstrates generating a Swiss QR Code and exporting it as a JPEG image suitable for web usage.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator and SwissQRCodetext to create Swiss QR payment codes, then saves the result as a JPEG. Developers working with payment QR codes, image export, or web‑optimized barcode rendering commonly use these APIs.
+// Prompt: Export the generated Swiss QR Code as a JPEG image with adjustable quality settings for web usage.
+// Tags: swiss qr, barcode generation, jpeg export, quality settings, aspose.barcode, complexbarcodegenerator, swissqrcodetext
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a Swiss QR Bill barcode and saving it as a JPEG image.
+/// Generates a Swiss QR Code and saves it as a JPEG image.
///
class Program
{
///
- /// Entry point of the application. Creates a Swiss QR Bill, encodes it, and writes the image to disk.
+ /// Entry point of the example. Accepts an optional JPEG quality argument (0‑100) and creates the barcode image.
///
- static void Main()
+ /// Command‑line arguments; the first argument can specify JPEG quality.
+ static void Main(string[] args)
{
- // Build the full path for the output JPEG file in the current working directory.
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "SwissQR.jpeg");
+ // Default JPEG quality (placeholder – actual quality is controlled by resolution/anti‑alias settings).
+ int jpegQuality = 90;
- // Initialize a new Swiss QR code text object.
- var swissQr = new SwissQRCodetext();
+ // Parse optional quality argument if provided.
+ if (args.Length > 0 && int.TryParse(args[0], out int q) && q >= 0 && q <= 100)
+ {
+ jpegQuality = q;
+ }
- // Populate the creditor information and bill details.
- swissQr.Bill.Creditor.Name = "John Doe"; // Creditor's name
- swissQr.Bill.Creditor.CountryCode = "CH"; // Creditor's country (Switzerland)
- swissQr.Bill.Account = "CH9300762011623852957"; // IBAN account number
- swissQr.Bill.Amount = 199.95m; // Amount to be paid
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // QR bill version
+ // --------------------------------------------------------------------
+ // Prepare Swiss QR Code data (creditor, account, amount, version, etc.).
+ // --------------------------------------------------------------------
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Generate the barcode using the ComplexBarcodeGenerator and save it as JPEG.
+ // --------------------------------------------------------------------
+ // Generate the Swiss QR barcode using ComplexBarcodeGenerator.
+ // --------------------------------------------------------------------
using (var generator = new ComplexBarcodeGenerator(swissQr))
{
+ // Set image resolution and anti‑aliasing for better web quality.
+ generator.Parameters.Resolution = 300f;
+ generator.Parameters.UseAntiAlias = true;
+
+ // Define output file path.
+ string outputPath = "SwissQR.jpeg";
+
+ // Save the barcode as a JPEG image.
generator.Save(outputPath, BarCodeImageFormat.Jpeg);
- }
- // Inform the user where the QR code image has been saved.
- Console.WriteLine($"Swiss QR Code saved to: {outputPath}");
+ // Inform the user about the saved file and the quality placeholder.
+ Console.WriteLine($"Swiss QR Code saved to '{outputPath}' (JPEG quality placeholder: {jpegQuality}).");
+ }
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/generate-swiss-qr-code-image-from-payment-details-using-complexbarcodegenerator-and-swissqrcodetext.cs b/swiss-qr-code/generate-swiss-qr-code-image-from-payment-details-using-complexbarcodegenerator-and-swissqrcodetext.cs
index 7956ea5..40d45c5 100644
--- a/swiss-qr-code/generate-swiss-qr-code-image-from-payment-details-using-complexbarcodegenerator-and-swissqrcodetext.cs
+++ b/swiss-qr-code/generate-swiss-qr-code-image-from-payment-details-using-complexbarcodegenerator-and-swissqrcodetext.cs
@@ -1,45 +1,61 @@
+// Title: Generate Swiss QR Code for payment using Aspose.BarCode
+// Description: Demonstrates creating a Swiss QR Code image with payment details and saving it as PNG.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of ComplexBarcodeGenerator and SwissQRCodetext to produce Swiss QR Bill codes. Developers often need to generate QR payment slips for Swiss banking, requiring correct creditor, account, and amount fields. The snippet illustrates typical setup, optional fields, and image export, useful for integration in billing systems.
+// Prompt: Generate a Swiss QR Code image from payment details using ComplexBarcodeGenerator and SwissQRCodetext.
+// Tags: swiss qr code, payment, complex barcode, generation, png, aspose.barcode
+
using System;
-using System.IO;
using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
-///
-/// Demonstrates generation of a Swiss QR Code using Aspose.BarCode library.
-///
-class Program
+namespace SwissQRExample
{
///
- /// Entry point of the application. Generates a Swiss QR Code image and saves it to disk.
+ /// Example program that creates a Swiss QR Code (QR‑Bill) image using Aspose.BarCode.
///
- static void Main()
+ class Program
{
- // Determine the full path for the output PNG file in the current directory.
- string outputFile = Path.Combine(Directory.GetCurrentDirectory(), "SwissQR.png");
+ ///
+ /// Entry point. Builds the QR‑Bill data, generates the barcode, and saves it as a PNG file.
+ ///
+ static void Main()
+ {
+ // Initialize Swiss QR code data container
+ var swissQr = new SwissQRCodetext();
- // Instantiate a Swiss QR code text object which holds all required bill data.
- var swissQr = new SwissQRCodetext();
+ // ----- Mandatory creditor information -----
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
- // Set creditor (payee) mandatory details.
- swissQr.Bill.Creditor.Name = "John Doe";
- swissQr.Bill.Creditor.CountryCode = "CH";
+ // ----- Account (IBAN) -----
+ // Valid IBAN for a Swiss bank account
+ swissQr.Bill.Account = "CH9300762011623852957";
- // Assign the creditor's IBAN (must be a valid Swiss IBAN).
- swissQr.Bill.Account = "CH9300762011623852957";
+ // ----- Payment amount -----
+ swissQr.Bill.Amount = 199.95m;
- // Specify the amount to be paid.
- swissQr.Bill.Amount = 199.95m;
+ // ----- QR‑Bill version -----
+ // V2.0 is the current standard for Swiss QR Bills
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Choose the QR bill version (standard V2.0).
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+ // ----- Optional fields (uncomment to use) -----
+ // swissQr.Bill.Creditor.Street = "Example Street 1";
+ // swissQr.Bill.Creditor.PostalCode = "8000";
+ // swissQr.Bill.Creditor.Town = "Zurich";
- // Create a barcode generator for the Swiss QR code and save it as a PNG image.
- using (var generator = new ComplexBarcodeGenerator(swissQr))
- {
- generator.Save(outputFile, BarCodeImageFormat.Png);
- }
+ // Generate the barcode image using ComplexBarcodeGenerator
+ using (ComplexBarcodeGenerator generator = new ComplexBarcodeGenerator(swissQr))
+ {
+ // Do not throw on minor codetext issues; allow generation to continue
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
- // Inform the user where the image has been saved.
- Console.WriteLine($"Swiss QR Code image saved to: {outputFile}");
+ // Save the generated QR code as a PNG file
+ generator.Save("SwissQR.png");
+ }
+
+ // Inform the user that the image has been created
+ Console.WriteLine("Swiss QR Code image generated: SwissQR.png");
+ }
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/implement-error-handling-for-missing-mandatory-fields-when-constructing-swissqrcodetext-to-prevent-invalid-barcode-gener.cs b/swiss-qr-code/implement-error-handling-for-missing-mandatory-fields-when-constructing-swissqrcodetext-to-prevent-invalid-barcode-gener.cs
index 33c3d26..b73bdf6 100644
--- a/swiss-qr-code/implement-error-handling-for-missing-mandatory-fields-when-constructing-swissqrcodetext-to-prevent-invalid-barcode-gener.cs
+++ b/swiss-qr-code/implement-error-handling-for-missing-mandatory-fields-when-constructing-swissqrcodetext-to-prevent-invalid-barcode-gener.cs
@@ -1,90 +1,89 @@
+// Title: Generate Swiss QR Code barcode with validation
+// Description: Demonstrates creating a Swiss QR Code barcode, validating mandatory fields, and saving it as PNG.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on Swiss QR Bill (QR‑Bill) creation. It showcases the use of SwissQRCodetext, ComplexBarcodeGenerator, and related API classes to build a valid QR‑Bill, a common requirement for Swiss financial documents. Developers often need to ensure mandatory fields are set before generating the barcode to avoid errors.
+// Prompt: Implement error handling for missing mandatory fields when constructing SwissQRCodetext to prevent invalid barcode generation.
+// Tags: swissqr, qr-bill, barcode generation, validation, aspnet, aspnet-core, aspnet-barcode, complexbarcode, png
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generation of a Swiss QR code barcode using Aspose.BarCode.
+/// Demonstrates generating a Swiss QR Code barcode with mandatory field validation.
///
class Program
{
///
- /// Entry point of the application. Constructs a Swiss QR code, validates it,
- /// generates the barcode image, and saves it to disk.
+ /// Entry point. Builds SwissQRCodetext, validates required fields, and saves the barcode as PNG.
///
static void Main()
{
- // Construct SwissQR codetext object which holds all QR bill data
+ // Create a new SwissQRCodetext instance to hold QR‑Bill data
var swissQr = new SwissQRCodetext();
- // Populate mandatory fields required for a valid QR bill
+ // Populate mandatory fields required for a valid QR‑Bill
swissQr.Bill.Creditor.Name = "John Doe";
swissQr.Bill.Creditor.CountryCode = "CH";
swissQr.Bill.Account = "CH9300762011623852957";
swissQr.Bill.Amount = 199.95m;
swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+ // Optional: add additional information such as invoice reference
+ swissQr.Bill.BillInformation = "Invoice 12345";
+
+ // Validate that all required fields are present and correct
try
{
- // Validate mandatory fields before attempting barcode generation
ValidateSwissQr(swissQr);
-
- // Define output file path and generate the barcode image
- const string outputPath = "SwissQR.png";
- using (var generator = new ComplexBarcodeGenerator(swissQr))
- {
- // Save the generated barcode as a PNG file
- generator.Save(outputPath, BarCodeImageFormat.Png);
- }
-
- Console.WriteLine($"SwissQR barcode saved to {outputPath}");
}
- // Handle validation errors explicitly
catch (ArgumentException ex)
{
+ // Output validation error and abort execution
Console.WriteLine($"Validation error: {ex.Message}");
+ return;
}
- // Catch any other unexpected exceptions
- catch (Exception ex)
+
+ // Generate the Swiss QR barcode using the validated codetext
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- Console.WriteLine($"Unexpected error: {ex.Message}");
+ // Configure generator to throw if the codetext is incorrect (defensive programming)
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = true;
+
+ // Determine output file path in the current working directory
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "SwissQR.png");
+
+ // Save the generated barcode as a PNG image
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"SwissQR barcode saved to: {outputPath}");
}
}
- ///
- /// Validates that all required properties of the SwissQRCodetext instance are set.
- /// Throws if any mandatory field is missing or invalid.
- ///
- /// The SwissQRCodetext object to validate.
- static void ValidateSwissQr(SwissQRCodetext swissQr)
+ // Validates mandatory fields of SwissQRCodetext; throws ArgumentException if any are missing or invalid.
+ static void ValidateSwissQr(SwissQRCodetext codetext)
{
- // Ensure the SwissQRCodetext instance itself is not null
- if (swissQr == null)
+ if (codetext == null)
throw new ArgumentException("SwissQRCodetext instance cannot be null.");
- var bill = swissQr.Bill;
- // Ensure the Bill property is not null
+ var bill = codetext.Bill;
if (bill == null)
- throw new ArgumentException("Bill cannot be null.");
+ throw new ArgumentException("Bill data cannot be null.");
- // Creditor name is mandatory
- if (string.IsNullOrWhiteSpace(bill.Creditor.Name))
- throw new ArgumentException("Creditor Name is mandatory.");
+ if (string.IsNullOrWhiteSpace(bill.Creditor?.Name))
+ throw new ArgumentException("Creditor name is mandatory.");
- // Creditor country code is mandatory
- if (string.IsNullOrWhiteSpace(bill.Creditor.CountryCode))
- throw new ArgumentException("Creditor CountryCode is mandatory.");
+ if (string.IsNullOrWhiteSpace(bill.Creditor?.CountryCode))
+ throw new ArgumentException("Creditor country code is mandatory.");
- // Account number is mandatory
if (string.IsNullOrWhiteSpace(bill.Account))
- throw new ArgumentException("Account is mandatory.");
+ throw new ArgumentException("Account (IBAN) is mandatory.");
- // Amount must be a positive value
if (bill.Amount <= 0)
throw new ArgumentException("Amount must be greater than zero.");
- // Version must be a defined enum value
+ // Version is an enum; ensure it has a defined value
if (!Enum.IsDefined(typeof(SwissQRBill.QrBillStandardVersion), bill.Version))
- throw new ArgumentException("Bill.Version is mandatory and must be a valid enum value.");
+ throw new ArgumentException("Invalid SwissQR bill version.");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/implement-logging-of-barcode-generation-parameters-and-outcomes-using-net-built-in-logging-framework-for-audit-trails.cs b/swiss-qr-code/implement-logging-of-barcode-generation-parameters-and-outcomes-using-net-built-in-logging-framework-for-audit-trails.cs
index 953e6b3..73018a6 100644
--- a/swiss-qr-code/implement-logging-of-barcode-generation-parameters-and-outcomes-using-net-built-in-logging-framework-for-audit-trails.cs
+++ b/swiss-qr-code/implement-logging-of-barcode-generation-parameters-and-outcomes-using-net-built-in-logging-framework-for-audit-trails.cs
@@ -1,53 +1,81 @@
+// Title: Barcode generation with audit logging using Aspose.BarCode
+// Description: Demonstrates creating a Code128 barcode image while logging generation parameters and outcomes to a file for audit purposes.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode settings, save the image, and record detailed audit information. It highlights key API classes such as BarcodeGenerator, BaseEncodeType, and EncodeTypes, which developers commonly use for automated barcode creation, compliance tracking, and troubleshooting in enterprise applications.
+// Prompt: Implement logging of barcode generation parameters and outcomes using .NET built‑in logging framework for audit trails.
+// Tags: barcode, code128, generation, audit, logging, aspose.barcode, image, .net
+
using System;
using System.IO;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates generating a Code128 barcode and saving it as an image file.
+/// Generates a Code128 barcode image and logs the generation process for audit trails.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode with specified parameters and saves it to disk.
+ /// Entry point of the application. Configures barcode parameters, generates the image, and records audit information.
///
static void Main()
{
- // Define the barcode symbology (Code128) and the text to encode.
+ // Define the path for the audit log file.
+ string logFile = "barcode_audit.log";
+
+ // Ensure the audit log file exists; create it with a header if it does not.
+ if (!File.Exists(logFile))
+ {
+ File.WriteAllText(logFile, $"Barcode generation audit log - {DateTime.UtcNow:u}{Environment.NewLine}");
+ }
+
+ // Barcode configuration: type, data, and output file.
BaseEncodeType encodeType = EncodeTypes.Code128;
string codeText = "123ABC";
+ string outputPath = "code128.png";
- // Output file path for the generated barcode image.
- string outputPath = "barcode.png";
+ // Log the start of the barcode generation process with key parameters.
+ File.AppendAllText(logFile,
+ $"[{DateTime.UtcNow:u}] Starting barcode generation. Type: {encodeType.TypeName}, CodeText: \"{codeText}\"{Environment.NewLine}");
- try
+ // Create and configure the barcode generator.
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
{
- // Create a BarcodeGenerator instance with the chosen symbology and text.
- using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Set barcode generation parameters.
- generator.Parameters.Resolution = 300; // Image resolution in DPI.
- generator.Parameters.RotationAngle = 0; // No rotation applied.
- generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; // Enable checksum.
-
- // Output the configuration details to the console for verification.
- Console.WriteLine("Generating barcode:");
- Console.WriteLine($" Symbology: {encodeType}");
- Console.WriteLine($" CodeText: {codeText}");
- Console.WriteLine($" Resolution: {generator.Parameters.Resolution} DPI");
- Console.WriteLine($" RotationAngle: {generator.Parameters.RotationAngle} degrees");
- Console.WriteLine($" ChecksumEnabled: {generator.Parameters.Barcode.IsChecksumEnabled}");
+ // Set visual appearance and sizing options.
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; // Bar color
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White; // Background color
+ generator.Parameters.Barcode.XDimension.Point = 2f; // Module size (points)
+ generator.Parameters.Barcode.BarHeight.Point = 50f; // Bar height for 1D barcodes (points)
+ generator.Parameters.AutoSizeMode = AutoSizeMode.None; // Disable auto-sizing
+
+ // Log the configured generator parameters for traceability.
+ File.AppendAllText(logFile,
+ $"[{DateTime.UtcNow:u}] Configured parameters:{Environment.NewLine}" +
+ $" BarColor: {generator.Parameters.Barcode.BarColor}{Environment.NewLine}" +
+ $" BackColor: {generator.Parameters.BackColor}{Environment.NewLine}" +
+ $" XDimension: {generator.Parameters.Barcode.XDimension.Point} pt{Environment.NewLine}" +
+ $" BarHeight: {generator.Parameters.Barcode.BarHeight.Point} pt{Environment.NewLine}" +
+ $" AutoSizeMode: {generator.Parameters.AutoSizeMode}{Environment.NewLine}");
+ try
+ {
// Save the generated barcode image to the specified file.
generator.Save(outputPath);
+ // Log successful save operation.
+ File.AppendAllText(logFile,
+ $"[{DateTime.UtcNow:u}] Barcode saved successfully to \"{outputPath}\".{Environment.NewLine}");
+ Console.WriteLine($"Barcode generated and saved to {outputPath}");
+ }
+ catch (Exception ex)
+ {
+ // Log any errors that occur during generation or saving.
+ File.AppendAllText(logFile,
+ $"[{DateTime.UtcNow:u}] Error during barcode generation: {ex.Message}{Environment.NewLine}");
+ Console.WriteLine($"Error: {ex.Message}");
}
-
- // Inform the user that the barcode was generated successfully and display the full path.
- Console.WriteLine($"Barcode generated successfully. Saved to '{Path.GetFullPath(outputPath)}'.");
- }
- catch (Exception ex)
- {
- // Write any errors that occur during barcode generation to the error output stream.
- Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}");
}
+
+ // Log the completion of the entire barcode generation workflow.
+ File.AppendAllText(logFile,
+ $"[{DateTime.UtcNow:u}] Barcode generation process completed.{Environment.NewLine}");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/implement-parallel-generation-of-swiss-qr-code-barcodes-for-multiple-payment-records-to-boost-performance.cs b/swiss-qr-code/implement-parallel-generation-of-swiss-qr-code-barcodes-for-multiple-payment-records-to-boost-performance.cs
index 1c2cd08..52d1db3 100644
--- a/swiss-qr-code/implement-parallel-generation-of-swiss-qr-code-barcodes-for-multiple-payment-records-to-boost-performance.cs
+++ b/swiss-qr-code/implement-parallel-generation-of-swiss-qr-code-barcodes-for-multiple-payment-records-to-boost-performance.cs
@@ -1,96 +1,79 @@
+// Title: Parallel generation of Swiss QR Code barcodes for payment records
+// Description: Demonstrates creating Swiss QR Code barcodes for multiple payment records using Aspose.BarCode in parallel to improve performance.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Swiss QR Codes. It showcases the use of ComplexBarcodeGenerator, SwissQRCodetext, and related classes to encode payment information into QR bills, a common requirement for Swiss financial applications. Developers can adapt this pattern for batch processing of payment data and high‑throughput barcode creation.
+// Prompt: Implement parallel generation of Swiss QR Code barcodes for multiple payment records to boost performance.
+// Tags: swiss qr code, barcode generation, parallel processing, aspnet, aspose.barcode, complexbarcodegenerator
+
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Aspose.BarCode;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
-namespace SwissQRParallelGeneration
+///
+/// Demonstrates parallel generation of Swiss QR Code barcodes for multiple payment records.
+///
+class Program
{
///
- /// Simple DTO for payment information required by Swiss QR Code.
+ /// Simple payment record model containing the data required for a Swiss QR bill.
///
class PaymentRecord
{
public string CreditorName { get; set; }
- public string CountryCode { get; set; } // ISO country code, e.g., "CH"
- public string Account { get; set; } // IBAN
- public decimal Amount { get; set; } // Amount in CHF
+ public string CreditorCountryCode { get; set; }
+ public string AccountIban { get; set; }
+ public decimal Amount { get; set; }
}
///
- /// Demonstrates parallel generation of Swiss QR Code barcodes using Aspose.BarCode.
+ /// Entry point that creates sample payment records, generates Swiss QR Code barcodes in parallel, and saves them as PNG files.
///
- class Program
+ static void Main()
{
- ///
- /// Entry point of the application. Creates sample payment records,
- /// sets up the output directory, and generates QR code images in parallel.
- ///
- static void Main()
+ // Prepare a small set of sample payment records.
+ var payments = new List
{
- // Sample payment records (safe small batch)
- var records = new List
- {
- new PaymentRecord { CreditorName = "John Doe", CountryCode = "CH", Account = "CH9300762011623852957", Amount = 199.95m },
- new PaymentRecord { CreditorName = "Alice Smith", CountryCode = "CH", Account = "CH9300762011623852957", Amount = 250.00m },
- new PaymentRecord { CreditorName = "Bob Johnson", CountryCode = "CH", Account = "CH9300762011623852957", Amount = 75.50m },
- new PaymentRecord { CreditorName = "Carol White", CountryCode = "CH", Account = "CH9300762011623852957", Amount = 120.00m },
- new PaymentRecord { CreditorName = "David Brown", CountryCode = "CH", Account = "CH9300762011623852957", Amount = 300.00m }
- };
+ new PaymentRecord { CreditorName = "John Doe", CreditorCountryCode = "CH", AccountIban = "CH9300762011623852957", Amount = 199.95m },
+ new PaymentRecord { CreditorName = "John Doe", CreditorCountryCode = "CH", AccountIban = "CH9300762011623852957", Amount = 250.00m },
+ new PaymentRecord { CreditorName = "John Doe", CreditorCountryCode = "CH", AccountIban = "CH9300762011623852957", Amount = 75.50m },
+ new PaymentRecord { CreditorName = "John Doe", CreditorCountryCode = "CH", AccountIban = "CH9300762011623852957", Amount = 120.00m },
+ new PaymentRecord { CreditorName = "John Doe", CreditorCountryCode = "CH", AccountIban = "CH9300762011623852957", Amount = 99.99m }
+ };
- // Output directory for generated PNG files
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "SwissQRBarcodes");
+ // Ensure the output directory exists.
+ string outputDir = "SwissQR_Output";
+ if (!Directory.Exists(outputDir))
+ {
Directory.CreateDirectory(outputDir);
-
- // Configure parallel execution to use all available processors
- var parallelOptions = new ParallelOptions
- {
- MaxDegreeOfParallelism = Environment.ProcessorCount
- };
-
- // Parallel generation of Swiss QR Code barcodes
- Parallel.ForEach(records, parallelOptions, (record, state, index) =>
- {
- // Build file name based on the record index (1‑based)
- string filePath = Path.Combine(outputDir, $"SwissQR_{index + 1}.png");
-
- // Generate the QR code image and save it to disk
- GenerateSwissQR(record, filePath);
-
- // Log progress to the console
- Console.WriteLine($"Generated: {filePath}");
- });
-
- Console.WriteLine("All barcodes have been generated.");
}
- ///
- /// Generates a Swiss QR Code barcode for a single payment record and saves it to the specified path.
- ///
- /// The payment information to encode.
- /// The full file path where the PNG image will be saved.
- static void GenerateSwissQR(PaymentRecord record, string outputPath)
- {
- // Build the Swiss QR codetext object with required fields
- var swissQr = new SwissQRCodetext
+ // Generate Swiss QR Code barcodes in parallel, one per payment record.
+ Parallel.ForEach(
+ payments,
+ new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
+ (payment, state, index) =>
{
- Bill =
+ // Build the Swiss QR code text using the payment data.
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Creditor.Name = payment.CreditorName;
+ swissQr.Bill.Creditor.CountryCode = payment.CreditorCountryCode;
+ swissQr.Bill.Account = payment.AccountIban;
+ swissQr.Bill.Amount = payment.Amount;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+
+ // Create a generator for the current record and save the barcode as PNG.
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- Creditor = { Name = record.CreditorName, CountryCode = record.CountryCode },
- Account = record.Account,
- Amount = record.Amount,
- Version = SwissQRBill.QrBillStandardVersion.V2_0
+ string filePath = Path.Combine(outputDir, $"SwissQR_{index + 1}.png");
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
- };
- // Use ComplexBarcodeGenerator to create the image
- using (var generator = new ComplexBarcodeGenerator(swissQr))
- {
- // Save directly to file (PNG format is default)
- generator.Save(outputPath);
- }
- }
+ Console.WriteLine($"Generated Swiss QR barcode for record {index + 1}");
+ });
+
+ Console.WriteLine("All Swiss QR barcodes have been generated.");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/integrate-barcode-generation-into-background-service-that-processes-payment-requests-from-message-queue.cs b/swiss-qr-code/integrate-barcode-generation-into-background-service-that-processes-payment-requests-from-message-queue.cs
index e826a25..499c3fc 100644
--- a/swiss-qr-code/integrate-barcode-generation-into-background-service-that-processes-payment-requests-from-message-queue.cs
+++ b/swiss-qr-code/integrate-barcode-generation-into-background-service-that-processes-payment-requests-from-message-queue.cs
@@ -1,71 +1,107 @@
+// Title: Barcode generation in a background service for payment processing
+// Description: Demonstrates creating Code128 barcodes for payment references and saving them as PNG files, suitable for integration with a message‑queue‑driven background service.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, EncodeTypes, and related parameter settings to produce barcodes programmatically. Typical use cases include encoding transaction identifiers, invoices, or other payment data for printing or digital distribution. Developers often need to generate barcodes in batch jobs or background services, handling errors and managing output files.
+// Prompt: Integrate barcode generation into a background service that processes payment requests from a message queue.
+// Tags: barcode generation, code128, png, background service, payment processing, aspose.barcode, encode types
+
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
-///
-/// Demonstrates generating Code128 barcodes for a list of payment requests using Aspose.BarCode.
-///
-class Program
+namespace BarcodeBackgroundServiceDemo
{
///
- /// Simple payment request model containing a transaction identifier and an amount.
+ /// Simple model representing a payment request.
///
class PaymentRequest
{
- public string TransactionId { get; set; }
- public decimal Amount { get; set; }
+ public string Id { get; set; } // Unique identifier.
+ public decimal Amount { get; set; } // Payment amount.
+ public string Reference { get; set; } // Reference string to encode in the barcode.
}
///
- /// Entry point of the application. Generates barcode images for sample payment requests.
+ /// Demonstrates processing a collection of payment requests and generating barcodes for each.
///
- static void Main()
+ class Program
{
- // Sample payment requests simulating messages from a queue
- var paymentRequests = new List
+ ///
+ /// Entry point that simulates a background service processing payment requests and creating barcode images.
+ ///
+ static void Main()
{
- new PaymentRequest { TransactionId = "TXN001", Amount = 123.45m },
- new PaymentRequest { TransactionId = "TXN002", Amount = 67.89m },
- new PaymentRequest { TransactionId = "TXN003", Amount = 250.00m },
- new PaymentRequest { TransactionId = "TXN004", Amount = 5.99m },
- new PaymentRequest { TransactionId = "TXN005", Amount = 99.99m }
- };
-
- // Determine output directory for generated barcode images
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ // Sample payment requests – in a real scenario these would come from a message queue.
+ var payments = new List
+ {
+ new PaymentRequest { Id = "PAY001", Amount = 123.45m, Reference = "INV001-12345" },
+ new PaymentRequest { Id = "PAY002", Amount = 67.89m, Reference = "INV002-67890" },
+ new PaymentRequest { Id = "PAY003", Amount = 250.00m, Reference = "INV003-25000" },
+ new PaymentRequest { Id = "PAY004", Amount = 5.00m, Reference = "INV004-00005" },
+ new PaymentRequest { Id = "PAY005", Amount = 99.99m, Reference = "INV005-99999" }
+ };
- // Ensure the output directory exists
- if (!Directory.Exists(outputDir))
- {
- Directory.CreateDirectory(outputDir);
- }
+ // Determine the output directory for generated barcode images.
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
- // Process each payment request and generate a corresponding barcode image
- foreach (var request in paymentRequests)
- {
- // Use Code128 symbology; encode the transaction ID as the barcode value
- BaseEncodeType encodeType = EncodeTypes.Code128;
+ // Process each payment request.
+ foreach (var payment in payments)
+ {
+ try
+ {
+ // Resolve the symbology name to a BaseEncodeType using reflection (rule 26).
+ string symbologyName = "Code128"; // Using Code128 for payment references.
+ var field = typeof(EncodeTypes).GetField(symbologyName);
+ if (field == null)
+ {
+ Console.WriteLine($"Unknown symbology: {symbologyName}");
+ continue;
+ }
+ BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
- // Build the full file path for the barcode image (e.g., barcode_TXN001.png)
- string barcodePath = Path.Combine(outputDir, $"barcode_{request.TransactionId}.png");
+ // Create the barcode generator with the selected symbology and payment reference.
+ using (var generator = new BarcodeGenerator(encodeType, payment.Reference))
+ {
+ // Configure barcode appearance.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ generator.Parameters.ImageWidth.Point = 300f; // Width in points.
+ generator.Parameters.ImageHeight.Point = 100f; // Height in points.
+ generator.Parameters.Barcode.XDimension.Point = 2f; // Module size.
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ 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.FilledBars = false;
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
- // Generate and save the barcode using Aspose.BarCode
- using (var generator = new BarcodeGenerator(encodeType, request.TransactionId))
- {
- // Optional: set resolution for better image quality (dots per inch)
- generator.Parameters.Resolution = 300f;
+ // Human‑readable text styling (optional).
+ generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial";
+ generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f;
+ generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
- // Save the barcode image as a PNG file
- generator.Save(barcodePath);
+ // Save the barcode image to the output directory.
+ string fileName = $"{payment.Id}_{payment.Reference}.png";
+ string filePath = Path.Combine(outputDir, fileName);
+ generator.Save(filePath);
+ Console.WriteLine($"Generated barcode for payment {payment.Id} at: {filePath}");
+ }
+ }
+ catch (Exception ex)
+ {
+ // Handle any unexpected errors gracefully.
+ Console.WriteLine($"Failed to generate barcode for payment {payment.Id}: {ex.Message}");
+ }
}
- // Log the successful generation of the barcode
- Console.WriteLine($"Generated barcode for Transaction {request.TransactionId} (Amount: {request.Amount:C}) at: {barcodePath}");
+ // Program completes after processing the sample batch.
}
-
- // Indicate that all barcodes have been processed
- Console.WriteLine("All barcodes have been generated.");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/integrate-swiss-qr-code-generation-into-aspnet-mvc-controller-action-returning-barcode-image-as-http-response.cs b/swiss-qr-code/integrate-swiss-qr-code-generation-into-aspnet-mvc-controller-action-returning-barcode-image-as-http-response.cs
index 9e7b875..5522fee 100644
--- a/swiss-qr-code/integrate-swiss-qr-code-generation-into-aspnet-mvc-controller-action-returning-barcode-image-as-http-response.cs
+++ b/swiss-qr-code/integrate-swiss-qr-code-generation-into-aspnet-mvc-controller-action-returning-barcode-image-as-http-response.cs
@@ -1,54 +1,51 @@
+// Title: Generate Swiss QR Code and return as image
+// Description: Demonstrates creating a Swiss QR Bill barcode using Aspose.BarCode and saving it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode symbologies such as Swiss QR Bill. It showcases the use of ComplexBarcodeGenerator and related classes to produce QR codes for financial documents, a common requirement for developers integrating payment features into web applications.
+// Prompt: Integrate Swiss QR Code generation into an ASP.NET MVC controller action returning the barcode image as HTTP response.
+// Tags: barcode symbology, generation, png, aspnet-mvc, aspose.barcode, swiss-qr
+
using System;
using System.IO;
-using Aspose.BarCode;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing.Imaging;
+using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a Swiss QR Code using Aspose.BarCode library.
+/// Example program that generates a Swiss QR Bill barcode and saves it as a PNG file.
///
class Program
{
///
- /// Entry point of the console application.
- /// Generates a Swiss QR Code, converts it to PNG, and prints the Base64 representation.
+ /// Entry point that builds the QR bill data, creates the barcode, and writes the image to disk.
///
static void Main()
{
- // NOTE: Full ASP.NET MVC integration cannot be demonstrated in this console application.
- // The core logic for generating a Swiss QR Code is shown below.
- // In an MVC controller, you would return the image bytes as a FileResult.
+ // NOTE: In a real ASP.NET MVC controller this logic would be placed inside an action method
+ // and the image would be written directly to the HTTP response stream.
- // Create and populate the Swiss QR codetext.
+ // Prepare Swiss QR bill data
var swissQr = new SwissQRCodetext();
- // Set creditor details.
swissQr.Bill.Creditor.Name = "John Doe";
swissQr.Bill.Creditor.CountryCode = "CH";
- // Set account number (IBAN).
swissQr.Bill.Account = "CH9300762011623852957";
- // Set payment amount.
swissQr.Bill.Amount = 199.95m;
- // Set QR bill version.
swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Generate the barcode image into a memory stream.
- using (var ms = new MemoryStream())
+ // Create the complex barcode generator using the prepared QR bill data
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- // Initialize the complex barcode generator with the Swiss QR data.
- using (var generator = new ComplexBarcodeGenerator(swissQr))
+ // Optional: set QR error correction level to improve readability under adverse conditions
+ generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelM;
+
+ // Generate the barcode image and write it to a memory stream
+ using (var ms = new MemoryStream())
{
- // Save the generated barcode as PNG into the memory stream.
generator.Save(ms, BarCodeImageFormat.Png);
- }
-
- // Retrieve the image bytes from the memory stream.
- byte[] imageBytes = ms.ToArray();
- // Convert the image bytes to a Base64 string for demonstration purposes.
- string base64 = Convert.ToBase64String(imageBytes);
- Console.WriteLine("Swiss QR Code (Base64 PNG):");
- Console.WriteLine(base64);
+ // Persist the image to a file for demonstration purposes
+ File.WriteAllBytes("SwissQR.png", ms.ToArray());
+ }
}
+
+ Console.WriteLine("Swiss QR Code image saved as SwissQR.png");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/load-saved-qr-code-png-image-into-barcodereader-and-set-decodetype-to-qr-for-recognition.cs b/swiss-qr-code/load-saved-qr-code-png-image-into-barcodereader-and-set-decodetype-to-qr-for-recognition.cs
index 5769a9a..b7e0bad 100644
--- a/swiss-qr-code/load-saved-qr-code-png-image-into-barcodereader-and-set-decodetype-to-qr-for-recognition.cs
+++ b/swiss-qr-code/load-saved-qr-code-png-image-into-barcodereader-and-set-decodetype-to-qr-for-recognition.cs
@@ -1,49 +1,49 @@
+// Title: QR Code Recognition from PNG using BarCodeReader
+// Description: Demonstrates loading a saved QR Code PNG image and recognizing its content with Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating how to use BarCodeReader with DecodeType to identify QR symbology. It shows typical steps such as file validation, reader initialization, and result processing—common tasks for developers integrating barcode scanning into .NET applications.
+// Prompt: Load a saved QR Code PNG image into BarCodeReader and set DecodeType to QR for recognition.
+// Tags: qr, barcode, recognition, png, decode, aspose.barcode, csharp
+
using System;
using System.IO;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Demonstrates how to read a QR code from an image file using Aspose.BarCode.
+/// Demonstrates loading a saved QR Code PNG image and recognizing it using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point. Validates the image file, reads QR codes, and prints detected values.
///
- /// Command‑line arguments (not used).
- static void Main(string[] args)
+ static void Main()
{
- // Define the path to the QR code image (PNG format)
+ // Path to the saved QR Code PNG image
string imagePath = "qr.png";
- // Check that the image file exists before attempting to read it
+ // Verify that the image file exists before attempting to read it
if (!File.Exists(imagePath))
{
- // Inform the user if the file cannot be found and exit
- Console.WriteLine($"Image file not found: {imagePath}");
+ Console.WriteLine($"File not found: {imagePath}");
return;
}
- // Create a BarCodeReader for the specified image, limiting decoding to QR codes
- using (var reader = new BarCodeReader(imagePath, DecodeType.QR))
+ // Initialize BarCodeReader with the image file and specify QR as the decode type
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.QR))
{
- // Read all barcodes present in the image
+ // Perform the recognition operation
BarCodeResult[] results = reader.ReadBarCodes();
- // Determine whether any QR codes were detected
+ // Check if any QR codes were detected and output the results
if (results.Length == 0)
{
- // No QR code found – notify the user
- Console.WriteLine("No QR code detected in the image.");
+ Console.WriteLine("No QR code detected.");
}
else
{
- // Iterate through each detected barcode and display its details
- foreach (var result in results)
+ foreach (BarCodeResult result in results)
{
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ Console.WriteLine($"Detected QR Code: {result.CodeText}");
}
}
}
diff --git a/swiss-qr-code/provide-configuration-file-to-map-custom-field-names-to-swissqrcodetext-properties-for-dynamic-barcode-generation.cs b/swiss-qr-code/provide-configuration-file-to-map-custom-field-names-to-swissqrcodetext-properties-for-dynamic-barcode-generation.cs
index c5a3e57..f5e61e9 100644
--- a/swiss-qr-code/provide-configuration-file-to-map-custom-field-names-to-swissqrcodetext-properties-for-dynamic-barcode-generation.cs
+++ b/swiss-qr-code/provide-configuration-file-to-map-custom-field-names-to-swissqrcodetext-properties-for-dynamic-barcode-generation.cs
@@ -1,123 +1,93 @@
+// Title: Dynamic Swiss QR Code Generation Using Configuration Mapping
+// Description: Demonstrates how to map custom configuration fields to SwissQRCodetext properties and generate a Swiss QR barcode.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of Aspose.BarCode.Generation.ComplexBarcodeGenerator together with SwissQRCodetext to create Swiss QR bills. Developers often need to populate QR code data dynamically from configuration files or user input, and this pattern illustrates typical mapping, validation, and image output steps.
+// Prompt: Provide a configuration file to map custom field names to SwissQRCodetext properties for dynamic barcode generation.
+// Tags: barcode, swissqr, configuration, dynamic, generation, aspose.barcode, complexbarcode
+
using System;
using System.Collections.Generic;
-using System.Globalization;
+using System.IO;
using Aspose.BarCode;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generating a Swiss QR barcode using Aspose.BarCode with
-/// dynamic field mapping from a dictionary of input values.
+/// Example program that reads a dictionary of custom field names,
+/// maps them to properties, validates required data,
+/// and generates a Swiss QR barcode image.
///
class Program
{
///
- /// Entry point of the application. Builds a
- /// instance from custom input data, validates required fields, and generates
- /// a Swiss QR barcode image saved to disk.
+ /// Entry point of the example. Performs configuration mapping,
+ /// validation, and barcode generation.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Prepare sample input data using custom field names.
- // ------------------------------------------------------------
- var inputData = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ // Sample configuration mapping custom field names to values
+ var config = new Dictionary(StringComparer.OrdinalIgnoreCase)
{
{ "CreditorName", "John Doe" },
- { "CountryCode", "CH" },
+ { "CreditorCountryCode", "CH" },
{ "Account", "CH9300762011623852957" },
{ "Amount", "199.95" },
- { "Version", "V2_0" } // corresponds to SwissQRBill.QrBillStandardVersion.V2_0
- };
-
- // ------------------------------------------------------------
- // 2. Define mapping from custom field names to actions that set
- // properties on a SwissQRCodetext instance.
- // ------------------------------------------------------------
- var fieldMappings = new Dictionary>(StringComparer.OrdinalIgnoreCase)
- {
- { "CreditorName", (s, v) => s.Bill.Creditor.Name = v },
- { "CountryCode", (s, v) => s.Bill.Creditor.CountryCode = v },
- { "Account", (s, v) => s.Bill.Account = v },
- {
- "Amount",
- (s, v) =>
- {
- // Parse amount using invariant culture; report if invalid.
- if (decimal.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out var amt))
- s.Bill.Amount = amt;
- else
- Console.WriteLine($"Invalid amount value: {v}");
- }
- },
- {
- "Version",
- (s, v) =>
- {
- // Convert enum name (e.g., "V2_0") to SwissQRBill.QrBillStandardVersion.
- if (Enum.TryParse(v, out var ver))
- s.Bill.Version = ver;
- else
- Console.WriteLine($"Invalid version value: {v}");
- }
- }
+ { "Version", "V2_0" } // maps to SwissQRBill.QrBillStandardVersion.V2_0
};
- // ------------------------------------------------------------
- // 3. Create a SwissQRCodetext object and populate it using the mapping.
- // ------------------------------------------------------------
+ // Create an empty SwissQRCodetext instance
var swissQr = new SwissQRCodetext();
- foreach (var kvp in inputData)
+ // Apply configuration values to the corresponding SwissQRCodetext properties
+ foreach (var kvp in config)
{
- if (fieldMappings.TryGetValue(kvp.Key, out var setter))
+ switch (kvp.Key)
{
- try
- {
- // Apply the mapped setter action.
- setter(swissQr, kvp.Value);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error setting field '{kvp.Key}': {ex.Message}");
- }
- }
- else
- {
- Console.WriteLine($"No mapping defined for field '{kvp.Key}'.");
+ case "CreditorName":
+ swissQr.Bill.Creditor.Name = kvp.Value;
+ break;
+ case "CreditorCountryCode":
+ swissQr.Bill.Creditor.CountryCode = kvp.Value;
+ break;
+ case "Account":
+ swissQr.Bill.Account = kvp.Value;
+ break;
+ case "Amount":
+ // Parse amount string to decimal; throw if invalid
+ if (decimal.TryParse(kvp.Value, out var amount))
+ swissQr.Bill.Amount = amount;
+ else
+ throw new ArgumentException($"Invalid amount value: {kvp.Value}");
+ break;
+ case "Version":
+ // Convert string to enum; fall back to default if parsing fails
+ if (Enum.TryParse(kvp.Value, out var version))
+ swissQr.Bill.Version = version;
+ else
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+ break;
+ default:
+ // Unknown field – ignore or handle as needed
+ break;
}
}
- // ------------------------------------------------------------
- // 4. Validate that all mandatory fields are present and correct.
- // ------------------------------------------------------------
+ // Verify that all mandatory fields have been populated
if (string.IsNullOrWhiteSpace(swissQr.Bill.Creditor.Name) ||
string.IsNullOrWhiteSpace(swissQr.Bill.Creditor.CountryCode) ||
string.IsNullOrWhiteSpace(swissQr.Bill.Account) ||
- swissQr.Bill.Amount <= 0 ||
- swissQr.Bill.Version == 0)
+ swissQr.Bill.Amount <= 0m)
{
- Console.WriteLine("Missing required SwissQR fields. Barcode generation aborted.");
+ Console.WriteLine("Missing required Swiss QR bill information.");
return;
}
- // ------------------------------------------------------------
- // 5. Generate the Swiss QR barcode and save it to a PNG file.
- // ------------------------------------------------------------
+ // Generate the Swiss QR barcode and save it as a PNG file
const string outputPath = "SwissQR.png";
-
using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- try
- {
- generator.Save(outputPath);
- Console.WriteLine($"Swiss QR barcode saved to '{outputPath}'.");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Failed to generate barcode: {ex.Message}");
- }
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
+
+ Console.WriteLine($"Swiss QR barcode generated and saved to '{Path.GetFullPath(outputPath)}'.");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/read-raw-encoded-text-from-swiss-qr-code-image-and-gracefully-handle-possible-decoding-exceptions.cs b/swiss-qr-code/read-raw-encoded-text-from-swiss-qr-code-image-and-gracefully-handle-possible-decoding-exceptions.cs
index 5bc1afe..bc93290 100644
--- a/swiss-qr-code/read-raw-encoded-text-from-swiss-qr-code-image-and-gracefully-handle-possible-decoding-exceptions.cs
+++ b/swiss-qr-code/read-raw-encoded-text-from-swiss-qr-code-image-and-gracefully-handle-possible-decoding-exceptions.cs
@@ -1,73 +1,87 @@
+// Title: Read Swiss QR Code raw text and handle decoding errors
+// Description: Demonstrates how to read a Swiss QR Code image, extract the raw encoded text, and safely decode it while handling possible exceptions.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on reading and decoding complex barcode symbologies such as Swiss QR. It showcases the use of BarCodeReader, DecodeType, and ComplexCodetextReader classes, typical for applications that need to process payment QR codes and handle errors gracefully. Developers often need to extract payment details from images and ensure robust error handling.
+// Prompt: Read raw encoded text from a Swiss QR Code image and gracefully handle possible decoding exceptions.
+// Tags: barcode symbology, decoding, swiss qr, aspose.barcode, complex barcode
+
using System;
using System.IO;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates reading a Swiss QR Code image, extracting the raw encoded text,
-/// and decoding it into a structured Swiss QR Bill object.
+/// Example program that reads a Swiss QR Code image, extracts its raw text,
+/// and attempts to decode it into structured payment information while handling errors.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Performs image validation, barcode detection,
+ /// raw text extraction, and Swiss QR specific decoding with graceful error handling.
///
static void Main()
{
- // Path to the Swiss QR Code image file.
+ // Path to the input image containing the Swiss QR Code
string imagePath = "SwissQR.png";
- // Verify that the specified image file exists before proceeding.
+ // Verify that the image file exists before attempting to read it
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
+ Console.WriteLine($"Image file not found: {imagePath}");
return;
}
try
{
- // Initialize a barcode reader configured to decode QR codes.
- using (var reader = new BarCodeReader(imagePath, DecodeType.QR))
+ // Initialize the barcode reader for all supported types
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Read all barcodes present in the image.
- BarCodeResult[] results = reader.ReadBarCodes();
+ // Read all barcodes present in the image
+ var results = reader.ReadBarCodes();
- // If no barcodes were detected, inform the user and exit.
- if (results == null || results.Length == 0)
+ // If no barcodes were detected, inform the user and exit
+ if (results.Length == 0)
{
Console.WriteLine("No barcode detected in the image.");
return;
}
- // Assume the first detected barcode corresponds to the Swiss QR Code.
- var result = results[0];
- string rawEncodedText = result.CodeText;
- Console.WriteLine($"Raw encoded text: {rawEncodedText}");
+ // Process each detected barcode
+ foreach (var result in results)
+ {
+ Console.WriteLine($"Detected barcode type: {result.CodeTypeName}");
- // Attempt to decode the raw Swiss QR codetext into a structured object.
- SwissQRCodetext decoded = ComplexCodetextReader.TryDecodeSwissQR(rawEncodedText);
+ // Retrieve the raw encoded text from the barcode
+ string codeText = result.CodeText;
+ if (string.IsNullOrEmpty(codeText))
+ {
+ Console.WriteLine("Barcode detected but codetext is empty.");
+ continue;
+ }
- // If decoding fails, notify the user.
- if (decoded == null)
- {
- Console.WriteLine("Failed to decode Swiss QR codetext.");
- }
- else
- {
- // Display selected fields from the decoded Swiss QR Bill.
- Console.WriteLine("Decoded Swiss QR Bill:");
- Console.WriteLine($" Account: {decoded.Bill.Account}");
- Console.WriteLine($" Amount: {decoded.Bill.Amount}");
- Console.WriteLine($" Creditor Name: {decoded.Bill.Creditor.Name}");
- Console.WriteLine($" Creditor Country Code: {decoded.Bill.Creditor.CountryCode}");
- Console.WriteLine($" Version: {decoded.Bill.Version}");
+ // Attempt to decode the raw text as a Swiss QR code
+ SwissQRCodetext swissQr = ComplexCodetextReader.TryDecodeSwissQR(codeText);
+ if (swissQr != null)
+ {
+ // Successful decoding – output payment details
+ Console.WriteLine("Successfully decoded Swiss QR code.");
+ Console.WriteLine($"Account: {swissQr.Bill.Account}");
+ Console.WriteLine($"Amount: {swissQr.Bill.Amount}");
+ Console.WriteLine($"Creditor Name: {swissQr.Bill.Creditor.Name}");
+ Console.WriteLine($"Creditor Country: {swissQr.Bill.Creditor.CountryCode}");
+ }
+ else
+ {
+ // Decoding failed – inform the user
+ Console.WriteLine("Failed to decode Swiss QR codetext.");
+ }
}
}
}
catch (Exception ex)
{
- // Handle any unexpected errors that occur during reading or decoding.
- Console.WriteLine($"An error occurred: {ex.Message}");
+ // Catch any unexpected errors during processing and display a friendly message
+ Console.WriteLine($"An error occurred while processing the image: {ex.Message}");
}
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/save-generated-swiss-qr-code-to-png-file-with-custom-dimensions-and-margins.cs b/swiss-qr-code/save-generated-swiss-qr-code-to-png-file-with-custom-dimensions-and-margins.cs
index 1bff7dc..b433ed3 100644
--- a/swiss-qr-code/save-generated-swiss-qr-code-to-png-file-with-custom-dimensions-and-margins.cs
+++ b/swiss-qr-code/save-generated-swiss-qr-code-to-png-file-with-custom-dimensions-and-margins.cs
@@ -1,51 +1,54 @@
+// Title: Generate Swiss QR Code with custom size and margins
+// Description: Demonstrates creating a Swiss QR Bill barcode, customizing its image dimensions and padding, and saving it as a PNG file.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of ComplexBarcodeGenerator with SwissQRCodetext. Developers often need to generate QR codes for payment bills, adjust image size, margins, and colors before exporting to common image formats like PNG.
+// Prompt: Save the generated Swiss QR Code to a PNG file with custom dimensions and margins.
+// Tags: barcode symbology, generation, png, swissqr, complexbarcodegenerator, aspose.barcode
+
using System;
-using System.IO;
using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates generating a Swiss QR Code barcode using Aspose.BarCode.
+/// Demonstrates generating a Swiss QR Bill barcode with custom dimensions and margins, then saving it as a PNG file.
///
class Program
{
///
- /// Entry point of the application. Generates a Swiss QR Code and saves it as a PNG file.
+ /// Entry point that builds the QR bill data, configures the generator, and writes the image to disk.
///
static void Main()
{
- // Define the output file name for the generated barcode image.
- string outputPath = "SwissQR.png";
-
- // Create a Swiss QR code text object and populate mandatory bill fields.
+ // Prepare Swiss QR bill data
var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe"; // Creditor's name
- swissQr.Bill.Creditor.CountryCode = "CH"; // Creditor's country (Switzerland)
- swissQr.Bill.Account = "CH9300762011623852957"; // IBAN account number
- swissQr.Bill.Amount = 199.95m; // Invoice amount
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // QR bill version
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Initialize the barcode generator with the prepared Swiss QR code text.
+ // Create generator for the complex Swiss QR code
using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- // Configure image dimensions (in points). 1 point = 1/72 inch.
- generator.Parameters.ImageWidth.Point = 400f;
- generator.Parameters.ImageHeight.Point = 400f;
+ // Set custom image dimensions (points)
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 300f;
- // Set padding (margins) around the barcode to ensure proper whitespace.
+ // Set custom margins (padding) around the barcode (points)
generator.Parameters.Barcode.Padding.Left.Point = 10f;
generator.Parameters.Barcode.Padding.Top.Point = 10f;
generator.Parameters.Barcode.Padding.Right.Point = 10f;
generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
- // Optional: define the image resolution (dots per inch).
- generator.Parameters.Resolution = 300f;
+ // Optional: set background and bar colors
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- // Save the generated barcode as a PNG file at the specified path.
+ // Save the generated Swiss QR code as PNG
+ const string outputPath = "SwissQR.png";
generator.Save(outputPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Swiss QR Code saved to '{outputPath}'.");
}
-
- // Output the full path of the saved image to the console for verification.
- Console.WriteLine($"Swiss QR Code saved to: {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/serialize-swissqrcodetext-object-to-xml-for-archival-storage-of-payment-information.cs b/swiss-qr-code/serialize-swissqrcodetext-object-to-xml-for-archival-storage-of-payment-information.cs
index 7546e08..9a50852 100644
--- a/swiss-qr-code/serialize-swissqrcodetext-object-to-xml-for-archival-storage-of-payment-information.cs
+++ b/swiss-qr-code/serialize-swissqrcodetext-object-to-xml-for-archival-storage-of-payment-information.cs
@@ -1,46 +1,52 @@
+// Title: Serialize SwissQR Code Text to XML
+// Description: Demonstrates how to serialize a SwissQR code text object to XML for archival storage of payment information.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode operations category, focusing on Swiss QR Bill generation and data persistence. It showcases the use of Aspose.BarCode.ComplexBarcode.SwissQRCodetext and related classes to create payment QR codes, then serialize the object with System.Xml.Serialization for later retrieval. Developers working with payment QR codes, invoicing systems, or financial data archiving will find this pattern useful.
+// Prompt: Serialize the SwissQRCodetext object to XML for archival storage of payment information.
+// Tags: barcode symbology, serialization, xml, swissqr, aspose.barcode, complexbarcode
+
using System;
using System.IO;
using System.Xml.Serialization;
+using Aspose.BarCode;
using Aspose.BarCode.ComplexBarcode;
-///
-/// Demonstrates creation, serialization, and barcode generation for a Swiss QR Bill using Aspose.BarCode.
-///
-class Program
+namespace SwissQRSerialization
{
///
- /// Entry point of the application.
+ /// Provides an entry point that creates a SwissQR code text object,
+ /// populates required billing fields, and serializes it to an XML file.
///
- static void Main()
+ class Program
{
- // Initialize a SwissQRCodetext instance with sample payment details.
- var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe";
- swissQr.Bill.Creditor.CountryCode = "CH";
- swissQr.Bill.Account = "CH9300762011623852957";
- swissQr.Bill.Amount = 199.95m;
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+ ///
+ /// Main method – builds a SwissQR bill, serializes it to XML, and outputs the file path.
+ ///
+ static void Main()
+ {
+ // Initialize a new SwissQRCodetext instance
+ var swissQr = new SwissQRCodetext();
- // Prepare XML serializer for the SwissQRCodetext type.
- var serializer = new XmlSerializer(typeof(SwissQRCodetext));
- string xmlPath = "SwissQR.xml";
+ // Populate mandatory bill fields
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Serialize the object to an XML file for archival storage.
- using (var fileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.Write))
- {
- serializer.Serialize(fileStream, swissQr);
- }
+ // Prepare XML serializer for the SwissQRCodetext type
+ var serializer = new XmlSerializer(typeof(SwissQRCodetext));
- Console.WriteLine($"SwissQRCodetext serialized to '{Path.GetFullPath(xmlPath)}'.");
+ // Define output XML file path
+ var xmlPath = "SwissQRCodetext.xml";
- // Generate a barcode image from the SwissQRCodetext instance.
- string imagePath = "SwissQR.png";
- using (var generator = new ComplexBarcodeGenerator(swissQr))
- {
- // Save the barcode as a PNG file.
- generator.Save(imagePath, Aspose.BarCode.Generation.BarCodeImageFormat.Png);
- }
+ // Serialize the object to the specified file
+ using (var fileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.Write))
+ {
+ serializer.Serialize(fileStream, swissQr);
+ }
- Console.WriteLine($"Barcode image saved to '{Path.GetFullPath(imagePath)}'.");
+ // Inform the user where the XML file was saved
+ Console.WriteLine($"SwissQRCodetext has been serialized to: {Path.GetFullPath(xmlPath)}");
+ }
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/set-specific-qr-error-correction-level-for-swiss-qr-code-generation-to-ensure-readability-under-distortion.cs b/swiss-qr-code/set-specific-qr-error-correction-level-for-swiss-qr-code-generation-to-ensure-readability-under-distortion.cs
index 3c88234..7b2b9d6 100644
--- a/swiss-qr-code/set-specific-qr-error-correction-level-for-swiss-qr-code-generation-to-ensure-readability-under-distortion.cs
+++ b/swiss-qr-code/set-specific-qr-error-correction-level-for-swiss-qr-code-generation-to-ensure-readability-under-distortion.cs
@@ -1,42 +1,45 @@
+// Title: Swiss QR Code Generation with High Error Correction
+// Description: Demonstrates generating a Swiss QR Bill and setting QR error correction level H to improve readability under distortion.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of ComplexBarcodeGenerator and SwissQRCodetext for creating Swiss QR Codes. Developers commonly need to generate QR codes for payment bills, adjust error correction levels, and export images in various formats. The example highlights key API classes and typical steps for QR code customization.
+// Prompt: Set a specific QR error correction level for Swiss QR Code generation to ensure readability under distortion.
+// Tags: qr code, swiss qr, error correction, barcode generation, aspose.barcode, png
+
using System;
-using System.IO;
-using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
///
-/// Demonstrates generating a Swiss QR code using Aspose.BarCode library.
+/// Generates a Swiss QR Bill with a high error correction level (Level H) and saves it as a PNG image.
///
class Program
{
///
- /// Entry point of the application. Creates a Swiss QR code with mandatory fields,
- /// configures high error correction, and saves the barcode image to disk.
+ /// Entry point of the example. Creates the Swiss QR codetext, configures error correction, and saves the barcode image.
///
static void Main()
{
- // Initialize Swiss QR codetext and populate required bill information
+ // Create Swiss QR codetext and populate mandatory bill fields
var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe"; // Creditor's name
- swissQr.Bill.Creditor.CountryCode = "CH"; // Creditor's country code (Switzerland)
- swissQr.Bill.Account = "CH9300762011623852957"; // IBAN account number
- swissQr.Bill.Amount = 199.95m; // Invoice amount
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // QR bill version
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // Create a barcode generator for the Swiss QR code
+ // Initialize ComplexBarcodeGenerator with the codetext
using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- // Set QR error correction level to high (Level H) for better resilience
+ // Set high error correction level (Level H) for better readability under distortion
generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
- // Determine output file path in the current working directory
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "SwissQR.png");
+ // Define output file path
+ string outputPath = "SwissQR.png";
- // Save the generated barcode image to the specified path
- generator.Save(outputPath);
+ // Save the generated Swiss QR Code image in PNG format
+ generator.Save(outputPath, BarCodeImageFormat.Png);
- // Inform the user where the file was saved
- Console.WriteLine($"Swiss QR code saved to: {outputPath}");
+ // Inform the user where the image was saved
+ Console.WriteLine($"Swiss QR Code saved to {outputPath}");
}
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/use-complexbarcodegenerator-to-embed-logo-at-center-of-swiss-qr-code-without-affecting-scannability.cs b/swiss-qr-code/use-complexbarcodegenerator-to-embed-logo-at-center-of-swiss-qr-code-without-affecting-scannability.cs
index e500bd7..64bb3b3 100644
--- a/swiss-qr-code/use-complexbarcodegenerator-to-embed-logo-at-center-of-swiss-qr-code-without-affecting-scannability.cs
+++ b/swiss-qr-code/use-complexbarcodegenerator-to-embed-logo-at-center-of-swiss-qr-code-without-affecting-scannability.cs
@@ -1,3 +1,9 @@
+// Title: Swiss QR Code with Embedded Center Logo using ComplexBarcodeGenerator
+// Description: Generates a Swiss QR bill QR code and overlays a logo at its center while preserving scan reliability.
+// Category-Description: Demonstrates Aspose.BarCode complex barcode generation for Swiss QR bills, showing how to configure QR error correction, embed a central logo, and save as PNG. Uses ComplexBarcodeGenerator, SwissQRCodetext, and drawing classes. Ideal for developers needing to customize QR codes with branding without compromising readability.
+// Prompt: Use ComplexBarcodeGenerator to embed a logo at the center of the Swiss QR Code without affecting scannability.
+// Tags: swiss qr, barcode, logo overlay, complexbarcodegenerator, qrcode, png, aspnet, aspose.barcode
+
using System;
using System.IO;
using Aspose.BarCode.ComplexBarcode;
@@ -6,44 +12,24 @@
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of a Swiss QR code with an embedded logo using Aspose.BarCode.
+/// Example program that creates a Swiss QR bill QR code, embeds a logo at its centre,
+/// and saves the result as a PNG image.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Swiss QR barcode, embeds a logo at its centre, and saves the result as a PNG file.
+ /// Entry point of the example. Generates the QR code, adds the logo if available,
+ /// and writes the output file.
///
static void Main()
{
- // Output file for the final QR code image and optional logo source file
- string outputPath = "SwissQR_with_logo.png";
- string logoPath = "logo.png";
+ // Output file for the final QR code image
+ const string outputPath = "SwissQR_with_logo.png";
- // --------------------------------------------------------------------
- // Ensure a placeholder logo exists if the specified logo file is missing
- // --------------------------------------------------------------------
- if (!File.Exists(logoPath))
- {
- // Create a 100x100 white bitmap and draw the word "Logo" on it
- using (var placeholder = new Bitmap(100, 100))
- {
- using (var g = Graphics.FromImage(placeholder))
- {
- g.Clear(Color.White);
- using (var font = new Font("Arial", 12f))
- {
- g.DrawString("Logo", font, Brushes.Black, new PointF(10f, 40f));
- }
- }
- // Save the placeholder as a PNG file
- placeholder.Save(logoPath, ImageFormat.Png);
- }
- }
+ // Optional logo file to embed at the centre of the QR code
+ const string logoPath = "logo.png";
- // --------------------------------------------------------------
- // Build the Swiss QR code text with required billing information
- // --------------------------------------------------------------
+ // Prepare Swiss QR bill data (mandatory fields)
var swissQr = new SwissQRCodetext();
swissQr.Bill.Creditor.Name = "John Doe";
swissQr.Bill.Creditor.CountryCode = "CH";
@@ -51,50 +37,45 @@ static void Main()
swissQr.Bill.Amount = 199.95m;
swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
- // --------------------------------------------------------------
- // Generate the QR barcode with high error correction (Level H)
- // --------------------------------------------------------------
+ // Generate the Swiss QR code with high error correction (Level H) to tolerate a logo
using (var generator = new ComplexBarcodeGenerator(swissQr))
{
generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
- // Create the barcode image
- using (var barcodeImage = generator.GenerateBarCodeImage())
+ // Create the QR code bitmap
+ using (Bitmap barcodeBitmap = generator.GenerateBarCodeImage())
{
- // Load the logo image from file
- using (var logoImage = new Bitmap(logoPath))
+ // If a logo file exists, overlay it at the centre of the QR code
+ if (File.Exists(logoPath))
{
- int barcodeWidth = barcodeImage.Width;
- int barcodeHeight = barcodeImage.Height;
-
- // ------------------------------------------------------
- // Create a new bitmap to hold the combined barcode + logo
- // ------------------------------------------------------
- using (var finalImage = new Bitmap(barcodeWidth, barcodeHeight))
+ using (var logoImage = new Bitmap(logoPath))
{
- using (var graphics = Graphics.FromImage(finalImage))
- {
- // Draw the QR barcode onto the final image
- graphics.DrawImage(barcodeImage, 0, 0, barcodeWidth, barcodeHeight);
+ // Limit logo size to 20% of the QR code dimensions while preserving aspect ratio
+ int maxLogoWidth = (int)(barcodeBitmap.Width * 0.2);
+ int maxLogoHeight = (int)(barcodeBitmap.Height * 0.2);
+ float widthRatio = (float)maxLogoWidth / logoImage.Width;
+ float heightRatio = (float)maxLogoHeight / logoImage.Height;
+ float scale = Math.Min(widthRatio, heightRatio);
+ int logoWidth = (int)(logoImage.Width * scale);
+ int logoHeight = (int)(logoImage.Height * scale);
- // Calculate logo size (20% of barcode dimensions) and centre position
- int logoWidth = (int)(barcodeWidth * 0.2f);
- int logoHeight = (int)(barcodeHeight * 0.2f);
- int logoX = (barcodeWidth - logoWidth) / 2;
- int logoY = (barcodeHeight - logoHeight) / 2;
+ // Calculate centre position for the logo
+ int posX = (barcodeBitmap.Width - logoWidth) / 2;
+ int posY = (barcodeBitmap.Height - logoHeight) / 2;
- // Draw the logo at the calculated position
- graphics.DrawImage(logoImage, new Rectangle(logoX, logoY, logoWidth, logoHeight));
+ // Draw the logo onto the QR code bitmap
+ using (Graphics graphics = Graphics.FromImage(barcodeBitmap))
+ {
+ graphics.DrawImage(logoImage, posX, posY, logoWidth, logoHeight);
}
-
- // Save the combined image as a PNG file
- finalImage.Save(outputPath, ImageFormat.Png);
}
}
+
+ // Save the final image in PNG format
+ barcodeBitmap.Save(outputPath, ImageFormat.Png);
}
}
- // Output the full path of the saved image to the console
- Console.WriteLine($"Swiss QR code with embedded logo saved to: {Path.GetFullPath(outputPath)}");
+ Console.WriteLine($"Swiss QR code saved to {outputPath}");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/use-complexcodetextreadertrydecodeswissqr-to-parse-raw-text-into-swissqrcodetext-object-for-extraction.cs b/swiss-qr-code/use-complexcodetextreadertrydecodeswissqr-to-parse-raw-text-into-swissqrcodetext-object-for-extraction.cs
index 4f8a1dd..1399415 100644
--- a/swiss-qr-code/use-complexcodetextreadertrydecodeswissqr-to-parse-raw-text-into-swissqrcodetext-object-for-extraction.cs
+++ b/swiss-qr-code/use-complexcodetextreadertrydecodeswissqr-to-parse-raw-text-into-swissqrcodetext-object-for-extraction.cs
@@ -1,51 +1,45 @@
+// Title: Decode Swiss QR Code Text Using ComplexCodetextReader
+// Description: Demonstrates how to parse raw Swiss QR code text (SPC format) into a SwissQRCodetext object and extract billing details.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode decoding category, focusing on Swiss QR (QR‑IBAN) processing. It showcases the ComplexCodetextReader and SwissQRCodetext classes, which developers use to interpret QR‑IBAN payment strings, retrieve creditor and payment information, and integrate QR‑based payment data into financial applications. Typical use cases include validating QR‑IBAN data, generating payment receipts, and automating invoice processing.
+// Prompt: Use ComplexCodetextReader.TryDecodeSwissQR to parse raw text into a SwissQRCodetext object for extraction.
+// Tags: swissqr, barcode, decoding, complexcodetextreader, aspose.barcode
+
using System;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates creating, encoding, and decoding a Swiss QR Bill using Aspose.BarCode.
+/// Example program that decodes a raw Swiss QR code string into a object
+/// and prints selected billing information to the console.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Parses a sample SPC‑formatted string, extracts the
+ /// and displays key fields such as creditor name, country code, IBAN, amount and version.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Create a SwissQRCodetext instance and populate required fields
- // ------------------------------------------------------------
- var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe"; // Creditor's name
- swissQr.Bill.Creditor.CountryCode = "CH"; // ISO country code (Switzerland)
- swissQr.Bill.Account = "CH9300762011623852957"; // IBAN account number
- swissQr.Bill.Amount = 199.95m; // Invoice amount
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // QR bill version
-
- // ------------------------------------------------------------
- // 2. Generate the raw codetext string from the populated object
- // ------------------------------------------------------------
- string rawText = swissQr.GetConstructedCodetext();
+ // Sample encoded Swiss QR codetext in SPC format (lines separated by LF)
+ string rawCodetext = "SPC\n0200\n1\nCH9300762011623852957\nJohn Doe\nCH\n1000\nCHF\nInvoice 123\n";
- // ------------------------------------------------------------
- // 3. Decode the raw codetext back into a SwissQRCodetext object
- // ------------------------------------------------------------
- SwissQRCodetext decoded = ComplexCodetextReader.TryDecodeSwissQR(rawText);
+ // Attempt to decode the raw text into a SwissQRCodetext object using the ComplexCodetextReader API
+ SwissQRCodetext swiss = ComplexCodetextReader.TryDecodeSwissQR(rawCodetext);
- // ------------------------------------------------------------
- // 4. Output the decoded information or an error message
- // ------------------------------------------------------------
- if (decoded != null)
- {
- Console.WriteLine("Decoded Swiss QR Bill:");
- Console.WriteLine($"Creditor Name: {decoded.Bill.Creditor.Name}");
- Console.WriteLine($"Country Code: {decoded.Bill.Creditor.CountryCode}");
- Console.WriteLine($"Account: {decoded.Bill.Account}");
- Console.WriteLine($"Amount: {decoded.Bill.Amount}");
- Console.WriteLine($"Version: {decoded.Bill.Version}");
- }
- else
+ // If decoding fails, inform the user and exit
+ if (swiss == null)
{
Console.WriteLine("Failed to decode Swiss QR codetext.");
+ return;
}
+
+ // Retrieve the Bill component which holds payment details
+ var bill = swiss.Bill;
+
+ // Output selected bill information to the console
+ Console.WriteLine($"Creditor Name: {bill.Creditor.Name}");
+ Console.WriteLine($"Creditor Country Code: {bill.Creditor.CountryCode}");
+ Console.WriteLine($"Account (IBAN): {bill.Account}");
+ Console.WriteLine($"Amount: {bill.Amount}");
+ Console.WriteLine($"Version: {bill.Version}");
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/use-swissqrbill-class-to-generate-pdf-qr-bill-document-embedding-generated-swiss-qr-code-image.cs b/swiss-qr-code/use-swissqrbill-class-to-generate-pdf-qr-bill-document-embedding-generated-swiss-qr-code-image.cs
index b1c4be9..f62b986 100644
--- a/swiss-qr-code/use-swissqrbill-class-to-generate-pdf-qr-bill-document-embedding-generated-swiss-qr-code-image.cs
+++ b/swiss-qr-code/use-swissqrbill-class-to-generate-pdf-qr-bill-document-embedding-generated-swiss-qr-code-image.cs
@@ -1,20 +1,29 @@
+// Title: Generate Swiss QR Bill PDF with embedded QR code
+// Description: Demonstrates creating a Swiss QR‑Bill PDF by generating a QR code using Aspose.BarCode and embedding it into a PDF with Aspose.Pdf.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and Aspose.Pdf document creation category. It shows how to use the SwissQRBill class together with ComplexBarcodeGenerator to produce a Swiss QR‑Code, and then embed the resulting image into a PDF document using Aspose.Pdf. Developers working on invoicing, payment slips, or any financial documents that require Swiss QR‑Bills can follow this pattern to automate PDF generation.
+// Prompt: Use SwissQRBill class to generate a PDF QR‑bill document embedding the generated Swiss QR Code image.
+// Tags: swissqr, qr-bill, pdf, barcode generation, aspose.barcode, aspose.pdf
+
using System;
using System.IO;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
using Aspose.Pdf;
+using Aspose.Pdf.Text;
///
-/// Demonstrates generating a Swiss QR bill QR code and embedding it into a PDF using Aspose libraries.
+/// Example program that creates a Swiss QR‑Bill PDF by generating a QR code image
+/// with Aspose.BarCode and embedding it into a PDF document using Aspose.Pdf.
///
class Program
{
///
- /// Entry point of the application. Prepares QR bill data, creates a QR code image, and embeds it into a PDF.
+ /// Entry point of the example. Prepares QR‑Bill data, generates the QR code,
+ /// embeds it into a PDF, adds bill details as text, and saves the document.
///
static void Main()
{
- // Prepare Swiss QR bill data
+ // Prepare Swiss QR‑Bill data
var swissQr = new SwissQRCodetext();
swissQr.Bill.Creditor.Name = "John Doe";
swissQr.Bill.Creditor.CountryCode = "CH";
@@ -22,40 +31,43 @@ static void Main()
swissQr.Bill.Amount = 199.95m;
swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+ // Optional additional fields
+ swissQr.Bill.BillInformation = "Invoice 12345";
+
// Generate QR code image into a memory stream
- using (var generator = new ComplexBarcodeGenerator(swissQr))
+ using (var qrGenerator = new ComplexBarcodeGenerator(swissQr))
{
using (var qrStream = new MemoryStream())
{
- // Save QR code as PNG into the stream
- generator.Save(qrStream, BarCodeImageFormat.Png);
- // Reset stream position for reading
- qrStream.Position = 0;
+ qrGenerator.Save(qrStream, BarCodeImageFormat.Png);
+ qrStream.Position = 0; // Reset stream position for reading
- // Create a new PDF document
+ // Create PDF document and embed the QR code image
using (var pdfDoc = new Document())
{
- // Add a page to the PDF
var page = pdfDoc.Pages.Add();
- // Create an image object that reads from the QR code stream
- var pdfImage = new Aspose.Pdf.Image
+ // Add QR code image to the PDF page
+ var pdfImage = new Image
{
- ImageStream = qrStream,
- // Set desired dimensions for the QR code image
- FixWidth = 200.0,
- FixHeight = 200.0
+ ImageStream = new MemoryStream(qrStream.ToArray())
};
-
- // Add the image to the page's paragraph collection
+ // Set image size and remove margins
+ pdfImage.Margin = new MarginInfo(0, 0, 0, 0);
+ pdfImage.FixHeight = 150;
+ pdfImage.FixWidth = 150;
page.Paragraphs.Add(pdfImage);
- // Define output file name
- string outputPdf = "SwissQRBill.pdf";
- // Save the PDF to disk
- pdfDoc.Save(outputPdf);
- // Inform the user where the file was saved
- Console.WriteLine($"PDF QR‑bill generated: {Path.GetFullPath(outputPdf)}");
+ // Add bill information as text below the QR code
+ var tf = new TextFragment("Swiss QR Bill\nCreditor: John Doe\nAmount: CHF 199.95")
+ {
+ TextState = { FontSize = 12, Font = FontRepository.FindFont("Helvetica") }
+ };
+ tf.Position = new Position(0, 200);
+ page.Paragraphs.Add(tf);
+
+ // Save the final PDF document to disk
+ pdfDoc.Save("SwissQRBill.pdf");
}
}
}
diff --git a/swiss-qr-code/validate-decoded-payment-information-against-iso-20022-constraints-using-custom-net-business-rules.cs b/swiss-qr-code/validate-decoded-payment-information-against-iso-20022-constraints-using-custom-net-business-rules.cs
index e24bfa7..46b3b6b 100644
--- a/swiss-qr-code/validate-decoded-payment-information-against-iso-20022-constraints-using-custom-net-business-rules.cs
+++ b/swiss-qr-code/validate-decoded-payment-information-against-iso-20022-constraints-using-custom-net-business-rules.cs
@@ -1,215 +1,217 @@
+// Title: Validate payment barcode against ISO 20022 rules
+// Description: Demonstrates generating a Code128 barcode with payment data, decoding it, and validating fields per ISO 20022 constraints using custom .NET business rules.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to use BarcodeGenerator, BarCodeReader, and related parameter classes to create, read, and process barcodes. Typical use cases include encoding payment information, scanning, and applying business‑level validation such as ISO 20022 compliance. Developers often need to generate barcodes, extract data, and enforce domain‑specific rules.
+// Prompt: Validate decoded payment information against ISO 20022 constraints using custom .NET business rules.
+// Tags: barcode, code128, generation, recognition, iso20022, validation, payment, aspnet, aspose.barcode
+
using System;
+using System.Collections.Generic;
+using System.Globalization;
using System.IO;
-using System.Text.RegularExpressions;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates generating a QR code containing simple ISO 20022‑like payment data,
-/// reading it back, and validating the extracted information.
+/// Generates a Code128 barcode containing simple payment data, decodes it,
+/// and validates the extracted fields against a subset of ISO 20022 rules.
///
class Program
{
- // Sample payment data in a simple "key:value" per line format.
- private const string SamplePaymentData =
- "BIC:DEUTDEFF" + "\n" +
- "IBAN:DE89370400440532013000" + "\n" +
- "Amount:1234.56" + "\n" +
- "Currency:EUR";
-
///
- /// Entry point of the application.
- /// Generates a QR code, reads it, validates the decoded payment information,
- /// and cleans up the temporary image file.
+ /// Entry point of the example. Performs barcode creation, decoding, and validation.
///
static void Main()
{
- // Define a temporary file path for the generated QR code image.
- string imagePath = Path.Combine(Path.GetTempPath(), "payment_qr.png");
+ // Sample payment data encoded in a simple key=value; format
+ string paymentData = "IBAN=DE89370400440532013000;BIC=DEUTDEFF;Amt=123.45;Ccy=EUR";
+
+ // Prepare temporary file path for the barcode image
+ string tempFolder = Path.GetTempPath();
+ string barcodePath = Path.Combine(tempFolder, "payment.png");
- // ------------------------------------------------------------
- // Generate QR code containing the sample payment data.
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, SamplePaymentData))
+ // Generate a Code128 barcode containing the payment data
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, paymentData))
{
- // Use a high error correction level to improve readability.
- generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
- generator.Save(imagePath);
+ // Optional: set barcode appearance
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+
+ // Save the barcode image to the temporary location
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
}
- // Verify that the image file was successfully created.
- if (!File.Exists(imagePath))
+ // Verify that the barcode image was created successfully
+ if (!File.Exists(barcodePath))
{
Console.WriteLine("Failed to create barcode image.");
return;
}
- // ------------------------------------------------------------
- // Read and decode the QR code from the generated image.
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.QR))
+ // Decode the barcode from the saved image
+ using (BarCodeReader reader = new BarCodeReader(barcodePath, DecodeType.Code128))
{
- // Disable checksum validation (not required for QR codes).
+ // Disable checksum validation for this simple example
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
- var results = reader.ReadBarCodes();
- if (results.Length == 0)
+ // Read barcodes (there should be exactly one)
+ BarCodeResult[] results = reader.ReadBarCodes();
+ if (results == null || results.Length == 0)
{
Console.WriteLine("No barcode detected.");
return;
}
- foreach (var result in results)
+ // Extract the decoded text
+ string decodedText = results[0].CodeText;
+ Console.WriteLine("Decoded text: " + decodedText);
+
+ // Parse key=value pairs into a dictionary
+ Dictionary fields = ParseKeyValuePairs(decodedText);
+
+ // Validate the extracted fields according to simplified ISO 20022 rules
+ List validationErrors = ValidatePaymentFields(fields);
+
+ // Output validation results
+ if (validationErrors.Count == 0)
+ {
+ Console.WriteLine("Payment information is valid.");
+ }
+ else
{
- Console.WriteLine("Decoded Text:");
- Console.WriteLine(result.CodeText);
- Console.WriteLine();
-
- // Validate the decoded payment information.
- var validation = ValidatePaymentInfo(result.CodeText);
- Console.WriteLine("Validation Result: " + (validation.IsValid ? "Valid" : "Invalid"));
- if (!validation.IsValid)
+ Console.WriteLine("Validation errors:");
+ foreach (string err in validationErrors)
{
- Console.WriteLine("Errors:");
- foreach (var err in validation.Errors)
- {
- Console.WriteLine("- " + err);
- }
+ Console.WriteLine("- " + err);
}
}
}
- // ------------------------------------------------------------
- // Clean up the temporary QR code image file.
- // ------------------------------------------------------------
- try { File.Delete(imagePath); } catch { }
+ // Clean up the temporary barcode image file
+ try
+ {
+ File.Delete(barcodePath);
+ }
+ catch
+ {
+ // Ignored – best effort cleanup
+ }
}
- // ------------------------------------------------------------------------
- // Helper classes and methods for validation.
- // ------------------------------------------------------------------------
-
///
- /// Represents the outcome of validating payment information.
+ /// Parses a string formatted as "Key1=Value1;Key2=Value2" into a case‑insensitive dictionary.
///
- private class ValidationResult
+ /// The input string containing key/value pairs.
+ /// A dictionary of parsed fields.
+ private static Dictionary ParseKeyValuePairs(string input)
{
- ///
- /// Gets a value indicating whether the validation succeeded (no errors).
- ///
- public bool IsValid => Errors.Count == 0;
-
- ///
- /// Collection of validation error messages.
- ///
- public System.Collections.Generic.List Errors { get; } = new System.Collections.Generic.List();
+ var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ string[] pairs = input.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string pair in pairs)
+ {
+ int idx = pair.IndexOf('=');
+ if (idx > 0 && idx < pair.Length - 1)
+ {
+ string key = pair.Substring(0, idx).Trim();
+ string value = pair.Substring(idx + 1).Trim();
+ dict[key] = value;
+ }
+ }
+ return dict;
}
///
- /// Validates raw payment text against simple ISO 20022‑like rules.
+ /// Performs simple ISO 20022‑style validation on payment fields.
///
- /// The decoded QR code text.
- /// A containing validation status and errors.
- private static ValidationResult ValidatePaymentInfo(string rawText)
+ /// Dictionary containing payment fields.
+ /// List of validation error messages; empty if all checks pass.
+ private static List ValidatePaymentFields(Dictionary fields)
{
- var result = new ValidationResult();
+ var errors = new List();
- // Ensure the text is not null, empty, or whitespace.
- if (string.IsNullOrWhiteSpace(rawText))
+ // IBAN validation (basic length and format)
+ if (fields.TryGetValue("IBAN", out string iban))
{
- result.Errors.Add("Code text is empty.");
- return result;
+ if (iban.Length != 22)
+ errors.Add("IBAN must be 22 characters long.");
+ else if (!char.IsLetter(iban[0]) || !char.IsLetter(iban[1]))
+ errors.Add("IBAN must start with two letters.");
+ else if (!IsAllAlphanumeric(iban))
+ errors.Add("IBAN must contain only alphanumeric characters.");
}
-
- // Split the text into lines and parse each "Key:Value" pair.
- var lines = rawText.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
- var dict = new System.Collections.Generic.Dictionary(StringComparer.OrdinalIgnoreCase);
- foreach (var line in lines)
+ else
{
- var parts = line.Split(new[] { ':' }, 2);
- if (parts.Length != 2)
- {
- result.Errors.Add($"Invalid line format: '{line}'. Expected 'Key:Value'.");
- continue;
- }
- dict[parts[0].Trim()] = parts[1].Trim();
+ errors.Add("IBAN field is missing.");
}
- // Validate each required field.
- ValidateBic(dict, result);
- ValidateIban(dict, result);
- ValidateAmount(dict, result);
- ValidateCurrency(dict, result);
-
- return result;
- }
-
- private static void ValidateBic(System.Collections.Generic.Dictionary dict, ValidationResult result)
- {
- // Check for presence of BIC.
- if (!dict.TryGetValue("BIC", out var bic))
+ // BIC validation (8 or 11 characters, letters/digits)
+ if (fields.TryGetValue("BIC", out string bic))
{
- result.Errors.Add("Missing BIC.");
- return;
+ if (bic.Length != 8 && bic.Length != 11)
+ errors.Add("BIC must be 8 or 11 characters long.");
+ else if (!IsAllLettersOrDigits(bic))
+ errors.Add("BIC must contain only letters and digits.");
}
-
- // BIC must be 8 or 11 alphanumeric characters.
- if (!Regex.IsMatch(bic, @"^[A-Z0-9]{8}([A-Z0-9]{3})?$"))
+ else
{
- result.Errors.Add($"Invalid BIC format: '{bic}'.");
+ errors.Add("BIC field is missing.");
}
- }
- private static void ValidateIban(System.Collections.Generic.Dictionary dict, ValidationResult result)
- {
- // Check for presence of IBAN.
- if (!dict.TryGetValue("IBAN", out var iban))
+ // Amount validation (positive decimal)
+ if (fields.TryGetValue("Amt", out string amtStr))
{
- result.Errors.Add("Missing IBAN.");
- return;
+ if (!decimal.TryParse(amtStr, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal amt) || amt <= 0)
+ errors.Add("Amount must be a positive decimal number.");
}
-
- // Basic IBAN pattern: 2 letters, 2 digits, up to 30 alphanumerics.
- if (!Regex.IsMatch(iban, @"^[A-Z]{2}\d{2}[A-Z0-9]{1,30}$"))
+ else
{
- result.Errors.Add($"Invalid IBAN format: '{iban}'.");
+ errors.Add("Amt (amount) field is missing.");
}
- }
- private static void ValidateAmount(System.Collections.Generic.Dictionary dict, ValidationResult result)
- {
- // Check for presence of Amount.
- if (!dict.TryGetValue("Amount", out var amountStr))
+ // Currency validation (3 uppercase letters)
+ if (fields.TryGetValue("Ccy", out string ccy))
{
- result.Errors.Add("Missing Amount.");
- return;
+ if (ccy.Length != 3 || !IsAllUppercaseLetters(ccy))
+ errors.Add("Currency code must be three uppercase letters.");
}
+ else
+ {
+ errors.Add("Ccy (currency) field is missing.");
+ }
+
+ return errors;
+ }
- // Ensure the amount is a positive decimal number.
- if (!decimal.TryParse(
- amountStr,
- System.Globalization.NumberStyles.AllowDecimalPoint,
- System.Globalization.CultureInfo.InvariantCulture,
- out var amount) || amount <= 0)
+ // Helper: checks that a string contains only letters or digits
+ private static bool IsAllAlphanumeric(string s)
+ {
+ foreach (char c in s)
{
- result.Errors.Add($"Invalid Amount value: '{amountStr}'. Must be a positive number.");
+ if (!char.IsLetterOrDigit(c))
+ return false;
}
+ return true;
}
- private static void ValidateCurrency(System.Collections.Generic.Dictionary dict, ValidationResult result)
+ // Helper: duplicate of IsAllAlphanumeric (kept for semantic clarity)
+ private static bool IsAllLettersOrDigits(string s)
{
- // Check for presence of Currency.
- if (!dict.TryGetValue("Currency", out var currency))
+ foreach (char c in s)
{
- result.Errors.Add("Missing Currency.");
- return;
+ if (!char.IsLetterOrDigit(c))
+ return false;
}
+ return true;
+ }
- // Currency must be three uppercase letters (ISO 4217).
- if (!Regex.IsMatch(currency, @"^[A-Z]{3}$"))
+ // Helper: checks that a string contains only uppercase letters
+ private static bool IsAllUppercaseLetters(string s)
+ {
+ foreach (char c in s)
{
- result.Errors.Add($"Invalid Currency code: '{currency}'.");
+ if (!char.IsUpper(c) || !char.IsLetter(c))
+ return false;
}
+ return true;
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/validate-that-generated-swiss-qr-code-complies-with-swiss-implementation-guidelines-by-checking-required-data-fields.cs b/swiss-qr-code/validate-that-generated-swiss-qr-code-complies-with-swiss-implementation-guidelines-by-checking-required-data-fields.cs
index a1d8d72..7690043 100644
--- a/swiss-qr-code/validate-that-generated-swiss-qr-code-complies-with-swiss-implementation-guidelines-by-checking-required-data-fields.cs
+++ b/swiss-qr-code/validate-that-generated-swiss-qr-code-complies-with-swiss-implementation-guidelines-by-checking-required-data-fields.cs
@@ -1,116 +1,87 @@
+// Title: Validate Swiss QR Code against Implementation Guidelines
+// Description: Demonstrates creating a Swiss QR Code, validating required fields per Swiss guidelines, generating the barcode image, and verifying the encoded data.
+// Category-Description: This example belongs to the Aspose.BarCode Swiss QR Code generation and validation category. It showcases the use of SwissQRCodetext, ComplexBarcodeGenerator, and ComplexCodetextReader classes to create, encode, and decode Swiss QR Bills. Developers commonly need to generate compliant QR codes for payments and verify that all mandatory fields are correctly embedded, making this pattern essential for financial and invoicing applications.
+// Prompt: Validate that the generated Swiss QR Code complies with Swiss Implementation Guidelines by checking required data fields.
+// Tags: swiss qr, barcode, validation, generation, aspose.barcode, swissqr, payment
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates generation, reading, and validation of a Swiss QR Code using Aspose.BarCode.
+/// Example program that creates, validates, generates, and decodes a Swiss QR Code
+/// according to the Swiss Implementation Guidelines.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Swiss QR Code, reads it back, and validates required fields.
+ /// Entry point of the example. Performs field validation, barcode generation,
+ /// and round‑trip verification of the Swiss QR Code data.
///
static void Main()
{
// ------------------------------------------------------------
- // 1. Prepare Swiss QR code data according to the Swiss Implementation Guidelines
+ // 1. Build the Swiss QR code data structure and populate required fields
// ------------------------------------------------------------
var swissQr = new SwissQRCodetext();
- swissQr.Bill.Account = "CH9300762011623852957"; // Valid IBAN
- swissQr.Bill.Amount = 199.95m; // Amount (decimal with 'm' suffix)
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; // Required version
- swissQr.Bill.Creditor.Name = "John Doe"; // Creditor name (mandatory)
- swissQr.Bill.Creditor.CountryCode = "CH"; // Creditor country code (mandatory)
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+
+ // ------------------------------------------------------------
+ // 2. Validate required fields according to Swiss Implementation Guidelines
+ // ------------------------------------------------------------
+ if (string.IsNullOrWhiteSpace(swissQr.Bill.Creditor.Name))
+ throw new ArgumentException("Creditor name is required.");
+ if (string.IsNullOrWhiteSpace(swissQr.Bill.Creditor.CountryCode))
+ throw new ArgumentException("Creditor country code is required.");
+ if (string.IsNullOrWhiteSpace(swissQr.Bill.Account))
+ throw new ArgumentException("Account (IBAN) is required.");
+ if (swissQr.Bill.Amount <= 0)
+ throw new ArgumentException("Amount must be greater than zero.");
+ if (swissQr.Bill.Version != SwissQRBill.QrBillStandardVersion.V2_0)
+ throw new ArgumentException("Bill version must be V2_0.");
// ------------------------------------------------------------
- // 2. Generate the Swiss QR barcode image into a memory stream
+ // 3. Generate the Swiss QR barcode image and save it to disk
// ------------------------------------------------------------
using (var generator = new ComplexBarcodeGenerator(swissQr))
- using (var ms = new MemoryStream())
{
- // Save the barcode as PNG into the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for subsequent reading
+ // Save the barcode image for visual verification (optional)
+ generator.Save("SwissQR.png");
// ------------------------------------------------------------
- // 3. Recognize the barcode from the generated image
+ // 4. Retrieve the constructed codetext for decoding
// ------------------------------------------------------------
- using (var reader = new BarCodeReader(ms, DecodeType.QR))
- {
- var results = reader.ReadBarCodes();
-
- // If no QR code was detected, inform the user and exit
- if (results.Length == 0)
- {
- Console.WriteLine("No QR code detected in the generated image.");
- return;
- }
-
- // Process each detected QR code (should be only one in this scenario)
- foreach (var result in results)
- {
- // ------------------------------------------------------------
- // 4. Decode the complex Swiss QR codetext
- // ------------------------------------------------------------
- var decoded = ComplexCodetextReader.TryDecodeSwissQR(result.CodeText);
- if (decoded == null)
- {
- Console.WriteLine("Failed to decode Swiss QR codetext.");
- continue;
- }
-
- // ------------------------------------------------------------
- // 5. Validate required fields of the decoded Swiss QR bill
- // ------------------------------------------------------------
- bool valid = true;
+ string constructedCodetext = swissQr.GetConstructedCodetext();
- // Validate IBAN (Account)
- if (string.IsNullOrWhiteSpace(decoded.Bill.Account))
- {
- Console.WriteLine("Missing or empty Account (IBAN).");
- valid = false;
- }
-
- // Validate amount (must be greater than zero)
- if (decoded.Bill.Amount <= 0)
- {
- Console.WriteLine("Amount must be greater than zero.");
- valid = false;
- }
-
- // Validate version (must be V2_0)
- if (decoded.Bill.Version != SwissQRBill.QrBillStandardVersion.V2_0)
- {
- Console.WriteLine($"Invalid version: {decoded.Bill.Version}");
- valid = false;
- }
-
- // Validate creditor name
- if (decoded.Bill.Creditor == null ||
- string.IsNullOrWhiteSpace(decoded.Bill.Creditor.Name))
- {
- Console.WriteLine("Creditor name is missing.");
- valid = false;
- }
+ // ------------------------------------------------------------
+ // 5. Decode the codetext back into a SwissQRCodetext object
+ // ------------------------------------------------------------
+ SwissQRCodetext decoded = ComplexCodetextReader.TryDecodeSwissQR(constructedCodetext);
+ if (decoded == null)
+ {
+ Console.WriteLine("Failed to decode the generated Swiss QR codetext.");
+ return;
+ }
- // Validate creditor country code
- if (decoded.Bill.Creditor == null ||
- string.IsNullOrWhiteSpace(decoded.Bill.Creditor.CountryCode))
- {
- Console.WriteLine("Creditor country code is missing.");
- valid = false;
- }
+ // ------------------------------------------------------------
+ // 6. Verify that decoded fields match the original input data
+ // ------------------------------------------------------------
+ bool isValid = decoded.Bill.Creditor.Name == swissQr.Bill.Creditor.Name &&
+ decoded.Bill.Creditor.CountryCode == swissQr.Bill.Creditor.CountryCode &&
+ decoded.Bill.Account == swissQr.Bill.Account &&
+ decoded.Bill.Amount == swissQr.Bill.Amount &&
+ decoded.Bill.Version == swissQr.Bill.Version;
- // Output validation result
- Console.WriteLine(valid
- ? "Swiss QR Code validation passed: all required fields are present."
- : "Swiss QR Code validation failed: some required fields are missing or invalid.");
- }
- }
+ Console.WriteLine(isValid
+ ? "Swiss QR Code validation succeeded: all required fields are present and correct."
+ : "Swiss QR Code validation failed: decoded fields do not match the original data.");
}
}
}
\ No newline at end of file
diff --git a/swiss-qr-code/write-unit-tests-to-verify-complexbarcodegenerator-produces-correct-qr-code-data-for-given-payment-fields.cs b/swiss-qr-code/write-unit-tests-to-verify-complexbarcodegenerator-produces-correct-qr-code-data-for-given-payment-fields.cs
index 6cbd10c..283e283 100644
--- a/swiss-qr-code/write-unit-tests-to-verify-complexbarcodegenerator-produces-correct-qr-code-data-for-given-payment-fields.cs
+++ b/swiss-qr-code/write-unit-tests-to-verify-complexbarcodegenerator-produces-correct-qr-code-data-for-given-payment-fields.cs
@@ -1,94 +1,142 @@
+// Title: Verify ComplexBarcodeGenerator QR code generation for SwissQR payment data
+// Description: Demonstrates unit-test style verification that the generated QR code matches the expected SwissQR codetext for minimal and full payment scenarios.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on QR code creation for payment standards such as SwissQR. It showcases the use of ComplexBarcodeGenerator, SwissQRCodetext, and BarCodeReader to encode and decode QR codes, a common task for developers implementing payment QR codes, invoicing, or financial data exchange.
+// Prompt: Write unit tests to verify ComplexBarcodeGenerator produces correct QR code data for given payment fields.
+// Tags: qr code, payment, swissqr, complexbarcode, generation, decoding, aspose.barcode, unit-test
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation and verification of a Swiss QR payment barcode using Aspose.BarCode.
+/// Contains example tests that generate SwissQR QR codes using ComplexBarcodeGenerator
+/// and verify the encoded data by decoding the image.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Swiss QR code, reads it back, and validates the encoded data.
+ /// Entry point that runs two verification scenarios: minimal and full SwissQR data.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Prepare Swiss QR payment data
- // ------------------------------------------------------------
- var swissQr = new SwissQRCodetext();
- swissQr.Bill.Creditor.Name = "John Doe";
- swissQr.Bill.Creditor.CountryCode = "CH";
- swissQr.Bill.Account = "CH9300762011623852957";
- swissQr.Bill.Amount = 199.95m;
- swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+ int passed = 0, failed = 0;
- // ------------------------------------------------------------
- // 2. Build the expected codetext string for later comparison
- // ------------------------------------------------------------
- string expectedCodetext = swissQr.GetConstructedCodetext();
+ // Helper to execute a test and capture pass/fail status
+ void RunTest(string name, Action test)
+ {
+ try
+ {
+ test();
+ Console.WriteLine($"PASS: {name}");
+ passed++;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"FAIL: {name} - {ex.Message}");
+ failed++;
+ }
+ }
// ------------------------------------------------------------
- // 3. Generate QR code image using ComplexBarcodeGenerator
+ // Test 1: Minimal SwissQR fields
// ------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(swissQr))
+ RunTest("SwissQR Minimal", () =>
{
- using (var ms = new MemoryStream())
+ // Build minimal SwissQR payload
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Creditor.Name = "John Doe";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 199.95m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+
+ // Generate QR code with high error correction
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
{
- // Save the generated QR code as PNG into the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading
-
- // ------------------------------------------------------------
- // 4. Recognize the QR code from the generated image
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(ms, DecodeType.QR))
+ generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
+ generator.Parameters.Barcode.FilledBars = false;
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+
+ // Save QR image to memory stream
+ using (var ms = new MemoryStream())
{
- var results = reader.ReadBarCodes();
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0;
- // Ensure at least one barcode was detected
- if (results.Length == 0)
+ // Decode the QR code to verify its content
+ using (var reader = new BarCodeReader(ms, DecodeType.QR))
{
- Console.WriteLine("FAIL: No barcode detected.");
- return;
- }
+ var results = reader.ReadBarCodes();
+ if (results.Length == 0)
+ throw new InvalidOperationException("No barcode detected.");
- var result = results[0];
- string recognizedCodetext = result.CodeText;
+ string decoded = results[0].CodeText;
+ string expected = swissQr.GetConstructedCodetext();
- // ------------------------------------------------------------
- // 5. Verify that the recognized codetext matches the expected one
- // ------------------------------------------------------------
- if (recognizedCodetext == expectedCodetext)
- {
- Console.WriteLine("PASS: Recognized QR code matches expected codetext.");
- }
- else
- {
- Console.WriteLine("FAIL: Mismatch in QR code data.");
- Console.WriteLine($"Expected: {expectedCodetext}");
- Console.WriteLine($"Actual : {recognizedCodetext}");
+ if (!string.Equals(decoded, expected, StringComparison.Ordinal))
+ throw new InvalidOperationException($"Decoded text does not match. Expected: {expected}, Got: {decoded}");
}
+ }
+ }
+ });
- // ------------------------------------------------------------
- // 6. Additional verification using ComplexCodetextReader
- // ------------------------------------------------------------
- var decoded = ComplexCodetextReader.TryDecodeSwissQR(recognizedCodetext);
- if (decoded != null && decoded.GetConstructedCodetext() == expectedCodetext)
- {
- Console.WriteLine("PASS: ComplexCodetextReader successfully decoded the QR code.");
- }
- else
+ // ------------------------------------------------------------
+ // Test 2: Full SwissQR fields
+ // ------------------------------------------------------------
+ RunTest("SwissQR Full", () =>
+ {
+ // Build full SwissQR payload with creditor, debtor, and additional data
+ var swissQr = new SwissQRCodetext();
+ swissQr.Bill.Creditor.Name = "Acme Corp";
+ swissQr.Bill.Creditor.CountryCode = "CH";
+ swissQr.Bill.Account = "CH9300762011623852957";
+ swissQr.Bill.Amount = 1234.56m;
+ swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
+ swissQr.Bill.Creditor.Street = "Musterstrasse 1";
+ swissQr.Bill.Creditor.PostalCode = "8000";
+ swissQr.Bill.Creditor.Town = "Zürich";
+ swissQr.Bill.Debtor.Name = "John Smith";
+ swissQr.Bill.Debtor.Street = "Example Ave 5";
+ swissQr.Bill.Debtor.PostalCode = "3000";
+ swissQr.Bill.Debtor.Town = "Bern";
+ swissQr.Bill.Reference = "RF18539007547034";
+ swissQr.Bill.UnstructuredMessage = "Invoice 2023-001";
+
+ // Generate QR code with medium error correction
+ using (var generator = new ComplexBarcodeGenerator(swissQr))
+ {
+ generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelM;
+ generator.Parameters.Barcode.FilledBars = false;
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+
+ // Save QR image to memory stream
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0;
+
+ // Decode the QR code to verify its content
+ using (var reader = new BarCodeReader(ms, DecodeType.QR))
{
- Console.WriteLine("FAIL: ComplexCodetextReader could not decode the QR code correctly.");
+ var results = reader.ReadBarCodes();
+ if (results.Length == 0)
+ throw new InvalidOperationException("No barcode detected.");
+
+ string decoded = results[0].CodeText;
+ string expected = swissQr.GetConstructedCodetext();
+
+ if (!string.Equals(decoded, expected, StringComparison.Ordinal))
+ throw new InvalidOperationException($"Decoded text does not match. Expected: {expected}, Got: {decoded}");
}
}
}
- }
+ });
+
+ // Output summary of test results
+ Console.WriteLine($"Summary: {passed} passed, {failed} failed.");
}
}
\ No newline at end of file