Przejdź do treści stopki
POMOC .NET

NServiceBus C# (jak to działa dla programistów)

NServiceBus to potężna i elastyczna magistrala usług zaprojektowana dla platformy .NET Framework, która usprawnia tworzenie systemów rozproszonych. Oferowane przez nią solidne wzorce komunikacyjne gwarantują niezawodną obsługę i dostarczanie komunikatów w wielu mikrousługach i aplikacjach. NServiceBus abstrahuje podstawową architekturę komunikacyjną, pozwalając programistom skupić się na logice biznesowej zamiast na zawiłościach tworzenia systemów rozproszonych.

Natomiast IronPDF to popularna biblioteka .NET służąca do generowania, przeglądania i modyfikowania plików PDF. Jest znane z łatwości obsługi i wysokiej wydajności w tworzeniu plików PDF z różnych źródeł, takich jak pliki ASPX i HTML.

Dzięki połączeniu NServiceBus i IronPDF programiści mogą tworzyć niezawodne, skalowalne i łatwe w utrzymaniu systemy oprogramowania, które mogą generować dokumenty PDF i zarządzać nimi w ramach działalności biznesowej.

W tym artykule przyjrzymy się, jak skonfigurować prosty projekt C# NServiceBus i zintegrować go z IronPDF, abyś mógł zbudować usprawniony przepływ pracy do zarządzania i tworzenia dokumentów PDF w architekturze aplikacji rozproszonej. Po przeczytaniu tego wprowadzającego samouczka powinieneś dokładnie wiedzieć, w jaki sposób te dwie skuteczne technologie mogą współpracować, aby uprościć zadania związane z plikami PDF w środowisku rozproszonym.

Czym jest NServiceBus C#?

NServiceBus to potężny i elastyczny framework, który ułatwia tworzenie systemów rozproszonych i architektur .NET Framework zorientowanych na usługi. Korzystając z NServiceBus, można łatwo zarządzać różnymi typami komunikatów i zapewnić niezawodną komunikację. Ma to kluczowe znaczenie, szczególnie w aplikacjach internetowych i podobnych architekturach, gdzie niezbędne jest płynne kierowanie i przetwarzanie komunikatów. Moduły obsługi komunikatów NServiceBus skutecznie radzą sobie z odbieraniem komunikatów, zapewniając płynną interakcję wszystkich komponentów logicznych. NServiceBus posiada następujące ważne funkcje:

NServiceBus C# (How It Works For Developers): Figure 1 - NServiceBus C#

Funkcje NServiceBus

Komunikacja oparta na komunikatach

NServiceBus wspiera komunikację opartą na komunikatach między różnymi usługami lub komponentami w systemie. Dzięki rozdzieleniu komponentów metoda ta pozwala tworzyć projekty, które łatwiej skalować i zarządzać nimi.

Niezawodna komunikacja

Dzięki automatycznemu zarządzaniu ponownymi próbami, kolejkami wiadomości nieosiągniętych adresatów i innymi technikami odporności na awarie gwarantuje niezawodne dostarczanie wiadomości. W systemach rozproszonych, gdzie często zdarzają się awarie sieci i inne problemy, ta niezawodność jest niezbędna.

Model publikowania/subskrypcji

Wzorzec publikowania/subskrypcji jest obsługiwany przez NServiceBus, umożliwiając usługom publikowanie zdarzeń i pozwalając innym usługom subskrybować te zdarzenia. Umożliwia to tworzenie architektur sterowanych zdarzeniami, w których modyfikacje wprowadzone w zdarzeniach w jednym komponencie systemu mogą wywołać reakcje w innych komponentach.

Zarządzanie sagą

Długotrwałe procesy biznesowe mogą być zarządzane za pomocą NServiceBus dzięki zintegrowanej obsłudze sag. Sagi umożliwiają platformie usługowej zarządzanie stanem i koordynowanie skomplikowanych operacji między kilkoma usługami.

Rozszerzalność i dostosowywanie

It offers an exceptional level of extensibility, enabling developers to personalize the handling, processing, and transportation process of messages. Because of its adaptability, it can be used in a variety of scenarios.

Integration with Various Messaging Platforms

Numerous messaging systems, including MSMQ, RabbitMQ, Azure Service Bus, Amazon SQS, and others, can be integrated with NServiceBus. This enables developers to select the communications infrastructure solution that best suits their requirements.

Create and configure NServiceBus in C

You must first set up your development environment, create a basic project, and build a basic messaging service and scenario before you can begin using NServiceBus in a C# project. Here's a step-by-step guide to get you going.

Utwórz nowy projekt Visual Studio

