public static async Task Stage(string connectionString, string inputQueue, string destinationQueue)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.QueueExistsAsync(inputQueue))
            {
                await client.DeleteQueueAsync(inputQueue);
            }
            await client.CreateQueueAsync(new CreateQueueOptions(inputQueue) { MaxDeliveryCount = 1 });

            if (await client.QueueExistsAsync(destinationQueue))
            {
                await client.DeleteQueueAsync(destinationQueue);
            }
            await client.CreateQueueAsync(destinationQueue);
        }
Exemplo n.º 2
0
        private static async Task SendTextMessage()
        {
            const string queueName = "sbq-text-message";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            if (!await managementClient.QueueExistsAsync(queueName))
            {
                await managementClient.CreateQueueAsync(queueName);
            }

            await using var client = new ServiceBusClient(Config.Namespace, Config.Credential);

            var sender = client.CreateSender(queueName);

            var message = new ServiceBusMessage(Encoding.UTF8.GetBytes("This is a simple test message"));

            Console.WriteLine("Press any key to send a message. Press Enter to exit.");

            while (Console.ReadKey(true).Key != ConsoleKey.Enter)
            {
                await sender.SendMessageAsync(message);

                Console.WriteLine($"Message Sent for {nameof(SendTextMessage)}");
            }

            Console.ReadLine();

            await managementClient.DeleteQueueAsync(queueName);
        }
Exemplo n.º 3
0
        private static async Task ReceiveTextMessage()
        {
            const string queueName = "sbq-text-message";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            if (!await managementClient.QueueExistsAsync(queueName))
            {
                await managementClient.CreateQueueAsync(queueName);
            }

            Console.WriteLine($"Receiving messages for {nameof(ReceiveTextMessage)}...");

            await using var client = new ServiceBusClient(Config.Namespace, Config.Credential);

            // get the options to use for configuring the processor
            var options = new ServiceBusProcessorOptions
            {
                // By default after the message handler returns, the processor will complete the message
                // If we want more fine-grained control over settlement, we can set this to false.
                AutoCompleteMessages = false,

                // I can also allow for multi-threading
                MaxConcurrentCalls = 2
            };

            // create a processor that we can use to process the messages
            var processor = client.CreateProcessor(queueName, options);

            processor.ProcessMessageAsync += MessageHandler;
            processor.ProcessErrorAsync   += ErrorHandler;
        private static async Task <ServiceBusAdministrationClient> Cleanup(string connectionString, string inputQueue,
                                                                           string topicName, string rushSubscription, string currencySubscription)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.SubscriptionExistsAsync(topicName, rushSubscription))
            {
                await client.DeleteSubscriptionAsync(topicName, rushSubscription);
            }

            if (await client.SubscriptionExistsAsync(topicName, currencySubscription))
            {
                await client.DeleteSubscriptionAsync(topicName, currencySubscription);
            }

            if (await client.TopicExistsAsync(topicName))
            {
                await client.DeleteTopicAsync(topicName);
            }

            var topicDescription = new CreateTopicOptions(topicName);
            await client.CreateTopicAsync(topicDescription);

            if (await client.QueueExistsAsync(inputQueue))
            {
                await client.DeleteQueueAsync(inputQueue);
            }

            var queueDescription = new CreateQueueOptions(inputQueue);
            await client.CreateQueueAsync(queueDescription);

            return(client);
        }
        private async Task CreateQueueIfNotExistsAsync(string name, CancellationToken cancellationToken)
        {
            // if entity creation is not enabled, just return
            if (!TransportOptions.EnableEntityCreation)
            {
                Logger.LogTrace("Entity creation is diabled. Queue creation skipped");
                return;
            }

            // If the queue does not exist, create it
            Logger.LogDebug("Checking if queue '{QueueName}' exists", name);
            if (!await managementClient.QueueExistsAsync(name: name, cancellationToken: cancellationToken))
            {
                Logger.LogTrace("Queue '{QueueName}' does not exist, preparing creation.", name);
                var options = new CreateQueueOptions(name: name)
                {
                    // set the defaults for a queue here
                    Status           = EntityStatus.Active,
                    MaxDeliveryCount = 10,
                };

                // Allow for the defaults to be overriden
                TransportOptions.SetupQueueOptions?.Invoke(options);
                Logger.LogInformation("Creating queue '{QueueName}'", name);
                _ = await managementClient.CreateQueueAsync(options : options, cancellationToken : cancellationToken);
            }
        }
