Пример #1
0
        public void Subscribe <T, TH>() where T : IntegrationEvent where TH : IIntegrationEventHandler <T>
        {
            var eventName = typeof(T).Name.Replace(IntegrationEventSufix, string.Empty);

            if (_subscriptionsManager.HasSubscriptionsForEvent <T>())
            {
                return;
            }

            try
            {
                _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} with {EventHandler}", eventName, nameof(TH));

            _subscriptionsManager.AddSubscription <T, TH>();
        }
        async Task CorrelationFilterTestCase(string topicName, int messageCount = 10)
        {
            var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
            var subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicName,
                this.SubscriptionName,
                ReceiveMode.ReceiveAndDelete);

            try
            {
                try
                {
                    await subscriptionClient.RemoveRuleAsync(SubscriptionClient.DefaultRule);
                }
                catch
                {
                    // ignored
                }

                await subscriptionClient.AddRuleAsync(new RuleDescription
                {
                    Filter = new CorrelationFilter {
                        Label = "Red"
                    },
                    Name = "RedCorrelation"
                });

                var messageId1 = Guid.NewGuid().ToString();
                await topicClient.SendAsync(new Message { MessageId = messageId1, Label = "Blue" });

                TestUtility.Log($"Sent Message: {messageId1}");

                var messageId2 = Guid.NewGuid().ToString();
                await topicClient.SendAsync(new Message { MessageId = messageId2, Label = "Red" });

                TestUtility.Log($"Sent Message: {messageId2}");

                var messages = await subscriptionClient.InnerSubscriptionClient.InnerReceiver.ReceiveAsync(maxMessageCount : 2);

                Assert.NotNull(messages);
                Assert.True(messages.Count == 1);
                Assert.True(messageId2.Equals(messages.First().MessageId));
            }
            finally
            {
                await subscriptionClient.RemoveRuleAsync("RedCorrelation");

                await subscriptionClient.AddRuleAsync(SubscriptionClient.DefaultRule, new TrueFilter());

                await subscriptionClient.CloseAsync();

                await topicClient.CloseAsync();
            }
        }
        private async Task CreateCustomFilters()
        {
            try
            {
                for (int i = 0; i < Subscriptions.Length; i++)
                {
                    SubscriptionClient s       = new SubscriptionClient(ServiceBusConnectionString, TopicName, Subscriptions[i]);
                    string[]           filters = SubscriptionFilters[Subscriptions[i]];
                    if (filters[0] != "")
                    {
                        int count = 0;
                        foreach (var myFilter in filters)
                        {
                            count++;

                            string action = SubscriptionAction[Subscriptions[i]];
                            if (action != "")
                            {
                                await s.AddRuleAsync(new RuleDescription
                                {
                                    Filter = new SqlFilter(myFilter),
                                    Action = new SqlRuleAction(action),
                                    Name   = $"MyRule{count}"
                                });
                            }
                            else
                            {
                                await s.AddRuleAsync(new RuleDescription
                                {
                                    Filter = new SqlFilter(myFilter),
                                    Name   = $"MyRule{count}"
                                });
                            }
                        }
                    }

                    Console.WriteLine($"Filters and actions for {Subscriptions[i]} have been created.");
                }

                Console.WriteLine("All filters and actions have been created.\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            await PresentMenu();
        }
Пример #4
0
        public async Task SubscribeAsync <TEvent, TEventHandler>()
            where TEvent : IntegrationEvent
            where TEventHandler : IntegrationEventHandler <TEvent>
        {
            try
            {
                var eventTypeName = typeof(TEvent).Name;
                if (!_subscribedEvents.Add(eventTypeName))
                {
                    _logger.LogWarning($"Event {eventTypeName} is already subscribed");
                    return;
                }

                await _subscriptionClient.AddRuleAsync(new RuleDescription
                {
                    Filter = new CorrelationFilter {
                        Label = eventTypeName
                    },
                    Name = eventTypeName
                });

                _logger.LogInformation($"Created service bus subscription rule for {typeof(TEvent).Name}");
            }
            catch (ServiceBusException) { }
        }
        private async void ReceiveMessages(string topicName, List <ProductionArea> productionAreas)
        {
            serviceBusConfiguration = _configuration.GetSection("serviceBus").Get <ServiceBusConfiguration>();
            var subscriptionClient = new SubscriptionClient(serviceBusConfiguration.ConnectionString, topicName, SubscriptionName);

            //by default a 1=1 rule is added when subscription is created, so we need to remove it
            await subscriptionClient.RemoveRuleAsync("$Default");

            int cont = 0;

            foreach (ProductionArea pa in productionAreas)
            {
                await subscriptionClient.AddRuleAsync(new RuleDescription
                {
                    Filter = new CorrelationFilter {
                        CorrelationId = pa.Id.ToString()
                    },
                    Name = "filter-productionAreaId_" + cont
                });

                cont++;
            }

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

            subscriptionClient.RegisterMessageHandler(Handle, mo);

            Console.ReadLine();
        }
        public void Subscribe <T, TH>() where T : IntegrationEvent where TH : IIntegrationEventHandler <T>
        {
            var eventName = typeof(T).Name.Replace(IntegrationEventSuffix, "");

            var containsKey = _subsManager.HasSubscriptionsForEvent <T>();

            if (!containsKey)
            {
                try
                {
                    _subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        Filter = new CorrelationFilter {
                            Label = eventName
                        },
                        Name = eventName
                    }).GetAwaiter().GetResult();
                }
                catch (ServiceBusException)
                {
                }
            }

            _subsManager.AddSubscription <T, TH>();
        }
        public void Subscribe <T, TH>() where T : IntegrationEvent where TH : IIntegrationEventHandler <T>
        {
            string eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFIX, String.Empty);

            bool isContainsKeys = _subscriptionManager.HasSubscriptionsForEvent <T>();

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

            _subscriptionManager.AddSubscription <T, TH>();
        }
        public void Subscribe <T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler <T>
        {
            var eventName = GetEventName <T>();

            var containsKey = _subsManager.HasSubscriptionsForEvent <T>();

            if (!containsKey)
            {
                try
                {
                    _subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        Filter = new CorrelationFilter {
                            Label = eventName
                        },
                        Name = eventName
                    }).GetAwaiter().GetResult();
                }
                catch (ServiceBusException ex)
                {
                    _logger.LogInformation($"The messaging entity {eventName} already exists.", ex);
                }
            }

            _subsManager.AddSubscription <T, TH>();
        }
