Esempio n. 1
0
        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                _activeSubscriptionClient?.CloseAsync()
                .GetAwaiter().GetResult();

                _passiveSubscriptionClient?.CloseAsync()
                .GetAwaiter().GetResult();
            }

            base.Dispose(isDisposing);
        }
        private void CloseSubscriptionClient()
        {
            if (_subscriptionClient == null)
            {
                return;
            }

            using (_lock.Lock()) {
                if (_subscriptionClient == null)
                {
                    return;
                }

                _subscriptionClient?.CloseAsync();
                _subscriptionClient = null;
            }
        }
Esempio n. 3
0
 public Task StopAsync(CancellationToken cancellationToken)
 {
     return(_logClient.CloseAsync());
 }
Esempio n. 4
0
        public async Task GetRulesTestCase()
        {
            var subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                TestConstants.NonPartitionedTopicName,
                TestConstants.SubscriptionName,
                ReceiveMode.ReceiveAndDelete);
            var sqlRuleName         = "sqlRule";
            var correlationRuleName = "correlationRule";

            try
            {
                var rules = (await subscriptionClient.GetRulesAsync()).ToList();
                Assert.Single(rules);
                var firstRule = rules[0];
                Assert.Equal(RuleDescription.DefaultRuleName, firstRule.Name);
                Assert.IsType <SqlFilter>(firstRule.Filter);
                Assert.Null(firstRule.Action);

                await subscriptionClient.AddRuleAsync(sqlRuleName, new SqlFilter("price > 10"));

                var ruleDescription = new RuleDescription(correlationRuleName)
                {
                    Filter = new CorrelationFilter
                    {
                        CorrelationId = "correlationId",
                        Label         = "label",
                        MessageId     = "messageId",
                        Properties    =
                        {
                            { "key1", "value1" }
                        },
                        ReplyTo          = "replyTo",
                        ReplyToSessionId = "replyToSessionId",
                        SessionId        = "sessionId",
                        To = "to"
                    },
                    Action = new SqlRuleAction("Set CorrelationId = 'newValue'")
                };
                await subscriptionClient.AddRuleAsync(ruleDescription);

                rules = (await subscriptionClient.GetRulesAsync()).ToList();
                Assert.Equal(3, rules.Count);

                var sqlRule = rules.FirstOrDefault(rule => rule.Name.Equals(sqlRuleName));
                Assert.NotNull(sqlRule);
                Assert.Null(sqlRule.Action);
                Assert.IsType <SqlFilter>(sqlRule.Filter);
                Assert.Equal("price > 10", ((SqlFilter)sqlRule.Filter).SqlExpression);

                var correlationRule = rules.FirstOrDefault(rule => rule.Name.Equals(correlationRuleName));
                Assert.NotNull(correlationRule);
                Assert.IsType <SqlRuleAction>(correlationRule.Action);
                var sqlRuleAction = correlationRule.Action as SqlRuleAction;
                Assert.NotNull(sqlRuleAction);
                Assert.Equal("Set CorrelationId = 'newValue'", sqlRuleAction.SqlExpression);
                Assert.IsType <CorrelationFilter>(correlationRule.Filter);
                var correlationFilter = correlationRule.Filter as CorrelationFilter;
                Assert.NotNull(correlationFilter);
                Assert.Equal("correlationId", correlationFilter.CorrelationId);
                Assert.Equal("label", correlationFilter.Label);
                Assert.Equal("messageId", correlationFilter.MessageId);
                Assert.Equal("replyTo", correlationFilter.ReplyTo);
                Assert.Equal("replyToSessionId", correlationFilter.ReplyToSessionId);
                Assert.Equal("sessionId", correlationFilter.SessionId);
                Assert.Equal("to", correlationFilter.To);
                Assert.NotNull(correlationFilter.Properties);
                Assert.Equal("value1", correlationFilter.Properties["key1"]);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                try
                {
                    await subscriptionClient.RemoveRuleAsync(sqlRuleName);

                    await subscriptionClient.RemoveRuleAsync(correlationRuleName);
                }
                catch (Exception)
                {
                    // Ignore the exception as we are just trying to clean up the rules that we MIGHT have added.
                }
                await subscriptionClient.CloseAsync();
            }
        }