Exemplo n.º 6
0
        private static async Task SendRequestMessageWithResponse()
        {
            const string requestQueue  = "sbq-request-queue";
            const string responseQueue = "sbq-response-queue";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            if (!await managementClient.QueueExistsAsync(requestQueue))
            {
                await managementClient.CreateQueueAsync(requestQueue);
            }

            if (!await managementClient.QueueExistsAsync(responseQueue))
            {
                var createQueueOptions = new CreateQueueOptions(responseQueue)
                {
                    RequiresSession = true
                };

                await managementClient.CreateQueueAsync(createQueueOptions);
            }

            var responseSessionId = Guid.NewGuid().ToString();

            await using var requestClient = new ServiceBusClient(Config.Namespace, Config.Credential);

            var sender = requestClient.CreateSender(requestQueue);

            var message = new ServiceBusMessage(Encoding.UTF8.GetBytes("This is a simple test message"))
            {
                ReplyToSessionId = responseSessionId
            };

            Console.WriteLine("Press any key to send a message. Press Enter to exit.");

            await using var responseClient = new ServiceBusClient(Config.Namespace, Config.Credential);

            var serviceBusSessionProcessorOptions = new ServiceBusSessionProcessorOptions();

            serviceBusSessionProcessorOptions.SessionIds.Add(responseSessionId);

            var sessionProcessor = responseClient.CreateSessionProcessor(responseQueue, serviceBusSessionProcessorOptions);

            sessionProcessor.ProcessMessageAsync += MessageHandler;
            sessionProcessor.ProcessErrorAsync   += ErrorHandler;
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _cancellationToken = cancellationToken;
            _client            = await _clientFactory.GetReceiverClient <T>(new ServiceBusProcessorOptions
            {
                AutoCompleteMessages       = false,
                MaxAutoLockRenewalDuration = Settings.MessageLockTimeout,
                MaxConcurrentCalls         = Settings.MaxConcurrentCalls,
                PrefetchCount = Settings.PrefetchCount,
                ReceiveMode   = ServiceBusReceiveMode.PeekLock
            }).ConfigureAwait(false);

            var queueName = AutoMessageMapper.GetQueueName <T>();

            if (!await _managementClient.QueueExistsAsync(queueName, _cancellationToken).ConfigureAwait(false))
            {
                try
                {
                    var serviceBusCreationOptions = GetServiceBusCreationOptions();

                    await _managementClient.CreateQueueAsync(new CreateQueueOptions(queueName)
                    {
                        EnablePartitioning      = serviceBusCreationOptions.EnablePartitioning,
                        EnableBatchedOperations = serviceBusCreationOptions.EnableBatchedOperations
                    }, cancellationToken).ConfigureAwait(false);
                }
                catch (ServiceBusException e)
                {
                    _log.Error(e, "Failed to create queue {QueueName}", queueName);
                    throw;
                }
            }
            _deadLetterLimit = Settings.DeadLetterDeliveryLimit;

            _client.ProcessMessageAsync += ClientOnProcessMessageAsync;
            _client.ProcessErrorAsync   += ClientOnProcessErrorAsync;

            await _client.StartProcessingAsync(cancellationToken);

#pragma warning disable 4014
            // ReSharper disable once MethodSupportsCancellation
            Task.Run(async() =>
            {
                _cancellationToken.WaitHandle.WaitOne();
                //Cancellation requested
                try
                {
                    _log.Information($"Closing ServiceBus channel receiver for {typeof(T).Name}");
                    await _client.CloseAsync(CancellationToken.None);
                }
                catch (Exception)
                {
                    //Swallow
                }
            });
#pragma warning restore 4014
        }