Пример #9
0
        /// <inheritdoc />
        public void Subscribe <TEvent, TEventHandler>()
            where TEvent : IIntegrationEvent
            where TEventHandler : IIntegrationEventHandler <TEvent>
        {
            var eventName = typeof(TEvent).Name.Replace(IntegrationEventSufix, "");

            var containsKey = _subsManager.HasSubscriptionsForEvent <TEvent>();

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

            _subsManager.AddSubscription <TEvent, TEventHandler>();
        }
Пример #10
0
        public async Task AddSubscriptionRuleAsync <TIntegrationEvent>()
            where TIntegrationEvent : IIntegrationEvent
        {
            var integrationEventType = typeof(TIntegrationEvent);
            var integrationEventName = integrationEventType.Name.Replace(IntegrationEventSuffix, "");
            var rules = await _subscriptionClient.GetRulesAsync();

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

            if (ruleDescription is null)
            {
                await _subscriptionClient.AddRuleAsync(new RuleDescription
                {
                    Filter = new CorrelationFilter {
                        Label = integrationEventName
                    },
                    Name = integrationEventName
                });
            }

            if (!HasSubscriptionsForIntegrationEvent(integrationEventName))
            {
                _integrationEventTypes.Add(integrationEventName, integrationEventType);
            }
        }
        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);
        }
Пример #12
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);
            }
        }
