.NET HELP

Azure.Messaging.ServiceBus Example C# (How It Works)

Published August 13, 2024
Share:

In today's interconnected digital landscape, efficient communication is the cornerstone of successful businesses. Whether it's transmitting critical data between applications or ensuring real-time updates across distributed systems, a reliable messaging infrastructure is indispensable.

Azure Service Bus, a cloud-based messaging service, emerges as a robust solution empowering developers to build scalable, decoupled, and resilient applications. Let's delve into the realm of Azure Service Bus to understand its significance and explore its myriad capabilities. Later in this article, we will also look into IronPDF to manage, generate, and read PDF documents.

Understanding Azure Service Bus

Azure Service Bus is a fully managed enterprise integration message broker that facilitates reliable communication between applications and services, whether they are running on the cloud, on-premises, or hybrid environments.

It provides flexible messaging capabilities, including queuing and publish/subscribe mechanisms, to enable seamless communication among disparate components of a distributed system. Additionally, it allows batch messages, which permits multiple messages without exceeding the total size constraint.

Azure Service Bus offers the following benefits:

  1. Decoupling Applications: Service Bus allows you to separate applications and services from each other. This decoupling enhances reliability and scalability.
  2. Load Balancing: It balances work across competing workers, ensuring efficient resource utilization.
  3. Message Transfer: Data is transferred between applications and services using messages. The message body of these messages can contain various types of data, such as JSON, XML, or plain text.
  4. Messaging Scenarios: Common scenarios include transferring business data (e.g., sales orders), load balancing, and enabling relationships between publishers and subscribers using topics and subscriptions.
  5. Transactions: Service Bus supports atomic transactions, allowing multiple operations within a single transaction scope. A transaction would have multiple concurrent calls, whereas a message batch would have a single call.
  6. Message Sessions: It facilitates high-scale coordination of workflows and ordered message transfers.

Key Features and Capabilities

  1. Queues and Topics: Azure Service Bus offers both queues and topics as communication channels. Queues enable point-to-point communication, ensuring that each message is processed by only one receiver, making it ideal for workload distribution and load-leveling scenarios. On the other hand, topics support publish/subscribe messaging patterns, allowing multiple subscribers to receive relevant messages independently, and facilitating scalable event-driven architectures.

  2. Reliable Message Delivery: With Azure Service Bus, message delivery is inherently reliable. It ensures message persistence, can configure the message and error handler, fault tolerance, and at-least-once delivery semantics, minimizing the risk of data loss or duplication. Additionally, it supports transactions, enabling atomic operations across multiple messages, thereby ensuring data integrity.

  3. Dead-Lettering and Retry Policies: To handle erroneous messages effectively, Azure Service Bus provides dead-lettering capabilities, allowing problematic messages to be automatically moved to a separate queue for analysis and troubleshooting. Moreover, it offers flexible retry policies, enabling developers to configure automatic retries with exponential back-off strategies, enhancing the resilience of applications in the face of transient failures.

  4. Partitioning and Scaling: Azure Service Bus supports the partitioning of messaging entities to distribute workload across multiple nodes, ensuring horizontal scalability and high throughput. This capability is crucial for handling large volumes of messages and accommodating fluctuating workloads without compromising performance or reliability.

  5. Integration with Azure Ecosystem: Azure Service Bus seamlessly integrates with other Azure services, such as Azure Functions, Logic Apps, Event Grid, and Azure Kubernetes Service (AKS), enabling developers to build end-to-end solutions with ease. Whether it's triggering serverless functions in response to incoming messages or orchestrating complex workflows using Logic Apps, Azure Service Bus serves as a linchpin for building robust, event-driven architectures.

Introduction to IronPDF

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 1

IronPDF is a powerful C# PDF library that allows you to generate, edit, and extract content from PDF documents in .NET projects. Here are some key features:

  1. HTML to PDF Conversion:

    • Convert HTML, CSS, and JavaScript content to PDF format.

    • Use the Chrome Rendering Engine for pixel-perfect PDFs.

    • Generate PDFs from URLs, HTML files, or HTML strings.
  2. Image and Content Conversion:

    • Convert images to and from PDF.

    • Extract text and images from existing PDFs.

    • Support for various image formats.
  3. Editing and Manipulation:

    • Set properties, security, and permissions for PDFs.

    • Add digital signatures.

    • Edit metadata and revision history.
  4. Cross-Platform Support:

    • Works with .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), and .NET Framework (4.6.2+).

    • Compatible with Windows, Linux, and macOS.

    • Available on NuGet for easy installation.

Generate a PDF document Using IronPDF And Azure.Messaging.ServiceBus

To start with create a console application using Visual Studio as below.

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 2

Provide Project Name

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 3

Provide .NET Version

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 4

Install the IronPDF package.

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 5

Creating Azure Service Bus

Create a namespace with a unique name across Azure. A namespace is a container for Service Bus resources like queues and topics within your application.

