Exemplo n.º 1
0
        public static async Task CreateTopology(IConfiguration configuration,
                                                string topicName  = "bundle-1",
                                                string auditQueue = "audit",
                                                string errorQueue = "error")
        {
            var connectionString = configuration.GetValue <string>("AzureWebJobsServiceBus");
            var managementClient = new ManagementClient(connectionString);

            var attribute = Assembly.GetExecutingAssembly().GetTypes()
                            .SelectMany(t => t.GetMethods())
                            .Where(m => m.GetCustomAttribute <FunctionNameAttribute>(false) != null)
                            .SelectMany(m => m.GetParameters())
                            .SelectMany(p => p.GetCustomAttributes <ServiceBusTriggerAttribute>(false))
                            .FirstOrDefault();

            if (attribute == null)
            {
                throw new Exception("No endpoint was found");
            }

            //var endpointQueueName = attribute.QueueName
            var endpointQueueName = configuration["NServiceBus:EndpointName"];

            //create the queue
            if (!await managementClient.QueueExistsAsync(endpointQueueName))
            {
                await managementClient.CreateQueueAsync(endpointQueueName);
            }

            //create the topic
            if (!await managementClient.TopicExistsAsync(topicName))
            {
                await managementClient.CreateTopicAsync(topicName);
            }

            //subscribe to the topic
            if (!await managementClient.SubscriptionExistsAsync(topicName, endpointQueueName))
            {
                var subscriptionDescription = new SubscriptionDescription(topicName, endpointQueueName)
                {
                    ForwardTo    = endpointQueueName,
                    UserMetadata = $"Events {endpointQueueName} subscribed to"
                };
                await managementClient.CreateSubscriptionAsync(subscriptionDescription);
            }

            //create audit queue
            if (!await managementClient.QueueExistsAsync(auditQueue))
            {
                await managementClient.CreateQueueAsync(auditQueue);
            }

            //create error queue
            if (!await managementClient.QueueExistsAsync(errorQueue))
            {
                await managementClient.CreateQueueAsync(errorQueue);
            }
        }
Exemplo n.º 2
0
        static async Task Main(string[] args)
        {
            var          connectionString    = Environment.GetEnvironmentVariable("AzureServiceBus_ConnectionString");
            const string sqlConnectionString = Environment.GetEnvironmentVariable("SQLServer_ConnectionString");

            var management = new ManagementClient(connectionString);

            if (!await management.QueueExistsAsync("input"))
            {
                await management.CreateQueueAsync("input");
            }
            if (!await management.QueueExistsAsync("output"))
            {
                await management.CreateQueueAsync("output");
            }

            var message = new Message(Encoding.UTF8.GetBytes("test message"));
            var sender  = new MessageSender(connectionString, "input");
            await sender.SendAsync(message);

            await sender.CloseAsync();

            // receive a message
            var connection = new ServiceBusConnection(connectionString);
            var receiver   = new MessageReceiver(connection, "input");

            sender = new MessageSender(connection, entityPath: "output", viaEntityPath: "input");
            var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(30));

            message = await receiver.ReceiveAsync();

            using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await sender.SendAsync(new Message(Encoding.Default.GetBytes("response")));

                await receiver.CompleteAsync(message.SystemProperties.LockToken);

                using (var suppress = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
                {
                    await ExecuteInnerTransaction(sqlConnectionString);

                    suppress.Complete();
                }

                tx.Complete();
            }

            await management.CloseAsync();

            await sender.CloseAsync();

            await receiver.CloseAsync();
        }
        private static async Task BuildServiceBusQueues(IFunctionsHostBuilder builder)
        {
            TimeSpan  lockDuration     = TimeSpan.FromMinutes(5);
            const int maxDeliveryCount = 10;
            const int maxSizeInMB      = 5120;

            var configuration = builder.Services.BuildServiceProvider().GetService <IConfiguration>();

            var serviceBusConnectionString = configuration["DASServiceBusConnectionString"];

            var managementClient = new ManagementClient(serviceBusConnectionString);

            var applyFileExtractQueue = configuration["ApplyFileExtractQueue"];

            if (!await managementClient.QueueExistsAsync(applyFileExtractQueue))
            {
                var applyQueueDescription = new QueueDescription(applyFileExtractQueue)
                {
                    LockDuration     = lockDuration,
                    MaxDeliveryCount = maxDeliveryCount,
                    MaxSizeInMB      = maxSizeInMB
                };
                await managementClient.CreateQueueAsync(applyQueueDescription);
            }

            var adminFileExtractQueue = configuration["AdminFileExtractQueue"];

            if (!await managementClient.QueueExistsAsync(adminFileExtractQueue))
            {
                var adminQueueDescription = new QueueDescription(adminFileExtractQueue)
                {
                    LockDuration     = lockDuration,
                    MaxDeliveryCount = maxDeliveryCount,
                    MaxSizeInMB      = maxSizeInMB
                };
                await managementClient.CreateQueueAsync(adminQueueDescription);
            }

            var appealFileExtractQueue = configuration["AppealFileExtractQueue"];

            if (!await managementClient.QueueExistsAsync(appealFileExtractQueue))
            {
                var appealQueueDescription = new QueueDescription(appealFileExtractQueue)
                {
                    LockDuration     = lockDuration,
                    MaxDeliveryCount = maxDeliveryCount,
                    MaxSizeInMB      = maxSizeInMB
                };
                await managementClient.CreateQueueAsync(appealQueueDescription);
            }
        }
