Пример #1
0
 public void Dispose()
 {
     _processor.DisposeAsync().GetAwaiter().GetResult();
     _processor = null;
     _client.DisposeAsync().GetAwaiter().GetResult();
     _client = null;
 }
        static async Task SendSalesMessageAsync()
        {
            await using var client = new ServiceBusClient(ServiceBusConnectionString);

            await using ServiceBusSender sender = client.CreateSender(QueueName);
            try
            {
                string messageBody = $"$10,000 order for bicycle parts from retailer Adventure Works.";
                var    message     = new ServiceBusMessage(messageBody);
                Console.WriteLine($"Sending message: {messageBody}");
                await sender.SendMessageAsync(message);
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
            finally
            {
                // Calling DisposeAsync on client types is required to ensure that network
                // resources and other unmanaged objects are properly cleaned up.
                await sender.DisposeAsync();

                await client.DisposeAsync();
            }
        }
Пример #3
0
        //private static string _subscriptionName = "demosubscription2";

        static async Task Main(string[] args)
        {
            var connStr   = "";
            var topicName = "demotopic1";

            _topicClient = new ServiceBusClient(connStr);
            _processor   = _topicClient.CreateProcessor(topicName, _subscriptionName, new ServiceBusProcessorOptions());

            try
            {
                _processor.ProcessMessageAsync += MessageHandler;
                _processor.ProcessErrorAsync   += ErrorHandler;

                await _processor.StartProcessingAsync();

                Console.WriteLine("Wait for a minute and then press any key to end the processing");
                Console.ReadKey();

                Console.WriteLine("Stopping");

                await _processor.StopProcessingAsync();

                Console.WriteLine("Stopped");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                await _processor.DisposeAsync();

                await _topicClient.DisposeAsync();
            }
        }
Пример #4
0
        private static async Task PublishMessageToTopic()
        {
            using ServiceBusMessageBatch messageBatch = await _sender.CreateMessageBatchAsync();

            for (int i = 0; i < 10; i++)
            {
                if (!messageBatch.TryAddMessage(new ServiceBusMessage($"Message {i}")))
                {
                    throw new Exception($"The message {i} is too large to fit in the batch");
                }
            }

            try
            {
                await _sender.SendMessagesAsync(messageBatch);

                Console.WriteLine("A batch of message has been sent to the topic");
            }
            finally
            {
                await _sender.DisposeAsync();

                await _topicClient.DisposeAsync();
            }

            Console.WriteLine("Press enter to end the application");
            Console.ReadKey();
        }
Пример #5
0
        static async Task MainAsync()
        {
            serviceBusClient    = new ServiceBusClient(ServiceBusConnectionString);
            serviceBusProcessor = serviceBusClient.CreateProcessor(TopicName, SubscriptionName, RegisterOptions());
            //serviceBusProcessor = serviceBusClient.CreateProcessor(QueueName, RegisterOptions());
            serviceBusProcessor.ProcessErrorAsync   += ExceptionReceivedHandler;
            serviceBusProcessor.ProcessMessageAsync += ProcessMessagesAsync;



            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

            // Register the queue message handler and receive messages in a loop
            try
            {
                serviceBusProcessor.StartProcessingAsync();
            }
            catch (ServiceBusException e)
            {
                System.Console.WriteLine("OH SNAP!: " + e.Message);
            }


            Console.ReadLine();
            await serviceBusProcessor.StopProcessingAsync();

            await serviceBusProcessor.CloseAsync();

            await serviceBusClient.DisposeAsync();
        }
        public async Task MetricsInstanceIsNotMutated()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
            {
                await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, new ServiceBusClientOptions { EnableTransportMetrics = true });

                ServiceBusSender sender = client.CreateSender(scope.QueueName);

                await sender.SendMessageAsync(new ServiceBusMessage());

                var metrics        = client.GetTransportMetrics();
                var firstHeartBeat = metrics.LastHeartBeat;
                var firstOpen      = metrics.LastConnectionOpen;
                Assert.GreaterOrEqual(firstOpen, firstHeartBeat);

                SimulateNetworkFailure(client);
                await sender.SendMessageAsync(new ServiceBusMessage());

                Assert.AreEqual(firstOpen, metrics.LastConnectionOpen);

                await client.DisposeAsync();

                // The close frame does not come back from the service before the DisposeAsync
                // call is returned.
                await Task.Delay(500);

                Assert.IsNull(metrics.LastConnectionClose);
            }
        }
