Exemplo n.º 1
0
        private void ReceiveMessages(string filterName = null, string filter = null)
        {
            var subscriptionClient = new SubscriptionClient
                                         (_serviceBusConfiguration.ConnectionString, _topicName, _subscriptionName);

            var mo = new MessageHandlerOptions(ExceptionHandle)
            {
                AutoComplete = true
            };

            if (filterName != null && filter != null)
            {
                const string defaultRule = "$default";

                if (subscriptionClient.GetRulesAsync().Result.Any(x => x.Name == defaultRule))
                {
                    subscriptionClient.RemoveRuleAsync(defaultRule).Wait();
                }

                if (subscriptionClient.GetRulesAsync().Result.All(x => x.Name != filterName))
                {
                    subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        Filter = new CorrelationFilter {
                            Label = filter
                        },
                        Name = filterName
                    }).Wait();
                }
            }

            subscriptionClient.RegisterMessageHandler(Handle, mo);
        }
Exemplo n.º 2
0
        public async Task RemoveDefaultSubscriptionRuleAsync()
        {
            var rules = await _subscriptionClient.GetRulesAsync();

            var ruleDescription = rules.SingleOrDefault(x => x.Name.Equals(RuleDescription.DefaultRuleName));

            if (ruleDescription != null)
            {
                await _subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
            }
        }
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                // Check if there is a previous result in the cache that has not expired yet.
                if (_cache.TryGetValue("result", out HealthCheckResult result))
                {
                    return(result);
                }

                // This is the only way I can see to check if the subscription queue is available.
                SubscriptionClient subscriptionClient = new SubscriptionClient(new ServiceBusConnectionStringBuilder(_topicconnectionstring), _subscriptionname, ReceiveMode.PeekLock, RetryPolicy.NoRetry);
                await subscriptionClient.GetRulesAsync();

                // Subscription is available.
                // Let's cache the result for 5 minutes, as it is very slow and once up, the state shouldn't change very much.
                result = HealthCheckResult.Healthy();
                _cache.Set("result", result, TimeSpan.FromMinutes(5));
                return(result);
            }
            catch (Microsoft.Azure.ServiceBus.MessagingEntityNotFoundException)
            {
                // Let's cache the result for 1 minute, as it is very slow and we want to know fairly quickly once it is up.
                HealthCheckResult result = new HealthCheckResult(context.Registration.FailureStatus, "the subscription doesn't exist");
                _cache.Set("result", result, TimeSpan.FromMinutes(1));
                return(result);
            }
            catch (Exception ex)
            {
                // Let's cache the result for 1 minute, as it is very slow and we want to know fairly quickly once it is up.
                HealthCheckResult result = new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
                _cache.Set("result", result, TimeSpan.FromMinutes(1));
                return(result);
            }
        }
        private async Task RemoveDefaultFilters()
        {
            Console.WriteLine($"Starting to remove default filters.");

            try
            {
                foreach (var subscription in Subscriptions)
                {
                    SubscriptionClient s = new SubscriptionClient(ServiceBusConnectionString, TopicName, subscription);
                    var rules            = (await s.GetRulesAsync()).Where(r => r.Name == RuleDescription.DefaultRuleName);
                    if (rules.Any())
                    {
                        await s.RemoveRuleAsync(RuleDescription.DefaultRuleName);

                        Console.WriteLine($"Default filter for {subscription} has been removed.");
                    }


                    await s.CloseAsync();
                }

                Console.WriteLine("All default Rules have been removed.\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            await PresentMenu();
        }
Exemplo n.º 5
0
        public async Task ReceiverAsync(string topic, string filter, string subscription, TopicType type)
        {
            await CreateTopicAsync(_option.ConnectionString, topic);
            await CreateSubscriptionAsync(_option.ConnectionString, topic, subscription);

            var subscriptionClient = new SubscriptionClient(_option.ConnectionString, topic, subscription);

            var rules = await subscriptionClient.GetRulesAsync();

            if (rules.Any(r => r.Name.Equals("$Default")))
            {
                //by default a 1=1 rule is added when subscription is created, so we need to remove it
                await subscriptionClient.RemoveRuleAsync("$Default");
            }

            if (!rules.Any(r => r.Name.Equals("filter-store")))
            {
                await subscriptionClient.AddRuleAsync(_rule);
            }

            var mo = new MessageHandlerOptions(ExceptionHandle)
            {
                MaxConcurrentCalls = 5,
                AutoComplete       = false
            };

            if (type == TopicType.Product)
            {
                subscriptionClient.RegisterMessageHandler(HandleProduct, mo);
            }
            else
            {
                subscriptionClient.RegisterMessageHandler(HandleArea, mo);
            }
        }
        public async Task SubscriptionsEventsAreNotCapturedWhenDiagnosticsIsDisabled()
        {
            await ServiceBusScope.UsingTopicAsync(partitioned : false, sessionEnabled : false, async (topicName, subscriptionName) =>
            {
                var subscriptionClient = new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName, ReceiveMode.ReceiveAndDelete);
                var eventQueue         = this.CreateEventQueue();
                var entityName         = $"{topicName}/Subscriptions/{subscriptionName}";

                try
                {
                    using (var listener = this.CreateEventListener(entityName, eventQueue))
                        using (var subscription = this.SubscribeToEvents(listener))
                        {
                            listener.Disable();

                            var ruleName = Guid.NewGuid().ToString();
                            await subscriptionClient.AddRuleAsync(ruleName, new TrueFilter());
                            await subscriptionClient.GetRulesAsync();
                            await subscriptionClient.RemoveRuleAsync(ruleName);

                            Assert.True(eventQueue.IsEmpty, "There were events present when none were expected");
                        }
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                }
            });
        }
        private static async Task <bool> CheckRulesAsync(
            Subscriber subscriber, SubscriptionClient subscriptionClient)
        {
            IEnumerable <RuleDescription> rules = await subscriptionClient.GetRulesAsync();

            return(subscriber.Labels.All(sr => rules.Any(r => r.Name == sr)));
        }
Exemplo n.º 8
0
        private async void ReceiveMessages(string topicName)
        {
            serviceBusConfiguration = _configuration.GetSection("serviceBus").Get <ServiceBusConfiguration>();
            var subscriptionClient = new SubscriptionClient(serviceBusConfiguration.ConnectionString, topicName, SubscriptionName);

            try
            {
                var rules = await subscriptionClient.GetRulesAsync();

                if (rules.Any(x => x.Name == "$Default"))
                {
                    //await subscriptionClient.RemoveRuleAsync("$Default");
                }

                var messageHandlerOptions = new MessageHandlerOptions(ExceptionHandle)
                {
                    AutoComplete = true
                };

                _logService.SendMessagesAsync("Order Changed Received in Production");

                subscriptionClient.RegisterMessageHandler(Handle, messageHandlerOptions);
            }
            catch (Exception)
            {
            }
        }
        private async Task CleanUpCustomFilters()
        {
            foreach (var subscription in Subscriptions)
            {
                try
                {
                    SubscriptionClient            s     = new SubscriptionClient(ServiceBusConnectionString, TopicName, subscription);
                    IEnumerable <RuleDescription> rules = await s.GetRulesAsync();

                    foreach (RuleDescription r in rules)
                    {
                        await s.RemoveRuleAsync(r.Name);

                        Console.WriteLine($"Rule {r.Name} has been removed.");
                    }
                    await s.CloseAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            Console.WriteLine("All default filters have been removed.\n");

            await PresentMenu();
        }
        public void Subscribe(IEnumerable <string> topics)
        {
            if (topics == null)
            {
                throw new ArgumentNullException(nameof(topics));
            }

            ConnectAsync().GetAwaiter().GetResult();

            var allRuleNames = _consumerClient.GetRulesAsync().GetAwaiter().GetResult().Select(x => x.Name);

            foreach (var newRule in topics.Except(allRuleNames))
            {
                CheckValidSubscriptionName(newRule);

                _consumerClient.AddRuleAsync(new RuleDescription
                {
                    Filter = new CorrelationFilter {
                        Label = newRule
                    },
                    Name = newRule
                }).GetAwaiter().GetResult();

                _logger.LogInformation($"Azure Service Bus add rule: {newRule}");
            }

            foreach (var oldRule in allRuleNames.Except(topics))
            {
                _consumerClient.RemoveRuleAsync(oldRule).GetAwaiter().GetResult();

                _logger.LogInformation($"Azure Service Bus remove rule: {oldRule}");
            }
        }
        public void Subscribe(string eventName)
        {
            try
            {
                if (_subscriptionClient.GetRulesAsync().GetAwaiter().GetResult().Any(rule => rule.Name == eventName))
                {
                    _logger.LogWarning("The messaging entity {eventName} already exists.", eventName);
                    return;
                }

                _subscriptionClient.AddRuleAsync(new RuleDescription
                {
                    Filter = new CorrelationFilter {
                        Label = eventName
                    },
                    Name = eventName
                }).GetAwaiter().GetResult();
            }
            catch (ServiceBusException)
            {
                _logger.LogWarning("The messaging entity {eventName} already exists.", eventName);
            }

            _logger.LogInformation("Subscribing to event {EventName}", eventName);
        }
Exemplo n.º 12
0
        public static async Task RemoveDefaultFiltersIfExists(this SubscriptionClient subscription)
        {
            var rules = await subscription.GetRulesAsync();

            if (rules.Any(r => r.Name == RuleDescription.DefaultRuleName))
            {
                await subscription.RemoveRuleAsync(RuleDescription.DefaultRuleName);
            }
        }
Exemplo n.º 13
0
        private static async Task CleanUpRules(SubscriptionClient client, string ruleName)
        {
            var rules = await client.GetRulesAsync();

            if (rules.FirstOrDefault(r => r.Name == ruleName) != null)
            {
                await client.RemoveRuleAsync(ruleName);
            }
        }
Exemplo n.º 14
0
        private async Task RemoveDefaultFilters()
        {
            try
            {
                var rules = await _subscriptionClient.GetRulesAsync();

                foreach (var rule in rules)
                {
                    if (rule.Name == RuleDescription.DefaultRuleName)
                    {
                        await _subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.ToString());
            }
        }
Exemplo n.º 15
0
            private void UpdateRules(SubscriptionClient subscriptionClient, AzureBusTopicSettings settings)
            {
                subscriptionClient.GetRulesAsync()
                .Result
                .ToList()
                .ForEach(x => subscriptionClient.RemoveRuleAsync(x.Name).Wait());

                settings.AzureSubscriptionRules
                .ToList()
                .ForEach(x => subscriptionClient.AddRuleAsync(x.Key, x.Value).Wait());
            }
Exemplo n.º 16
0
        static async Task RemoveDefaultRuleAsync()
        {
            var rules = await subscriptionClient.GetRulesAsync();

            var defaultRule = rules.SingleOrDefault(rule => rule.Name == RuleDescription.DefaultRuleName);

            if (defaultRule != null)
            {
                await subscriptionClient.RemoveRuleAsync(defaultRule.Name);
            }
        }
Exemplo n.º 17
0
        private static async Task AddRule(SubscriptionClient client, string correlationFilter, string ruleName)
        {
            var rules = await client.GetRulesAsync();

            if (rules.FirstOrDefault(r => r.Name == ruleName) == null)
            {
                await client.AddRuleAsync(new RuleDescription
                {
                    Filter = new CorrelationFilter(correlationFilter),
                    Name = ruleName
                });
            }
        }
Exemplo n.º 18
0
        public static async Task AddRule(string topicName, string subName, RuleDescription ruleDescription)
        {
            var subClient = new SubscriptionClient(SBConnectionString, topicName, subName);

            // remove old rules
            foreach (var rule in await subClient.GetRulesAsync())
            {
                await subClient.RemoveRuleAsync(rule.Name);
            }

            // add rule
            await subClient.AddRuleAsync(ruleDescription);
        }
Exemplo n.º 19
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
        {
            return(await Task.Run(() =>
            {
                IDictionary <string, Object> data = new Dictionary <string, object>();
                data.Add("type", "ServiceBusHealthCheck");
                // data.Add("connectionString", this.connectionString);
                data.Add("topicName", this.topicName);
                try
                {
                    if (serviceBusHealthCheckType == ServiceBusHealthCheckType.Receive)
                    {
                        data.Add("subscriptionName", this.subscriptionName);
                        var subscriptionClient = new SubscriptionClient(ListenConnectionString, topicName, subscriptionName);
                        var clientid = subscriptionClient.ClientId;
                        data.Add("clientid", clientid);

                        var rulestask = subscriptionClient.GetRulesAsync();
                        rulestask.Wait();
                        data.Add("rules", string.Join(",", rulestask.Result));
                    }
                    else
                    {
                        var topicClient = new QueueClient(SendConnectionString, topicName);
                        var clientid = topicClient.ClientId;
                        data.Add("clientid", clientid);
                        var list = topicClient.Path;

                        Message mes = new Message();
                        mes.Body = System.Text.Encoding.UTF8.GetBytes("TestMessage");

                        var sendtask = topicClient.ScheduleMessageAsync(mes, DateTime.Now.AddDays(100));
                        sendtask.Wait();

                        var cancell = topicClient.CancelScheduledMessageAsync(sendtask.Result);
                        cancell.Wait();
                    }

                    string description = $"ServiceBus namespace {nameSpace}.servicebus.windows.net is healthy";
                    ReadOnlyDictionary <string, Object> rodata = new ReadOnlyDictionary <string, object>(data);
                    return HealthCheckResult.Healthy(description, rodata);
                }
                catch (Exception ex)
                {
                    string description = "ServiceBus is failed with exception " + ex.Message;
                    ReadOnlyDictionary <string, Object> rodata = new ReadOnlyDictionary <string, object>(data);
                    return HealthCheckResult.Unhealthy(description, data: rodata);
                }
            }));
        }
Exemplo n.º 20
0
        public static async Task AddFilterAsyc(this SubscriptionClient subscription, RuleDescription rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException(nameof(rule));
            }

            var rules = await subscription.GetRulesAsync();

            if (!rules.Any(r => r.Name == rule.Name))
            {
                await subscription.AddRuleAsync(rule);
            }
        }
Exemplo n.º 21
0
        public static async Task RemoveFilterAsyc(this SubscriptionClient subscription, string ruleName)
        {
            if (String.IsNullOrWhiteSpace(ruleName))
            {
                throw new ArgumentNullException(nameof(ruleName));
            }

            var rules = await subscription.GetRulesAsync();

            if (rules.Any(r => r.Name == ruleName))
            {
                await subscription.RemoveRuleAsync(ruleName);
            }
        }
        private async Task BuildSubscription(string connectionString, string[] messagesTypes, string handlerFullName)
        {
            var topicName = _config.EffectiveTopicName;

            var client = new SubscriptionClient(connectionString, topicName, _config.SubscriberName);

            var ruleApplier = new RuleApplier(_ruleApplierLog, client);
            var ruleBuilder = new RuleBuilder(ruleApplier, _subscriptionRuleVersionResolver, _config.SubscriberName);

            var rulesForCurrentSoftwareVersion    = ruleBuilder.GenerateSubscriptionRules(messagesTypes, handlerFullName, _config.OmitSpecificSubscriberFilter).ToArray();
            var rulesCurrentlyDefinedInServiceBus = await client.GetRulesAsync().ConfigureAwait(false);

            _log.LogInformation($"Validating subscription '{_config.SubscriberName}' rules on topic '{topicName}'...");
            await ruleBuilder.ApplyRuleChanges(rulesForCurrentSoftwareVersion, rulesCurrentlyDefinedInServiceBus.ToArray(), messagesTypes).ConfigureAwait(false);
        }
        private static async Task CreateSubscriptionFilters()
        {
            var client = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);

            var rules = await client.GetRulesAsync();

            // Remove default filter
            foreach (var rule in rules)
            {
                await client.RemoveRuleAsync(rule.Name);
            }

            // Add  InformCourier rule
            var filter = new SqlFilter("ProcessWarehouse = 1");
            await client.AddRuleAsync("ProcessWarehouse", filter);
        }
        public async Task AddRemoveGetFireEvents()
        {
            await ServiceBusScope.UsingTopicAsync(partitioned : false, sessionEnabled : false, async (topicName, subscriptionName) =>
            {
                var subscriptionClient = new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName, ReceiveMode.ReceiveAndDelete);
                var eventQueue         = this.CreateEventQueue();
                var entityName         = $"{topicName}/Subscriptions/{subscriptionName}";

                try
                {
                    using (var listener = this.CreateEventListener(entityName, eventQueue))
                        using (var subscription = this.SubscribeToEvents(listener))
                        {
                            listener.Enable((name, queue, id) => name.Contains("Rule"));

                            var ruleName = Guid.NewGuid().ToString();
                            await subscriptionClient.AddRuleAsync(ruleName, new TrueFilter());
                            await subscriptionClient.GetRulesAsync();
                            await subscriptionClient.RemoveRuleAsync(ruleName);

                            Assert.True(eventQueue.TryDequeue(out var addRuleStart));
                            AssertAddRuleStart(entityName, addRuleStart.eventName, addRuleStart.payload, addRuleStart.activity);

                            Assert.True(eventQueue.TryDequeue(out var addRuleStop));
                            AssertAddRuleStop(entityName, addRuleStop.eventName, addRuleStop.payload, addRuleStop.activity, addRuleStart.activity);

                            Assert.True(eventQueue.TryDequeue(out var getRulesStart));
                            AssertGetRulesStart(entityName, getRulesStart.eventName, getRulesStart.payload, getRulesStart.activity);

                            Assert.True(eventQueue.TryDequeue(out var getRulesStop));
                            AssertGetRulesStop(entityName, getRulesStop.eventName, getRulesStop.payload, getRulesStop.activity, getRulesStart.activity);

                            Assert.True(eventQueue.TryDequeue(out var removeRuleStart));
                            AssertRemoveRuleStart(entityName, removeRuleStart.eventName, removeRuleStart.payload, removeRuleStart.activity);

                            Assert.True(eventQueue.TryDequeue(out var removeRuleStop));
                            AssertRemoveRuleStop(entityName, removeRuleStop.eventName, removeRuleStop.payload, removeRuleStop.activity, removeRuleStart.activity);

                            Assert.True(eventQueue.IsEmpty, "There were events present when none were expected");
                        }
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                }
            });
        }
Exemplo n.º 25
0
        private async Task checkSubscriptionFiltersAsync(SubscriptionClient subscriptionClient, AzureTopicAttribute topicAttribute)
        {
            IEnumerable <RuleDescription> rules = await subscriptionClient.GetRulesAsync();

            // Delete default rule.
            if (rules.Any(r => r.Name == RuleDescription.DefaultRuleName))
            {
                await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
            }

            string ruleName = "RouteKey";

            if (!rules.Any(r => r.Name == ruleName))
            {
                var filter = new SqlFilter($"{ruleName}='{topicAttribute.RouteKey}'");

                // Add rule for RouteKey.
                await subscriptionClient.AddRuleAsync(ruleName, filter);
            }
        }
Exemplo n.º 26
0
        static async Task Main(string[] args)
        {
            var connectionString = "Endpoint=sb://etl-sb-poc.servicebus.windows.net/;SharedAccessKeyName=RootPolicy;SharedAccessKey=6U0k6rYLz6GqwxKFTFDmNPn4E8pgFSQIx1ljTTJ8oAI=";
            var topicName        = "configuration-topic";
            var subscriptionName = "client-service-configuration";

            var client = new SubscriptionClient(connectionString, topicName, subscriptionName);

            try
            {
                var rules = await client.GetRulesAsync();

                if (rules.All(r => r.Name != "client-service-configuration-filter"))
                {
                    var filter = new SqlFilter("MessageType IN ('ClientConfigurationMessage')");
                    await client.AddRuleAsync("client-service-configuration-filter", filter);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 27
0
        static async Task TopicReceiver()
        {
            var topicName        = "myfirsttopic";
            var subscriptionName = "myfirstsubscription";

            var receiver = new SubscriptionClient(NamespaceConnectionString, topicName, subscriptionName);

            (await receiver.GetRulesAsync())
            .ToList()
            .ForEach(async r => await receiver.RemoveRuleAsync(r.Name));
            await receiver.AddRuleAsync(new RuleDescription("firstRule", new SqlFilter("user.Type='No'")));

            receiver.RegisterMessageHandler(async(message, cancelationToken) => {
                Console.WriteLine($"Message: {Encoding.UTF8.GetString(message.Body)}");
                await receiver.CompleteAsync(message.SystemProperties.LockToken);
            }, new MessageHandlerOptions(async args => {})
            {
                AutoComplete = false
            });

            Console.ReadKey();

            await receiver.CloseAsync();
        }
Exemplo n.º 28
0
        private static async Task CreateSubscriptionRules()
        {
            try
            {
                var processPaymentInventoryCheckedClient = new SubscriptionClient(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"),
                                                                     CloudConfigurationManager.GetSetting("InventoryCheckedTopic"),
                                                                     CloudConfigurationManager.GetSetting("ProcessPaymentSubscription"));

                var sendEmailInventoryCheckedClient = new SubscriptionClient(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"),
                                                                     CloudConfigurationManager.GetSetting("InventoryCheckedTopic"),
                                                                     CloudConfigurationManager.GetSetting("SendEmailSubscription"));

                var updateInventoryPaymentProcessedClient = new SubscriptionClient(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"),
                                                                    CloudConfigurationManager.GetSetting("PaymentProcessedTopic"),
                                                                    CloudConfigurationManager.GetSetting("UpdateInventorySubscription"));

                var rules = await processPaymentInventoryCheckedClient.GetRulesAsync();

                await CleanUpRules(processPaymentInventoryCheckedClient, "$Default");
                await AddRule(processPaymentInventoryCheckedClient, "Verified", "VerifiedInventory-ProcessPayment");

                await CleanUpRules(sendEmailInventoryCheckedClient, "$Default");
                await AddRule(sendEmailInventoryCheckedClient, "Insufficient", "InsufficientInventory-SendEmail");

                await CleanUpRules(updateInventoryPaymentProcessedClient, "$Default");
                await AddRule(updateInventoryPaymentProcessedClient, "Verified", "VerifiedPayment-UpdateInventory");

                await processPaymentInventoryCheckedClient.CloseAsync();
                await sendEmailInventoryCheckedClient.CloseAsync();
                await updateInventoryPaymentProcessedClient.CloseAsync();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 29
0
        private static async Task ReadMessage(string topicName, string correlationId)
        {
            string subscriptionName   = "ReplySubscription";
            var    subscriptionClient = new SubscriptionClient(_connectionString, topicName, subscriptionName);

            var rules = await subscriptionClient.GetRulesAsync();

            if (rules.Any(a => a.Name == "OnlyToMe"))
            {
                await subscriptionClient.RemoveRuleAsync("OnlyToMe");
            }
            if (rules.Any(a => a.Name == RuleDescription.DefaultRuleName))
            {
                await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
            }

            var filter = new CorrelationFilter();

            filter.To = "MyUniqueClientName";
            var ruleDescription = new RuleDescription("OnlyToMe", filter);
            await subscriptionClient.AddRuleAsync(ruleDescription);

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionHandler)
            {
                AutoComplete = false
            };

            subscriptionClient.RegisterMessageHandler(
                (message, cancellationToken) => handleMessage(correlationId, subscriptionClient, message, cancellationToken),
                messageHandlerOptions);

            await _taskCompletionSource.Task;

            await subscriptionClient.UnregisterMessageHandlerAsync(
                new TimeSpan(0, 0, 20));
        }
Exemplo n.º 30
0
        static async Task MainAsync()
        {
            topicClient = new TopicClient(ServiceBusConnectionString, TopicName);
            allMessagessubscriptionClient         = new SubscriptionClient(ServiceBusConnectionString, TopicName, allMessagesSubscriptionName);
            sqlFilterOnlySubscriptionClient       = new SubscriptionClient(ServiceBusConnectionString, TopicName, sqlFilterOnlySubscriptionName);
            sqlFilterWithActionSubscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, sqlFilterWithActionSubscriptionName);
            correlationFilterSubscriptionClient   = new SubscriptionClient(ServiceBusConnectionString, TopicName, correlationFilterSubscriptionName);

            // First Subscription is already created with default rule. Leave as is.

            // 2nd Subscription: Add SqlFilter on Subscription 2
            // Delete Default Rule.
            // Add the required SqlFilter Rule
            // Note: Does not apply to this sample but if there are multiple rules configured for a
            // single subscription, then one message is delivered to the subscription when any of the
            // rule matches. If more than one rules match and if there is no `SqlRuleAction` set for the
            // rule, then only one message will be delivered to the subscription. If more than one rules
            // match and there is a `SqlRuleAction` specified for the rule, then one message per `SqlRuleAction`
            // is delivered to the subscription.
            Console.WriteLine($"SubscriptionName: {sqlFilterOnlySubscriptionName}, Removing Default Rule and Adding SqlFilter");
            await sqlFilterOnlySubscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);

            await sqlFilterOnlySubscriptionClient.AddRuleAsync(new RuleDescription
            {
                Filter = new SqlFilter("Color = 'Red'"),
                Name   = "RedSqlRule"
            });

            // 3rd Subscription: Add SqlFilter and SqlRuleAction on Subscription 3
            // Delete Default Rule
            // Add the required SqlFilter Rule and Action
            Console.WriteLine($"SubscriptionName: {sqlFilterWithActionSubscriptionName}, Removing Default Rule and Adding SqlFilter and SqlRuleAction");
            await sqlFilterWithActionSubscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);

            await sqlFilterWithActionSubscriptionClient.AddRuleAsync(new RuleDescription
            {
                Filter = new SqlFilter("Color = 'Blue'"),
                Action = new SqlRuleAction("SET Color = 'BlueProcessed'"),
                Name   = "BlueSqlRule"
            });

            // 4th Subscription: Add Correlation Filter on Subscription 4
            Console.WriteLine($"SubscriptionName: {sqlFilterWithActionSubscriptionName}, Removing Default Rule and Adding CorrelationFilter");
            await correlationFilterSubscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);

            await correlationFilterSubscriptionClient.AddRuleAsync(new RuleDescription
            {
                Filter = new CorrelationFilter()
                {
                    Label = "Red", CorrelationId = "important"
                },
                Name = "ImportantCorrelationRule"
            });

            // Get Rules on Subscription, called here only for one subscription as example
            var rules = (await correlationFilterSubscriptionClient.GetRulesAsync()).ToList();

            Console.WriteLine($"GetRules:: SubscriptionName: {correlationFilterSubscriptionName}, CorrelationFilter Name: {rules[0].Name}, Rule: {rules[0].Filter}");

            // Send messages to Topic
            await SendMessagesAsync();

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

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

            // Receive messages from 'sqlFilterWithActionSubscriptionClient'. 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 'correlationFilterSubscriptionName'. Should receive all messages  with Color = 'Red' and CorrelationId = "important"
            // i.e 1 message
            await ReceiveMessagesAsync(correlationFilterSubscriptionName);

            Console.WriteLine("=========================================================");
            Console.WriteLine("Completed Receiving all messages... Press any key to exit");
            Console.WriteLine("=========================================================");

            Console.ReadKey();

            await allMessagessubscriptionClient.CloseAsync();

            await sqlFilterOnlySubscriptionClient.CloseAsync();

            await sqlFilterWithActionSubscriptionClient.CloseAsync();

            await correlationFilterSubscriptionClient.CloseAsync();

            await topicClient.CloseAsync();
        }