Exemplo n.º 4
0
        public async Task MessagingEntityAlreadyExistsExceptionTest()
        {
            var queueName        = Guid.NewGuid().ToString("D").Substring(0, 8);
            var topicName        = Guid.NewGuid().ToString("D").Substring(0, 8);
            var subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var client           = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString));

            try
            {
                await client.CreateQueueAsync(queueName);

                await client.CreateTopicAsync(topicName);

                await client.CreateSubscriptionAsync(topicName, subscriptionName);

                await Assert.ThrowsAsync <MessagingEntityAlreadyExistsException>(
                    async() =>
                {
                    await client.CreateQueueAsync(queueName);
                });

                await Assert.ThrowsAsync <MessagingEntityAlreadyExistsException>(
                    async() =>
                {
                    await client.CreateTopicAsync(topicName);
                });

                await Assert.ThrowsAsync <MessagingEntityAlreadyExistsException>(
                    async() =>
                {
                    await client.CreateSubscriptionAsync(topicName, subscriptionName);
                });

                // Cleanup
                await client.DeleteQueueAsync(queueName);

                await client.DeleteTopicAsync(topicName);
            }
            catch
            {
                await Task.WhenAll(SafeDeleteTopic(client, topicName), SafeDeleteQueue(client, queueName));

                throw;
            }
            finally
            {
                await client.CloseAsync();
            }
        }
Exemplo n.º 5
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Server Console");


            // Create a new management client
            var managementClient = new ManagementClient(AccountDetails.ConnectionString);

            Console.Write("Creatng queues...");

            // Delete any existing queues
            if (await managementClient.QueueExistsAsync(AccountDetails.RequestQueueName))
            {
                await managementClient.DeleteQueueAsync(AccountDetails.RequestQueueName);
            }

            if (await managementClient.QueueExistsAsync(AccountDetails.ResponseQueueName))
            {
                await managementClient.DeleteQueueAsync(AccountDetails.ResponseQueueName);
            }

            // Create Request Queue
            //We receive messages sent by the sender with the ReplyToSessionId
            await managementClient.CreateQueueAsync(AccountDetails.RequestQueueName);

            // Create Response With Sessions
            QueueDescription responseQueueDescription =
                new QueueDescription(AccountDetails.ResponseQueueName)
            {
                //We create a session and set the session id received from the
                // ReplyToSessionId
                RequiresSession = true
            };

            await managementClient.CreateQueueAsync(responseQueueDescription);

            Console.WriteLine("Done!");

            RequestQueueClient.RegisterMessageHandler
                (ProcessRequestMessage, new MessageHandlerOptions(ProcessMessageException));
            Console.WriteLine("Processing, hit Enter to exit.");
            Console.ReadLine();

            // Close the queue clients...
            await RequestQueueClient.CloseAsync();

            await ResponseQueueClient.CloseAsync();
        }
        /// <summary>
        /// Create queue client
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private async Task <IQueueClient> NewQueueClientAsync(string name)
        {
            var managementClient = new ManagementClient(_config.ServiceBusConnString);

            while (true)
            {
                try {
                    var exists = await managementClient.QueueExistsAsync(name);

                    if (!exists)
                    {
                        await managementClient.CreateQueueAsync(new QueueDescription(name) {
                            EnablePartitioning      = true,
                            EnableBatchedOperations = true
                        });
                    }
                    return(new QueueClient(
                               _config.ServiceBusConnString, GetEntityName(name), ReceiveMode.PeekLock,
                               RetryPolicy.Default));
                }
                catch (ServiceBusException ex) {
                    if (IsRetryableException(ex))
                    {
                        await Task.Delay(2000);

                        continue; // 429
                    }
                    _logger.Error(ex, "Failed to create queue client.");
                    throw ex;
                }
            }
        }