In Visual Studio, the process of creating a console project is simple. Use these easy steps in the Visual Studio environment to launch a Console Application:

Przed użyciem upewnij się, że masz zainstalowane Visual Studio na swoim komputerze.

Rozpocznij nowy projekt

Click File, then select New, and finally Project.

NServiceBus C# (How It Works For Developers): Figure 2 - Click New

You can select the "Console App" or "Console App (.NET Core)" template from the list of project template references below.

W polu "Nazwa" podaj nazwę swojego projektu.

NServiceBus C# (How It Works For Developers): Figure 3 - Provide a name and location for the project

Choose a storage location for the project.

Kliknięcie przycisku "Utwórz" spowoduje uruchomienie projektu aplikacji konsolowej.

NServiceBus C# (How It Works For Developers): Figure 4 - Click create

Install NServiceBus Packages

Navigate to Tools > NuGet Package Manager > Package Manager Console to open the NuGet Package Manager Console.

Run the following command to install the NServiceBus NuGet package.

Install-Package NServiceBus

Choose a Transport

Transport is needed by NServiceBus to receive and send messages. We'll stick with the Learning Transport since it's easy to use and works well for testing and development.

Install the package for Learning Transport by executing.

Install-Package NServiceBus.RabbitMQ

Configure NServiceBus

Set Up the Endpoint

Set the NServiceBus endpoint configuration in your Program.cs file:

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new MyMessage
        {
            Content = "Hello, NServiceBus with RabbitMQ!"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new MyMessage
        {
            Content = "Hello, NServiceBus with RabbitMQ!"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
Imports NServiceBus
Imports System
Imports System.Threading.Tasks
Imports Messages

Friend Class Program
	Shared Async Function Main() As Task
		Console.Title = "Sender"
		Dim endpointConfiguration As New EndpointConfiguration("SenderEndpoint")

		' Use RabbitMQ Transport
		Dim transport = endpointConfiguration.UseTransport(Of RabbitMQTransport)()
		transport.ConnectionString("host=localhost")

		' Set up error queue
		endpointConfiguration.SendFailedMessagesTo("error")

		' Set up audit queue
		endpointConfiguration.AuditProcessedMessagesTo("audit")

		' Start the endpoint
		Dim endpointInstance = Await Endpoint.Start(endpointConfiguration).ConfigureAwait(False)
		Console.WriteLine("Press Enter to send a message...")
		Console.ReadLine()

		' Send a message
		Dim message = New MyMessage With {.Content = "Hello, NServiceBus with RabbitMQ!"}
		Await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(False)
		Console.WriteLine("Message sent. Press Enter to exit...")
		Console.ReadLine()

		' Stop the endpoint
		Await endpointInstance.Stop().ConfigureAwait(False)
	End Function
End Class
$vbLabelText   $csharpLabel

NServiceBus C# (How It Works For Developers): Figure 5 - Example console output

Create a Message

To represent the message, add a new class.

public class MyMessage : IMessage
{
    public string Content { get; set; }
}
public class MyMessage : IMessage
{
    public string Content { get; set; }
}
Public Class MyMessage
    Implements IMessage

    Public Property Content As String
End Class
$vbLabelText   $csharpLabel

Create a Message Handler

To handle the message, add a new class.

using NServiceBus;
using System.Threading.Tasks;

public class MyMessageHandler : IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message: {message.Content}");
        return Task.CompletedTask;
    }
}
using NServiceBus;
using System.Threading.Tasks;

public class MyMessageHandler : IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message: {message.Content}");
        return Task.CompletedTask;
    }
}
Imports NServiceBus
Imports System.Threading.Tasks

Public Class MyMessageHandler
	Implements IHandleMessages(Of MyMessage)

	Public Function Handle(ByVal message As MyMessage, ByVal context As IMessageHandlerContext) As Task
		Console.WriteLine($"Received message: {message.Content}")
		Return Task.CompletedTask
	End Function
End Class
$vbLabelText   $csharpLabel

Sending a Message

Send a Message from the Endpoint. Adapt your primary way to transmit a message with the help of the handler.