Пример #7
0
        public static async Task Main(string[] args)
        {
            client = new ServiceBusClient(connectionString);
            sender = client.CreateSender(queueName);

            using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

            for (int i = 1; i <= numOfMessages; i++)
            {
                if (!messageBatch.TryAddMessage(new ServiceBusMessage($"Message {i}")))
                {
                    throw new Exception($"The message {i} is too large to fit in the batch.");
                }
            }

            try
            {
                await sender.SendMessagesAsync(messageBatch);

                Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue.");
            }
            finally
            {
                await sender.DisposeAsync();

                await client.DisposeAsync();
            }
        }
Пример #8
0
 public void Dispose()
 {
     _sender.DisposeAsync().GetAwaiter().GetResult();
     _sender = null;
     _client.DisposeAsync().GetAwaiter().GetResult();
     _client = null;
 }
        static async Task Main()
        {
            client    = new ServiceBusClient(connectionString);
            processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());

            try
            {
                processor.ProcessMessageAsync += MessageHandler;
                processor.ProcessErrorAsync   += ErrorHandler;

                await processor.StartProcessingAsync();

                Console.WriteLine("Wait for a minute and then press any key to end the processing");
                Console.ReadKey();

                Console.WriteLine("\nStopping the receiver...");
                await processor.StopProcessingAsync();

                Console.WriteLine("Stopped receiving messages");
            }
            finally
            {
                await processor.DisposeAsync();

                await client.DisposeAsync();
            }
        }
 protected virtual async Task DisposeInternal()
 {
     // Hmmm... why does StopProcessingAsync take so long?
     _ = Task.Run(() => { try { _processor.StopProcessingAsync().Wait(); } catch { } });
     try { await DeleteSubscription(_connectionString, _topic, _subscription); } catch { }
     try { await _client.DisposeAsync().AsTask(); } catch { }
 }
Пример #11
0
        static async Task ReceiveMessagesAsync()
        {
            ServiceBusClient client = new ServiceBusClient(connectionString);
            // create a processor that we can use to process the messages
            ServiceBusProcessor processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());

            // add handler to process messages
            processor.ProcessMessageAsync += MessageHandler;

            // add handler to process any errors
            processor.ProcessErrorAsync += ErrorHandler;

            // start processing
            await processor.StartProcessingAsync();

            Console.WriteLine("Wait for a minute and then press any key to end the processing");
            Console.ReadKey();

            // stop processing
            Console.WriteLine("\nStopping the receiver...");
            await processor.StopProcessingAsync();

            await client.DisposeAsync();

            Console.WriteLine("Stopped receiving messages");
        }
Пример #12
0
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            await processor.DisposeAsync();

            await serviceBusClient.DisposeAsync();

            await base.StopAsync(cancellationToken);
        }
Пример #13
0
    public async Task CloseConnectionAsync()
    {
        await _serviceBusSender.CloseAsync();

        await _serviceBusClient.DisposeAsync();

        Console.WriteLine("Client connection closed");
    }
Пример #14
0
        public async ValueTask DisposeAsync()
        {
            if (!(_client is null))
            {
                await _client.DisposeAsync().ConfigureAwait(false);
            }

            GC.SuppressFinalize(this);
        }