Exemplo n.º 7
0
        internal async Task SetUpAsync()
        {
            _managmentclient         = new ManagementClient(TestContext.Parameters["ServiceBusConnectionString"]);
            _completedTodosQueueName = Guid.NewGuid().ToString();

            await _managmentclient.CreateQueueAsync(new QueueDescription(_completedTodosQueueName));
        }
Exemplo n.º 8
0
        static async Task Main(string[] args)
        {
            var connectionString = Environment.GetEnvironmentVariable("AzureServiceBus_ConnectionString");

            var management = new ManagementClient(connectionString);

            if (!await management.QueueExistsAsync("queue"))
            {
                await management.CreateQueueAsync("queue");
            }

            var sender = new MessageSender(connectionString, "queue");

            while (true)
            {
                using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                {
                    Debugger.Break();
                    await sender.SendAsync(new Message(Encoding.Default.GetBytes(DateTime.Now.ToString("s"))));

                    Console.WriteLine("message sent");

                    tx.Complete();

                    Console.WriteLine("tx completed");
                }
            }

            await management.CloseAsync();

            await sender.CloseAsync();
        }
Exemplo n.º 9
0
        private static async Task CreateQueue()
        {
            var managementClient = new ManagementClient(Settings.ConnectionString);

            if (!await managementClient.QueueExistsAsync(Settings.QueuePath))
            {
                await managementClient.CreateQueueAsync(new QueueDescription(Settings.QueuePath)
                {
                    LockDuration = TimeSpan.FromSeconds(5)
                });
            }
            if (!await managementClient.QueueExistsAsync(Settings.ForwardingQueuePath))
            {
                await managementClient.CreateQueueAsync(Settings.ForwardingQueuePath);
            }
        }
Exemplo n.º 10
0
 public async static Task CreateQueueIfNotExistsAsync(this ManagementClient client, QueueDescription queue)
 {
     if (!await client.QueueExistsAsync(queue.Path))
     {
         await client.CreateQueueAsync(queue);
     }
 }
        static async Task Main(string[] args)
        {
            var connectionString = Environment.GetEnvironmentVariable("AzureServiceBus_ConnectionString");
            var managementClient = new ManagementClient(connectionString);

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

            var queueClient = new QueueClient(connectionString, "attachments", ReceiveMode.ReceiveAndDelete);

            var configuration = new AzureStorageAttachmentConfiguration(new KeyVaultProvider("https://keyvaultplugin.vault.azure.net/secrets/storage-connection-string"));

            queueClient.RegisterAzureStorageAttachmentPlugin(configuration);
            await queueClient.SendAsync(new Message(Encoding.UTF8.GetBytes("hello")));

            var messageReceiver = new MessageReceiver(connectionString, "attachments", ReceiveMode.ReceiveAndDelete);

            messageReceiver.RegisterAzureStorageAttachmentPlugin(configuration);

            var message = await messageReceiver.ReceiveAsync(TimeSpan.FromSeconds(3));

            Console.WriteLine($"Received message with body: {Encoding.UTF8.GetString(message.Body)}");

            Console.ReadLine();
        }
Exemplo n.º 12
0
        private static async Task ProvisionSamplesAsync(string connectionString)
        {
            var management = new ManagementClient(connectionString);

            if (false == await management.TopicExistsAsync(TopicName))
            {
                await management.CreateTopicAsync(new TopicDescription(TopicName)
                {
                    AutoDeleteOnIdle = TimeSpan.FromMinutes(10)
                });
            }

            if (false == await management.SubscriptionExistsAsync(TopicName, SubscriptionName))
            {
                await management.CreateSubscriptionAsync(new SubscriptionDescription(TopicName, SubscriptionName)
                {
                    AutoDeleteOnIdle         = TimeSpan.FromMinutes(20),
                    DefaultMessageTimeToLive = TimeSpan.FromMinutes(1),
                    MaxDeliveryCount         = 2
                });
            }

            if (false == await management.QueueExistsAsync(QueueName))
            {
                await management.CreateQueueAsync(new QueueDescription(QueueName)
                {
                    AutoDeleteOnIdle         = TimeSpan.FromMinutes(20),
                    DefaultMessageTimeToLive = TimeSpan.FromMinutes(1),
                    MaxDeliveryCount         = 2
                });
            }
        }
Exemplo n.º 13
0
 private async Task CreateQueueAsync(ManagementClient management)
 {
     if (false == await management.QueueExistsAsync(QueueName))
     {
         await management.CreateQueueAsync(QueueName);
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Get service bus queue
        /// </summary>
        /// <param name="queueName"></param>
        /// <returns></returns>
        private Task <IQueueClient> GetQueue(string queueName)
        {
            var fullQueueName = $"{_configuration.ChannelPrefix}{queueName}";

            if (!CreatedChannels.Contains(fullQueueName))
            {
                lock (CreatedChannels)
                {
                    if (!CreatedChannels.Contains(fullQueueName))
                    {
                        var managementClient = new ManagementClient(_configuration.ConnectionString);
                        var exists           = managementClient.QueueExistsAsync(fullQueueName).Result;

                        if (!exists)
                        {
                            managementClient.CreateQueueAsync(fullQueueName).Wait();
                        }
                        CreatedChannels.Add(fullQueueName);
                    }
                }
            }

            var client = new QueueClient(_configuration.ConnectionString, fullQueueName, ReceiveMode.PeekLock, RetryPolicy.Default);

            client.OperationTimeout = TimeSpan.FromMinutes(5);

            return(Task.FromResult((IQueueClient)client));
        }
        public async Task <bool> Install()
        {
            if (_settings.TryGetContainer(out var container))
            {
                await container.CreateIfNotExistsAsync().ConfigureAwait(false);
            }

            var queue = await GetQueueAsync().ConfigureAwait(false);

            if (queue == null)
            {
                try
                {
                    await _client.CreateQueueAsync(_queueDescription).ConfigureAwait(false);

                    return(true);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    return(false);
                }
            }

            return(false);
        }
        public async Task <T> Request <T>(string queueName, object payload) where T : class
        {
            var temporaryQueueName = Guid.NewGuid().ToString();

            var timeoutMillis            = Math.Max(MinimumAutoDeleteOnIdleMillis, 2 * _options.RequestTimeOutMillis);
            var autoDeleteOnIdleTimespan = TimeSpan.FromMilliseconds(timeoutMillis);

            var temporaryQueueDescription = new QueueDescription(temporaryQueueName)
            {
                AutoDeleteOnIdle = autoDeleteOnIdleTimespan
            };
            await _managementClient.CreateQueueAsync(temporaryQueueDescription);

            var requestClient  = _clientFactory.CreateSendClient(queueName, RetryPolicy.Default);
            var receiverClient = _clientFactory.CreateReceiverClient(temporaryQueueName, ReceiveMode.ReceiveAndDelete);

            try
            {
                var outboundMessage = new Message(JsonSerializer.SerializeToUtf8Bytes(payload))
                {
                    ReplyTo = temporaryQueueName
                };
                await requestClient.SendAsync(outboundMessage);

                var reply = await receiverClient.ReceiveAsync(_options.RequestTimeout);

                return(reply != null
                    ? JsonSerializer.Deserialize <T>(reply.Body)
                    : null);
            }
            finally
            {
                await _managementClient.DeleteQueueAsync(temporaryQueueName);
            }
        }
Exemplo n.º 17
0
        public async Task CanGrabPeekLock()
        {
            await _managementClient.CreateQueueAsync(_queueName);

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

            await _messageSender.SendAsync(new Message
            {
                MessageId = messageId,
                Body      = new byte[] { 1, 2, 3 }
            });

            var message = await _messageReceiver.ReceiveAsync(TimeSpan.FromSeconds(2));

            Assert.That(message, Is.Not.Null);
            Assert.That(message.MessageId, Is.EqualTo(messageId));
            Assert.That(await _messageReceiver.ReceiveAsync(TimeSpan.FromSeconds(2)), Is.Null);

            var lockedUntilUtc = message.SystemProperties.LockedUntilUtc;

            Console.WriteLine($"The message is locked until {lockedUntilUtc} (message ID = {message.MessageId}, lock token = {message.SystemProperties.LockToken})");

            await _messageReceiver.CompleteAsync(message.SystemProperties.LockToken);

            Assert.That(await _messageReceiver.ReceiveAsync(TimeSpan.FromSeconds(2)), Is.Null);

            while (DateTime.UtcNow < lockedUntilUtc.AddSeconds(5))
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
            }

            var otherMessage = await _messageReceiver.ReceiveAsync(TimeSpan.FromSeconds(2));

            Assert.That(otherMessage, Is.Null, () => $"Got message at time {DateTime.UtcNow} (message ID = {otherMessage.MessageId}, lock token = {otherMessage.SystemProperties.LockToken})");
        }
Exemplo n.º 18
0
        public async Task CreateChannelsAsync(IEnumerable <string> channelNames, CancellationToken cancellationToken = default)
        {
            foreach (string channelName in channelNames)
            {
                Decompose(channelName, out string entityPath, out bool isQueue);

                if (isQueue)
                {
                    await _mgmt.CreateQueueAsync(entityPath, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    await _mgmt.CreateTopicAsync(entityPath, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 19
0
        public async Task QueueDescriptionParsedFromResponseEqualityCheckTest()
        {
            var client = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString));
            var name   = Guid.NewGuid().ToString("D").Substring(0, 8);

            try
            {
                var queueDescription        = new QueueDescription(name);
                var createdQueueDescription = await client.CreateQueueAsync(queueDescription);

                var identicalQueueDescription = new QueueDescription(name);
                Assert.Equal(identicalQueueDescription, createdQueueDescription);

                await client.DeleteQueueAsync(name);
            }
            catch
            {
                await SafeDeleteQueue(client, name);

                throw;
            }
            finally
            {
                await client.CloseAsync();
            }
        }
Exemplo n.º 20
0
        private static async Task SendMessagesAsync(int numberOfMessagesToSend = 1)
        {
            var client = new ManagementClient(ServiceBusConnectionString);

            if (!await client.QueueExistsAsync(QueueName))
            {
                await client.CreateQueueAsync(QueueName);
            }

            try
            {
                for (var i = 0; i < numberOfMessagesToSend; i++)
                {
                    // Create a new message to send to the queue.
                    var messageBody = $"Message {i}";
                    var message     = new Message(Encoding.UTF8.GetBytes(messageBody));

                    // Write the body of the message to the console.
                    Console.WriteLine($"Sending message: {messageBody}");

                    // Send the message to the queue.
                    await queueClient.SendAsync(message);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
        }
        private async Task SendMessageToQueue <T>(T message, AzureMessageContext context)
        {
            try
            {
                var mgmtQueueClient = new ManagementClient(context.ConnectionString);

                var queues = await mgmtQueueClient.GetQueuesAsync();

                if (queues.Count == 0 ||
                    (!queues.Any(x => x.Path == context.QueueOrTopicName.ToLower())))
                {
                    await mgmtQueueClient.CreateQueueAsync(context.QueueOrTopicName);
                }

                queueClient = new QueueClient(context.ConnectionString, context.QueueOrTopicName);

                queueClient.ServiceBusConnection.TransportType = TransportType.AmqpWebSockets;

                var sbMessage = FormatMessage(message);

                queueClient.SendAsync(sbMessage).Wait();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task InitializeAsync()
        {
            Console.WriteLine("Initializing AMQP...");

            var managementClient = new ManagementClient(_connectionString);

            for (int i = 0; i < _addresses.Length; i++)
            {
                string address       = _addresses[i];
                int    listenerCount = _addressListenerCounts[i];

                if (!await managementClient.QueueExistsAsync(address).ConfigureAwait(false))
                {
                    Console.WriteLine($"Creating AMQP queue {address}...");

                    await managementClient.CreateQueueAsync(new QueueDescription(address)
                    {
                        LockDuration       = TimeSpan.FromMinutes(1),
                        MaxDeliveryCount   = Int32.MaxValue,
                        EnablePartitioning = true,
                        MaxSizeInMB        = 2048
                    }).ConfigureAwait(false);

                    Console.WriteLine($"Created AMQP queue {address}");
                }

                await AddQueueClientAsync(listenerCount, address).ConfigureAwait(false);
            }

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

            Console.WriteLine($"AMQP initialized successfully");
        }
Exemplo n.º 23
0
        private static async Task SendMessagesAsync(string sessionId, string connectionString, string queueName)
        {
            var managementClient = new ManagementClient(connectionString);
            await managementClient.DeleteQueueAsync(queueName);

            await managementClient.CreateQueueAsync(new QueueDescription(queueName)
            {
                LockDuration = TimeSpan.FromMinutes(2), RequiresSession = true
            });

            var sender = new MessageSender(connectionString, queueName);

            var data = Enumerable.Range(1, 25).Select(i => new ExampleClass(i.ToString()));

            foreach (var item in data)
            {
                var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item)))
                {
                    SessionId   = sessionId,
                    ContentType = "application/json",
                    Label       = "RecipeStep",
                    MessageId   = item.ObjName,
                };
                await sender.SendAsync(message);

                lock (Console.Out)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Message sent: Session {0}, MessageId = {1}", message.SessionId,
                                      message.MessageId);
                    Console.ResetColor();
                }
            }
        }
Exemplo n.º 24
0
        public async Task CreateQueueAsync(string queuePath)
        {
            Console.WriteLine("Creating a queue {0} ...", queuePath);
            var description        = GetQueueDescription(queuePath);
            var createdDescription = await m_ManagementClient.CreateQueueAsync(description);

            Console.WriteLine("Done!");
        }
        public async Task ServiceBus_Node_DoesNotExhaustConnections()
        {
            var connectionString     = Environment.GetEnvironmentVariable("AzureWebJobsServiceBus");
            ManagementClient manager = new ManagementClient(connectionString);

            // Start with an empty queue
            if (await manager.QueueExistsAsync("node"))
            {
                await manager.DeleteQueueAsync("node");
            }

            // Pre-create the queue as we can end up with 409s if a bunch of requests
            // try to create the queue at once
            await manager.CreateQueueAsync("node");

            int i = 0, j = 0, lastConnectionCount = 0, lastConnectionLimit = 0;

            using (var client = CreateClient())
            {
                // make this longer as we'll start seeing long timeouts from Service Bus upon failure.
                client.Timeout = TimeSpan.FromMinutes(5);

                // max connections in dynamic is currently 300
                for (i = 0; i < 25; i++)
                {
                    List <Task <HttpResponseMessage> > requestTasks = new List <Task <HttpResponseMessage> >();

                    for (j = 0; j < 25; j++)
                    {
                        requestTasks.Add(client.GetAsync($"api/ServiceBusNode?code={_fixture.FunctionDefaultKey}"));
                    }

                    await Task.WhenAll(requestTasks);

                    foreach (var requestTask in requestTasks)
                    {
                        HttpResponseMessage response = await requestTask;
                        JObject             result   = await response.Content.ReadAsAsync <JObject>();

                        if (response.IsSuccessStatusCode)
                        {
                            // store these off for error details
                            lastConnectionCount = (int)result["connections"];
                            lastConnectionLimit = (int)result["connectionLimit"];

                            // make sure we have the correct limit
                            Assert.Equal(300, lastConnectionLimit);
                        }

                        Assert.True(response.IsSuccessStatusCode, $"Error: {response.StatusCode}, Last successful response: Connections: {lastConnectionCount}, ConnectionLimit: {lastConnectionLimit}");
                    }
                }
            }

            var queueInfo = await manager.GetQueueRuntimeInfoAsync("node");

            Assert.Equal(i * j, queueInfo.MessageCount);
        }
Exemplo n.º 26
0
        private static async Task CreateQueue()
        {
            var managementClient = new ManagementClient(ServiceBusConnectionString);

            if (!(await managementClient.QueueExistsAsync(QueueName)))
            {
                await managementClient.CreateQueueAsync(new QueueDescription(QueueName));
            }
        }
Exemplo n.º 27
0
        private static Task CreateQueueAsync(IConfiguration configuration, string queuePath)
        {
            var connectionString = configuration.GetServiceBusConnectionString();
            var channelName      = configuration.GetChannelName(queuePath);

            var managementClient = new ManagementClient(connectionString);

            return(managementClient.CreateQueueAsync(channelName).IgnoreRaceConditionException <MessagingEntityAlreadyExistsException>());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Creates a new Queue using the managementClient with the name provided.
        /// </summary>
        private async Task CreateQueueAsync(string queueName, ManagementClient managementClient)
        {
            // All the values have defaults and hence optional.
            // The only required parameter is the path of the queue (in this case, queueName)
            //var queueDescription = new QueueDescription(queueName)
            //{
            //    // The duration of a peek lock; that is, the amount of time that a message is locked from other receivers.
            //    LockDuration = TimeSpan.FromSeconds(45),

            //    // Size of the Queue. For non-partitioned entity, this would be the size of the queue.
            //    // For partitioned entity, this would be the size of each partition.
            //    MaxSizeInMB = 2048,

            //    // This value indicates if the queue requires guard against duplicate messages.
            //    // Find out more in DuplicateDetection sample
            //    RequiresDuplicateDetection = false,

            //    //Since RequiresDuplicateDetection is false, the following need not be specified and will be ignored.
            //    //DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2),

            //    // This indicates whether the queue supports the concept of session.
            //    // Find out more in "Session and Workflow Management Features" sample
            //    RequiresSession = false,

            //    // The default time to live value for the messages
            //    // Find out more in "TimeToLive" sample.
            //    DefaultMessageTimeToLive = TimeSpan.FromDays(7),

            //    // Duration of idle interval after which the queue is automatically deleted.
            //    AutoDeleteOnIdle = TimeSpan.MaxValue,

            //    // Decides whether an expired message due to TTL should be dead-letterd
            //    // Find out more in "TimeToLive" sample.
            //    EnableDeadLetteringOnMessageExpiration = false,

            //    // The maximum delivery count of a message before it is dead-lettered
            //    // Find out more in "DeadletterQueue" sample
            //    MaxDeliveryCount = 8,

            //    // Creating only one partition.
            //    // Find out more in PartitionedQueues sample.
            //    EnablePartitioning = false
            //};

            try
            {
                if (!await managementClient.QueueExistsAsync(queueName))
                {
                    QueueDescription createdQueue = await managementClient.CreateQueueAsync(queueName).ConfigureAwait(false);
                }
            }
            catch (ServiceBusException ex)
            {
                Console.WriteLine($"Encountered exception while creating Queue -\n{ex}");
                throw;
            }
        }
        private async Task CreateQueueIfNotExist(string connectionString, string endpointName)
        {
            var managementClient = new ManagementClient(connectionString);

            if (!await managementClient.QueueExistsAsync(endpointName))
            {
                var queue = await managementClient.CreateQueueAsync(new QueueDescription(endpointName));
            }
        }
        private async Task CreateQueueIfNotExistAsync <T>(T command)
        {
            var managerClient = new ManagementClient(_connectionString);

            if (!await managerClient.QueueExistsAsync(typeof(T).Name))
            {
                await managerClient.CreateQueueAsync(typeof(T).Name);
            }
        }