Exemplo n.º 8
0
        private void CreateServiceBusQueue(string serviceBusQueueName)
        {
            var busAdmin = new ServiceBusAdministrationClient(Connections.ServiceBusConnectionString);

            if (!busAdmin.QueueExistsAsync(serviceBusQueueName).Result.Value)
            {
                busAdmin.CreateQueueAsync(serviceBusQueueName).Wait();
            }
        }
Exemplo n.º 9
0
        private async Task EnsureQueueExistsAsync(string queueName, CancellationToken cancellationToken)
        {
            if (await _administrationClient.QueueExistsAsync(queueName, cancellationToken))
            {
                return;
            }

            await _administrationClient.CreateQueueAsync(queueName, cancellationToken);
        }
Exemplo n.º 10
0
        public static async Task <IAsyncDisposable> Stage(string connectionString, string destination)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (!await client.QueueExistsAsync(destination))
            {
                await client.CreateQueueAsync(destination);
            }
            return(new Leave(connectionString, destination));
        }
Exemplo n.º 11
0
        public static async Task Stage(string connectionString, string destination)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.QueueExistsAsync(destination))
            {
                await client.DeleteQueueAsync(destination);
            }
            await client.CreateQueueAsync(destination);
        }
Exemplo n.º 12
0
 async Task CheckPermission(CancellationToken cancellationToken)
 {
     try
     {
         await administrativeClient.QueueExistsAsync("$nservicebus-verification-queue", cancellationToken).ConfigureAwait(false);
     }
     catch (UnauthorizedAccessException e)
     {
         throw new Exception("Management rights are required to run this endpoint. Verify that the SAS policy has the Manage claim.", e);
     }
 }
        public static async Task Hazard(string connectionString, string destinationQueue)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.QueueExistsAsync(destinationQueue))
            {
                QueueProperties queueProperties = await client.GetQueueAsync(destinationQueue);

                queueProperties.Status = EntityStatus.SendDisabled;

                await client.UpdateQueueAsync(queueProperties);
            }
        }
Exemplo n.º 14
0
        public static async Task Stage(string connectionString)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            async Task DeleteIfExists(string queueName)
            {
                if (await client.QueueExistsAsync(queueName))
                {
                    await client.DeleteQueueAsync(queueName);
                }
            }

            await Task.WhenAll(
                DeleteIfExists("Hop4"),
                DeleteIfExists("Hop3"),
                DeleteIfExists("Hop2"),
                DeleteIfExists("Hop1"),
                DeleteIfExists("Hop0"),
                DeleteIfExists("Hop")
                );

            var description = new CreateQueueOptions("Hop");
            await client.CreateQueueAsync(description);

            description = new CreateQueueOptions("Hop0");
            await client.CreateQueueAsync(description);

            description = new CreateQueueOptions("Hop1")
            {
                ForwardTo = "Hop0"
            };
            await client.CreateQueueAsync(description);

            description = new CreateQueueOptions("Hop2")
            {
                ForwardTo = "Hop1"
            };
            await client.CreateQueueAsync(description);

            description = new CreateQueueOptions("Hop3")
            {
                ForwardTo = "Hop2"
            };
            await client.CreateQueueAsync(description);

            description = new CreateQueueOptions("Hop4")
            {
                ForwardTo = "Hop3"
            };
            await client.CreateQueueAsync(description);
        }