Here's how to create a namespace:

  1. Log in to the Azure portal.
  2. Go to the "All services" page.
  3. In the left navigation pane, select "Integration" from the categories list.
  4. Hover over "Service Bus" and click on the "+" button on the Service Bus tile.

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 6

To configure the Basics tab on the Create namespace page, follow these steps:

  1. Subscription: Select the Azure subscription where you want to create the namespace.
  2. Resource group: Choose an existing resource group where the namespace will be located, or create a new one.

  3. Namespace name: Enter a name for the namespace. Ensure the name meets the following criteria:

    • Must be unique across Azure.

    • Length must be between 6 and 50 characters.

    • Can only contain letters, numbers, and hyphens "-".

    • Must start with a letter and end with a letter or number.

    • Cannot end with "-sb" or "-mgmt".
  4. Location: Select the region where your namespace should be hosted.
  5. Pricing tier: Choose the pricing tier (Basic, Standard, or Premium) for the namespace. For this example, select Standard.

  6. Select Review + Create at the bottom of the page.

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 7

  1. Select Create on the Review + Create page.

  2. Once the deployment of the resource is successful, Go to the resource.

You see the home page for your Service Bus namespace.

Create Service Bus Queues in the Azure Portal

To set up a queue in your Service Bus namespace, follow these steps:

  1. Navigate to Queues: Go to the Service Bus Namespace page in the Azure portal. Select "Queues" from the left navigation menu.
  2. Create a New Queue: On the Queues page, click on the "+ Queue" button on the toolbar.
  3. Configure Queue: Enter a name for your queue in the provided field. Leave the other settings with their default values. The options you need to configure when creating an Azure Service Bus queue:
    1. Name: This is the unique identifier for your queue. Choose a name that is descriptive and easy to remember.
    2. Max Queue Size: This defines the maximum storage capacity of the queue. You can set it to 1 GB, 2 GB, 5 GB, 10 GB, 20 GB, 40 GB, 80 GB, or 100 GB. For your case, it’s set to 1 GB.
    3. Max Delivery Count: This specifies the maximum number of times a message can be delivered before it is sent to the dead-letter queue or discarded. This helps in handling message processing failures.
    4. Message Time to Live (TTL): This determines how long a message remains in the queue before it expires. You can set this in days, hours, minutes, and seconds. Once the TTL is reached, the dead letter messages are either discarded or moved to the dead-letter queue if dead-lettering is enabled.
    5. Lock Duration: This is the amount of time a message is locked for processing by a receiver. During this time, other receivers cannot process the same message. You can set this duration in days, hours, minutes, and seconds.
    6. Enable Dead Lettering on Message Expiration: When enabled, messages that expire (i.e., exceed their TTL) are moved to the dead-letter queue instead of being discarded. This allows for further inspection and handling of expired messages.
    7. Enable Partitioning: This option enables partitioning of the queue across multiple message brokers, which can improve scalability and throughput. Partitioning is useful for handling large volumes of messages.

These settings help you control the behavior and performance of your Azure Service Bus queue, ensuring it meets your application’s requirements.

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 8

  1. Complete Creation: Click on the "Create" button to finalize the creation of the queue. These steps ensure you successfully create a queue within your Service Bus namespace using the Azure portal.

Install Azure.Messaging.ServiceBus, a Service Bus client library, to connect to the Azure queue using a connection string.

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 9

Add the code below to send messages and receive messages using Azure.Messaging.ServiceBus.