Пример #13
0
        public void Subscribe <TEvent, THandler>()
            where TEvent : Event
            where THandler : IEventHandler <TEvent>
        {
            var eventName = typeof(TEvent).Name;

            var containsKey = _subsManager.HasSubscriptionsForEvent <TEvent>();

            if (!containsKey)
            {
                try
                {
                    _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} with {EventHandler}", eventName, typeof(THandler).Name);

            _subsManager.AddSubscription <TEvent, THandler>();
        }
Пример #14
0
        public async Task AddRule(RuleDescription rule)
        {
            var newRule = (SqlFilter)rule.Filter;

            _log.LogInformation($"Creating rule {rule.Name} for subscriber {_client.SubscriptionName}");
            await _client.AddRuleAsync(rule).ConfigureAwait(false);
        }
        private static async Task AddRules(Subscriber subscriber, SubscriptionClient subscriptionClient)
        {
            foreach (string label in subscriber.Labels)
            {
                RuleDescription ruleDescription = new RuleDescription
                {
                    Name   = label,
                    Filter = new CorrelationFilter {
                        Label = label
                    }
                };

                try
                {
                    await RemoveDefaultRuleAsync(subscriptionClient);

                    Console.WriteLine(
                        $"Trying to add the following rule: Name: {label}, Label: {label}");

                    await subscriptionClient.AddRuleAsync(ruleDescription);

                    Console.WriteLine("Rule was successfully added");
                }
                catch (ServiceBusException e)
                    when(e.Message != null && e.Message.Contains("already exists", StringComparison.InvariantCulture))
                    {
                        Console.WriteLine("The rule already exists");
                    }
                catch (Exception e)
                {
                    Console.WriteLine($"Some error occurred: {e.Message}");
                    throw;
                }
            }
        }
Пример #16
0
        protected override void InstantiateReceiving(IDictionary <int, SubscriptionClient> serviceBusReceivers, string topicName, string topicSubscriptionName)
        {
            base.InstantiateReceiving(serviceBusReceivers, topicName, topicSubscriptionName);

            // https://docs.microsoft.com/en-us/azure/application-insights/app-insights-analytics-reference#summarize-operator
            // http://www.summa.com/blog/business-blog/everything-you-need-to-know-about-azure-service-bus-brokered-messaging-part-2#rulesfiltersactions
            // https://github.com/Azure-Samples/azure-servicebus-messaging-samples/tree/master/TopicFilters
            SubscriptionClient client = serviceBusReceivers[0];

            try
            {
                client.RemoveRule("CqrsConfiguredFilter");
            }
            catch (MessagingEntityNotFoundException)
            {
            }

            string filter = ConfigurationManager.GetSetting(FilterKeyConfigurationKey);

            if (!string.IsNullOrWhiteSpace(filter))
            {
                RuleDescription ruleDescription = new RuleDescription
                                                  (
                    "CqrsConfiguredFilter",
                    new SqlFilter(filter)
                                                  );
                client.AddRuleAsync(ruleDescription);
            }
        }
Пример #17
0
        private static async void ReceiveMessageProductionAreaChangedAsync()
        {
            #region OrderChanged
            var subscriptionClient = new SubscriptionClient(serviceBusConfiguration.ConnectionString, TopicProductionAreaChanged, SubscriptionName);

            //by default a 1=1 rule is added when subscription is created, so we need to remove it
            await subscriptionClient.RemoveRuleAsync("$Default");

            await subscriptionClient.AddRuleAsync(new RuleDescription
            {
                Filter = new CorrelationFilter {
                    Label = _storeId
                },
                Name = "filter-store"
            });

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

            subscriptionClient.RegisterMessageHandler(MessageTopicHandleProductionAreaChanged, mo);
            Console.WriteLine($"Topico {TopicProductionAreaChanged} escutada!");
            #endregion

            Console.ReadKey();
        }
        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}");
            }
        }
Пример #19
0
        public void Subscribe <T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler <T>
        {
            var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFFIX, "");

            var containsKey = _subsManager.HasSubscriptionsForEvent <T>();

            if (!containsKey)
            {
                try
                {
                    _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} with {EventHandler}", eventName, typeof(TH).Name);

            _subsManager.AddSubscription <T, TH>();
        }
        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();
                }
            });
        }
Пример #21
0
        public void Subscribe <T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler <T>
        {
            var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFIX, "");

            var containsKey = _subscriptionManager.HasSubscriptionForEvent <T>();

            if (!containsKey)
            {
                try
                {
                    _subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        //CorrelationFilter - Holds a set of conditions that is evaluated in the ServiceBus service against the arriving messages'
                        //user -defined properties and system properties. A match exists when an arriving message's value for a
                        //property is equal to the value specified in the correlation filter.
                        Filter = new CorrelationFilter {
                            Label = eventName
                        },
                        Name = eventName
                    }).GetAwaiter().GetResult();
                }
                catch (ServiceBusException)
                {
                    _logger.LogInformation($"This messaging entity { eventName } already exist!!");
                }
            }
            _subscriptionManager.AddSubscription <T, TH>();
        }
        public async Task SubscibeAsync <T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler <T>
        {
            var eventName = typeof(T).Name;

            var containsKey = _subscriptionManager.HasSubscriptionsForEvent <T>();

            if (!containsKey)
            {
                try
                {
                    await _subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        Filter = new CorrelationFilter {
                            Label = eventName
                        },
                        Name = eventName
                    });
                }
                catch (ServiceBusException)
                {
                    _logger.LogWarning("The messaging entity '{eventName} already exists.", eventName);
                }
            }

            _logger.LogInformation("Subscibing to event '{EventName}' with '{EventHandler}'", eventName, typeof(TH).Name);
            _subscriptionManager.AddSubscription <T, TH>();
        }
