Exemple #1
0
        public static Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string connectionStringServiceBus = "Endpoint=sb://plenttdata.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=H04PgzviylO3hman4MOuXfSWPHgrCUDOKd5835UQYas=";
            string topicName        = "pletopic";
            string SubscriptionName = "plesubscription";

            subscriptionClient = new SubscriptionClient(connectionStringServiceBus, topicName, SubscriptionName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press any key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

            var newRule = new RuleDescription("FilteredRule", new SqlFilter("From LIKE '%manhduc'"));

            subscriptionClient.AddRuleAsync(newRule);

            topicClient = new TopicClient(connectionStringServiceBus, topicName);

            RegisterMessageHandlerAndReceiveMessages();

            Console.ReadKey();

            topicClient.CloseAsync().Wait();

            return(null);
        }
Exemple #2
0
        static async Task MainAsync()
        {
            const int numberOfMessages = 10;

            topicClient        = new TopicClient(ServiceBusConnectionString, TopicName);
            subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);

            // Ensure default rule exists
            await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);

            await subscriptionClient.AddRuleAsync(new RuleDescription(RuleDescription.DefaultRuleName, new TrueFilter()));

            Console.WriteLine("======================================================");
            Console.WriteLine("Press any key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

            // Register Subscription's MessageHandler and receive messages in a loop
            RegisterOnMessageHandlerAndReceiveMessages();

            // Send Messages
            await SendMessagesAsync(numberOfMessages);

            Console.ReadKey();

            await subscriptionClient.CloseAsync();

            await topicClient.CloseAsync();
        }
        public async Task SetupSubscriptionRules()
        {
            var exitstingRules = await _subscriptionClient.GetRulesAsync();

            var subscriptionRuleName = _subscriptionName + "-rule";

            if (exitstingRules != null)
            {
                exitstingRules
                .Where(r => r.Name != subscriptionRuleName)
                .ToList()
                .ForEach(async r => await _subscriptionClient.RemoveRuleAsync(r.Name));

                if (exitstingRules.Any(r => r.Name == subscriptionRuleName))
                {
                    return;
                }
            }

            var corrFilter = new CorrelationFilter();

            corrFilter.Properties.Add(_filterProperty, true);
            var rule = new RuleDescription
            {
                Filter = corrFilter,
                Name   = subscriptionRuleName
            };

            await _subscriptionClient.AddRuleAsync(rule);
        }
        public async Task SubscribeAsync <T, H>()
            where T : EventBase
            where H : IEventHandler <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 ex)
                {
                    //TODO: Logging
                }
            }

            _subscriptionManager.AddSubscriptionForEvent <T, H>();
        }
Exemple #5
0
        public async Task RegisterMessageReceivingAsync(OrderPaidMessageFilter filter)
        {
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            };

            var rules = (await _subscriptionClient.GetRulesAsync()).ToList();

            if (rules.Any())
            {
                await _subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
            }

            await _subscriptionClient.AddRuleAsync(new RuleDescription()
            {
                Filter = new CorrelationFilter
                {
                    CorrelationId = filter.Value
                }
            });

            _subscriptionClient.RegisterMessageHandler(HandleMessage, messageHandlerOptions);
        }
Exemple #6
0
        private static async Task AddSQLFilters(ISubscriptionClient subscriptionClient)
        {
            var rules = await subscriptionClient.GetRulesAsync();

            if (!rules.Any(r => r.Name == "PriceGreaterThan100"))
            {
                var filter = new SqlFilter("price > 100");
                await subscriptionClient.AddRuleAsync("PriceGreaterThan100", filter);
            }
        }
Exemple #7
0
 static async Task MainAsync()
 {
     subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);
     var rules = new RuleDescription()
     {
         Filter = new SqlFilter("series = '3'"),
         Action = new SqlRuleAction("set label = '3 series'"),
         Name   = "series"
     };
     await subscriptionClient.AddRuleAsync(rules);
 }
Exemple #8
0
        private static async Task AddBooleanFilters(bool _catch)
        {
            var rules = await salesCancelSubscriptionClient.GetRulesAsync();

            if (_catch)
            {
                if (!rules.Any(r => r.Name == "CatchAll"))
                {
                    var catchAllFilter = new TrueFilter();
                    await salesCancelSubscriptionClient.AddRuleAsync("CatchAll", catchAllFilter);
                }
            }
            else
            {
                if (!rules.Any(r => r.Name == "CatchNothing"))
                {
                    var catchNothingFilter = new FalseFilter();
                    await salesCancelSubscriptionClient.AddRuleAsync("CatchNothing", catchNothingFilter);
                }
            }
        }
Exemple #9
0
        private async Task ValidateSubscriptionRulesAsync(ISubscriptionClient subscriptionClient, string filterName)
        {
            var filterExists     = false;
            var hasDefaultFilter = false;
            var filterCount      = 0;

            foreach (var rule in await subscriptionClient.GetRulesAsync())
            {
                if (rule.Name == filterName && rule.Filter is CorrelationFilter filter &&
                    filter.Label == filterName)
                {
                    filterExists = true;
                }

                if (rule.Name == "$Default")
                {
                    hasDefaultFilter = true;
                }

                filterCount++;
            }

            if (hasDefaultFilter && filterName == "all")
            {
                return;
            }

            if (filterCount != 1 && filterExists || filterCount != 1 && hasDefaultFilter)
            {
                throw new Exception("Invalid combination of subscription name and filter");
            }

            if (hasDefaultFilter)
            {
                await subscriptionClient.RemoveRuleAsync("$Default");
            }

            if (filterExists == false)
            {
                await subscriptionClient.AddRuleAsync(new RuleDescription(filterName, new CorrelationFilter
                {
                    ContentType = "application/json",
                    Label = filterName
                }));
            }
        }
Exemple #10
0
        public void Subscribe <T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler <T>
        {
            var eventName = typeof(T).Name;

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

            if (!containsKey)
            {
                try
                {
                    if (_labelFiltering)
                    {
                        _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));

            bool registerHandler = false;

            lock (_subscriptionLock)
            {
                if (_subsManager.IsEmpty)
                {
                    registerHandler = true;
                }
                _subsManager.AddSubscription <T, TH>();
            }
            if (registerHandler)
            {
                RegisterSubscriptionClientMessageHandler();
            }
        }
        private static async Task ConfigureServiceBusAsync()
        {
            var mgmtClient = new ManagementClient(ServiceBusConnectionString);

            // Create our topic
            if (!await mgmtClient.TopicExistsAsync(TopicName))
            {
                await mgmtClient.CreateTopicAsync(new TopicDescription(TopicName) { EnableBatchedOperations = true });
            }

            // Create the subscription we need
            if (!await mgmtClient.SubscriptionExistsAsync(TopicName, SubscriptionName))
            {
                await mgmtClient.CreateSubscriptionAsync(new SubscriptionDescription(TopicName, SubscriptionName) { RequiresSession = true, MaxDeliveryCount = 3 });

                await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);

                await subscriptionClient.AddRuleAsync(new RuleDescription { Filter = new CorrelationFilter {
                                                                                Label = "Renderer"
                                                                            }, Name = SubscriptionName });
            }
        }
        static async Task MainAsync()
        {
            await AsyncSetCalcbenchCredentials();

            var connectionStringBuilder = new ServiceBusConnectionStringBuilder(ConfigurationManager.AppSettings["AzureServiceBusConnectionString"]);

            Enum.TryParse(ConfigurationManager.AppSettings["AzureServiceBusTransportType"], out TransportType transportType);
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(connectionStringBuilder.SasKeyName, connectionStringBuilder.SasKey);

            subscriptionClient = new SubscriptionClient(endpoint: connectionStringBuilder.Endpoint,
                                                        topicPath: CalcbenchFilingsTopic,
                                                        subscriptionName: ConfigurationManager.AppSettings["QueueSubscription"],
                                                        tokenProvider: tokenProvider,
                                                        transportType: transportType);

            var rules = await subscriptionClient.GetRulesAsync();

            await Task.WhenAll(rules.Select(async rule => await subscriptionClient.RemoveRuleAsync(rule.Name)));

            await subscriptionClient.AddRuleAsync(new RuleDescription
            {
                Filter = new SqlFilter("FilingType = 'eightk_earningsPressRelease'"),
                Name   = "PressReleasesOnly"
            });


            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

            // Register subscription message handler and receive messages in a loop.
            RegisterOnMessageHandlerAndReceiveMessages();

            Console.ReadKey();

            await subscriptionClient.CloseAsync();
        }
Exemple #13
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.
            Console.WriteLine($"SubscriptionName: {allMessagesSubscriptionName}, Removing and re-adding Default Rule");
            await allMessagessubscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);

            await allMessagessubscriptionClient.AddRuleAsync(new RuleDescription(RuleDescription.DefaultRuleName, new TrueFilter()));

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