using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Serialization configuration
        endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.UseConventionalRoutingTopology(QueueType.Quorum);
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Serialization configuration
        endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.UseConventionalRoutingTopology(QueueType.Quorum);
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
Imports NServiceBus
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main() As Task
		Console.Title = "Receiver"
		Dim endpointConfiguration As New EndpointConfiguration("ReceiverEndpoint")

		' Serialization configuration
		endpointConfiguration.UseSerialization(Of NewtonsoftJsonSerializer)()

		' Use RabbitMQ Transport
		Dim transport = endpointConfiguration.UseTransport(Of RabbitMQTransport)()
		transport.UseConventionalRoutingTopology(QueueType.Quorum)
		transport.ConnectionString("host=localhost")

		' Set up error queue
		endpointConfiguration.SendFailedMessagesTo("error")

		' Set up audit queue
		endpointConfiguration.AuditProcessedMessagesTo("audit")
		endpointConfiguration.EnableInstallers()

		' Start the endpoint
		Dim endpointInstance = Await Endpoint.Start(endpointConfiguration).ConfigureAwait(False)
		Console.WriteLine("Press Enter to exit...")
		Console.ReadLine()

		' Stop the endpoint
		Await endpointInstance.Stop().ConfigureAwait(False)
	End Function
End Class
$vbLabelText   $csharpLabel

NServiceBus C# (How It Works For Developers): Figure 6 - Example console output

Launch the application and build the project. The console should display the message "Received message: Hello, NServiceBus!"

Pierwsze kroki

In a C# project, integrating NServiceBus with RabbitMQ and IronPDF entails configuring messages between NServiceBus and RabbitMQ as well as using IronPDF to create PDFs. Here is a thorough how-to to get you going:

What is IronPDF?

IronPDF is a .NET library designed for creating, reading, editing, and converting PDF files. With it, programmers may work with PDF files in C# or VB.NET applications with a powerful and intuitive tool. The characteristics and capabilities of IronPDF are fully described below:

NServiceBus C# (How It Works For Developers): Figure 7 - IronPDF: The C# PDF Library homepage

Funkcje IronPDF

Generowanie plików PDF z HTML

Konwertuj JavaScript, HTML i CSS do formatu PDF. Obsługuje zapytania o media i responsywny projekt, dwa współczesne standardy internetowe. Useful for producing dynamically styled PDF documents, invoices, and reports using HTML and CSS.

Edycja plików PDF

To already existing PDFs, add text, pictures, and other material. Wyodrębnij tekst i obrazy z plików PDF. Combine several PDFs into one file. Divide PDF files into several documents. Include annotations, footers, headers, and watermarks.

PDF Conversion

Convert Word, Excel, image, and other file formats to PDF. PDF to image conversion (PNG, JPEG, etc.).

Wydajność i niezawodność

High performance and dependability are the design goals in production settings. Efficiently manages huge documents.

Instalacja IronPDF

Install IronPDF by opening the NuGet Package Manager Console.

Install-Package IronPdf

Configure the Sender With Message

Messages is a shared project (class library) that the sender and the recipient will both use. Define the message class in the Messages project. Create a new Class Library project called Messages and add it to the solution.

Define the Message:

Inside the Messages project, create a new class called GeneratePdfMessage.cs:

using NServiceBus;

public class GeneratePdfMessage : IMessage
{
    public string Content { get; set; }
    public string OutputPath { get; set; }
}
using NServiceBus;

public class GeneratePdfMessage : IMessage
{
    public string Content { get; set; }
    public string OutputPath { get; set; }
}
Imports NServiceBus

Public Class GeneratePdfMessage
	Implements IMessage

	Public Property Content() As String
	Public Property OutputPath() As String
End Class
$vbLabelText   $csharpLabel

In both the Sender and Receiver projects, include a reference to the Messages project.

