Example #1
0
        static async Task TransactionAsync(bool commit)
        {
            ServiceBusSender sender = srv.CreateSender(QueueOrTopicName);

            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
                await sender.SendMessageAsync(new ServiceBusMessage("Paso1"));

                await sender.SendMessageAsync(new ServiceBusMessage("Paso2"));

                await sender.SendMessageAsync(new ServiceBusMessage("Paso3"));

                // ...
                if (commit)
                {
                    ts.Complete();
                    Console.WriteLine("Messages was sent successfully.");
                }
                else
                {
                    Console.WriteLine("Messages was cancel.");
                    ts.Dispose();
                }
            }
            await sender.CloseAsync();
        }
Example #2
0
        static async Task SendMessageAsync()
        {
            ServiceBusSender sender = srv.CreateSender(QueueOrTopicName);

            try {
                string messageBody = $"Mensaje {DateTime.Now:mm:ss:ff}: valor {rnd.Next(1, 100)}.";
                var    item        = new Item()
                {
                    Id = 1, Mensaje = messageBody
                };
                var message = item.AsMessage();
                message.To      = item.Categoria;
                message.Subject = item.Nivel;
                message.ApplicationProperties.Add("nivel", item.Nivel);
                message.MessageId = $"{DateTime.Now.Minute}-1";
                message.SessionId = Guid.NewGuid().ToString();
                if (TimeToLive > 0)
                {
                    message.TimeToLive = TimeSpan.FromSeconds(TimeToLive);
                }
                await sender.SendMessageAsync(message);

                Console.WriteLine($"Sending message: {message.MessageId} - {item}");
            } catch (Exception exception) {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
            await sender.CloseAsync();

            Console.WriteLine("Messages was sent successfully.");
        }
Example #3
0
    public async Task CloseConnectionAsync()
    {
        await _serviceBusSender.CloseAsync();

        await _serviceBusClient.DisposeAsync();

        Console.WriteLine("Client connection closed");
    }
        static async Task MainAsync(string ServiceBusConnectionString, string QueueName, string recipientEmail, string MessageBody)
        {
            Console.WriteLine($"mainAsync");
            var client = new ServiceBusClient(ServiceBusConnectionString);

            sender = client.CreateSender(QueueName);
            Console.WriteLine($"before send ansync");
            // Send Messages
            await SendMessagesAsync(recipientEmail, MessageBody);

            await sender.CloseAsync();
        }
        //ServiceBusProcessor.StopProcessingAsync currently has a bug when using the AMQP protocol that prevents it from gracefully shutting down in a timely manner
        //it will timeout after 1 min and eventually shutdown but we don't want to wait for that so do all shutdown waiting in an async void method.
        private async void Stop()
        {
            await using (_sender)
                await using (_processor)
                {
                    await _processor.StopProcessingAsync();

                    await _processor.CloseAsync();

                    await _sender.CloseAsync();
                }
        }
Example #6
0
        public async Task <ActionResult> Send(ServiceBusMessageData messageInfo)
        {
            if (string.IsNullOrEmpty(messageInfo.MessageToSend))
            {
                return(RedirectToAction("Index"));
            }

            ServiceBusSender  sender  = client.CreateSender(Config.Queue);
            ServiceBusMessage message = new ServiceBusMessage(messageInfo.MessageToSend);
            await sender.SendMessageAsync(message).ConfigureAwait(false);

            await sender.CloseAsync().ConfigureAwait(false);

            return(RedirectToAction("Index"));
        }
Example #7
0
        /// <summary>
        /// Simulate the message processing of the message pump using the Service Bus.
        /// </summary>
        public async Task SimulateMessageProcessingAsync()
        {
            if (_serviceBusEventConsumerHost is null)
            {
                throw new InvalidOperationException(
                          "Cannot simulate the message pump because the service is not yet started; please start this service before simulating");
            }

            var operationId   = Guid.NewGuid().ToString();
            var transactionId = Guid.NewGuid().ToString();

            string connectionString           = _configuration.GetServiceBusConnectionString(_entity);
            var    connectionStringProperties = ServiceBusConnectionStringProperties.Parse(connectionString);

            await using (var client = new ServiceBusClient(connectionString))
                await using (ServiceBusSender messageSender = client.CreateSender(connectionStringProperties.EntityPath))
                {
                    try
                    {
                        Order             order        = GenerateOrder();
                        ServiceBusMessage orderMessage = order.AsServiceBusMessage(operationId, transactionId);
                        await messageSender.SendMessageAsync(orderMessage);

                        string receivedEvent = _serviceBusEventConsumerHost.GetReceivedEvent(operationId);
                        Assert.NotEmpty(receivedEvent);

                        EventBatch <Event> eventBatch = EventParser.Parse(receivedEvent);
                        Assert.NotNull(eventBatch);
                        Event orderCreatedEvent = Assert.Single(eventBatch.Events);
                        Assert.NotNull(orderCreatedEvent);

                        var orderCreatedEventData = orderCreatedEvent.GetPayload <OrderCreatedEventData>();
                        Assert.NotNull(orderCreatedEventData);
                        Assert.NotNull(orderCreatedEventData.CorrelationInfo);
                        Assert.Equal(order.Id, orderCreatedEventData.Id);
                        Assert.Equal(order.Amount, orderCreatedEventData.Amount);
                        Assert.Equal(order.ArticleNumber, orderCreatedEventData.ArticleNumber);
                        Assert.Equal(transactionId, orderCreatedEventData.CorrelationInfo.TransactionId);
                        Assert.Equal(operationId, orderCreatedEventData.CorrelationInfo.OperationId);
                        Assert.NotEmpty(orderCreatedEventData.CorrelationInfo.CycleId);
                    }
                    finally
                    {
                        await messageSender.CloseAsync();
                    }
                }
        }
Example #8
0
        static async Task SendMessageBatchAsync()
        {
            ServiceBusSender sender = srv.CreateSender(QueueOrTopicName);

            string[] sessionIds = { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString() };
            ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

            try {
                for (int i = 0; i < NumeroDeEnvios; i++)
                {
                    string messageBody = $"Mensaje {DateTime.Now:mm:ss:ff}: valor {rnd.Next(1, 100)}.";
                    var    item        = new Item()
                    {
                        Id = i, Mensaje = messageBody
                    };
                    var message = item.AsMessage();
                    message.To      = item.Categoria;
                    message.Subject = item.Nivel;
                    message.ApplicationProperties.Add("nivel", item.Nivel);
                    message.MessageId = $"{DateTime.Now.Minute}-{i}";
                    message.SessionId = sessionIds[i % 3];
                    if (TimeToLive > 0)
                    {
                        message.TimeToLive = TimeSpan.FromSeconds(TimeToLive);
                    }
                    Console.WriteLine($"Sending message: {message.MessageId} - {item}");
                    if (!messageBatch.TryAddMessage(message))
                    {
                        await sender.SendMessagesAsync(messageBatch);

                        Console.WriteLine($"Sending Batch: {messageBatch.Count} - {messageBatch.SizeInBytes}");
                        messageBatch.Dispose();
                        messageBatch = await sender.CreateMessageBatchAsync();

                        messageBatch.TryAddMessage(message);
                    }
                }
                Console.WriteLine($"Sending Batch: {messageBatch.Count} - {messageBatch.SizeInBytes}");
                await sender.SendMessagesAsync(messageBatch);
            } catch (Exception exception) {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
            await sender.CloseAsync();

            Console.WriteLine("Messages was sent successfully.");
        }
Example #9
0
        public async Task EnviarMensajeAsync(string sesionId, string cadenaConexion, string nombreQueueRequest, T body)
        {
            await using (ServiceBusClient client = new ServiceBusClient(cadenaConexion))
            {
                // create a sender for the queue
                ServiceBusSender sender = client.CreateSender(nombreQueueRequest);

                // create a message that we can send
                ServiceBusMessage message = new ServiceBusMessage(JsonConvert.SerializeObject(body));
                message.SessionId   = sesionId;
                message.ContentType = "application/json";

                // send the message
                await sender.SendMessageAsync(message);

                await sender.CloseAsync();
            }
        }
Example #10
0
        public async Task CloseRespectsCancellationToken()
        {
            var mockTransportSender = new Mock <TransportSender>();
            var cts = new CancellationTokenSource();

            // mutate the cancellation token to distinguish it from CancellationToken.None
            cts.CancelAfter(100);

            var mockConnection = CreateMockConnection();

            mockConnection.Setup(
                connection => connection.CreateTransportSender(
                    It.IsAny <string>(),
                    It.IsAny <ServiceBusRetryPolicy>(),
                    It.IsAny <string>()))
            .Returns(mockTransportSender.Object);

            var sender = new ServiceBusSender("fake", mockConnection.Object);
            await sender.CloseAsync(cts.Token);

            mockTransportSender.Verify(transportReceiver => transportReceiver.CloseAsync(It.Is <CancellationToken>(ct => ct == cts.Token)));
        }
Example #11
0
    public async ValueTask DisposeAsync()
    {
        await _sender.CloseAsync();

        await _sender.DisposeAsync();
    }
Example #12
0
        private static async Task RunAsync(string fullyQualifiedNamespace, string connection)
        {
            if (!string.IsNullOrEmpty(connection))
            {
                s_client      = new ServiceBusClient(Environment.GetEnvironmentVariable(connection));
                s_adminClient = new ServiceBusAdministrationClient(Environment.GetEnvironmentVariable(connection));
            }
            else if (!string.IsNullOrEmpty(fullyQualifiedNamespace))
            {
                var defaultAzureCredential = new DefaultAzureCredential();
                s_client      = new ServiceBusClient(fullyQualifiedNamespace, defaultAzureCredential);
                s_adminClient = new ServiceBusAdministrationClient(fullyQualifiedNamespace, defaultAzureCredential);
            }
            else
            {
                throw new ArgumentException(
                          "Either a fully qualified namespace or a connection string environment variable must be specified.");
            }

            Console.WriteLine($"Creating topic {TopicName}");
            await s_adminClient.CreateTopicAsync(TopicName);

            s_sender = s_client.CreateSender(TopicName);

            // First Subscription is already created with default rule. Leave as is.
            Console.WriteLine($"Creating subscription {NoFilterSubscriptionName}");
            await s_adminClient.CreateSubscriptionAsync(TopicName, NoFilterSubscriptionName);

            Console.WriteLine($"SubscriptionName: {NoFilterSubscriptionName}, Removing and re-adding Default Rule");
            await s_adminClient.DeleteRuleAsync(TopicName, NoFilterSubscriptionName, RuleProperties.DefaultRuleName);

            await s_adminClient.CreateRuleAsync(TopicName, NoFilterSubscriptionName,
                                                new CreateRuleOptions(RuleProperties.DefaultRuleName, new TrueRuleFilter()));

            // 2nd Subscription: Add SqlFilter on Subscription 2
            // In this scenario, rather than deleting the default rule after creating the subscription,
            // we will create the subscription along with our desired rule in a single operation.
            // See https://docs.microsoft.com/en-us/azure/service-bus-messaging/topic-filters to learn more about topic filters.
            Console.WriteLine($"Creating subscription {SqlFilterOnlySubscriptionName}");
            await s_adminClient.CreateSubscriptionAsync(
                new CreateSubscriptionOptions(TopicName, SqlFilterOnlySubscriptionName),
                new CreateRuleOptions { Name = "RedSqlRule", Filter = new SqlRuleFilter("Color = 'Red'") });

            // 3rd Subscription: Add the SqlFilter Rule and Action
            // See https://docs.microsoft.com/en-us/azure/service-bus-messaging/topic-filters#actions to learn more about actions.
            Console.WriteLine($"Creating subscription {SqlFilterWithActionSubscriptionName}");
            await s_adminClient.CreateSubscriptionAsync(
                new CreateSubscriptionOptions(TopicName, SqlFilterWithActionSubscriptionName),
                new CreateRuleOptions
            {
                Name   = "BlueSqlRule",
                Filter = new SqlRuleFilter("Color = 'Blue'"),
                Action = new SqlRuleAction("SET Color = 'BlueProcessed'")
            });

            // 4th Subscription: Add Correlation Filter on Subscription 4
            Console.WriteLine($"Creating subscription {CorrelationFilterSubscriptionName}");
            await s_adminClient.CreateSubscriptionAsync(
                new CreateSubscriptionOptions(TopicName, CorrelationFilterSubscriptionName),
                new CreateRuleOptions
            {
                Name   = "ImportantCorrelationRule",
                Filter = new CorrelationRuleFilter {
                    Subject = "Red", CorrelationId = "important"
                }
            });

            // Get Rules on Subscription, called here only for one subscription as example
            var rules = s_adminClient.GetRulesAsync(TopicName, CorrelationFilterSubscriptionName);

            await foreach (var rule in rules)
            {
                Console.WriteLine(
                    $"GetRules:: SubscriptionName: {CorrelationFilterSubscriptionName}, CorrelationFilter Name: {rule.Name}, Rule: {rule.Filter}");
            }

            // Send messages to Topic
            await SendMessagesAsync();

            // Receive messages from 'NoFilterSubscription'. Should receive all 9 messages
            await ReceiveMessagesAsync(NoFilterSubscriptionName);

            // Receive messages from 'SqlFilterOnlySubscription'. Should receive all messages with Color = 'Red' i.e 3 messages
            await ReceiveMessagesAsync(SqlFilterOnlySubscriptionName);

            // Receive messages from 'SqlFilterWithActionSubscription'. Should receive all messages with Color = 'Blue'
            // i.e 3 messages AND all messages should have color set to 'BlueProcessed'
            await ReceiveMessagesAsync(SqlFilterWithActionSubscriptionName);

            // Receive messages from 'CorrelationFilterSubscription'. Should receive all messages  with Color = 'Red' and CorrelationId = "important"
            // i.e 1 message
            await ReceiveMessagesAsync(CorrelationFilterSubscriptionName);

            Console.ResetColor();

            Console.WriteLine("=======================================================================");
            Console.WriteLine("Completed Receiving all messages. Disposing clients and deleting topic.");
            Console.WriteLine("=======================================================================");

            Console.WriteLine("Disposing sender");
            await s_sender.CloseAsync();

            Console.WriteLine("Disposing client");
            await s_client.DisposeAsync();

            Console.WriteLine("Deleting topic");

            // Deleting the topic will handle deleting all the subscriptions as well.
            await s_adminClient.DeleteTopicAsync(TopicName);
        }
Example #13
0
 public async ValueTask StopAsync()
 {
     await using (_sender)
         await _sender.CloseAsync();
 }
Example #14
0
 public static void Cleanup()
 {
     Task.Run(() => queueClient.CloseAsync()).Wait();
 }
 public void Close()
 {
     _serviceBusSender.CloseAsync().Wait();
 }