Пример #23
0
 public static async Task AddRuleIfNotExistsAsync(this SubscriptionClient client, RuleDescription rule)
 {
     if (!await client.ContainsRuleAsync(rule.Name))
     {
         await client.AddRuleAsync(rule);
     }
 }
Пример #24
0
        private async Task CreateSubscription()
        {
            if (_subscriptionClient == null)
            {
                using (var httpClient = new HttpClient())
                {
                    var uri           = GetSubscriptionUri(_nodeId);
                    var tokenProvider = CreateTokenProvider();
                    var token         = await tokenProvider.GetTokenAsync(uri.ToString(), _serviceBusTokenTimeOut);

                    httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(token.TokenValue);

                    using (var content = new StringContent(CreateSubscriptionDescription().ToString(SaveOptions.None), Encoding.UTF8, "application/atom+xml"))
                    {
                        content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("type", "entry"));
                        var subscriptionResponse = await httpClient.PutAsync(uri, content);

                        subscriptionResponse.Dispose();
                    }
                }

                _subscriptionClient = new SubscriptionClient(_connectionString, _topicName, _nodeId);
                _logger?.LogDebug(Resources.AzureServiceBus_Debug_SubscriptionCreated, _topicName, _nodeId);

                string sqlPattern              = "{0} <> '{2}' AND ({1} IS NULL OR {1} = '{2}')";
                string senderIdPropertyName    = ServiceBus.MessageConverter.SenderIdPropertyName;
                string recipientIdPropertyName = ServiceBus.MessageConverter.RecipientIdPropertyName;
                var    filter = new SqlFilter(string.Format(CultureInfo.InvariantCulture, sqlPattern, senderIdPropertyName, recipientIdPropertyName, _nodeId));
                await _subscriptionClient.AddRuleAsync("RecipientFilter", filter);

                _subscriptionClient.RegisterMessageHandler(ReceiveMessage, ex => Task.CompletedTask);
            }
        }
Пример #25
0
        public async Task Subscribe <T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler <T>
        {
            var eventName   = typeof(T).Name;
            var containsKey = _subscriptionsManager.HasSubscriptionsForEvent <T>();

            if (!containsKey)
            {
                try
                {
                    await _subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        Filter = new CorrelationFilter {
                            Label = eventName
                        },
                        Name = eventName
                    });
                }
                catch (ServiceBusException)
                {
                    _logger.LogInformation("Stopped adding the rule {ruleName} as it already exists.", eventName);
                }
            }
            _subscriptionsManager.AddSubscription <T, TH>();
        }
Пример #26
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);
        }
Пример #27
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());
            }