Пример #15
0
        public async Task CancelScheduledMessagesAsyncValidatesClientIsNotDisposed()
        {
            await using var client = new ServiceBusClient("not.real.com", Mock.Of <TokenCredential>());
            await using var sender = client.CreateSender("fake");

            await client.DisposeAsync();

            Assert.That(async() => await sender.CancelScheduledMessagesAsync(new[] { 12345L, 678910L }),
                        Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
        }
Пример #16
0
        public async Task RenewMessageLockValidatesClientIsNotDisposed()
        {
            await using var client   = new ServiceBusClient("not.real.com", Mock.Of <TokenCredential>());
            await using var receiver = client.CreateReceiver("fake");

            await client.DisposeAsync();

            Assert.That(async() => await receiver.RenewMessageLockAsync(new ServiceBusReceivedMessage()),
                        Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
        }
    public async Task CloseConnectionAsync()
    {
        await _serviceBusProcessor.StopProcessingAsync();

        await _serviceBusProcessor.CloseAsync();

        await _serviceBusClient.DisposeAsync();

        Console.WriteLine("Client connection closed");
    }
Пример #18
0
        public async Task ScheduleMessagesAsyncValidatesClientIsNotDisposed()
        {
            await using var client = new ServiceBusClient("not.real.com", Mock.Of <TokenCredential>());
            await using var sender = client.CreateSender("fake");

            await client.DisposeAsync();

            Assert.That(async() => await sender.ScheduleMessagesAsync(new[] { new ServiceBusMessage("one"), new ServiceBusMessage("two") }, new DateTimeOffset(2015, 10, 27, 12, 0, 0, TimeSpan.Zero)),
                        Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
        }
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
            _topicClient.DisposeAsync().GetAwaiter().GetResult();
        }
    public async ValueTask DisposeAsync()
    {
        if (_disposed)
        {
            return;
        }

        _disposed = true;
        await _topicClient.DisposeAsync();
    }
Пример #21
0
        public async void Dispose()
        {
            // stop processing
            await processor.StopProcessingAsync();

            await processor.DisposeAsync();

            await sender.DisposeAsync();

            await serviceBusClient.DisposeAsync();
        }
Пример #22
0
        public async Task SendMessagesAsyncValidatesClientIsNotDisposed()
        {
            await using var client = new ServiceBusClient("not.real.com", Mock.Of <TokenCredential>());
            await using var sender = client.CreateSender("fake");

            using var batch = ServiceBusModelFactory.ServiceBusMessageBatch(4096, new List <ServiceBusMessage> { new ServiceBusMessage("test") });

            await client.DisposeAsync();

            Assert.That(async() => await sender.SendMessagesAsync(batch),
                        Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
        }
        private static async Task MainServiceBusAsync(string[] args)
        {
            WriteLine("Enter your Service Bus connection string:");
            var ServiceBusConnectionString = ReadLine();

            while (ServiceBusConnectionString.Length == 0)
            {
                WriteLine("Try again, this value must have a length > 0");
                WriteLine("Enter your Service Bus connection string:");
                ServiceBusConnectionString = ReadLine();
            }
            WriteLine("Send message(s) to a Queue or Topic?");
            var QueueOrTopic = ReadLine();

            while (QueueOrTopic.Length == 0)
            {
                WriteLine("Try again, enter either 'Queue' or 'Topic'");
                WriteLine("Enter your Queue name:");
                QueueOrTopic = ReadLine();
            }
            WriteLine("Enter your Queue/Topic name:");
            var QueueName = ReadLine();

            while (QueueName.Length == 0)
            {
                WriteLine("Try again, this value must have a length > 0");
                WriteLine("Enter your Queue/Topic name:");
                QueueName = ReadLine();
            }
            WriteLine("Send messages in 'batch' or 'single'?");
            var BatchOrSingle = ReadLine();

            while (BatchOrSingle.Length == 0)
            {
                WriteLine("Try again, this value must have a length > 0");
                WriteLine("'batch' messages together or send 'single', one by one:");
                BatchOrSingle = ReadLine();
            }
            WriteLine("Enter number of messages to add: ");
            int ServiceBusMessagesToSend = 0;

            while (!int.TryParse(ReadLine(), out ServiceBusMessagesToSend))
            {
                WriteLine("Try again, this value must be numeric.");
            }

            await using var client = new ServiceBusClient(ServiceBusConnectionString);
            ServiceBusSender sender = client.CreateSender(QueueName);

            await SendMessagesToServicebus(sender, QueueOrTopic.ToLower(), BatchOrSingle, ServiceBusMessagesToSend);

            await client.DisposeAsync();
        }
        /// <summary>
        /// Unsubscribe from messagebus and closes connection.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task UnSubscribeFromMessageBusAsync(CancellationToken cancellationToken = default)
        {
            if (_serviceBusProcessor is not null)
            {
                await _serviceBusProcessor.DisposeAsync();
            }

            if (_serviceBusClient is not null)
            {
                await _serviceBusClient.DisposeAsync();
            }
        }
        public async Task StopAsync()
        {
            if (string.IsNullOrWhiteSpace(_subscriptionName))
            {
                return;
            }

            var tskStopProcessing = _sbProcessor.StopProcessingAsync();
            var tskDeleteSub      = DeleteSubscriptionAsync();
            await _sbClient.DisposeAsync();

            await Task.WhenAll(tskStopProcessing, tskDeleteSub);

            _subscriptionName = null;
        }
Пример #26
0
        public async Task PublishMessage(BaseMessage message, string topicName)
        {
            await using var client = new ServiceBusClient(connectionString);

            ServiceBusSender sender = client.CreateSender(topicName);

            var jsonMessage = JsonConvert.SerializeObject(message);
            ServiceBusMessage finalMessage = new ServiceBusMessage(Encoding.UTF8.GetBytes(jsonMessage))
            {
                CorrelationId = Guid.NewGuid().ToString()
            };

            await sender.SendMessageAsync(finalMessage);

            await client.DisposeAsync();
        }
Пример #27
0
        public async Task CreateBatchReactsToClosingTheClient()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
            {
                await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
                await using var sender = client.CreateSender(scope.QueueName);

                using var batch = await sender.CreateMessageBatchAsync();

                // Close the client and attempt to create another batch.

                await client.DisposeAsync();

                Assert.That(async() => await sender.CreateMessageBatchAsync(),
                            Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
            }
        }
        public async Task GetChildClientFromClosedParentClientThrows(bool useSessions)
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: useSessions))
            {
                var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
                var sender = client.CreateSender(scope.QueueName);

                var message = GetMessage(useSessions ? "sessionId" : null);
                await sender.SendMessageAsync(message);

                await sender.DisposeAsync();

                ServiceBusReceiver receiver;
                if (!useSessions)
                {
                    receiver = client.CreateReceiver(scope.QueueName);
                }
                else
                {
                    receiver = await client.CreateSessionReceiverAsync(scope.QueueName);
                }
                var receivedMessage = await receiver.ReceiveMessageAsync().ConfigureAwait(false);

                Assert.AreEqual(message.Body.ToString(), receivedMessage.Body.ToString());

                await client.DisposeAsync();

                Assert.IsTrue(client.IsClosed);
                if (!useSessions)
                {
                    Assert.Throws <ObjectDisposedException>(() => client.CreateReceiver(scope.QueueName));
                    Assert.Throws <ObjectDisposedException>(() => client.CreateReceiver(scope.QueueName, scope.QueueName));
                    Assert.Throws <ObjectDisposedException>(() => client.CreateSender(scope.QueueName));
                }
                else
                {
                    Assert.ThrowsAsync <ObjectDisposedException>(async() => await client.CreateSessionReceiverAsync(scope.QueueName));
                    Assert.ThrowsAsync <ObjectDisposedException>(async() => await client.CreateSessionReceiverAsync(
                                                                     scope.QueueName,
                                                                     new ServiceBusSessionReceiverOptions {
                        SessionId = "sessionId"
                    }));
                }
                Assert.Throws <ObjectDisposedException>(() => client.CreateProcessor(scope.QueueName));
            }
        }