Exemplo n.º 15
0
        public ServiceBusQueue(string connectionString, string queueName, ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PeekLock, bool createQueueIfItDoesNotExist = true)
            : base(connectionString)
        {
            this.connectionString = connectionString;
            this.queueName        = queueName;
            this.receiveMode      = receiveMode;
            this.SubQueue         = SubQueue.None;
            busAdmin = new ServiceBusAdministrationClient(this.connectionString);

            if (createQueueIfItDoesNotExist && !busAdmin.QueueExistsAsync(queueName).Result.Value)
            {
                busAdmin.CreateQueueAsync(queueName).Wait();
            }
        }
        public static async Task Stage(string connectionString, string destination)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.QueueExistsAsync(destination))
            {
                await client.DeleteQueueAsync(destination);
            }

            var description = new CreateQueueOptions(destination)
            {
                MaxDeliveryCount = int.MaxValue
            };
            await client.CreateQueueAsync(description);
        }
Exemplo n.º 17
0
        public async Task EnsureQueue(string queueName, CancellationToken cancellationToken = default)
        {
            if (!await _administrationClient.QueueExistsAsync(queueName, cancellationToken))
            {
                var options = new CreateQueueOptions(queueName)
                {
                    Status                   = EntityStatus.Active,
                    MaxSizeInMegabytes       = 1024,
                    DefaultMessageTimeToLive = TimeSpan.FromDays(10000),
                    RequiresSession          = queueName.Contains("response", StringComparison.OrdinalIgnoreCase)
                };

                await _administrationClient.CreateQueueAsync(options, cancellationToken);
            }
        }
        public async Task RunBeforeAllTests()
        {
            var connectionString = Environment.GetEnvironmentVariable(ServiceBusTriggeredEndpointConfiguration.DefaultServiceBusConnectionName);

            Assert.IsNotNull(connectionString, $"Environment variable '{ServiceBusTriggeredEndpointConfiguration.DefaultServiceBusConnectionName}' should be defined to run tests.");

            var client = new ServiceBusAdministrationClient(connectionString);

            const string errorQueueName = "error";

            if (!await client.QueueExistsAsync(errorQueueName))
            {
                await client.CreateQueueAsync(errorQueueName);
            }
        }
        public static async Task Stage(string connectionString, string destination)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.QueueExistsAsync(destination))
            {
                await client.DeleteQueueAsync(destination);
            }

            var queueDescription = new CreateQueueOptions(destination)
            {
                RequiresSession = true
            };
            await client.CreateQueueAsync(queueDescription);
        }
Exemplo n.º 20
0
        public static async Task Stage(string connectionString, string destination)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.QueueExistsAsync(destination))
            {
                await client.DeleteQueueAsync(destination);
            }

            var description = new CreateQueueOptions(destination)
            {
                DeadLetteringOnMessageExpiration = true, // default false
                MaxDeliveryCount = 1
            };
            await client.CreateQueueAsync(description);
        }
Exemplo n.º 21
0
        public static async Task Stage(string connectionString, string destination)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (await client.QueueExistsAsync(destination))
            {
                await client.DeleteQueueAsync(destination);
            }

            var queueDescription = new CreateQueueOptions(destination)
            {
                RequiresDuplicateDetection          = true,
                DuplicateDetectionHistoryTimeWindow = TimeSpan.FromSeconds(20)
            };
            await client.CreateQueueAsync(queueDescription);
        }
Exemplo n.º 22
0
        private static async Task SendComplexObjectMessage()
        {
            const string queueName = "sbq-complex-object-message";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            if (!await managementClient.QueueExistsAsync(queueName))
            {
                await managementClient.CreateQueueAsync(queueName);
            }

            await using var client = new ServiceBusClient(Config.Namespace, Config.Credential);

            var sender = client.CreateSender(queueName);

            var payment = new Payment
            {
                PaymentId     = Guid.NewGuid(),
                AccountNumber = "132456789",
                Amount        = 1337m,
                PaymentDate   = DateTime.Today.AddDays(1),
                Payee         = "Mr John Smith"
            };

            var message = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(payment));

            Console.WriteLine("Press any key to send a message. Press Enter to exit.");

            while (Console.ReadKey(true).Key != ConsoleKey.Enter)
            {
                await sender.SendMessageAsync(message);

                Console.WriteLine($"Message Sent for {nameof(SendComplexObjectMessage)}");
            }

            Console.ReadLine();

            await managementClient.DeleteQueueAsync(queueName);
        }
