### Add CI Feed and Install Pre-release Package Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/README.md Use these commands to add the Foundatio CI feed and install the pre-release version of Foundatio.AzureServiceBus. ```bash dotnet nuget add source https://f.feedz.io/foundatio/foundatio/nuget -n foundatio-feedz dotnet add package Foundatio.AzureServiceBus --prerelease ``` -------------------------------- ### Fanout Pattern Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md This example demonstrates the fanout pattern where multiple message bus instances, each with a unique subscription, can receive the same message. ```csharp // Multiple instances can receive the same message var messageBus1 = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("events")); // No subscription name - gets unique subscription var messageBus2 = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("events")); // Another unique subscription await messageBus1.PublishAsync("EventType", @event); // Both messageBus1 and messageBus2 receive the message ``` -------------------------------- ### Start Azure Service Bus Emulator Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/samples/README.md This command starts the Azure Service Bus emulator using Docker Compose. It is recommended for local development. ```bash docker-compose up -d ``` -------------------------------- ### Publishing a Message Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md This example shows how to publish a message. The topic will be created automatically if it doesn't exist and creation is enabled. ```csharp // Called automatically during first publish or subscribe await messageBus.PublishAsync(myMessage); ``` -------------------------------- ### Subscribing to a Topic Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md This example demonstrates subscribing to a topic. The subscription will be created automatically if it doesn't exist and creation is enabled. ```csharp // Called automatically when first subscriber is added await messageBus.SubscribeAsync(handler); ``` -------------------------------- ### Add Foundatio.AzureServiceBus Package Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/README.md Install the Foundatio.AzureServiceBus NuGet package to your project. ```bash dotnet add package Foundatio.AzureServiceBus ``` -------------------------------- ### AzureServiceBusQueue Lifecycle Options Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Example demonstrating how to set `AutoDeleteOnIdle` and `DefaultMessageTimeToLive` for a queue. This configures a temporary queue that auto-deletes after 30 minutes of inactivity and messages expire after 1 hour. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("temporary-queue") .AutoDeleteOnIdle(TimeSpan.FromMinutes(30)) .DefaultMessageTimeToLive(TimeSpan.FromHours(1))); ``` -------------------------------- ### Named Subscription Pattern Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md This example demonstrates the named subscription pattern where multiple message bus instances share the same subscription, leading to load-balanced message delivery. ```csharp // Multiple instances share the same subscription var messageBus1 = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("events") .SubscriptionName("order-processor")); var messageBus2 = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("events") .SubscriptionName("order-processor")); await messageBus1.PublishAsync("EventType", @event); // Only one instance receives per message (load balanced) ``` -------------------------------- ### Configure AzureServiceBusMessageBus Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/types.md Example of configuring an AzureServiceBusMessageBus instance with various options. ```csharp var messageBus = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("events") .SubscriptionName("processor") .MaxConcurrentCalls(10) .PrefetchCount(5) .SubscriptionReceiveMode(ServiceBusReceiveMode.PeekLock) .SubscriptionMaxDeliveryCount(5)); ``` -------------------------------- ### Message Bus Initialization and Disposal Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md This example demonstrates initializing the AzureServiceBusMessageBus and highlights that cleanup occurs automatically upon disposal. ```csharp using var messageBus = new AzureServiceBusMessageBus(options); // Use message bus // Auto-cleanup on disposal ``` -------------------------------- ### Message Handler Invocation Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md This example shows how to set up a message handler for a specific event type. It illustrates accessing message context like CorrelationId and custom ApplicationProperties. ```csharp await messageBus.SubscribeAsync(async ev => { // ev.CorrelationId available from message context // ev.Properties contains custom ApplicationProperties await ProcessOrderAsync(ev); }); ``` -------------------------------- ### AzureServiceBusQueueOptionsBuilder Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/types.md Demonstrates how to use the fluent builder to configure an Azure Service Bus queue with specific options like connection string, name, retries, timeouts, and duplicate detection. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("my-queue") .Retries(3) .ReadQueueTimeout(TimeSpan.FromSeconds(30)) .DequeueInterval(TimeSpan.FromMilliseconds(500)) .RequiresDuplicateDetection(true) .DuplicateDetectionHistoryTimeWindow(TimeSpan.FromMinutes(1))); ``` -------------------------------- ### Add Foundatio.AzureServiceBus NuGet Package Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Install the Foundatio.AzureServiceBus NuGet package using the .NET CLI. You can add the latest version or specify a particular version. ```bash dotnet add package Foundatio.AzureServiceBus ``` ```bash dotnet add package Foundatio.AzureServiceBus --version 13.0.2 ``` -------------------------------- ### Start Service Bus Subscriber Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/samples/README.md Run this command in a terminal to start the subscriber application. This application will listen for messages on the Azure Service Bus. ```bash dotnet run --project samples/Foundatio.AzureServiceBus.Subscribe ``` -------------------------------- ### SubscribeAsync Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md Subscribe to message types to handle incoming messages. Topics and subscriptions are automatically created, and message processing begins upon subscription. ```csharp await messageBus.SubscribeAsync(async msg => { Console.WriteLine($ ``` -------------------------------- ### AzureServiceBusQueue Deduplication Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Example of configuring a queue to require duplicate detection with a 5-minute history window. This ensures that messages with the same message ID within the specified window are not processed more than once. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("idempotent-queue") .RequiresDuplicateDetection(true) .DuplicateDetectionHistoryTimeWindow(TimeSpan.FromMinutes(5))); ``` -------------------------------- ### AzureServiceBusQueue Custom Retry Delay Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Example of setting a custom retry delay function for abandoned messages. This example implements a linear delay based on the attempt number. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("my-queue") .Retries(5) .RetryDelay(attempt => TimeSpan.FromSeconds(attempt * 10))); ``` -------------------------------- ### Dependency Injection Setup for Queue and Message Bus Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Register Azure Service Bus queue and message bus as singletons using Microsoft.Extensions.DependencyInjection. Requires LoggerFactory for logging. ```csharp using Microsoft.Extensions.DependencyInjection; using Foundatio.Queues; using Foundatio.Messaging; var services = new ServiceCollection(); // Register queue services.AddSingleton(sp => new AzureServiceBusQueue(options => options .ConnectionString(connectionString) .Name("work-queue") .LoggerFactory(sp.GetRequiredService()))); // Register message bus services.AddSingleton(sp => new AzureServiceBusMessageBus(options => options .ConnectionString(connectionString) .Topic("events") .LoggerFactory(sp.GetRequiredService()))); var provider = services.BuildServiceProvider(); var queue = provider.GetRequiredService>(); var messageBus = provider.GetRequiredService(); ``` -------------------------------- ### Unit Test Example: GetAsync with Expired Key Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/AGENTS.md Demonstrates the Arrange-Act-Assert pattern for testing cache expiration. Requires an InMemoryCacheClient and simulates a delay to ensure the key expires. ```csharp ```csharp [Fact] public async Task GetAsync_WithExpiredKey_ReturnsNull() { // Arrange var cache = new InMemoryCacheClient(); await cache.SetAsync("key", "value", TimeSpan.FromMilliseconds(1)); await Task.Delay(10); // Act var result = await cache.GetAsync("key"); // Assert Assert.Null(result); } ``` ``` -------------------------------- ### PublishAsync Example Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md Publish a message to the Azure Service Bus topic. Supports custom options like correlation ID, delivery delay, and properties. The message is serialized and wrapped in a resilience policy. ```csharp var options = new MessageOptions { UniqueId = Guid.NewGuid().ToString(), CorrelationId = "order-123", DeliveryDelay = TimeSpan.FromSeconds(30), Properties = new Dictionary { ["priority"] = "high" } }; await messageBus.PublishAsync( "OrderCreated", new OrderCreatedEvent { OrderId = 123, Amount = 99.99 }, options); ``` -------------------------------- ### Define Message Classes Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Example definitions for custom message classes used with Foundatio.AzureServiceBus queues and message buses. ```csharp public class WorkItem { public int Id { get; set; } public string Data { get; set; } } public class OrderCreatedEvent { public int OrderId { get; set; } public decimal Amount { get; set; } } public class OrderShippedEvent { public int OrderId { get; set; } public DateTime ShippedAt { get; set; } } ``` -------------------------------- ### StartWorking Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusQueue.md Starts a background worker loop to process messages from the queue. It continuously dequeues messages and invokes a provided handler. Options for auto-completing messages and cancellation are available. ```APIDOC ## StartWorking ### Description Starts a background worker loop to process messages from the queue. It continuously dequeues messages and invokes a provided handler. Options for auto-completing messages and cancellation are available. ### Method Signature ```csharp protected override void StartWorkingImpl( Func, CancellationToken, Task> handler, bool autoComplete, CancellationToken cancellationToken) ``` ### Parameters #### Handler - **handler** (Func, CancellationToken, Task>) - Required - Async handler to invoke for each message. #### AutoComplete - **autoComplete** (bool) - Required - Auto-complete messages if handler succeeds. #### CancellationToken - **cancellationToken** (CancellationToken) - Required - Cancellation token. ### Behavior - Runs in background Task. - Continuously dequeues and invokes handler. - Auto-completes if enabled and handler succeeds. - Auto-abandons on handler exception. - Increments workerErrorCount on exceptions. - Gracefully exits on cancellation. ### Example ```csharp queue.StartWorking(async (entry, token) => { Console.WriteLine($"Processing: {entry.Value.Data}"); await Task.Delay(1000); }, autoComplete: true, cancellationToken); // Worker runs until cancellation requested await Task.Delay(TimeSpan.FromMinutes(10)); cancellationTokenSource.Cancel(); ``` ``` -------------------------------- ### Tracking Message Retries Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusQueueEntry.md Provides an example of how to use the Attempts property to track and react to message retries, differentiating between first attempts and subsequent retries. ```csharp var entry = await queue.DequeueAsync(); if (entry.Attempts == 1) Console.WriteLine("First attempt"); else if (entry.Attempts == 2) Console.WriteLine("Retry #1"); else if (entry.Attempts > 3) Console.WriteLine($"Attempt {entry.Attempts} - approaching limit"); ``` -------------------------------- ### Build Project Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/README.md Build the Foundatio.AzureServiceBus project using the dotnet CLI. ```bash dotnet build ``` -------------------------------- ### Start Background Worker Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusQueue.md Starts a background worker loop to process messages from the queue. The handler is invoked for each message, with options for auto-completion and cancellation. ```csharp protected override void StartWorkingImpl( Func, CancellationToken, Task> handler, bool autoComplete, CancellationToken cancellationToken) ``` ``` ```csharp queue.StartWorking(async (entry, token) => { Console.WriteLine($"Processing: {entry.Value.Data}"); await Task.Delay(1000); }, autoComplete: true, cancellationToken); // Worker runs until cancellation requested await Task.Delay(TimeSpan.FromMinutes(10)); cancellationTokenSource.Cancel(); ``` -------------------------------- ### Queue Demo Workflow - Send Messages Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/samples/README.md Demonstrates sending multiple messages with metadata to a queue as part of a demo workflow. Ensure the emulator and dequeue process are running. ```bash dotnet run --project samples/Foundatio.AzureServiceBus.Enqueue -- \ --message "Hello from Foundatio" \ --correlation-id "demo-123" \ --property "Source=Demo" \ --count 3 ``` -------------------------------- ### Configure Development Queue with Emulator Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Sets up an Azure Service Bus queue for development using the emulator connection string. Includes basic retry configuration. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString("Endpoint=sb://localhost:5672;...;UseDevelopmentEmulator=true") .Name("dev-queue") .Retries(1)); ``` -------------------------------- ### Run Tests Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/README.md Execute the unit tests for the Foundatio.AzureServiceBus project using the dotnet CLI. ```bash dotnet test ``` -------------------------------- ### Configure Queue with Connection String Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/README.md Initializes an AzureServiceBusQueue using a direct connection string. This is suitable for environments where a connection string is readily available. ```csharp var connectionString = "Endpoint=sb://namespace.servicebus.windows.net/வதற்காக; "SharedAccessKeyName=RootManageSharedAccessKey;" "SharedAccessKey=..."; var queue = new AzureServiceBusQueue(o => o .ConnectionString(connectionString) .Name("queue")); ``` -------------------------------- ### Running All Tests Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/AGENTS.md Command to execute all tests in the Foundatio.AzureServiceBus solution. ```bash # All tests dotnet test Foundatio.AzureServiceBus.slnx ``` -------------------------------- ### Batch Enqueue Messages Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Enqueue multiple items in a batch, each with its own CorrelationId. This example iterates through items and enqueues them individually with shared batch correlation. ```csharp var items = new[] { item1, item2, item3 }; foreach (var item in items) { var options = new QueueEntryOptions { CorrelationId = "batch-123" }; await queue.EnqueueAsync(item, options); } ``` -------------------------------- ### AzureServiceBusQueue Constructor with Options Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusQueue.md Initializes the AzureServiceBusQueue with explicit configuration options. Ensure ConnectionString or FullyQualifiedNamespace is provided, and Credential is set when using FullyQualifiedNamespace. ```csharp var queue = new AzureServiceBusQueue(options => options .ConnectionString("Endpoint=sb://myns.servicebus.windows.net/;...") .Name("my-queue") .Retries(3) .WorkItemTimeout(TimeSpan.FromMinutes(5))); ``` -------------------------------- ### EnsureTopicSubscriptionAsync Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md Ensures the Azure Service Bus subscription exists and starts message processing. It handles topic existence, subscription creation, and processor configuration. ```APIDOC ## EnsureTopicSubscriptionAsync ### Description Ensures the Azure Service Bus subscription exists and starts message processing. It handles topic existence, subscription creation, and processor configuration. ### Method protected override async Task EnsureTopicSubscriptionAsync(CancellationToken cancellationToken) ### Behavior: - First ensures topic exists - Checks if subscription exists (skipped for emulator) - Creates subscription if not found and CanCreateTopic is true - Throws MessageBusException if subscription missing and CanCreateTopic is false - Creates ServiceBusProcessor with configured MaxConcurrentCalls - Starts processor to begin receiving messages - Thread-safe with AsyncLock ### Processor Configuration: - AutoCompleteMessages: true (messages auto-complete on successful handler) - MaxConcurrentCalls: From options (default 6) - ReceiveMode: From options (default ReceiveAndDelete) - PrefetchCount: From options if set ### Example: ```csharp // Called automatically when first subscriber is added await messageBus.SubscribeAsync(handler); // Creates subscription ``` ``` -------------------------------- ### Get Queue Statistics Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Retrieve and display statistics for the Azure Service Bus queue, including queued, dead-letter, enqueued, completed, and error counts. ```csharp var stats = await queue.GetQueueStatsAsync(); Console.WriteLine($"Active: {stats.Queued}"); Console.WriteLine($"Dead-letter: {stats.Deadletter}"); Console.WriteLine($"Total enqueued: {stats.Enqueued}"); Console.WriteLine($"Total completed: {stats.Completed}"); Console.WriteLine($"Errors: {stats.Errors}"); ``` -------------------------------- ### Running Tests with Detailed Logging Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/AGENTS.md Command to execute tests and enable detailed console logging output. ```bash # With logging dotnet test --logger "console;verbosity=detailed" ``` -------------------------------- ### Disposing Message Bus Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md This example shows the internal call to dispose the message bus, which gracefully stops message processing while allowing in-flight handlers to complete. ```csharp // Called internally during disposal await messageBus.DisposeAsync(); ``` -------------------------------- ### Enqueue Message with Basic Options Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/types.md Demonstrates enqueuing a message with standard options including correlation ID, unique ID, and custom properties. ```csharp var options = new QueueEntryOptions { CorrelationId = "order-123", UniqueId = Guid.NewGuid().ToString(), Properties = new Dictionary { ["priority"] = "high" } }; await queue.EnqueueAsync(message, options); ``` -------------------------------- ### Parameterized Test Example: SetAsync with Invalid Key Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/AGENTS.md Illustrates using [Theory] and [InlineData] to test multiple invalid key inputs for the SetAsync method, expecting an ArgumentException. ```csharp ```csharp [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public async Task SetAsync_WithInvalidKey_ThrowsArgumentException(string key) { var cache = new InMemoryCacheClient(); await Assert.ThrowsAsync(() => cache.SetAsync(key, "value")); } ``` ``` -------------------------------- ### Configure Azure Service Bus Connection for Development Emulator Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Shows how to configure the connection string to use the Azure Service Bus development emulator. ```csharp const string EmulatorConnection = "Endpoint=sb://localhost:5672;" + "SharedAccessKeyName=RootManageSharedAccessKey;" + "SharedAccessKey=SAS_KEY_VALUE;" + "UseDevelopmentEmulator=true"; var queue = new AzureServiceBusQueue(options => options .ConnectionString(EmulatorConnection) .Name("dev-queue")); ``` -------------------------------- ### Process Messages in Background with Azure Service Bus Queue Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Configures and starts a background worker to continuously process messages from a queue. Includes options for retries and graceful shutdown. ```csharp using Foundatio.Queues; var queue = new AzureServiceBusQueue(options => options .ConnectionString(connectionString) .Name("work-queue") .Retries(3)); var cts = new CancellationTokenSource(); // Start background worker queue.StartWorking(async (entry, token) => { Console.WriteLine($"Processing: {entry.Value.Data}"); await Task.Delay(1000, token); // Simulate work }, autoComplete: true, cts.Token); // Run for a while await Task.Delay(TimeSpan.FromSeconds(30)); // Gracefully stop cts.Cancel(); await queue.DisposeAsync(); ``` -------------------------------- ### AzureServiceBusQueue Constructors Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusQueue.md Provides documentation for the two constructors of the AzureServiceBusQueue class, used for initializing the queue with either direct options or a configuration builder. ```APIDOC ## AzureServiceBusQueue(AzureServiceBusQueueOptions options) ### Description Initializes a new instance of the AzureServiceBusQueue class with the specified configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (AzureServiceBusQueueOptions) - Required - Queue configuration options including connection string and queue settings. ### Request Example ```csharp var queue = new AzureServiceBusQueue(options => options .ConnectionString("Endpoint=sb://myns.servicebus.windows.net/;...") .Name("my-queue") .Retries(3) .WorkItemTimeout(TimeSpan.FromMinutes(5))); ``` ## AzureServiceBusQueue(Builder config) ### Description Initializes a new instance of the AzureServiceBusQueue class using a configuration builder delegate for fluent setup. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config** (Builder delegate) - Required - Configuration builder delegate for fluent setup. ### Request Example ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connectionString) .Name("queue-name")); ``` ``` -------------------------------- ### AzureServiceBusMessageBus Constructor with Options Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md Instantiate AzureServiceBusMessageBus using configuration options. Ensure ConnectionString, Topic, and SubscriptionName are set. ```csharp var messageBus = new AzureServiceBusMessageBus(options => options .ConnectionString("Endpoint=sb://myns.servicebus.windows.net/;...") .Topic("my-topic") .SubscriptionName("my-subscription") .MaxConcurrentCalls(10)); ``` -------------------------------- ### Enqueue a Message to Azure Service Bus Queue Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Demonstrates how to create an AzureServiceBusQueue instance and enqueue a message. Ensure you have the necessary connection string and queue name configured. ```csharp using Foundatio.Queues; // Create queue instance var queue = new AzureServiceBusQueue(options => options .ConnectionString("Endpoint=sb://myns.servicebus.windows.net/;...") .Name("work-queue")); // Enqueue a message var messageId = await queue.EnqueueAsync(new WorkItem { Id = 123, Data = "Process this work" }); Console.WriteLine($"Enqueued: {messageId}"); await queue.DisposeAsync(); ``` -------------------------------- ### Configure Scalable Azure Service Bus Queue Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/advanced-usage.md Configure an Azure Service Bus queue for horizontal scaling by enabling partitioning and batched operations. This setup allows multiple instances to efficiently process messages from the same queue. ```csharp // Configuration for scale-out var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("scalable-queue") .Retries(3) .WorkItemTimeout(TimeSpan.FromMinutes(5)) .ReadQueueTimeout(TimeSpan.FromSeconds(30)) .DequeueInterval(TimeSpan.Zero) .EnableBatchedOperations(true) .EnablePartitioning(true) .MaxSizeInMegabytes(10240)); // Start on Instance 1, 2, 3, N... queue.StartWorking(async (entry, token) => { logger.LogInformation("Instance {MachineName} processing {MessageId}", Environment.MachineName, entry.Id); await ProcessAsync(entry.Value, token); }, autoComplete: true, cts.Token); // Service Bus distributes messages across all running instances ``` -------------------------------- ### Subscribe to events from Azure Service Bus Topic Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/samples/README.md Use this command to subscribe to events from an Azure Service Bus Topic. Allows specifying a custom subscription name. Defaults to the emulator connection string. ```bash dotnet run --project samples/Foundatio.AzureServiceBus.Subscribe -- [options] ``` ```bash # Subscribe to events using emulator dotnet run --project samples/Foundatio.AzureServiceBus.Subscribe ``` ```bash # Subscribe with a specific subscription name dotnet run --project samples/Foundatio.AzureServiceBus.Subscribe -- \ --subscription "my-subscription" ``` -------------------------------- ### Reliable Azure Service Bus Message Bus with Dead-Lettering Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Configure a reliable message bus with dead-lettering enabled for critical events. This setup forwards dead-lettered messages to a specified queue and sets a maximum delivery count. ```csharp var messageBus = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("critical-events") .SubscriptionName("critical-processor") .SubscriptionMaxDeliveryCount(10) .SubscriptionEnableDeadLetteringOnMessageExpiration(true) .SubscriptionForwardDeadLetteredMessagesTo("critical-deadletter") .MaxConcurrentCalls(5)); ``` -------------------------------- ### AzureServiceBusQueue Queue Creation Options Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Configure whether the queue should be automatically created if it doesn't exist. Use `.EnableCreateQueue()` or `.DisableCreateQueue()` for convenience. ```csharp .CanCreateQueue(bool enabled) ``` ```csharp .EnableCreateQueue() ``` ```csharp .DisableCreateQueue() ``` -------------------------------- ### Configure Production Queue with Connection String Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Sets up an Azure Service Bus queue for production using an environment variable for the connection string. Configures retries, work item timeout, and batched operations. ```csharp var connectionString = Environment.GetEnvironmentVariable("AZURE_SERVICEBUS_CONNECTION_STRING") ?? throw new InvalidOperationException("Missing connection string"); var queue = new AzureServiceBusQueue(o => o .ConnectionString(connectionString) .Name("prod-queue") .Retries(3) .WorkItemTimeout(TimeSpan.FromMinutes(5)) .EnableBatchedOperations(true)); ``` -------------------------------- ### Configure Queue with Credentials Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/errors.md Provides Azure credentials for connecting to a Service Bus namespace when using a fully qualified namespace. ```csharp var credential = new DefaultAzureCredential(); var queue = new AzureServiceBusQueue(options => options .FullyQualifiedNamespace("ns.servicebus.windows.net") .Credential(credential) // Must provide credential .Name("queue")) ``` -------------------------------- ### AzureServiceBusMessageBus Constructors Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md Provides documentation for the two constructors available for initializing the AzureServiceBusMessageBus. ```APIDOC ## AzureServiceBusMessageBus(AzureServiceBusMessageBusOptions options) ### Description Initializes a new instance of the AzureServiceBusMessageBus with the specified configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (AzureServiceBusMessageBusOptions) - Required - Message bus configuration including connection string and topic/subscription settings. **Validation Rules:** - `ConnectionString` or `FullyQualifiedNamespace` must be provided - `Credential` is required when using `FullyQualifiedNamespace` - `Topic` must be set (inherited from SharedMessageBusOptions) ### Request Example ```csharp var messageBus = new AzureServiceBusMessageBus(options => options .ConnectionString("Endpoint=sb://myns.servicebus.windows.net/;...") .Topic("my-topic") .SubscriptionName("my-subscription") .MaxConcurrentCalls(10)); ``` ## AzureServiceBusMessageBus(Builder config) ### Description Initializes a new instance of the AzureServiceBusMessageBus using a fluent builder configuration delegate. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config** (Builder delegate) - Required - Configuration builder delegate for fluent setup. ### Request Example ```csharp var messageBus = new AzureServiceBusMessageBus(o => o .ConnectionString(connectionString) .Topic("events")); ``` ``` -------------------------------- ### Configure AzureServiceBusQueue Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/README.md Configure an AzureServiceBusQueue with connection string, name, retries, and timeouts. ```csharp new AzureServiceBusQueue(o => o .ConnectionString(string) .Name(string) .Retries(int) .WorkItemTimeout(TimeSpan) .ReadQueueTimeout(TimeSpan) .DequeueInterval(TimeSpan) // ... more options ) ``` -------------------------------- ### Production Queue with Connection String Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Configure an Azure Service Bus queue for production using a connection string. Ensure the AZURE_SERVICE_BUS_CONNECTION_STRING environment variable is set. ```csharp var connectionString = Environment.GetEnvironmentVariable("AZURE_SERVICEBUS_CONNECTION_STRING") ?? throw new InvalidOperationException("Missing connection string"); var queue = new AzureServiceBusQueue(options => options .ConnectionString(connectionString) .Name("prod-queue") .Retries(5) .WorkItemTimeout(TimeSpan.FromMinutes(5))); ``` -------------------------------- ### Configure Queue with Auto-Creation Enabled Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/errors.md Enables the Azure Service Bus client to automatically create the queue if it does not exist. ```csharp var queue = new AzureServiceBusQueue(options => options .ConnectionString(connStr) .Name("myqueue") .EnableCreateQueue()) // Allow creation ``` -------------------------------- ### Immediate Retry Delay Strategy Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/advanced-usage.md Set up an immediate retry strategy where there is no delay between message processing attempts. This is suitable for scenarios where retries should be attempted as quickly as possible. ```csharp new AzureServiceBusQueue(o => o .RetryDelay(attempt => TimeSpan.Zero)) // All retries immediate ``` -------------------------------- ### Configure Advanced Azure Service Bus Queue Options Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Configure advanced settings for an Azure Service Bus queue, such as maximum size, partitioning, and dead-lettering. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("large-queue") .MaxSizeInMegabytes(5120) // 5 GB .EnablePartitioning(true) .EnableBatchedOperations(true) .Status(EntityStatus.Active) .ForwardDeadLetteredMessagesTo("deadletter-queue")); ``` -------------------------------- ### Configure Azure Service Bus Message Bus with Topic Options Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Configure an Azure Service Bus Message Bus with topic-specific options, including partitioning and ordering. ```csharp var messageBus = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("domain-events") .TopicEnablePartitioning(true) .TopicSupportOrdering(true)); ``` -------------------------------- ### Subscribe to Messages on Azure Service Bus Topic Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/SUMMARY.txt Demonstrates how to subscribe to messages on an Azure Service Bus topic. This allows a client to receive messages published to the topic. ```csharp await _messageBus.SubscribeAsync(async msg => { // Process message }); ``` -------------------------------- ### AzureServiceBusQueue Constructor with Builder Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusQueue.md Initializes the AzureServiceBusQueue using a fluent builder pattern for configuration. This is a convenient way to set up connection details and queue names. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connectionString) .Name("queue-name")); ``` -------------------------------- ### Configure Queue for Emulator Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/README.md Configures an AzureServiceBusQueue to connect to the local Azure Service Bus emulator for development purposes. Ensure the emulator is running and the connection string is correctly set. ```csharp const string EmulatorConnection = "Endpoint=sb://localhost:5672;" "SharedAccessKeyName=RootManageSharedAccessKey;" "SharedAccessKey=SAS_KEY_VALUE;" "UseDevelopmentEmulator=true"; var queue = new AzureServiceBusQueue(o => o .ConnectionString(EmulatorConnection) .Name("queue")); ``` -------------------------------- ### Publish events to Azure Service Bus Topic Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/samples/README.md Use this command to publish events to an Azure Service Bus Topic. Supports custom event types, data, and correlation IDs. Defaults to the emulator connection string. ```bash dotnet run --project samples/Foundatio.AzureServiceBus.Publish -- [options] ``` ```bash # Publish a simple event using emulator dotnet run --project samples/Foundatio.AzureServiceBus.Publish ``` ```bash # Publish event with correlation ID dotnet run --project samples/Foundatio.AzureServiceBus.Publish -- \ --event-type "OrderCreated" \ --data "Order #12345" \ --correlation-id "order-12345" ``` -------------------------------- ### Publish and Subscribe Messages Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/README.md Demonstrates how to publish a message to a topic and subscribe to messages from that topic. Ensure the AzureServiceBusMessageBus is configured with the correct connection string and topic name. ```csharp // Publisher var messageBus = new AzureServiceBusMessageBus(o => o .ConnectionString(connStr) .Topic("events")); await messageBus.PublishAsync("OrderCreated", new OrderEvent { OrderId = 123 }); // Subscriber await messageBus.SubscribeAsync(async msg => { await ProcessOrderAsync(msg); }); ``` -------------------------------- ### Complete or Abandon Already Processed Entry Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusQueueEntry.md Demonstrates attempting to complete an already completed queue entry, which results in a QueueException. This highlights the importance of checking entry state or handling exceptions for idempotency. ```csharp var entry = await queue.DequeueAsync(); await entry.CompleteAsync(); try { await entry.CompleteAsync(); // Already completed! } catch (QueueException ex) { Console.WriteLine($"Error: {ex.Message}"); // Output: "Queue entry has already been completed or abandoned." } ``` -------------------------------- ### Dequeue and Process a Message from Azure Service Bus Queue Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/getting-started.md Shows how to dequeue a message, process it, and then mark it as complete or abandon it for retry. Includes basic error handling. ```csharp using Foundatio.Queues; var queue = new AzureServiceBusQueue(options => options .ConnectionString(connectionString) .Name("work-queue")); // Dequeue one message var entry = await queue.DequeueAsync(); if (entry != null) { try { Console.WriteLine($"Processing: {entry.Value.Data}"); // Process the item await ProcessWorkAsync(entry.Value); // Mark as completed await entry.CompleteAsync(); Console.WriteLine("Completed"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); // Return to queue for retry await entry.AbandonAsync(); } } await queue.DisposeAsync(); ``` -------------------------------- ### AzureServiceBusQueue Lifecycle Options Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Configure automatic deletion and message time-to-live for the queue. `AutoDeleteOnIdle` has a minimum of 5 minutes. ```csharp .AutoDeleteOnIdle(TimeSpan duration) ``` ```csharp .DefaultMessageTimeToLive(TimeSpan ttl) ``` -------------------------------- ### Enqueue Message to Azure Service Bus Queue Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/SUMMARY.txt Demonstrates how to enqueue a message to an Azure Service Bus queue. This is a fundamental operation for sending messages. ```csharp await _queue.EnqueueAsync(new SomeMessage { Data = "Hello" }); ``` -------------------------------- ### Enable Partitioning for Parallel Processing Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/advanced-usage.md Configure an Azure Service Bus queue to enable partitioning, which distributes messages across multiple brokers for parallel processing. Messages with the same PartitionKey are guaranteed to be processed in order. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("partitioned-queue") .EnablePartitioning(true) .MaxSizeInMegabytes(5120)); // Service Bus partitions across multiple brokers for parallel processing // Messages with same PartitionKey processed in order ``` -------------------------------- ### Running Specific Test File Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/AGENTS.md Command to filter and run tests specifically from the AzureServiceBusQueueTests file. ```bash # Specific test file dotnet test --filter "FullyQualifiedName~AzureServiceBusQueueTests" ``` -------------------------------- ### Configure Queue with Azure Identity Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/README.md Sets up an AzureServiceBusQueue using Azure Identity for authentication, which is recommended for cloud-based deployments. This requires the FullyQualifiedNamespace and a credential object. ```csharp using Azure.Identity; var credential = new DefaultAzureCredential(); var queue = new AzureServiceBusQueue(o => o .FullyQualifiedNamespace("namespace.servicebus.windows.net") .Credential(credential) .Name("queue")); ``` -------------------------------- ### Azure Service Bus Emulator Connection String Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/configuration.md Provides a connection string for the Azure Service Bus emulator, enabling local testing without requiring a live Azure connection. The emulator skips admin API calls and existence checks. ```text Endpoint=sb://localhost:5672;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true ``` -------------------------------- ### QueueEntryOptions Class Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/types.md Options for enqueuing messages, including unique ID, correlation ID, delivery delay, and custom properties. ```csharp public class QueueEntryOptions { public string? UniqueId { get; set; } public string? CorrelationId { get; set; } public TimeSpan? DeliveryDelay { get; set; } public IDictionary? Properties { get; set; } } ``` -------------------------------- ### Configure AzureServiceBusMessageBus Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/README.md Configure an AzureServiceBusMessageBus with connection string, topic, subscription name, and concurrency settings. ```csharp new AzureServiceBusMessageBus(o => o .ConnectionString(string) .Topic(string) .SubscriptionName(string) .MaxConcurrentCalls(int) // ... more options ) ``` -------------------------------- ### Configure NuGet.config for CI Feed Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/README.md Add this configuration to your NuGet.config file to include the Foundatio CI feed and map Foundatio packages to it. ```xml ``` -------------------------------- ### Enqueue messages to Azure Service Bus Queue Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/samples/README.md Use this command to send messages to an Azure Service Bus Queue. Supports custom properties and correlation IDs. Defaults to the emulator connection string. ```bash dotnet run --project samples/Foundatio.AzureServiceBus.Enqueue -- [options] ``` ```bash # Send a simple message using emulator dotnet run --project samples/Foundatio.AzureServiceBus.Enqueue ``` ```bash # Send message with metadata dotnet run --project samples/Foundatio.AzureServiceBus.Enqueue -- \ --message "Test Message" \ --correlation-id "12345" \ --property "Source=Sample" \ --property "Priority=High" ``` ```bash # Send multiple messages dotnet run --project samples/Foundatio.AzureServiceBus.Enqueue -- \ --message "Batch Message" \ --count 5 ``` -------------------------------- ### Configure Message Forwarding Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/advanced-usage.md Set up message forwarding for a queue by specifying ForwardTo and ForwardDeadLetteredMessagesTo options. This automatically routes messages to a different queue or topic, and dead-lettered messages to an archive. ```csharp var queue = new AzureServiceBusQueue(o => o .ConnectionString(connStr) .Name("main-queue") .ForwardTo("audit-queue") // All messages forwarded .ForwardDeadLetteredMessagesTo("deadletter-archive")); // Dead-lettered messages forwarded to archive ``` -------------------------------- ### Enqueue Message with Scheduled Delivery Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/types.md Illustrates enqueuing a message with a specified `DeliveryDelay` to schedule its availability in the queue. ```csharp var options = new QueueEntryOptions { CorrelationId = "order-123", DeliveryDelay = TimeSpan.FromMinutes(30) // Deliver in 30 minutes }; await queue.EnqueueAsync(message, options); ``` -------------------------------- ### AzureServiceBusMessageBus Constructor with Builder Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/api-reference/AzureServiceBusMessageBus.md Instantiate AzureServiceBusMessageBus using a fluent builder delegate for configuration. ConnectionString and Topic are essential. ```csharp var messageBus = new AzureServiceBusMessageBus(o => o .ConnectionString(connectionString) .Topic("events")); ``` -------------------------------- ### Environment-Based Queue Configuration Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/advanced-usage.md Dynamically configure AzureServiceBusQueue based on the environment (production, staging, development). Connection strings and specific settings like retries and timeouts are adjusted per environment. ```csharp IQueue CreateQueue(string environment) { var connStr = Environment.GetEnvironmentVariable( $"AZURE_SERVICEBUS_{environment.ToUpper()}"); return new AzureServiceBusQueue(o => { o.ConnectionString(connStr); o.Name($"work-queue-{environment}"); if (environment == "production") { o.Retries(10) .WorkItemTimeout(TimeSpan.FromMinutes(5)) .EnableBatchedOperations(true) .MaxSizeInMegabytes(10240); } else if (environment == "staging") { o.Retries(5) .WorkItemTimeout(TimeSpan.FromMinutes(3)) .EnableBatchedOperations(true); } else // development { o.Retries(1) .WorkItemTimeout(TimeSpan.FromMinutes(1)) .DisableCreateQueue() // Pre-created via emulator .ConnectionString("Endpoint=sb://localhost:5672;...;UseDevelopmentEmulator=true"); } }); } var queue = CreateQueue(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")); ``` -------------------------------- ### Exponential Backoff with Maximum Delay Source: https://github.com/foundatiofx/foundatio.azureservicebus/blob/main/_autodocs/advanced-usage.md Implement an exponential backoff retry strategy that caps the maximum delay between attempts. This prevents excessively long waits for retries while still benefiting from increasing delays. ```csharp new AzureServiceBusQueue(o => o .RetryDelay(attempt => { var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt)); var maxDelay = TimeSpan.FromMinutes(5); return delay > maxDelay ? maxDelay : delay; })) // Caps at 5 minutes ```