Пример #28
0
 /*
  * private void CreateSubscriptionIfNotExists(NamespaceManager namespaceManager, TopicSettings topic, SubscriptionSettings subscription)
  * {
  *  var subscriptionDescription =
  *      new SubscriptionDescription(topic.Path, subscription.Name)
  *      {
  *          RequiresSession = subscription.RequiresSession,
  *          LockDuration = TimeSpan.FromSeconds(150),
  *      };
  *
  *  try
  *  {
  *      namespaceManager.CreateSubscription(subscriptionDescription);
  *  }
  *  //catch (MessagingEntityAlreadyExistsException) { }
  *  catch (ServiceBusException) { }
  * }
  *
  * private static void UpdateSubscriptionIfExists(NamespaceManager namespaceManager, TopicSettings topic, UpdateSubscriptionIfExists action)
  * {
  *  if (string.IsNullOrWhiteSpace(action.Name)) throw new ArgumentException("action");
  *  if (string.IsNullOrWhiteSpace(action.SqlFilter)) throw new ArgumentException("action");
  *
  *  UpdateSqlFilter(namespaceManager, action.SqlFilter, action.Name, topic.Path);
  * }
  *
  * private static void UpdateRules(NamespaceManager namespaceManager, TopicSettings topic, SubscriptionSettings subscription)
  * {
  *  string sqlExpression = null;
  *  if (!string.IsNullOrWhiteSpace(subscription.SqlFilter))
  *  {
  *      sqlExpression = subscription.SqlFilter;
  *  }
  *
  *  UpdateSqlFilter(namespaceManager, sqlExpression, subscription.Name, topic.Path);
  * }
  * /*
  * private static async void UpdateSqlFilter(NamespaceManager namespaceManager, string sqlExpression, string subscriptionName, string topicPath)
  * {
  *  bool needsReset = false;
  *  List<RuleDescription> existingRules;
  *  try
  *  {
  *      existingRules = namespaceManager.GetRules(topicPath, subscriptionName).ToList();
  *  }
  *  catch (MessagingEntityNotFoundException)
  *  {
  *      // the subscription does not exist, no need to update rules.
  *      return;
  *  }
  *  if (existingRules.Count != 1)
  *  {
  *      needsReset = true;
  *  }
  *  else
  *  {
  *      var existingRule = existingRules.First();
  *      if (sqlExpression != null && existingRule.Name == RuleDescription.DefaultRuleName)
  *      {
  *          needsReset = true;
  *      }
  *      else if (sqlExpression == null && existingRule.Name != RuleDescription.DefaultRuleName)
  *      {
  *          needsReset = true;
  *      }
  *      else if (sqlExpression != null && existingRule.Name != RuleName)
  *      {
  *          needsReset = true;
  *      }
  *      else if (sqlExpression != null && existingRule.Name == RuleName)
  *      {
  *          var filter = existingRule.Filter as SqlFilter;
  *          if (filter == null || filter.SqlExpression != sqlExpression)
  *          {
  *              needsReset = true;
  *          }
  *      }
  *  }
  *
  *  if (needsReset)
  *  {
  *      SubscriptionClient client = null;
  *      try
  *      {
  *          client = new SubscriptionClient(namespaceManager.Address, topicPath, subscriptionName);
  *
  *          // first add the default rule, so no new messages are lost while we are updating the subscription
  *          await TryAddRule(client, new RuleDescription(RuleDescription.DefaultRuleName, new TrueFilter()));
  *
  *          // then delete every rule but the Default one
  *          foreach (var existing in existingRules.Where(x => x.Name != RuleDescription.DefaultRuleName))
  *          {
  *              await TryRemoveRule(client, existing.Name);
  *          }
  *
  *          if (sqlExpression != null)
  *          {
  *              // Add the desired rule.
  *              await TryAddRule(client, new RuleDescription(RuleName, new SqlFilter(sqlExpression)));
  *
  *              // once the desired rule was added, delete the default rule.
  *              await TryRemoveRule(client, RuleDescription.DefaultRuleName);
  *          }
  *      }
  *      finally
  *      {
  *          if (client != null)
  *          {
  *              await client.CloseAsync();
  *              //client.Close();
  *          }
  *      }
  *  }
  * }
  */
 private static async Task TryAddRule(SubscriptionClient client, RuleDescription rule)
 {
     // try / catch is because there could be other processes initializing at the same time.
     try
     {
         await client.AddRuleAsync(rule);
     }
     //TODO: pay attention to this type of exception
     //catch (MessagingEntityAlreadyExistsException) { }
     catch (MessagingEntityDisabledException) { }
 }
Пример #29
0
        static async Task AddFilter()
        {
            SubscriptionClient _subscription_client = new SubscriptionClient(_bus_connectionstring, _topic_name, _subscription_name);
            var _subscription_rule = new RuleDescription("MessageRule", new SqlFilter("MessageId='5'"));
            await _subscription_client.AddRuleAsync(_subscription_rule);

            await _subscription_client.RemoveRuleAsync("$Default");

            Console.WriteLine("Rule added");
            Console.ReadLine();
        }
Пример #30
0
 public void SetRule(string rule)
 {
     try
     {
         subscriptionClient.RemoveRuleAsync("$Default").Wait();
     }
     catch
     {
     }
     subscriptionClient.AddRuleAsync(new RuleDescription(ruleName, new SqlFilter(rule)));
 }