Exemplo n.º 23
0
        private static async Task SendTextMessageWithProperties()
        {
            const string queueName = "sbq-text-message-with-properties";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            if (!await managementClient.QueueExistsAsync(queueName))
            {
                await managementClient.CreateQueueAsync(queueName);
            }

            await using var client = new ServiceBusClient(Config.Namespace, Config.Credential);

            var sender = client.CreateSender(queueName);

            var message = new ServiceBusMessage
            {
                Body                  = new BinaryData("This is a simple test message"),
                ContentType           = "text/plain",
                CorrelationId         = Guid.NewGuid().ToString(),
                MessageId             = Guid.NewGuid().ToString(),
                TimeToLive            = TimeSpan.FromMinutes(10),
                ScheduledEnqueueTime  = DateTime.UtcNow,
                ApplicationProperties = { { "custom-property", "Custom Value" } }
            };

            Console.WriteLine("Press any key to send a message. Press Enter to exit.");

            while (Console.ReadKey(true).Key != ConsoleKey.Enter)
            {
                await sender.SendMessageAsync(message);

                Console.WriteLine($"Message Sent for {nameof(SendTextMessageWithProperties)}");
            }

            Console.ReadLine();

            await managementClient.DeleteQueueAsync(queueName);
        }
Exemplo n.º 24
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (Subscription == null)
            {
                if (!await _administrationClient.QueueExistsAsync(QueueOrTopic, cancellationToken))
                {
                    await _administrationClient.CreateQueueAsync(QueueOrTopic, cancellationToken);
                }
            }
            else
            {
                if (!await _administrationClient.TopicExistsAsync(QueueOrTopic, cancellationToken))
                {
                    await _administrationClient.CreateTopicAsync(QueueOrTopic, cancellationToken);
                }

                if (!await _administrationClient.SubscriptionExistsAsync(QueueOrTopic, Subscription, cancellationToken))
                {
                    await _administrationClient.CreateSubscriptionAsync(QueueOrTopic, Subscription, cancellationToken);
                }
            }

            await _processor.StartProcessingAsync(cancellationToken);
        }
Exemplo n.º 25
0
        public async Task <bool> IsQueue(string name)
        {
            var administrationClient = new ServiceBusAdministrationClient(ConnectionString);

            return(await administrationClient.QueueExistsAsync(name).ConfigureAwait(false));
        }