Пример #29
0
        public async Task ScheduleMessagesReactsToClosingTheClient()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
            {
                var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);

                await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
                await using var sender = client.CreateSender(scope.QueueName);

                await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);

                // Close the client and attempt to schedule another set of messages.

                await client.DisposeAsync();

                Assert.That(async() => await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime),
                            Throws.InstanceOf <ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
            }
        }
Пример #30
0
        static async Task Main()
        {
            // The Service Bus client types are safe to cache and use as a singleton for the lifetime
            // of the application, which is best practice when messages are being published or read
            // regularly.
            //
            // Create the clients that we'll use for sending and processing messages.
            client = new ServiceBusClient(connectionString);
            sender = client.CreateSender(queueName);

            // create a batch
            using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

            for (int i = 1; i <= numOfMessages; i++)
            {
                // try adding a message to the batch
                if (!messageBatch.TryAddMessage(new ServiceBusMessage($"Message {i} Data")))
                {
                    // if it is too large for the batch
                    throw new Exception($"The message {i} is too large to fit in the batch.");
                }
            }

            try
            {
                // Use the producer client to send the batch of messages to the Service Bus queue
                await sender.SendMessagesAsync(messageBatch);

                Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue.");
            }
            finally
            {
                // Calling DisposeAsync on client types is required to ensure that network
                // resources and other unmanaged objects are properly cleaned up.
                await sender.DisposeAsync();

                await client.DisposeAsync();
            }

            Console.WriteLine("Press any key to end the application");
            Console.ReadKey();
        }