Set up the NServiceBus endpoint in the Sender project to use RabbitMQ for message delivery.

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new GeneratePdfMessage
        {
            Content = "<h1>Hello, NServiceBus with RabbitMQ and IronPDF!</h1>",
            OutputPath = "output.pdf"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;

class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();

        // Send a message
        var message = new GeneratePdfMessage
        {
            Content = "<h1>Hello, NServiceBus with RabbitMQ and IronPDF!</h1>",
            OutputPath = "output.pdf"
        };
        await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
Imports NServiceBus
Imports System
Imports System.Threading.Tasks
Imports Messages

Friend Class Program
	Shared Async Function Main() As Task
		Console.Title = "Sender"
		Dim endpointConfiguration As New EndpointConfiguration("SenderEndpoint")

		' Use RabbitMQ Transport
		Dim transport = endpointConfiguration.UseTransport(Of RabbitMQTransport)()
		transport.ConnectionString("host=localhost")

		' Set up error queue
		endpointConfiguration.SendFailedMessagesTo("error")

		' Set up audit queue
		endpointConfiguration.AuditProcessedMessagesTo("audit")
		endpointConfiguration.EnableInstallers()

		' Start the endpoint
		Dim endpointInstance = Await Endpoint.Start(endpointConfiguration).ConfigureAwait(False)
		Console.WriteLine("Press Enter to send a message...")
		Console.ReadLine()

		' Send a message
		Dim message = New GeneratePdfMessage With {
			.Content = "<h1>Hello, NServiceBus with RabbitMQ and IronPDF!</h1>",
			.OutputPath = "output.pdf"
		}
		Await endpointInstance.Send("ReceiverEndpoint", message).ConfigureAwait(False)
		Console.WriteLine("Message sent. Press Enter to exit...")
		Console.ReadLine()

		' Stop the endpoint
		Await endpointInstance.Stop().ConfigureAwait(False)
	End Function
End Class
$vbLabelText   $csharpLabel

Endpoint Configuration: the endpoint is initialized with the name "SenderEndpoint" by calling new EndpointConfiguration("SenderEndpoint").

endpointConfiguration is the transport configuration. By connecting to a local RabbitMQ instance, the method UseTransport() sets up NServiceBus to use RabbitMQ as the transport mechanism.

Audit and Error Queues Where to send failed messages and audit processed messages is configured using SendFailedMessagesTo("error") and AuditProcessedMessagesTo("audit"), respectively.

Message Sent: endpointInstance.Send("ReceiverEndpoint", message) sends a GeneratePdfMessage to the "ReceiverEndpoint".

Configure the Receiver to Generate PDF

Set up the NServiceBus endpoint in the Receiver project to accept messages over RabbitMQ and produce PDFs using IronPDF.

using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");

        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");

        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");

        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

        // Stop the endpoint
        await endpointInstance.Stop().ConfigureAwait(false);
    }
}
Imports NServiceBus
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main() As Task
		Console.Title = "Receiver"
		Dim endpointConfiguration As New EndpointConfiguration("ReceiverEndpoint")

		' Use RabbitMQ Transport
		Dim transport = endpointConfiguration.UseTransport(Of RabbitMQTransport)()
		transport.ConnectionString("host=localhost")

		' Set up error queue
		endpointConfiguration.SendFailedMessagesTo("error")

		' Set up audit queue
		endpointConfiguration.AuditProcessedMessagesTo("audit")

		' Start the endpoint
		Dim endpointInstance = Await Endpoint.Start(endpointConfiguration).ConfigureAwait(False)
		Console.WriteLine("Press Enter to exit...")
		Console.ReadLine()

		' Stop the endpoint
		Await endpointInstance.Stop().ConfigureAwait(False)
	End Function
End Class
$vbLabelText   $csharpLabel

This setup, for the "ReceiverEndpoint" receiver endpoint, is comparable to the Sender configuration.

Message Handler

In the Receiver project, create a new class called GeneratePdfMessageHandler.cs.

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
using IronPdf;