Exemplo n.º 26
0
        private static async Task Main(string[] args)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            if (!await client.QueueExistsAsync($"{destination}"))
            {
                await client.CreateQueueAsync($"{destination}");
            }

            for (int i = 0; i < 100; i++)
            {
                if (!await client.QueueExistsAsync($"{destination}{i}"))
                {
                    await client.CreateQueueAsync($"{destination}{i}");
                }
            }

            await using var serviceBusClient = new ServiceBusClient(connectionString, new ServiceBusClientOptions
            {
                RetryOptions = new ServiceBusRetryOptions
                {
                    TryTimeout = TimeSpan.FromSeconds(2)
                }
            });

            await using var sender = serviceBusClient.CreateSender(destination);
            await sender.SendMessageAsync(new ServiceBusMessage(UTF8.GetBytes("Deep Dive")));

            WriteLine("Message sent");

            var processorOptions = new ServiceBusProcessorOptions
            {
                AutoCompleteMessages       = false,
                MaxConcurrentCalls         = 1,
                MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(10),
                ReceiveMode   = ServiceBusReceiveMode.PeekLock,
                PrefetchCount = 10
            };

            await using var receiver      = serviceBusClient.CreateProcessor(destination, processorOptions);
            receiver.ProcessMessageAsync += async messageEventArgs =>
            {
                var message = messageEventArgs.Message;
                await Out.WriteLineAsync(
                    $"Received message with '{message.MessageId}' and content '{UTF8.GetString(message.Body)}'");

                // throw new InvalidOperationException();
                await messageEventArgs.CompleteMessageAsync(message);

                syncEvent.TrySetResult(true);
            };
            receiver.ProcessErrorAsync += async errorEventArgs =>
            {
                await Out.WriteLineAsync($"Exception: {errorEventArgs.Exception}");

                await Out.WriteLineAsync($"FullyQualifiedNamespace: {errorEventArgs.FullyQualifiedNamespace}");

                await Out.WriteLineAsync($"ErrorSource: {errorEventArgs.ErrorSource}");

                await Out.WriteLineAsync($"EntityPath: {errorEventArgs.EntityPath}");
            };

            await receiver.StartProcessingAsync();

            await syncEvent.Task;

            await receiver.StopProcessingAsync();
        }
Exemplo n.º 27
0
        private static async Task SendComplexObjectMessageWithDuplicateDetection()
        {
            const string queueName = "sbq-complex-object-message-with-duplicate";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            var createQueueOptions = new CreateQueueOptions(queueName)
            {
                RequiresDuplicateDetection          = true,
                DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10)
            };

            if (!await managementClient.QueueExistsAsync(queueName))
            {
                await managementClient.CreateQueueAsync(createQueueOptions);
            }

            await using var client = new ServiceBusClient(Config.Namespace, Config.Credential);

            var sender = client.CreateSender(queueName);

            var payments = new List <Payment>
            {
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "132456789",
                    Amount        = 1337m,
                    PaymentDate   = DateTime.Today.AddDays(1),
                    Payee         = "Mr John Smith"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1576321357",
                    Amount        = 6984.56m,
                    PaymentDate   = DateTime.Today.AddDays(3),
                    Payee         = "Mrs Jane Doe"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1867817635",
                    Amount        = 13872m,
                    PaymentDate   = DateTime.Today,
                    Payee         = "Mr Robert Smith"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1779584565",
                    Amount        = 20000m,
                    PaymentDate   = DateTime.Today.AddDays(9),
                    Payee         = "Mrs James Doe"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1657892587",
                    Amount        = 900000m,
                    PaymentDate   = DateTime.Today,
                    Payee         = "Mr William Tell"
                }
            };

            Console.WriteLine("Press any key to send all payment messages. Press Enter to exit.");

            while (Console.ReadKey(true).Key != ConsoleKey.Enter)
            {
                Console.WriteLine($"Total Payments to send: {payments.Count}");

                foreach (var payment in payments)
                {
                    var message = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(payment))
                    {
                        MessageId = payment.PaymentId.ToString() // Needed to detect duplicate messages
                    };

                    var random = new Random();

                    if (random.NextDouble() > 0.4) // Randomly simulate sending duplicate messages
                    {
                        await sender.SendMessageAsync(message);

                        Console.WriteLine($"Message Sent for {nameof(SendComplexObjectMessageWithDuplicateDetection)} - Payment ID: {payment.PaymentId}");
                    }
                    else
                    {
                        await sender.SendMessageAsync(message);

                        Console.WriteLine($"Message Sent for {nameof(SendComplexObjectMessageWithDuplicateDetection)} - Payment ID: {payment.PaymentId}");

                        await sender.SendMessageAsync(message);

                        Console.WriteLine($"Message Sent for {nameof(SendComplexObjectMessageWithDuplicateDetection)} - Payment ID: {payment.PaymentId}");
                    }
                }
            }

            Console.ReadLine();

            await managementClient.DeleteQueueAsync(queueName);
        }