Esempio n. 5
0
 public Task StopReceivingMessages() => subscriptionClient?.CloseAsync() ?? Task.CompletedTask;
Esempio n. 6
0
        public async Task SqlActionTestCase(bool partitioned, bool sessionEnabled)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    ReceiveMode.ReceiveAndDelete);

                try
                {
                    try
                    {
                        await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
                    }
                    catch
                    {
                        // ignored
                    }

                    await subscriptionClient.AddRuleAsync(new RuleDescription
                    {
                        Filter = new SqlFilter("Color = 'RedSqlAction'"),
                        Action = new SqlRuleAction("SET Color = 'RedSqlActionProcessed'"),
                        Name   = "RedSqlAction"
                    });

                    var messageId1 = Guid.NewGuid().ToString();
                    await topicClient.SendAsync(new Message
                    {
                        MessageId      = messageId1,
                        Label          = "BlueSqlAction",
                        UserProperties = { { "color", "BlueSqlAction" } }
                    });
                    TestUtility.Log($"Sent Message: {messageId1}");

                    var messageId2 = Guid.NewGuid().ToString();
                    await topicClient.SendAsync(new Message
                    {
                        MessageId      = messageId2,
                        Label          = "RedSqlAction",
                        UserProperties = { { "color", "RedSqlAction" } }
                    });
                    TestUtility.Log($"Sent Message: {messageId2}");

                    var messages = await subscriptionClient.InnerSubscriptionClient.InnerReceiver.ReceiveAsync(maxMessageCount: 2);
                    Assert.NotNull(messages);
                    Assert.True(messages.Count == 1);
                    Assert.Equal(messageId2, messages.First().MessageId);
                    Assert.True(messages.First().UserProperties["color"].Equals("RedSqlActionProcessed"));
                }
                finally
                {
                    await subscriptionClient.RemoveRuleAsync("RedSqlAction");
                    await subscriptionClient.AddRuleAsync(RuleDescription.DefaultRuleName, new TrueFilter());
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
 /// <summary>
 /// Stops message pump if started
 /// </summary>
 public void Dispose()
 {
     _client.CloseAsync().Wait(); //this also stops the message pump
 }
Esempio n. 8
0
 public void Dispose()
 {
     _subscriptionClient.CloseAsync().GetAwaiter().GetResult();
 }
        protected override async Task ExecuteAsync(CancellationToken token)
        {
            while (true)
            {
                SubscriptionClient serviceBusClient = null;

                try
                {
                    var subscription = await InitializeAzureServiceBus(token).ConfigureAwait(false);

                    serviceBusClient = new SubscriptionClient(
                        connectionString: _options.ServiceBusConnectionString,
                        topicPath: _options.Topic,
                        subscriptionName: subscription.Name,
                        receiveMode: ReceiveMode.PeekLock);

                    var opts = new MessageHandlerOptions(ex =>
                    {
                        _logger.LogError(ex.Exception, "unhandled exception in message handler");
                        return(Task.FromResult(0));
                    })
                    {
                        MaxConcurrentCalls = 1,
                    };

                    serviceBusClient.RegisterMessageHandler((msg, token) =>
                    {
                        this.HandleBackplaneMessage(serviceBusClient, msg, token);
                        return(Task.FromResult(0));
                    }, opts);

                    Task newSubscriptionSignal     = _subscribeSignal.WaitAsync();
                    Task subscriptionDisposeSignal = _unsubscribeSignal.WaitAsync();

                    while (true)
                    {
                        try
                        {
                            var result = await Task.WhenAny(newSubscriptionSignal, subscriptionDisposeSignal);

                            if (result == newSubscriptionSignal)
                            {
                                newSubscriptionSignal = _subscribeSignal.WaitAsync();
                            }
                            else if (result == subscriptionDisposeSignal)
                            {
                                subscriptionDisposeSignal = _unsubscribeSignal.WaitAsync();
                            }

                            await UpdateRules(subscription, token);
                        }
                        catch (TaskCanceledException)
                        {
                            _logger.LogDebug("inner loop cancelled");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "unhandled exeption in inner control loop");
                            await Task.Delay(100);
                        }
                    }
                }
                catch (TaskCanceledException)
                {
                    _logger.LogDebug("outer loop cancelled");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "unhandled exception in outer loop control loop");
                }

                _logger.LogDebug("closing backplane connection");
                Task close = serviceBusClient?.CloseAsync();
                if (close != null)
                {
                    await close;
                }

                _logger.LogDebug("something happend in the loop, retrying after a short delay");
                await Task.Delay(5000);
            }
        }
 public void Dispose()
 {
     _serviceBusPersisterConnection.Dispose();
     _subscriptionClient.CloseAsync();
 }
        private async Task OnMessageTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            const int messageCount = 10;

            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    mode);

                try
                {
                    await this.OnMessageAsyncTestCase(
                        topicClient.InnerSender,
                        subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        maxConcurrentCalls,
                        autoComplete,
                        messageCount);
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    mode);

                try
                {
                    await this.OnMessageAsyncUnregisterHandlerLongTimeoutTestCase(
                        topicClient.InnerSender,
                        subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        maxConcurrentCalls,
                        autoComplete,
                        messageCount);
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    mode);

                try
                {
                    await this.OnMessageAsyncUnregisterHandlerShortTimeoutTestCase(
                        topicClient.InnerSender,
                        subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        maxConcurrentCalls,
                        autoComplete,
                        messageCount);
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
Esempio n. 12
0
 public async Task CloseAsync() => await _client.CloseAsync();
Esempio n. 13
0
        private async void Restart()
        {
            await _subscriptionClient.CloseAsync();

            await CustomStartAsync();
        }
Esempio n. 14
0
 public void Unsubscribe()
 {
     _client.CloseAsync();
 }
 public async Task CloseQueueAsync()
 {
     await _subscriptionClient.CloseAsync();
 }
Esempio n. 16
0
 public async Task Close()
 {
     await m_SubscriptionClient.CloseAsync();
 }
Esempio n. 17
0
        public async Task CloseQueueAsync()
        {
            await _serviceBusClientProdutoAtualizado.CloseAsync();

            await _serviceBusClientProdutoCriado.CloseAsync();
        }
Esempio n. 18
0
 public Task CloseAsync()
 {
     return(_client.CloseAsync());
 }
Esempio n. 19
0
        public async Task CorrelationFilterTestCase(bool partitioned, bool sessionEnabled)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName,
                    ReceiveMode.ReceiveAndDelete);

                try
                {
                    try
                    {
                        await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
                    }
                    catch (Exception e)
                    {
                        TestUtility.Log($"Remove Default Rule failed with Exception: {e.Message}");
                    }

                    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.Equal(messageId2, messages.First().MessageId);
                }
                finally
                {
                    try
                    {
                        await subscriptionClient.RemoveRuleAsync("RedCorrelation");
                        await subscriptionClient.AddRuleAsync(RuleDescription.DefaultRuleName, new TrueFilter());
                    }
                    catch (Exception e)
                    {
                        TestUtility.Log($" Cleanup failed with Exception: {e.Message}");
                    }

                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
        private async Task OnSessionTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandler(sessionHandlerOptions);

                    // Verify messages were received.
                    await testSessionHandler.VerifyRun();

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            // test UnregisterSessionHandler can wait for message handling upto the timeout user defined.
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 8);

                    // Session handler set up has greater latency than message handler. Delay here to enable some processing time of the session pump.
                    await Task.Delay(TimeSpan.FromSeconds(2));

                    // UnregisterSessionHandler should wait up to the provided timeout to finish the message handling tasks
                    await testSessionHandler.UnregisterSessionHandler(TimeSpan.FromSeconds(10));
                    Assert.True(testSessionHandler.ReceivedMessageCount == maxConcurrentCalls);

                    // Reregister won't have any problems
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 0);
                    await testSessionHandler.WaitForAllMessagesReceived(ExpectedMessageCount);
                    Assert.True(testSessionHandler.ReceivedMessageCount == ExpectedMessageCount);

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });

            // test UnregisterSessionHandler can close down in time when message handling takes longer than wait timeout user defined.
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicClient.TopicName,
                    subscriptionName,
                    ReceiveMode.PeekLock);

                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = maxConcurrentCalls,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

                    var testSessionHandler = new TestSessionHandler(
                        subscriptionClient.ReceiveMode,
                        sessionHandlerOptions,
                        topicClient.InnerSender,
                        subscriptionClient.SessionPumpHost);

                    // Send messages to Session
                    await testSessionHandler.SendSessionMessages();

                    // Register handler
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 8);

                    // UnregisterSessionHandler should wait up to the provided timeout to finish the message handling tasks
                    await testSessionHandler.UnregisterSessionHandler(TimeSpan.FromSeconds(2));
                    Assert.True(testSessionHandler.ReceivedMessageCount == 0);

                    // Reregister won't have any problems
                    testSessionHandler.RegisterSessionHandlerAndRecordReceivedMessageCount(subscriptionClient.ReceiveMode == ReceiveMode.PeekLock, 0);
                    await testSessionHandler.WaitForAllMessagesReceived(ExpectedMessageCount);
                    Assert.True(testSessionHandler.ReceivedMessageCount == ExpectedMessageCount);

                    testSessionHandler.ClearData();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
 /// <summary>
 /// Close this subscriber
 /// </summary>
 /// <returns></returns>
 public async Task CloseSubscriber()
 {
     await _subscriptionClient.CloseAsync();
 }
Esempio n. 22
0
 private void Stop()
 {
     subscriptionClient?.CloseAsync().GetAwaiter().GetResult();
 }
Esempio n. 23
0
        public async Task SqlFilterTestCase(string topicName)
        {
            var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
            var subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicName,
                this.SubscriptionName,
                ReceiveMode.ReceiveAndDelete);

            try
            {
                try
                {
                    await subscriptionClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
                }
                catch (Exception e)
                {
                    TestUtility.Log($"Remove Default Rule failed with: {e.Message}");
                }

                await subscriptionClient.AddRuleAsync(new RuleDescription
                {
                    Filter = new SqlFilter("Color = 'RedSql'"),
                    Name   = "RedSql"
                });

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

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

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

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

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

                Assert.NotNull(messages);
                Assert.True(messages.Count == 1);
                Assert.Equal(messageId2, messages.First().MessageId);
            }
            finally
            {
                try
                {
                    await subscriptionClient.RemoveRuleAsync("RedSql");

                    await subscriptionClient.AddRuleAsync(RuleDescription.DefaultRuleName, new TrueFilter());
                }
                catch (Exception e)
                {
                    TestUtility.Log($" Cleanup failed with Exception: {e.Message}");
                }

                await subscriptionClient.CloseAsync();

                await topicClient.CloseAsync();
            }
        }
        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            await _client.CloseAsync();

            Console.WriteLine("Finalizando conexão com o Azure Service");
        }
        private async Task ReceiveMessages_FromTopicSessionStateSubscriptionsAsync(SubscriptionClient client, CancellationToken token, ConsoleColor color)
        {
            var doneReceiving = new TaskCompletionSource <bool>();

            token.Register(
                async() =>
            {
                await client.CloseAsync();
                doneReceiving.SetResult(true);
            });

            client.RegisterSessionHandler(
                async(session, message, token1) =>
            {
                try
                {
                    var stateData = await session.GetStateAsync();

                    var session_state = stateData != null ? Deserialize <SessionStateManager>(stateData) : new SessionStateManager();

                    if ((int)message.UserProperties["Order"] == session_state.LastProcessedCount + 1)      //check if message is next in the sequence
                    {
                        if (ProcessMessages(message, color))
                        {
                            await session.CompleteAsync(message.SystemProperties.LockToken);

                            session_state.LastProcessedCount = ((int)message.UserProperties["Order"]);
                            await session.SetStateAsync(Serialize <SessionStateManager>(session_state));
                            if (message.UserProperties["IsLast"].ToString().ToLower() == "true")
                            {
                                //end of the session
                                await session.SetStateAsync(null);
                                await session.CloseAsync();
                            }
                        }
                        else
                        {
                            await client.DeadLetterAsync(message.SystemProperties.LockToken, "Message is of the wrong type or could not be processed", "Cannot deserialize this message as the type is unknown.");
                        }
                    }
                    else
                    {
                        session_state.DeferredList.Add((int)message.UserProperties["Order"], message.SystemProperties.SequenceNumber);
                        await session.DeferAsync(message.SystemProperties.LockToken);
                        await session.SetStateAsync(Serialize(session_state));
                    }

                    long last_processed = await ProcessNextMessagesWithSessionStateAsync(client, session, session_state, color);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("-->> ERROR : Unable to receive {0} from subscription: Exception {1}", message.MessageId, ex);
                }
            },
                new SessionHandlerOptions(e => LogMessageHandlerException(e))
            {
                MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                MaxConcurrentSessions = 1,
                AutoComplete          = false
            });

            await doneReceiving.Task;
        }
 public void Dispose()
 {
     _subscriptionClient.CloseAsync();
 }
Esempio n. 27
0
 public async Task StopAsync(CancellationToken cancellationToken)
 {
     _logger.LogDebug($"BusListener stopping.");
     await _subscriptionClient.CloseAsync();
 }
Esempio n. 28
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();
        }
 public void Dispose()
 {
     _consumerClient?.CloseAsync().Wait(1500);
 }
Esempio n. 30
0
        async Task ReceiveMessagesAsync(string connectionString, string topicName, string subscriptionName, CancellationToken cancellationToken, ConsoleColor color)
        {
            // var subscriptionPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName);
            //var receiver = new MessageReceiver(connectionString,subscriptionPath, ReceiveMode.PeekLock);


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

            var doneReceiving = new TaskCompletionSource <bool>();

            // close the receiver and factory when the CancellationToken fires
            cancellationToken.Register(
                async() =>
            {
                await receiver.CloseAsync();
                doneReceiving.SetResult(true);
            });

            // register the RegisterMessageHandler callback
            receiver.RegisterMessageHandler(
                async(message, cancellationToken1) =>
            {
                if (message.Label != null &&
                    message.ContentType != null &&
                    message.Label.Equals("Scientist", StringComparison.InvariantCultureIgnoreCase) &&
                    message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                {
                    var body = message.Body;

                    dynamic scientist = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(body));

                    lock (Console.Out)
                    {
                        Console.ForegroundColor = color;
                        Console.WriteLine(
                            "\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = {0}, \n\t\t\t\t\t\tSequenceNumber = {1}, \n\t\t\t\t\t\tEnqueuedTimeUtc = {2}," +
                            "\n\t\t\t\t\t\tExpiresAtUtc = {5}, \n\t\t\t\t\t\tContentType = \"{3}\", \n\t\t\t\t\t\tSize = {4},  \n\t\t\t\t\t\tContent: [ firstName = {6}, name = {7} ]",
                            message.MessageId,
                            message.SystemProperties.SequenceNumber,
                            message.SystemProperties.EnqueuedTimeUtc,
                            message.ContentType,
                            message.Size,
                            message.ExpiresAtUtc,
                            scientist.firstName,
                            scientist.name);
                        Console.ResetColor();
                    }
                    await receiver.CompleteAsync(message.SystemProperties.LockToken);
                }
                else
                {
                    await receiver.DeadLetterAsync(message.SystemProperties.LockToken);    //, "ProcessingError", "Don't know what to do with this message");
                }
            },
                new MessageHandlerOptions((e) => LogMessageHandlerException(e))
            {
                AutoComplete = false, MaxConcurrentCalls = 1
            });

            await doneReceiving.Task;
        }