using Azure.Messaging.ServiceBus;
namespace CodeSample
{
    public static class AzureServiceBusDemo
    {
        public static async Task Execute()
        {
            string connectionString = "Endpoint=sb://iron-articles.servicebus.windows.net/;SharedAccessKeyName=all;SharedAccessKey=uqQIzpuc2HxbnAb9keqTINvzfTcFbkkU0+ASbJZ/tow=;EntityPath=ironpdf";
            string queName = "ironpdf";
            Console.WriteLine("Demo IronPDF with Azure.Messaging.ServiceBus");
            Installation.EnableWebSecurity = true;
            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo IronPDF with Azure.Messaging.ServiceBus</h1>";
            content += "<h2>Send Message to Azure.Messaging.ServiceBus Queue: ironpdf</h2>";
            await using var client = new ServiceBusClient(connectionString);
            var msgText = "IronPDF is Awesome Package";
            content += $"<p>Message:{msgText}</p>";
            var tx = client.CreateSender(queName);
            await tx.SendMessageAsync(new ServiceBusMessage(msgText)); // message await sender
            Console.WriteLine($"Sent Below message at:{DateTime.Now}");
            content += $"<p>Sent Below message at:{DateTime.Now}</p>";
            Console.Read(); // wait for user input to read the message;
            var rx = client.CreateReceiver(queName);
            var msg = await rx.ReceiveMessageAsync(); // receive messages
            content += "<h2>Receive Message from Azure.Messaging.ServiceBus Queue: ironpdf</h2>";
            content += $"<p>Recieved Below message at:{DateTime.Now}</p>";
            Console.WriteLine($"Recieved Below message at:{DateTime.Now}");
            content += $"<p>MessageID={msg}</p>";
            Console.WriteLine($"MessageID={msg}");
            content += $"<p>Message Received: {msg.Body}</p>";
            Console.WriteLine($"Message Received: {msg.Body}");
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeAzureServiceBusQueueAndIronPdf.pdf");
        }
    }
}
using Azure.Messaging.ServiceBus;
namespace CodeSample
{
    public static class AzureServiceBusDemo
    {
        public static async Task Execute()
        {
            string connectionString = "Endpoint=sb://iron-articles.servicebus.windows.net/;SharedAccessKeyName=all;SharedAccessKey=uqQIzpuc2HxbnAb9keqTINvzfTcFbkkU0+ASbJZ/tow=;EntityPath=ironpdf";
            string queName = "ironpdf";
            Console.WriteLine("Demo IronPDF with Azure.Messaging.ServiceBus");
            Installation.EnableWebSecurity = true;
            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo IronPDF with Azure.Messaging.ServiceBus</h1>";
            content += "<h2>Send Message to Azure.Messaging.ServiceBus Queue: ironpdf</h2>";
            await using var client = new ServiceBusClient(connectionString);
            var msgText = "IronPDF is Awesome Package";
            content += $"<p>Message:{msgText}</p>";
            var tx = client.CreateSender(queName);
            await tx.SendMessageAsync(new ServiceBusMessage(msgText)); // message await sender
            Console.WriteLine($"Sent Below message at:{DateTime.Now}");
            content += $"<p>Sent Below message at:{DateTime.Now}</p>";
            Console.Read(); // wait for user input to read the message;
            var rx = client.CreateReceiver(queName);
            var msg = await rx.ReceiveMessageAsync(); // receive messages
            content += "<h2>Receive Message from Azure.Messaging.ServiceBus Queue: ironpdf</h2>";
            content += $"<p>Recieved Below message at:{DateTime.Now}</p>";
            Console.WriteLine($"Recieved Below message at:{DateTime.Now}");
            content += $"<p>MessageID={msg}</p>";
            Console.WriteLine($"MessageID={msg}");
            content += $"<p>Message Received: {msg.Body}</p>";
            Console.WriteLine($"Message Received: {msg.Body}");
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeAzureServiceBusQueueAndIronPdf.pdf");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Code Explanation

  1. Connection String and Queue Name:

    • The connectionString variable contains the connection details for your Azure Service Bus namespace. It specifies the endpoint, shared access key, and entity path (queue name).

    • The queName variable holds the name of the Service Bus queue you want to work with.
  2. Demo Setup:

    • The code starts by printing a message: “Demo IronPDF with Azure.Messaging.ServiceBus.”

    • It enables web security using Installation.EnableWebSecurity = true;.
  3. Creating a Service Bus Client:

    • The ServiceBusClient is created using the provided connection string.

    • This client allows you to interact with Service Bus entities (queues, topics, etc.).
  4. Sending a Message:

    • A message with the content “IronPDF is Awesome Package” is sent to the specified queue using the CreateSender method.

    • The message is created using new ServiceBusMessage(msgText).

    • The timestamp of the sent message is printed to the console.
  5. Receiving a Message:

    • A receiver is created for the same queue using CreateReceiver.

    • The code waits for user input (using Console.Read()) to simulate message processing.

    • When a message is received, its ID and body are printed to the console.
  6. Generating a PDF:

    • The renderer creates a PDF from the HTML content (including the sent and received messages).

    • The resulting PDF is saved as “AwesomeAzureServiceBusQueueAndIronPdf.pdf.”

Output

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 10

PDF

Azure.Messaging.ServiceBus Example C# (How It Works): Figure 11

IronPDF Licensing

The IronPDF package requires a license to run and generate the PDF. Add the code below at the start of the application before the package is accessed.

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

A trial license is available on the IronPDF Trial License Page.

Conclusion

In an era characterized by digital transformation and rapid technological advancements, the Azure Service Bus emerges as a pivotal component in the modernization journey of businesses worldwide. By providing reliable, scalable, and flexible messaging capabilities, it empowers developers to architect resilient and agile solutions that can adapt to evolving business requirements.

Whether it's facilitating seamless integration, enabling event-driven architectures, or ensuring asynchronous communication, Azure Service Bus plays a transformative role in driving innovation and accelerating digital initiatives across industries.

As organizations continue to embrace cloud-native paradigms and distributed architectures, Azure Service Bus stands as a testament to Microsoft's commitment to empowering developers and enterprises on their journey to the cloud. IronPDF simplifies PDF generation within .NET applications, offering flexibility and functionality for creating professional-grade documents directly from code.

< PREVIOUS
WebGrease .NET Core (How It Works For Developers)
NEXT >
Simple Injector C# (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >