private static async Task Setup(this ServiceBusAdministrationClient admin, string topic)
 {
     if (!(await admin.TopicExistsAsync(topic)).Value)
     {
         await admin.CreateTopicAsync(new CreateTopicOptions(topic));
     }
 }
        private async Task CreateTopicIfNotExistsAsync(string name, CancellationToken cancellationToken)
        {
            // if entity creation is not enabled, just return
            if (!TransportOptions.EnableEntityCreation)
            {
                Logger.LogTrace("Entity creation is diabled. Topic creation skipped");
                return;
            }

            // If the topic does not exist, create it
            Logger.LogDebug("Checking if topic '{TopicName}' exists", name);
            if (!await managementClient.TopicExistsAsync(name: name, cancellationToken: cancellationToken))
            {
                Logger.LogTrace("Topic '{TopicName}' does not exist, preparing creation.", name);
                var options = new CreateTopicOptions(name: name)
                {
                    // set the defaults for a topic here
                    Status                              = EntityStatus.Active,
                    EnablePartitioning                  = false,
                    RequiresDuplicateDetection          = BusOptions.EnableDeduplication,
                    DuplicateDetectionHistoryTimeWindow = BusOptions.DuplicateDetectionDuration,
                };

                // Allow for the defaults to be overriden
                TransportOptions.SetupTopicOptions?.Invoke(options);
                Logger.LogInformation("Creating topic '{TopicName}'", name);
                _ = await managementClient.CreateTopicAsync(options : options, cancellationToken : cancellationToken);
            }
        }
示例#3
0
        public static async Task <TopicScope> CreateWithTopic(ServiceBusAdministrationClient adminClient)
        {
            var topicName = Guid.NewGuid().ToString("D");
            var response  = await adminClient.CreateTopicAsync(topicName).ConfigureAwait(false);

            return(new TopicScope(adminClient, topicName, null));
        }
示例#4
0
 public static async Task SetupTopicAsync(this ServiceBusAdministrationClient client, string topicName)
 {
     if (!await client.TopicExistsAsync(topicName))
     {
         await client.CreateTopicAsync(topicName);
     }
 }
示例#5
0
        private static async Task SendTextMessageToTopic()
        {
            const string topicName = "sbt-text-message";

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

            if (!await managementClient.TopicExistsAsync(topicName))
            {
                await managementClient.CreateTopicAsync(topicName);
            }

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

            var sender = client.CreateSender(topicName);

            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(SendTextMessageToTopic)}");
            }

            Console.ReadLine();

            await managementClient.DeleteQueueAsync(topicName);
        }
        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 EnsureTopicExistsAsync(string topicName, CancellationToken cancellationToken)
 {
     if (!await _administrationClient.TopicExistsAsync(topicName, cancellationToken))
     {
         await _administrationClient.CreateTopicAsync(topicName, cancellationToken);
     }
 }
示例#8
0
        public static async Task Main()
        {
            try
            {
                Console.WriteLine("Creating the Service Bus Administration Client object");
                adminClient = new ServiceBusAdministrationClient(connectionString);

                Console.WriteLine($"Creating the topic {topicName}");
                await adminClient.CreateTopicAsync(topicName);

                Console.WriteLine($"Creating the subscription {subscriptionAllOrders} for the topic with a SQL filter ");

                // Create a True Rule filter with an expression that always evaluates to true
                // It's equivalent to using SQL rule filter with 1=1 as the expression

                await adminClient.CreateSubscriptionAsync(
                    new CreateSubscriptionOptions(topicName, subscriptionAllOrders),
                    new CreateRuleOptions("AllOrders", new TrueRuleFilter()));

                Console.WriteLine($"Creating the subscription {subscriptionColorBlueSize10Orders} with a SQL filter");
                // Create a SQL filter with color set to blue and quantity to 10
                await adminClient.CreateSubscriptionAsync(
                    new CreateSubscriptionOptions(topicName, subscriptionColorBlueSize10Orders),
                    new CreateRuleOptions("BlueSize10Orders", new SqlRuleFilter("color='blue' AND quantity=10")));

                Console.WriteLine($"Creating the subscription {subscriptionColorRed} with a SQL filter");
                // Create a SQL filter with color equals to red and a SQL action with a set of statements
                await adminClient.CreateSubscriptionAsync(topicName, subscriptionColorRed);

                // remove the $Default rule
                await adminClient.DeleteRuleAsync(topicName, subscriptionColorRed, "$Default");

                // now create the new rule. notice that user. prefix is used for the user/application property
                await adminClient.CreateRuleAsync(topicName, subscriptionColorRed, new CreateRuleOptions
                {
                    Name   = "RedOrdersWithAction",
                    Filter = new SqlRuleFilter("user.color='red'"),
                    Action = new SqlRuleAction("SET quantity = quantity / 2; REMOVE priority;SET sys.CorrelationId = 'low';")
                }
                                                  );

                Console.WriteLine($"Creating the subscription {subscriptionHighPriorityRedOrders} with a correlation filter");
                // Create a correlation filter with color set to Red and priority set to High
                await adminClient.CreateSubscriptionAsync(
                    new CreateSubscriptionOptions(topicName, subscriptionHighPriorityRedOrders),
                    new CreateRuleOptions("HighPriorityRedOrders", new CorrelationRuleFilter()
                {
                    Subject = "red", CorrelationId = "high"
                } ));

                // delete resources
                //await adminClient.DeleteTopicAsync(topicName);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        public async Task CreateTopicAsync()
        {
            var connString    = _configuration.GetValue <string>("Azure:ServiceBus:SourceSynchronizer:ConnString");
            var sbAdminClient = new ServiceBusAdministrationClient(connString);

            if (!await sbAdminClient.TopicExistsAsync(_topicName))
            {
                await sbAdminClient.CreateTopicAsync(_topicName);
            }
        }
        public async Task GetUpdateDeleteTopicAndSubscription()
        {
            string topicName           = Guid.NewGuid().ToString("D").Substring(0, 8);
            string subscriptionName    = Guid.NewGuid().ToString("D").Substring(0, 8);
            string connectionString    = TestEnvironment.ServiceBusConnectionString;
            var    client              = new ServiceBusAdministrationClient(connectionString);
            var    topicOptions        = new CreateTopicOptions(topicName);
            var    subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName);
            await client.CreateTopicAsync(topicOptions);

            await client.CreateSubscriptionAsync(subscriptionOptions);

            #region Snippet:GetTopic
            TopicProperties topic = await client.GetTopicAsync(topicName);

            #endregion
            #region Snippet:GetSubscription
            SubscriptionProperties subscription = await client.GetSubscriptionAsync(topicName, subscriptionName);

            #endregion
            #region Snippet:UpdateTopic
            topic.UserMetadata = "some metadata";
            TopicProperties updatedTopic = await client.UpdateTopicAsync(topic);

            #endregion
            Assert.AreEqual("some metadata", updatedTopic.UserMetadata);

            #region Snippet:UpdateSubscription
            subscription.UserMetadata = "some metadata";
            SubscriptionProperties updatedSubscription = await client.UpdateSubscriptionAsync(subscription);

            #endregion
            Assert.AreEqual("some metadata", updatedSubscription.UserMetadata);

            // need to delete the subscription before the topic, as deleting
            // the topic would automatically delete the subscription
            #region Snippet:DeleteSubscription
            await client.DeleteSubscriptionAsync(topicName, subscriptionName);

            #endregion
            Assert.That(
                async() =>
                await client.GetSubscriptionAsync(topicName, subscriptionName),
                Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));

            #region Snippet:DeleteTopic
            await client.DeleteTopicAsync(topicName);

            #endregion
            Assert.That(
                async() =>
                await client.GetTopicAsync(topicName),
                Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));
        }
    async Task EnsureInitializationAsync()
    {
        if (!await adminClient.TopicExistsAsync(this.TopicName))
        {
            await adminClient.CreateTopicAsync(new CreateTopicOptions(this.TopicName)); /*Explore more options*/
        }

        if (!await adminClient.SubscriptionExistsAsync(this.TopicName, this.SubscriptionName))
        {
            await adminClient.CreateSubscriptionAsync(this.TopicName, this.SubscriptionName);
        }
    }
示例#12
0
        private ServiceBusSender GetServiceBusTopicSender(string topicName)
        {
            var busAdmin = new ServiceBusAdministrationClient(Connections.ServiceBusConnectionString);

            if (!busAdmin.TopicExistsAsync(topicName).Result.Value)
            {
                busAdmin.CreateTopicAsync(topicName).Wait();
            }

            ServiceBusClient client = new ServiceBusClient(Connections.ServiceBusConnectionString);

            return(client.CreateSender(topicName));
        }
        public static Task Create(ServiceBusAdministrationClient client, CommandOption topicName, CommandOption <int> size, CommandOption partitioning)
        {
            var topicNameToUse = topicName.HasValue() ? topicName.Value() : DefaultTopicName;

            var options = new CreateTopicOptions(topicNameToUse)
            {
                EnableBatchedOperations = true,
                EnablePartitioning      = partitioning.HasValue(),
                MaxSizeInMegabytes      = (size.HasValue() ? size.ParsedValue : 5) * 1024
            };

            return(client.CreateTopicAsync(options));
        }
        public async Task CreateTopicAndSubscription()
        {
            string topicName        = Guid.NewGuid().ToString("D").Substring(0, 8);
            string subscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8);
            string connectionString = TestEnvironment.ServiceBusConnectionString;
            var    client           = new ServiceBusAdministrationClient(connectionString);

            try
            {
                #region Snippet:CreateTopicAndSubscription
                //@@ string connectionString = "<connection_string>";
                //@@ string topicName = "<topic_name>";
                //@@ var client = new ServiceBusManagementClient(connectionString);
                var topicOptions = new CreateTopicOptions(topicName)
                {
                    AutoDeleteOnIdle                    = TimeSpan.FromDays(7),
                    DefaultMessageTimeToLive            = TimeSpan.FromDays(2),
                    DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1),
                    EnableBatchedOperations             = true,
                    EnablePartitioning                  = false,
                    MaxSizeInMegabytes                  = 2048,
                    RequiresDuplicateDetection          = true,
                    UserMetadata = "some metadata"
                };

                topicOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
                                                        "allClaims",
                                                        new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));

                TopicProperties createdTopic = await client.CreateTopicAsync(topicOptions);

                //@@ string subscriptionName = "<subscription_name>";
                var subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName)
                {
                    AutoDeleteOnIdle         = TimeSpan.FromDays(7),
                    DefaultMessageTimeToLive = TimeSpan.FromDays(2),
                    EnableBatchedOperations  = true,
                    UserMetadata             = "some metadata"
                };
                SubscriptionProperties createdSubscription = await client.CreateSubscriptionAsync(subscriptionOptions);

                #endregion
                Assert.AreEqual(topicOptions, new CreateTopicOptions(createdTopic));
                Assert.AreEqual(subscriptionOptions, new CreateSubscriptionOptions(createdSubscription));
            }
            finally
            {
                await client.DeleteTopicAsync(topicName);
            }
        }
        public async Task CreateQueues(string[] queues, CancellationToken cancellationToken = default)
        {
            await namespacePermissions.CanManage(cancellationToken).ConfigureAwait(false);

            var topic = new CreateTopicOptions(transportSettings.TopicName)
            {
                EnableBatchedOperations = true,
                EnablePartitioning      = transportSettings.EnablePartitioning,
                MaxSizeInMegabytes      = maxSizeInMb
            };

            try
            {
                await administrativeClient.CreateTopicAsync(topic, cancellationToken).ConfigureAwait(false);
            }
            catch (ServiceBusException sbe) when(sbe.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists)
            {
                Logger.Info($"Topic {topic.Name} already exists");
            }
            catch (ServiceBusException sbe) when(sbe.IsTransient) // An operation is in progress.
            {
                Logger.Info($"Topic creation for {topic.Name} is already in progress");
            }

            foreach (var address in queues)
            {
                var queue = new CreateQueueOptions(address)
                {
                    EnableBatchedOperations = true,
                    LockDuration            = TimeSpan.FromMinutes(5),
                    MaxDeliveryCount        = int.MaxValue,
                    MaxSizeInMegabytes      = maxSizeInMb,
                    EnablePartitioning      = transportSettings.EnablePartitioning
                };

                try
                {
                    await administrativeClient.CreateQueueAsync(queue, cancellationToken).ConfigureAwait(false);
                }
                catch (ServiceBusException sbe) when(sbe.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists)
                {
                    Logger.Debug($"Queue {queue.Name} already exists");
                }
                catch (ServiceBusException sbe) when(sbe.IsTransient) // An operation is in progress.
                {
                    Logger.Info($"Queue creation for {queue.Name} is already in progress");
                }
            }
        }
        /// <summary>
        /// Create a Topic
        /// </summary>
        /// <param name="topic">The name of the Topic</param>
        public void CreateTopic(string topic)
        {
            s_logger.LogInformation("Creating topic {Topic}...", topic);

            try
            {
                _administrationClient.CreateTopicAsync(topic).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                s_logger.LogError(e, "Failed to create topic {Topic}.", topic);
                throw;
            }

            s_logger.LogInformation("Topic {Topic} created.", topic);
        }
示例#17
0
        private void CreateTopicAndSubscriptions(string topicName, string[] subscriptions)
        {
            var busAdmin = new ServiceBusAdministrationClient(Connections.ServiceBusConnectionString);

            if (!busAdmin.TopicExistsAsync(topicName).Result.Value)
            {
                busAdmin.CreateTopicAsync(topicName).Wait();
            }

            foreach (var subscription in subscriptions)
            {
                if (!busAdmin.SubscriptionExistsAsync(topicName, subscription).Result.Value)
                {
                    busAdmin.CreateSubscriptionAsync(topicName, subscription).Wait();
                }
            }
        }
示例#18
0
        public static async Task <TopicProperties> CreateTopicAsync(string topicName, string connectionString)
        {
            var client       = new ServiceBusAdministrationClient(connectionString);
            var topicOptions = new CreateTopicOptions(topicName)
            {
                DefaultMessageTimeToLive            = TimeSpan.FromDays(2),
                DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1),
                EnableBatchedOperations             = true,
                EnablePartitioning = false,
                MaxSizeInMegabytes = 2048,
                UserMetadata       = "some metadata"
            };

            topicOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
                                                    "allClaims",
                                                    new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));

            return(await client.CreateTopicAsync(topicOptions));
        }
        public async Task SetupAsync(IHost host)
        {
            using var scope = host.Services.CreateScope();

            var referenceFactory = scope.ServiceProvider.GetRequiredService <IQueueReferenceFactory>();
            var policy           = referenceFactory.Create <TM>();

            var azureConfig = scope.ServiceProvider.GetRequiredService <AzureServiceBusConfiguration>();
            var adminClient = new ServiceBusAdministrationClient(azureConfig.ConnectionString);

            if (!(await adminClient.TopicExistsAsync(policy.TopicName)))
            {
                await adminClient.CreateTopicAsync(policy.TopicName);
            }

            if (!(await adminClient.SubscriptionExistsAsync(policy.TopicName, policy.SubscriptionName)))
            {
                await adminClient.CreateSubscriptionAsync(policy.TopicName, policy.SubscriptionName);
            }
        }
示例#20
0
        public ServiceBusQueue(string connectionString, string topicName, string subscription, ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PeekLock, bool createQueueIfItDoesNotExist = true)
            : base(connectionString)
        {
            this.connectionString = connectionString;
            this.queueName        = topicName;
            this.topicName        = topicName;
            this.subscription     = subscription;
            this.receiveMode      = receiveMode;
            this.SubQueue         = SubQueue.None;
            busAdmin = new ServiceBusAdministrationClient(this.connectionString);

            if (createQueueIfItDoesNotExist && !busAdmin.TopicExistsAsync(topicName).Result.Value)
            {
                busAdmin.CreateTopicAsync(topicName).Wait();
            }

            if (createQueueIfItDoesNotExist && !string.IsNullOrEmpty(subscription) && !busAdmin.SubscriptionExistsAsync(topicName, subscription).Result.Value)
            {
                busAdmin.CreateSubscriptionAsync(topicName, subscription).Wait();
            }
        }
示例#21
0
        public async Task EnsureTopic(string topicName, CancellationToken cancellationToken = default)
        {
            try
            {
                if (!await _administrationClient.TopicExistsAsync(topicName, cancellationToken))
                {
                    var options = new CreateTopicOptions(topicName)
                    {
                        Status                   = EntityStatus.Active,
                        MaxSizeInMegabytes       = 1024,
                        DefaultMessageTimeToLive = TimeSpan.FromDays(10000)
                    };

                    await _administrationClient.CreateTopicAsync(options, cancellationToken);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Service Bus ensure topic operation failure");
                throw new ServiceBusPublisherOperationException("Service Bus ensure topic operation failure", ex);
            }
        }
        public async Task SetupAsync(IHost host)
        {
            using var scope = host.Services.CreateScope();

            var referenceFactory = scope.ServiceProvider.GetRequiredService <IQueueReferenceFactory>();
            var policy           = referenceFactory.Create <TM>();

            var azureConfig = scope.ServiceProvider.GetRequiredService <AzureServiceBusConfiguration>();
            var adminClient = new ServiceBusAdministrationClient(azureConfig.ConnectionString);

            try
            {
                if (!await adminClient.TopicExistsAsync(policy.TopicName))
                {
                    await adminClient.CreateTopicAsync(new CreateTopicOptions(policy.TopicName)
                    {
                        RequiresDuplicateDetection = true
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                if (!await adminClient.SubscriptionExistsAsync(policy.TopicName, policy.SubscriptionName))
                {
                    await adminClient.CreateSubscriptionAsync(policy.TopicName, policy.SubscriptionName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#23
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);
        }
示例#24
0
        public static async Task EnsureTopicExists(string connectionString, string topic)
        {
            var sbClient = new ServiceBusAdministrationClient(connectionString);

            _ = await sbClient.CreateTopicAsync(topic);
        }
示例#25
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);
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _cancellationToken = cancellationToken;
            _client            = await _clientFactory.GetReceiverClient <TTopic, IEventSubscription <TTopic> >(_subscription, new ServiceBusProcessorOptions
            {
                AutoCompleteMessages       = false,
                MaxAutoLockRenewalDuration = Settings.MessageLockTimeout,
                MaxConcurrentCalls         = Settings.MaxConcurrentCalls,
                PrefetchCount = Settings.PrefetchCount,
                ReceiveMode   = ServiceBusReceiveMode.PeekLock
            }).ConfigureAwait(false);


            var topicName = AutoMessageMapper.GetQueueName <TTopic>();

            if (!await _managementClient.TopicExistsAsync(topicName, cancellationToken).ConfigureAwait(false))
            {
                try
                {
                    var serviceBusCreationOptions = GetServiceBusCreationOptions();

                    await _managementClient.CreateTopicAsync(new CreateTopicOptions(topicName)
                    {
                        EnablePartitioning      = serviceBusCreationOptions.EnablePartitioning,
                        EnableBatchedOperations = serviceBusCreationOptions.EnableBatchedOperations,
                        SupportOrdering         = serviceBusCreationOptions.SupportOrdering
                    }, cancellationToken).ConfigureAwait(false);
                }
                catch (ServiceBusException e)
                {
                    _log.Error(e, "Failed to create topic {TopicName}", topicName);
                    throw;
                }
            }
            if (!await _managementClient.SubscriptionExistsAsync(topicName, _subscription.Name, cancellationToken).ConfigureAwait(false))
            {
                try
                {
                    var serviceBusCreationOptions = GetServiceBusCreationOptions();

                    await _managementClient.CreateSubscriptionAsync(new CreateSubscriptionOptions(topicName, _subscription.Name)
                    {
                        EnableBatchedOperations = serviceBusCreationOptions.EnableBatchedOperations
                    }, cancellationToken).ConfigureAwait(false);
                }
                catch (ServiceBusException e)
                {
                    _log.Error(e, "Failed to create subscription {TopicName} {SubscriptionName}", topicName, _subscription.Name);
                    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(TTopic).Name}");
                    await _client.CloseAsync(CancellationToken.None);
                }
                catch (Exception)
                {
                    //Swallow
                }
            });
#pragma warning restore 4014
        }