public class GeneratePdfMessageHandler : IHandleMessages<GeneratePdfMessage>
{
    public Task Handle(GeneratePdfMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message to generate PDF with content: {message.Content}");

        // Generate PDF
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf(message.Content);
        pdf.SaveAs(message.OutputPath);
        Console.WriteLine($"PDF generated and saved to: {message.OutputPath}");

        return Task.CompletedTask;
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
using IronPdf;

public class GeneratePdfMessageHandler : IHandleMessages<GeneratePdfMessage>
{
    public Task Handle(GeneratePdfMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message to generate PDF with content: {message.Content}");

        // Generate PDF
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf(message.Content);
        pdf.SaveAs(message.OutputPath);
        Console.WriteLine($"PDF generated and saved to: {message.OutputPath}");

        return Task.CompletedTask;
    }
}
Imports NServiceBus
Imports System
Imports System.Threading.Tasks
Imports Messages
Imports IronPdf

Public Class GeneratePdfMessageHandler
	Implements IHandleMessages(Of GeneratePdfMessage)

	Public Function Handle(ByVal message As GeneratePdfMessage, ByVal context As IMessageHandlerContext) As Task
		Console.WriteLine($"Received message to generate PDF with content: {message.Content}")

		' Generate PDF
		Dim renderer = New HtmlToPdf()
		Dim pdf = renderer.RenderHtmlAsPdf(message.Content)
		pdf.SaveAs(message.OutputPath)
		Console.WriteLine($"PDF generated and saved to: {message.OutputPath}")

		Return Task.CompletedTask
	End Function
End Class
$vbLabelText   $csharpLabel

GeneratePdfMessageHandler uses the IHandleMessages interface to handle messages of type GeneratePdfMessage.

NServiceBus C# (How It Works For Developers): Figure 8 - Example console output

Handle Method: After receiving the message, the Handle function creates a PDF using IronPDF. The HTML content in the message is converted into a PDF by the HtmlToPdf renderer code, which then saves it to the designated output path.

NServiceBus C# (How It Works For Developers): Figure 9 - PDF output from using NServiceBus with RabbitMQ along with IronPDF

Wnioski

NServiceBus may be integrated with RabbitMQ and IronPDF in C# to provide a scalable and stable solution for distributed systems that need to generate PDFs dynamically and reliably. This combination makes use of NServiceBus's message processing capabilities, RabbitMQ's dependability and adaptability as a message broker, and IronPDF's robust PDF editing tools. Decoupling between services is ensured by the resultant architecture, allowing for autonomous evolution and scalability.

RabbitMQ also ensures message delivery even in the event of network or application failures. NServiceBus makes message routing and processing simpler, and IronPDF makes it possible to convert HTML text into high-quality PDF documents. This integration offers a flexible framework for developing sophisticated, large-scale applications in addition to improving the maintainability and dependability of the system.

Lastly, by adding IronPDF and Iron Software to your toolkit for .NET programming, you can effectively work with barcodes, generate PDFs, perform OCR, and link with Excel. IronPDF's Licensing Page, which starts at $799, seamlessly blends its features and the performance, compatibility, and ease of use of Iron Software's Official Site's flexible suite to provide additional web applications and capabilities and more efficient development.

If there are well-defined license options that are customized to the specific requirements of the project, developers can select the optimal model with confidence. These benefits allow developers to handle a range of difficulties effectively and transparently.

Często Zadawane Pytania

Jak mogę wykorzystać NServiceBus w języku C# do tworzenia systemów rozproszonych?

NServiceBus upraszcza tworzenie systemów rozproszonych w języku C# poprzez abstrakcję architektury komunikacyjnej. Pozwala to programistom skupić się na logice biznesowej, zapewniając jednocześnie niezawodną obsługę i dostarczanie komunikatów między mikrousługami.

Jakie są korzyści z integracji NServiceBus z bibliotekami do zarządzania plikami PDF?

Integracja NServiceBus z bibliotekami do zarządzania plikami PDF, takimi jak IronPDF, pozwala na wydajne generowanie i zarządzanie plikami PDF w aplikacjach rozproszonych, umożliwiając tworzenie skalowalnych i łatwych w utrzymaniu systemów oprogramowania.

Jak skonfigurować projekt C# z wykorzystaniem NServiceBus i RabbitMQ?

Aby skonfigurować projekt C# z wykorzystaniem NServiceBus i RabbitMQ, należy utworzyć nową aplikację konsolową w Visual Studio, zainstalować pakiety NuGet NServiceBus i RabbitMQ oraz skonfigurować punkt końcowy i transport komunikatów w kodzie.

W jaki sposób NServiceBus usprawnia komunikację opartą na komunikatach?

NServiceBus usprawnia komunikację opartą na komunikatach, zapewniając niezawodne wzorce komunikacyjne, takie jak model publikowania/subskrypcji oraz zarządzanie sagami, gwarantując prawidłowe dostarczanie i przetwarzanie komunikatów w systemach rozproszonych.

Jaką rolę odgrywa IronPDF w systemach rozproszonych wykorzystujących NServiceBus?

IronPDF odgrywa kluczową rolę w systemach rozproszonych wykorzystujących NServiceBus, oferując solidne możliwości generowania i edycji plików PDF, które można zintegrować z przepływami pracy opartymi na komunikatach w celu automatyzacji procesów obsługi dokumentów.

Jak zapewnić niezawodne generowanie plików PDF w systemach rozproszonych przy użyciu języka C#?

Niezawodne generowanie plików PDF w systemach rozproszonych przy użyciu języka C# można osiągnąć poprzez integrację NServiceBus do obsługi komunikatów oraz IronPDF do generowania plików PDF, wykorzystując możliwości komunikacyjne RabbitMQ do koordynacji zadań i zapewnienia spójności.

Jak działa model publikowania/subskrypcji w NServiceBus?

W NServiceBus model publikowania/subskrypcji pozwala usługom publikować zdarzenia, które mogą subskrybować inne usługi. Umożliwia to architekturę sterowaną zdarzeniami, w której zmiany w jednym komponencie mogą wywoływać działania w innych, poprawiając responsywność i skalowalność systemu.

Jakie znaczenie ma zarządzanie sagami w NServiceBus?

Zarządzanie sagami w NServiceBus ma duże znaczenie dla koordynacji długotrwałych procesów biznesowych w wielu usługach, zapewniając prawidłowe i spójne wykonywanie złożonych przepływów pracy w systemach rozproszonych.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie