Example #1
0
        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = 1,

                // Indicates whether the message pump should automatically complete the messages after returning from user callback.
                // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync().
                AutoComplete = false
            };

            // Register the function that processes messages.
            _queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);

            var sessionHandlerOptions = new SessionHandlerOptions(ExceptionSessionHandler)
            {
                AutoComplete          = false,
                MaxConcurrentSessions = 1
            };

            //_queueClient.RegisterSessionHandler(HandleMessageAsync, sessionHandlerOptions);
        }
        async Task OnSessionTestAsync(string queueName, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            TestUtility.Log($"Queue: {queueName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
            var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, mode);

            try
            {
                SessionHandlerOptions handlerOptions =
                    new SessionHandlerOptions(ExceptionReceivedHandler)
                {
                    MaxConcurrentSessions = maxConcurrentCalls,
                    MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                    AutoComplete          = autoComplete
                };

                TestSessionHandler testSessionHandler = new TestSessionHandler(
                    queueClient.ReceiveMode,
                    handlerOptions,
                    queueClient.InnerSender,
                    queueClient.SessionPumpHost);

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

                // Register handler
                testSessionHandler.RegisterSessionHandler(handlerOptions);

                // Verify messages were received.
                await testSessionHandler.VerifyRun();
            }
            finally
            {
                await queueClient.CloseAsync();
            }
        }
        public void Listen()
        {
            subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);
            RetryPolicy policy = new RetryExponential(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(29), 10);

            subscriptionClient.ServiceBusConnection.RetryPolicy = policy;

            var sessionOptions = new SessionHandlerOptions(ExceptionReceivedHandler)
            {
                AutoComplete          = false,
                MaxConcurrentSessions = _concurrentSessions,
                MaxAutoRenewDuration  = TimeSpan.FromSeconds(20)
                                        //MessageWaitTimeout = TimeSpan.FromSeconds(30)
            };

            subscriptionClient.PrefetchCount = 250;
            subscriptionClient.RegisterSessionHandler(OnMessage, sessionOptions);

            if (_autoTryReconnect)
            {
                while (true)
                {
                    Task.Delay(10000).GetAwaiter().GetResult();
                    TryReconnect();
                }
            }
        }
Example #4
0
        static void RegisterOnSessionHandlerAndReceiveSessionMessages()
        {
            // Configure the SessionHandler Options in terms of exception handling, number of concurrent sessions to deliver etc.
            var sessionHandlerOptions =
                new SessionHandlerOptions(ExceptionReceivedHandler)
            {
                // Maximum number of Concurrent calls to the callback `ProcessSessionMessagesAsync`
                // Value 2 below indicates the callback can be called with a message for 2 unique
                // session Id's in parallel. Set it according to how many messages the application
                // wants to process in parallel.
                MaxConcurrentSessions = 2,

                // Indicates the maximum time the Session Pump should wait for receiving messages for sessions.
                // If no message is received within the specified time, the pump will close that session and try to get messages
                // from a different session. Default is to wait for 1 minute to fetch messages for a session. Set to a 1 second
                // value here to allow the sample execution to finish fast but ideally leave this as 1 minute unless there
                // is a specific reason to timeout earlier.
                MessageWaitTimeout = TimeSpan.FromSeconds(1),

                // Indicates whether SessionPump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessSessionMessagesAsync`.
                AutoComplete = false
            };

            // Register the function that will process session messages
            queueClient.RegisterSessionHandler(ProcessSessionMessagesAsync, sessionHandlerOptions);
        }
        public async void TryReconnect()
        {
            if (MessagesListedBySession.Count == 0 && _sessionsInitializedCount >= _concurrentSessions)
            {
                _sessionsInitializedCount = 0;
                try {
                    await subscriptionClient.CloseAsync();
                } catch (Exception ex) {
                    if (!(logger is null))
                    {
                        logger.LogWarning(ex.Message);
                    }
                }
                subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);

                var sessionOptions = new SessionHandlerOptions(ExceptionReceivedHandler)
                {
                    AutoComplete          = false,
                    MaxConcurrentSessions = _concurrentSessions,
                    MaxAutoRenewDuration  = TimeSpan.FromSeconds(10)
                };

                subscriptionClient.PrefetchCount = 250;
                subscriptionClient.RegisterSessionHandler(OnMessage, sessionOptions);
            }
        }
        public void Start(IReceiverCallback callback)
        {
            _callback = callback;

            var options = new SessionHandlerOptions(handleException);

            var connectionString = _endpoint.ConnectionString;
            var tokenProvider    = _endpoint.TokenProvider;
            var subscriptionName = _endpoint.Uri.SubscriptionName;
            var queueName        = _endpoint.Uri.QueueName;
            var retryPolicy      = _endpoint.RetryPolicy;
            var receiveMode      = _endpoint.ReceiveMode;
            var transportType    = _endpoint.TransportType;
            var topicName        = _endpoint.Uri.TopicName;

            if (topicName.IsEmpty())
            {
                var client = tokenProvider != null
                    ? new QueueClient(connectionString, queueName, tokenProvider, transportType, receiveMode, retryPolicy)
                    : new QueueClient(connectionString, queueName, receiveMode, retryPolicy);

                client.RegisterSessionHandler(handleMessage, options);

                _clientEntities.Add(client);
            }
            else if (_endpoint.Uri.IsMessageSpecificTopic())
            {
                if (_endpoint.Uri.SubscriptionName.IsEmpty())
                {
                    throw new InvalidOperationException($"Invalid listener Uri '{_endpoint.Uri.ToUri()}', 'subscription' is required when listening to a topic.");
                }

                var topicNames = _handlers.Chains.Select(x => x.MessageType.ToMessageTypeName().ToLower());
                foreach (var name in topicNames)
                {
                    var client = tokenProvider != null
                        ? new SubscriptionClient(connectionString, name, subscriptionName, tokenProvider,
                                                 transportType, receiveMode, retryPolicy)
                        : new SubscriptionClient(connectionString, name, subscriptionName,
                                                 receiveMode, retryPolicy);

                    client.RegisterSessionHandler(handleMessage, options);

                    _clientEntities.Add(client);
                }
            }
            else
            {
                var client = tokenProvider != null
                    ? new SubscriptionClient(connectionString, topicName, subscriptionName, tokenProvider,
                                             transportType, receiveMode, retryPolicy)
                    : new SubscriptionClient(connectionString, topicName, subscriptionName,
                                             receiveMode, retryPolicy);

                client.RegisterSessionHandler(handleMessage, options);

                _clientEntities.Add(client);
            }
        }
        public Task StartAsync(OnSessionMessage messageHandler, OnSessionMessageException exceptionHandler, OnSessionMessageOptions options)
        {
            lock (_initializationLock)
            {
                if (_initialized)
                {
                    throw new MessageReceiverException("Message receiver has already been initialized.");
                }

                if (messageHandler == null)
                {
                    throw new ArgumentNullException("messageHandler");
                }

                if (options == null)
                {
                    options = _defaultOptions;
                }

                // Log.
                ServiceBusEventSource.Log.SessionMessagePumpStart(GetType().Name, Namespace, Path, options.AutoRenewSessionTimeout, options.MaxConcurrentSessions);

                // Initialize the handler options.
                var sessionHandlerOptions = new SessionHandlerOptions();
                sessionHandlerOptions.AutoComplete          = options.AutoComplete;
                sessionHandlerOptions.AutoRenewTimeout      = options.AutoRenewSessionTimeout;
                sessionHandlerOptions.MaxConcurrentSessions = options.MaxConcurrentSessions;
                sessionHandlerOptions.MessageWaitTimeout    = options.MessageWaitTimeout;
                sessionHandlerOptions.ExceptionReceived    += (s, e) =>
                {
                    if (e.Exception != null)
                    {
                        // Log.
                        ServiceBusEventSource.Log.MessagePumpExceptionReceived(Namespace, Path,
                                                                               e.Action, e.Exception);

                        // Handle exception.
                        if (exceptionHandler != null)
                        {
                            exceptionHandler(e.Action, e.Exception);
                        }
                    }
                };

                // Mark receiver as initialized.
                _initialized = true;

                // Start.
                return(OnStartAsync(new SessionMessageAsyncHandlerFactory(Namespace, Path, messageHandler, options), new SessionHandlerOptions
                {
                    AutoComplete = options.AutoComplete,
                    AutoRenewTimeout = options.AutoRenewSessionTimeout,
                    MaxConcurrentSessions = options.MaxConcurrentSessions,
                    MessageWaitTimeout = options.MessageWaitTimeout
                }));
            }
        }
Example #8
0
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 public ServiceBusSessionsOptions() : base()
 {
     SessionHandlerOptions = new SessionHandlerOptions(ExceptionReceivedHandler)
     {
         // SessionHandlerOptions.AutoComplete should be false by default to accomplish session close manually (when any business condition is verified)
         AutoComplete          = false,
         MaxConcurrentSessions = 16
     };
 }
        static void GetMessages()
        {
            var messageOptions = new SessionHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentSessions = 1,
                AutoComplete          = false
            };

            client.RegisterSessionHandler(ProcessMessagesAsync, messageOptions);
        }
Example #10
0
        /// <summary>
        /// Run
        /// </summary>
        public override void Run()
        {
            var eventDrivenMessagingOptions = new SessionHandlerOptions(this.OnExceptionReceived)
            {
                AutoComplete          = true,
                MaxConcurrentSessions = concurrentCalls
            };

            this.reciever.RegisterForEvents(OnMessageArrived, eventDrivenMessagingOptions);
        }
Example #11
0
        async Task OnSessionExceptionHandlerCalledWhenRegisteredOnNonSessionFulSubscription()
        {
            bool exceptionReceivedHandlerCalled = false;
            var  topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedTopicName);
            var  subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicClient.TopicName,
                TestConstants.SubscriptionName,
                ReceiveMode.PeekLock);

            SessionHandlerOptions sessionHandlerOptions = new SessionHandlerOptions(
                (eventArgs) =>
            {
                Assert.NotNull(eventArgs);
                Assert.NotNull(eventArgs.Exception);
                if (eventArgs.Exception is InvalidOperationException)
                {
                    exceptionReceivedHandlerCalled = true;
                }
                return(Task.CompletedTask);
            })
            {
                MaxConcurrentSessions = 1
            };

            subscriptionClient.RegisterSessionHandler(
                (session, message, token) =>
            {
                return(Task.CompletedTask);
            },
                sessionHandlerOptions);

            try
            {
                Stopwatch stopwatch = Stopwatch.StartNew();
                while (stopwatch.Elapsed.TotalSeconds <= 10)
                {
                    if (exceptionReceivedHandlerCalled)
                    {
                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(1));
                }

                TestUtility.Log($"{DateTime.Now}: ExceptionReceivedHandlerCalled: {exceptionReceivedHandlerCalled}");
                Assert.True(exceptionReceivedHandlerCalled);
            }
            finally
            {
                await subscriptionClient.CloseAsync();

                await topicClient.CloseAsync();
            }
        }
        void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Configure the MessageHandler Options in terms of exception handling, number of concurrent messages to deliver etc.
            var sessionHandlerOptions = new SessionHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentSessions = 4,
                AutoComplete          = false
            };

            _queueClient.RegisterSessionHandler(ProcessMessagesAsync, sessionHandlerOptions);
        }
Example #13
0
        public static SessionHandlerOptions GetSessionHandlerOptions(this ClientSettings settings, Func <ExceptionReceivedEventArgs, Task> exceptionHandler)
        {
            var options = new SessionHandlerOptions(exceptionHandler)
            {
                AutoComplete          = false,
                MaxAutoRenewDuration  = settings.MaxAutoRenewDuration,
                MaxConcurrentSessions = settings.MaxConcurrentCalls,
                MessageWaitTimeout    = settings.MessageWaitTimeout
            };

            return(options);
        }
 public TestSessionHandler(
     ReceiveMode receiveMode,
     SessionHandlerOptions sessionHandlerOptions,
     MessageSender sender,
     SessionPumpHost sessionPumpHost)
 {
     this.receiveMode           = receiveMode;
     this.sessionHandlerOptions = sessionHandlerOptions;
     this.sender            = sender;
     this.sessionPumpHost   = sessionPumpHost;
     this.sessionMessageMap = new ConcurrentDictionary <string, int>();
 }
Example #15
0
        /// <summary>
        /// Constructs a new instance.
        /// </summary>
        public ServiceBusOptions()
        {
            // Our default options will delegate to our own exception
            // logger. Customers can override this completely by setting their
            // own MessageHandlerOptions instance.
            MessageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = Utility.GetProcessorCount() * 16
            };

            SessionHandlerOptions = new SessionHandlerOptions(ExceptionReceivedHandler);
        }
        private static void ConsumeSessionedMessages()
        {
            // Similar to MessageHandlerOptions just different for sessions.
            var sessionHandlerOptions = new SessionHandlerOptions(ExceptionHandler)
            {
                AutoComplete          = false,
                MaxConcurrentSessions = 1
            };

            // This is for sessioned messages
            _queueClient.RegisterSessionHandler(ProcessSessionMessageAsync, sessionHandlerOptions);
        }
Example #17
0
        private static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            //var messageHandlerOption = new MessageHandlerOptions(ExceptionReceivedHandlerAsync);
            //subscriptionClient.RegisterMessageHandler(ProcessMessageAsync, messageHandlerOption);
            var sessionHandlerOptions = new SessionHandlerOptions(ExceptionReceivedHandlerAsync)
            {
                MaxConcurrentSessions = 100,
                AutoComplete          = true
            };

            subscriptionClient.RegisterSessionHandler(ProcessMessagesInSessionAsync, sessionHandlerOptions);
        }
Example #18
0
        public Task Start()
        {
            var sessionHandlerOptions = new SessionHandlerOptions(ExceptionHandler)
            {
                MaxConcurrentSessions = 1,
                AutoComplete          = false
            };

            _subscriptionClient.RegisterSessionHandler(
                MessageHandler, sessionHandlerOptions);

            return(Task.CompletedTask);
        }
Example #19
0
        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
            var messageHandlerOptions = new SessionHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentSessions = 100,
                AutoComplete          = true
            };

            // Register the function that processes messages.
            subscriptionClient.RegisterSessionHandler(ProcessMessagesAsync, messageHandlerOptions);
            Console.ReadKey();
        }
Example #20
0
        /// <summary>
        /// Starts listening for session messages on the configured Service Bus Queue.
        /// </summary>
        protected override void ListenForSessionMessages()
        {
            var options = new SessionHandlerOptions();

            if (AutoRenewTimeout.HasValue)
            {
                options.AutoRenewTimeout = AutoRenewTimeout.Value;
            }
            if (MaxConcurrentSessions.HasValue)
            {
                options.MaxConcurrentSessions = MaxConcurrentSessions.Value;
            }
            ServiceBusClient.RegisterSessionHandlerFactory(new SessionHandlerFactory(this), options);
        }
        public static SessionHandlerOptions GetSessionHandlerOptions(this ClientSettings settings, EventHandler <ExceptionReceivedEventArgs> exceptionHandler)
        {
            var options = new SessionHandlerOptions
            {
                AutoComplete          = false,
                AutoRenewTimeout      = settings.AutoRenewTimeout,
                MaxConcurrentSessions = settings.MaxConcurrentCalls,
                MessageWaitTimeout    = settings.MessageWaitTimeout
            };

            options.ExceptionReceived += exceptionHandler;

            return(options);
        }
        public async Task OnSessionExceptionHandlerCalledWhenRegisteredOnNonSessionFulQueue()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                var exceptionReceivedHandlerCalled = false;
                var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName);

                try
                {
                    var sessionHandlerOptions = new SessionHandlerOptions(
                        (eventArgs) =>
                    {
                        Assert.NotNull(eventArgs);
                        Assert.NotNull(eventArgs.Exception);
                        if (eventArgs.Exception is InvalidOperationException)
                        {
                            exceptionReceivedHandlerCalled = true;
                        }
                        return(Task.CompletedTask);
                    })
                    {
                        MaxConcurrentSessions = 1
                    };

                    queueClient.RegisterSessionHandler(
                        (session, message, token) =>
                    {
                        return(Task.CompletedTask);
                    },
                        sessionHandlerOptions);

                    var stopwatch = Stopwatch.StartNew();
                    while (stopwatch.Elapsed.TotalSeconds <= 10)
                    {
                        if (exceptionReceivedHandlerCalled)
                        {
                            break;
                        }

                        await Task.Delay(TimeSpan.FromSeconds(1));
                    }

                    Assert.True(exceptionReceivedHandlerCalled);
                }
                finally
                {
                    await queueClient.CloseAsync();
                }
            });
        }
Example #23
0
        static void ReadMessageWithSessionHandler()
        {
            var queueClient = QueueClient.CreateFromConnectionString(sbConnectionString, queueName);

            var sessionOptions = new SessionHandlerOptions()
            {
                AutoComplete          = false,
                AutoRenewTimeout      = TimeSpan.FromSeconds(30),
                MaxConcurrentSessions = 1,
                MessageWaitTimeout    = TimeSpan.FromSeconds(10)
            };

            queueClient.RegisterSessionHandler(typeof(MessageSessionHandler), sessionOptions);
        }
        public Task StartAsync(OnSessionMessage messageHandler, OnSessionMessageException exceptionHandler, OnSessionMessageOptions options)
        {
            lock (_initializationLock)
            {
                if (_initialized)
                    throw new MessageReceiverException("Message receiver has already been initialized.");

                if (messageHandler == null)
                    throw new ArgumentNullException("messageHandler");

                if (options == null)
                    options = new OnSessionMessageOptions();

                // Log.
                ServiceBusEventSource.Log.StartSessionMessageReceiver(GetType().Name, Namespace, Path);

                // Initialize the handler options.
                var sessionHandlerOptions = new SessionHandlerOptions();
                sessionHandlerOptions.AutoComplete = options.AutoComplete;
                sessionHandlerOptions.AutoRenewTimeout = options.AutoRenewSessionTimeout;
                sessionHandlerOptions.MaxConcurrentSessions = options.MaxConcurrentSessions;
                sessionHandlerOptions.MessageWaitTimeout = options.MessageWaitTimeout;
                sessionHandlerOptions.ExceptionReceived += (s, e) => 
                {
                    if (e.Exception != null)
                    {
                        // Log.
                        ServiceBusEventSource.Log.SessionMessageReceiverException(Namespace, Path,
                            null, null, null, e.Action, e.Exception.Message, e.Exception.StackTrace);

                        // Handle exception.
                        if (exceptionHandler != null)
                            exceptionHandler(e.Action, e.Exception);
                    }
                };

                // Mark receiver as initialized.
                _initialized = true;

                // Start.
                return OnStartAsync(new SessionMessageAsyncHandlerFactory(Namespace, Path, messageHandler, options), new SessionHandlerOptions
                {
                    AutoComplete = options.AutoComplete,
                    AutoRenewTimeout = options.AutoRenewSessionTimeout,
                    MaxConcurrentSessions = options.MaxConcurrentSessions,
                    MessageWaitTimeout = options.MessageWaitTimeout
                });
            }
        }
Example #25
0
        static QueueClient InitializeReceiver(string connectionString, string queueName)
        {
            var client = new QueueClient(connectionString, queueName, ReceiveMode.PeekLock);

            var sessionHandlerOptions = new SessionHandlerOptions(e => LogMessageHandlerException(e))
            {
                MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                MaxConcurrentSessions = 1,
                AutoComplete          = false
            };

            client.RegisterSessionHandler(HandleSessionMessage, sessionHandlerOptions);

            return(client);
        }
        public async Task OnSessionCanStartWithNullMessageButReturnSessionLater()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : true, async queueName =>
            {
                var queueClient = new QueueClient(
                    TestUtility.NamespaceConnectionString,
                    queueName,
                    ReceiveMode.PeekLock);
                try
                {
                    var sessionHandlerOptions =
                        new SessionHandlerOptions(ExceptionReceivedHandler)
                    {
                        MaxConcurrentSessions = 5,
                        MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                        AutoComplete          = true
                    };

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

                    // Register handler first without any messages
                    testSessionHandler.RegisterSessionHandler(sessionHandlerOptions);

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

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

                    // Clear the data and re-run the scenario.
                    testSessionHandler.ClearData();
                    await testSessionHandler.SendSessionMessages();

                    // Verify messages were received.
                    await testSessionHandler.VerifyRun();
                }
                finally
                {
                    await queueClient.CloseAsync();
                }
            });
        }
        public SessionReceiver(QueueClient queueClient, Uri inputAddress, IPipe <ReceiveContext> receivePipe, ReceiveSettings receiveSettings,
                               IReceiveObserver receiveObserver, ITaskSupervisor supervisor)
        {
            _queueClient     = queueClient;
            _inputAddress    = inputAddress;
            _receivePipe     = receivePipe;
            _receiveSettings = receiveSettings;
            _receiveObserver = receiveObserver;

            _participant = supervisor.CreateParticipant($"{TypeMetadataCache<Receiver>.ShortName} - {inputAddress}", Stop);

            var options = new SessionHandlerOptions
            {
                AutoComplete          = false,
                AutoRenewTimeout      = receiveSettings.AutoRenewTimeout,
                MaxConcurrentSessions = receiveSettings.MaxConcurrentCalls,
                MessageWaitTimeout    = receiveSettings.MessageWaitTimeout
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (!(x.Exception is OperationCanceledException))
                {
                    if (_log.IsErrorEnabled)
                    {
                        _log.Error($"Exception received on session receiver: {_inputAddress} during {x.Action}", x.Exception);
                    }
                }

                if (_currentPendingDeliveryCount == 0)
                {
                    if (_log.IsDebugEnabled)
                    {
                        _log.DebugFormat("Session receiver shutdown completed: {0}", _inputAddress);
                    }

                    _participant.SetComplete();
                }
            };

            IMessageSessionAsyncHandlerFactory handlerFactory = new MessageSessionAsyncHandlerFactory(supervisor, this);

            queueClient.RegisterSessionHandlerFactoryAsync(handlerFactory, options);

            _participant.SetReady();
        }
Example #28
0
        public SessionReceiver(QueueClient queueClient, Uri inputAddress, IPipe<ReceiveContext> receivePipe, ReceiveSettings receiveSettings,
            IReceiveObserver receiveObserver, ITaskSupervisor supervisor)
        {
            _queueClient = queueClient;
            _inputAddress = inputAddress;
            _receivePipe = receivePipe;
            _receiveSettings = receiveSettings;
            _receiveObserver = receiveObserver;
            _supervisor = supervisor;

            _participant = supervisor.CreateParticipant();

            var options = new SessionHandlerOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = receiveSettings.AutoRenewTimeout,
                MaxConcurrentSessions = receiveSettings.MaxConcurrentCalls,
                MessageWaitTimeout = receiveSettings.MessageWaitTimeout
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (!(x.Exception is OperationCanceledException))
                {
                    if (_log.IsErrorEnabled)
                        _log.Error($"Exception received on session receiver: {_inputAddress} during {x.Action}", x.Exception);
                }

                if (_currentPendingDeliveryCount == 0)
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Session receiver shutdown completed: {0}", _inputAddress);

                    _participant.SetComplete();
                }
            };

            IMessageSessionAsyncHandlerFactory handlerFactory = new MessageSessionAsyncHandlerFactory(supervisor, this);
            queueClient.RegisterSessionHandlerFactoryAsync(handlerFactory, options);

            _participant.SetReady();

            SetupStopTask();
        }
Example #29
0
        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 = 5,
                        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();
                }
                finally
                {
                    await subscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                }
            });
        }
        async Task OnSessionCanStartWithNullMessageButReturnSessionLater()
        {
            var queueClient = new QueueClient(
                TestUtility.NamespaceConnectionString,
                TestConstants.SessionNonPartitionedQueueName,
                ReceiveMode.PeekLock);

            try
            {
                SessionHandlerOptions handlerOptions =
                    new SessionHandlerOptions()
                {
                    MaxConcurrentSessions = 5,
                    MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                    AutoComplete          = true
                };

                TestSessionHandler testSessionHandler = new TestSessionHandler(
                    queueClient.ReceiveMode,
                    handlerOptions,
                    queueClient.InnerSender,
                    queueClient.SessionPumpHost);

                // Register handler first without any messages
                testSessionHandler.RegisterSessionHandler(handlerOptions);

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

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

                // Clear the data and re-run the scenario.
                testSessionHandler.ClearData();
                await testSessionHandler.SendSessionMessages();

                // Verify messages were received.
                await testSessionHandler.VerifyRun();
            }
            finally
            {
                await queueClient.CloseAsync();
            }
        }
Example #31
0
        public Task StartReceivingMessages()
        {
            queueClient = ServiceBusCommandQueueSender.CreateQueueClient(settings);

            var options = new SessionHandlerOptions
            {
                AutoComplete       = false,
                MessageWaitTimeout = TimeSpan.FromSeconds(3)
            };

            if (settings.MaxConcurrentSessions != null)
            {
                options.MaxConcurrentSessions = settings.MaxConcurrentSessions.Value;
            }

            options.ExceptionReceived += (sender, e) => exceptionSubject.OnNext(e.Exception);

            return(queueClient.RegisterSessionHandlerFactoryAsync(this, options));
        }
Example #32
0
        public void Register(CancellationToken stoppingToken)
        {
            IQueueClient client = _factory.Create();

            stoppingToken.Register(async() =>
            {
                _logger.LogInformation("StopListeningAsync");
                if (!client.IsClosedOrClosing)
                {
                    _logger.LogInformation("IQueueClient : close");
                    await client.CloseAsync();
                }
            });

            _logger.LogInformation("Sending session messages...");
            var s  = Guid.NewGuid().ToString();
            var m0 = new Message(Encoding.UTF8.GetBytes("0"));

            m0.SessionId = s;
            client.SendAsync(m0).GetAwaiter().GetResult();

            var m1 = new Message(Encoding.UTF8.GetBytes("1"));

            m1.SessionId = s;
            client.SendAsync(m1).GetAwaiter().GetResult();

            var m2 = new Message(Encoding.UTF8.GetBytes("2"));

            m2.SessionId = s;
            client.SendAsync(m2).GetAwaiter().GetResult();

            _logger.LogInformation("Waiting for 3 secs...");
            Task.Delay(TimeSpan.FromSeconds(3), stoppingToken).GetAwaiter().GetResult(); // simulate delay

            var sessionHandlerOptions = new SessionHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentSessions = 1,
                MessageWaitTimeout    = TimeSpan.FromSeconds(30),
                AutoComplete          = false
            };

            client.RegisterSessionHandler((session, message, cancellationToken) => ProcessMessageAsync(client, session, message, cancellationToken), sessionHandlerOptions);
        }
        public Task StartReceivingMessages()
        {
            queueClient = ServiceBusCommandQueueSender.CreateQueueClient(settings);

            var options = new SessionHandlerOptions
            {
                AutoComplete = false,
                MessageWaitTimeout = TimeSpan.FromSeconds(3)
            };

            if (settings.MaxConcurrentSessions != null)
            {
                options.MaxConcurrentSessions = settings.MaxConcurrentSessions.Value;
            }

            options.ExceptionReceived += (sender, e) => exceptionSubject.OnNext(e.Exception);

            return queueClient.RegisterSessionHandlerFactoryAsync(this, options);
        }
 private SessionHandlerOptions GetSessionHandlerOptions()
 {
     // Initialize message pump options
     var options = new SessionHandlerOptions
     {
         // Indicates if the message-pump should call complete on messages after the callback has completed processing.
         AutoComplete = checkBoxAutoComplete.Checked,
         // Gets or sets the maximum number of existing sessions.
         MaxConcurrentSessions = txtMaxConcurrentCalls.IntegerValue,
         // Gets or sets the time needed before the session renew its state.
         AutoRenewTimeout = TimeSpan.FromSeconds(30),
         // Gets or sets the time needed before the message waiting expires.
         MessageWaitTimeout  = TimeSpan.FromSeconds(30)
     };
     // Allows to get notified of any errors encountered by the message pump
     options.ExceptionReceived += LogErrors;
     return options;
 }
        public async Task Start(NamespaceContext context)
        {
            var options = new SessionHandlerOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = _clientSettings.AutoRenewTimeout,
                MaxConcurrentSessions = _clientSettings.MaxConcurrentCalls,
                MessageWaitTimeout = _clientSettings.MessageWaitTimeout
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (!(x.Exception is OperationCanceledException))
                {
                    if (_log.IsErrorEnabled)
                        _log.Error($"Exception received on session receiver: {_clientContext.InputAddress} during {x.Action}", x.Exception);
                }

                if (_tracker.ActiveDeliveryCount == 0)
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Session receiver shutdown completed: {0}", _clientContext.InputAddress);

                    _participant.SetComplete();
                }
            };

            IMessageSessionAsyncHandlerFactory handlerFactory = new MessageSessionAsyncHandlerFactory(context, _supervisor, this, _tracker, _sendEndpointProvider, _publishEndpointProvider);

            await _clientContext.RegisterSessionHandlerFactoryAsync(handlerFactory, options).ConfigureAwait(false);

            _participant.SetReady();
        }
 public Task RegisterSessionHandlerFactoryAsync(IMessageSessionAsyncHandlerFactory factory, SessionHandlerOptions options)
 {
     return _client.RegisterSessionHandlerFactoryAsync(factory, options);
 }
 internal abstract Task OnStartAsync(SessionMessageAsyncHandlerFactory sessionMessageAsyncHandlerFactory, SessionHandlerOptions sessionHandlerOptions);
Example #38
0
 /// <summary>
 /// Start the handler.
 /// </summary>
 /// <param name="sessionMessageAsyncHandlerFactory"></param>
 /// <param name="sessionHandlerOptions"></param>
 /// <returns></returns>
 internal override Task OnStartAsync(SessionMessageAsyncHandlerFactory sessionMessageAsyncHandlerFactory, SessionHandlerOptions sessionHandlerOptions)
 {
     return _client.RegisterSessionHandlerFactoryAsync(sessionMessageAsyncHandlerFactory, sessionHandlerOptions);
 }