public ReceiverPrepareState(ReceiverContext <T> logContext)
 {
     this._ctx    = logContext;
     _logTypes[0] = enLogType.API;
     _logTypes[1] = enLogType.BO;
     _logTypes[2] = enLogType.System;
 }
        public void ScenarioSetup()
        {
            this._senders  = new List <SenderContext <object> >();
            this._receiver = new ReceiverContext <object>();

            this._checker = new Rediser(_redisConString);
        }
        public void AReceiverHasBeenInitiated()
        {
            this._receiver = new ReceiverContext <object>();
            this._receiver.MsgConnection  = new Rediser(_redisConString, SerializerType.NewtonJson);
            this._receiver.DataConnection = new Rediser(_redisConString, SerializerType.NewtonJson);

            this._receiver.Initial();
        }
Exemplo n.º 4
0
 public void Initial()
 {
     this._ctx = new ReceiverContext <object>();
     this._ctx.MsgConnection  = Substitute.For <IRediser>();
     this._ctx.DataConnection = Substitute.For <IRediser>();
     this._ctx.DB             = Substitute.For <IDBer>();
     this._ctx.ES             = Substitute.For <IESer>();
 }
        private async Task ProcessMessages(ReceiverContext receiverContext)
        {
            TimeSpan backoffAmount = _backoffTime;

            while (!_cts.IsCancellationRequested)
            {
                try
                {
                    var messages = await receiverContext.Receiver.ReceiveBatchAsync(
                        ReceiverContext.ReceiveBatchSize, receiverContext.ReceiveTimeout);

                    receiverContext.OnMessage(messages);

                    // Reset the receive timeout if it changed
                    receiverContext.ReceiveTimeout = DefaultReadTimeout;

                    continue;
                }
                catch (OperationCanceledException)
                {
                    // This means the channel is closed
                    _trace.TraceError("Receiving messages from the service bus threw an OperationCanceledException, most likely due to a closed channel.");
                    return;
                }
                catch (MessagingEntityNotFoundException ex)
                {
                    try
                    {
                        await receiverContext.Receiver.CloseAsync();
                    }
                    catch { }

                    receiverContext.OnError(ex);
                    var ignored = TryCreateSubscription(receiverContext);
                    return;
                }
                catch (ServerBusyException ex)
                {
                    receiverContext.OnError(ex);
                }
                catch (Exception ex)
                {
                    receiverContext.OnError(ex);

                    // TODO: Exponential backoff
                    backoffAmount = ErrorBackOffAmount;

                    // After an error, we want to adjust the timeout so that we
                    // can recover as quickly as possible even if there's no message
                    receiverContext.ReceiveTimeout = ErrorReadTimeout;
                }

                // back off for ServerBusyException and other exceptions not handled is a specific way
                await Task.Delay(backoffAmount);
            }
        }
        private void CreateSubscription(ServiceBusConnectionContext connectionContext, int topicIndex)
        {
            lock (connectionContext.SubscriptionsLock)
            {
                if (connectionContext.IsDisposed)
                {
                    return;
                }

                string topicName = connectionContext.TopicNames[topicIndex];

                // Create a random subscription
                string subscriptionName = Guid.NewGuid().ToString();

                try
                {
                    var subscriptionDescription = new SubscriptionDescription(topicName, subscriptionName);

                    // This cleans up the subscription while if it's been idle for more than the timeout.
                    subscriptionDescription.AutoDeleteOnIdle = _idleSubscriptionTimeout;

                    _namespaceManager.CreateSubscription(subscriptionDescription);

                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} in the service bus completed successfully.", subscriptionName, topicName);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // The entity already exists
                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} threw an MessagingEntityAlreadyExistsException.", subscriptionName, topicName);
                }

                // Create a receiver to get messages
                string          subscriptionEntityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName);
                MessageReceiver receiver = _factory.CreateMessageReceiver(subscriptionEntityPath, ReceiveMode.ReceiveAndDelete);

                _trace.TraceInformation("Creation of a message receive for subscription entity path {0} in the service bus completed successfully.", subscriptionEntityPath);

                connectionContext.SetSubscriptionContext(new SubscriptionContext(topicName, subscriptionName, receiver), topicIndex);

                var receiverContext = new ReceiverContext(topicIndex, receiver, connectionContext);

                var task = Task.Run(() => ProcessMessages(receiverContext));
                _processMessagesTasks.GetOrAdd(task, false);
                task.ContinueWith(t =>
                {
                    bool value;
                    _processMessagesTasks.TryRemove(task, out value);
                });

                // Open the stream
                connectionContext.OpenStream(topicIndex);
            }
        }
Exemplo n.º 7
0
        private bool ContinueReceiving(IAsyncResult asyncResult, ReceiverContext receiverContext)
        {
            bool     shouldContinue = true;
            TimeSpan backoffAmount  = BackoffAmount;

            try
            {
                IEnumerable <BrokeredMessage> messages = receiverContext.Receiver.EndReceiveBatch(asyncResult);

                receiverContext.OnMessage(messages);

                // Reset the receive timeout if it changed
                receiverContext.ReceiveTimeout = DefaultReadTimeout;
            }
            catch (ServerBusyException ex)
            {
                receiverContext.OnError(ex);

                // Too busy so back off
                shouldContinue = false;
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                _trace.TraceError("Receiving messages from the service bus threw an OperationCanceledException, most likely due to a closed channel.");

                return(false);
            }
            catch (Exception ex)
            {
                receiverContext.OnError(ex);

                shouldContinue = false;

                // TODO: Exponential backoff
                backoffAmount = ErrorBackOffAmount;

                // After an error, we want to adjust the timeout so that we
                // can recover as quickly as possible even if there's no message
                receiverContext.ReceiveTimeout = ErrorReadTimeout;
            }

            if (!shouldContinue)
            {
                TaskAsyncHelper.Delay(backoffAmount)
                .Then(ctx => ProcessMessages(ctx), receiverContext);

                return(false);
            }

            return(true);
        }
        public void InitiateMulti_Receiver()
        {
            ReceiverContext <object> receiverA = new ReceiverContext <object>(),
                                     receiverB = new ReceiverContext <object>();

            receiverA.MsgConnection  = new Rediser(_redisConString, SerializerType.NewtonJson);
            receiverA.DataConnection = new Rediser(_redisConString, SerializerType.NewtonJson);

            receiverB.MsgConnection  = new Rediser(_redisConString, SerializerType.NewtonJson);
            receiverB.DataConnection = new Rediser(_redisConString, SerializerType.NewtonJson);

            receiverA.Initial();
            receiverB.Initial();

            this._receivers.Add(receiverA);
            this._receivers.Add(receiverB);
        }
Exemplo n.º 9
0
        private void ProcessMessages(ReceiverContext receiverContext)
        {
receive:

            try
            {
                IAsyncResult result = receiverContext.Receiver.BeginReceiveBatch(ReceiverContext.ReceiveBatchSize, receiverContext.ReceiveTimeout, ar =>
                {
                    if (ar.CompletedSynchronously)
                    {
                        return;
                    }

                    var ctx = (ReceiverContext)ar.AsyncState;

                    if (ContinueReceiving(ar, ctx))
                    {
                        ProcessMessages(ctx);
                    }
                },
                                                                                 receiverContext);

                if (result.CompletedSynchronously)
                {
                    if (ContinueReceiving(result, receiverContext))
                    {
                        goto receive;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                _trace.TraceError("OperationCanceledException was thrown in trying to receive the message from the service bus.");

                return;
            }
            catch (Exception ex)
            {
                _trace.TraceError(ex.Message);
                receiverContext.OnError(ex);

                Thread.Sleep(RetryDelay);
                goto receive;
            }
        }
Exemplo n.º 10
0
        private void ProcessMessages(ReceiverContext receiverContext)
        {
receive:

            try
            {
                IAsyncResult result = receiverContext.Receiver.BeginReceiveBatch(receiverContext.ReceiveBatchSize, receiverContext.ReceiveTimeout, ar =>
                {
                    if (ar.CompletedSynchronously)
                    {
                        return;
                    }

                    var ctx = (ReceiverContext)ar.AsyncState;

                    if (ContinueReceiving(ar, ctx))
                    {
                        ProcessMessages(ctx);
                    }
                },
                                                                                 receiverContext);

                if (result.CompletedSynchronously)
                {
                    if (ContinueReceiving(result, receiverContext))
                    {
                        goto receive;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                return;
            }
            catch (Exception ex)
            {
                receiverContext.OnError(ex);

                // REVIEW: What should we do here?
            }
        }
Exemplo n.º 11
0
        private bool ContinueReceiving(IAsyncResult asyncResult, ReceiverContext receiverContext)
        {
            bool shouldContinue = true;
            TimeSpan backoffAmount = BackoffAmount;

            try
            {
                IEnumerable<BrokeredMessage> messages = receiverContext.Receiver.EndReceiveBatch(asyncResult);

                receiverContext.OnMessage(messages);

                // Reset the receive timeout if it changed
                receiverContext.ReceiveTimeout = DefaultReadTimeout;
            }
            catch (ServerBusyException ex)
            {
                receiverContext.OnError(ex);

                // Too busy so back off
                shouldContinue = false;
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                _trace.TraceError("Receiving messages from the service bus threw an OperationCanceledException, most likely due to a closed channel.");

                return false;
            }
            catch (MessagingEntityNotFoundException ex)
            {
                receiverContext.Receiver.CloseAsync().Catch();
                receiverContext.OnError(ex);

                TaskAsyncHelper.Delay(RetryDelay)
                               .Then(() => Retry(() => CreateSubscription(receiverContext.ConnectionContext, receiverContext.TopicIndex)));
                return false;
            }
            catch (Exception ex)
            {
                receiverContext.OnError(ex);

                shouldContinue = false;

                // TODO: Exponential backoff
                backoffAmount = ErrorBackOffAmount;

                // After an error, we want to adjust the timeout so that we
                // can recover as quickly as possible even if there's no message
                receiverContext.ReceiveTimeout = ErrorReadTimeout;
            }

            if (!shouldContinue)
            {
                TaskAsyncHelper.Delay(backoffAmount)
                               .Then(ctx => ProcessMessages(ctx), receiverContext);

                return false;
            }

            return true;
        }
Exemplo n.º 12
0
        private void ProcessMessages(ReceiverContext receiverContext)
        {
        receive:

            try
            {
                IAsyncResult result = receiverContext.Receiver.BeginReceiveBatch(ReceiverContext.ReceiveBatchSize, receiverContext.ReceiveTimeout, ar =>
                {
                    if (ar.CompletedSynchronously)
                    {
                        return;
                    }

                    var ctx = (ReceiverContext)ar.AsyncState;

                    if (ContinueReceiving(ar, ctx))
                    {
                        ProcessMessages(ctx);
                    }
                },
                receiverContext);

                if (result.CompletedSynchronously)
                {
                    if (ContinueReceiving(result, receiverContext))
                    {
                        goto receive;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                _trace.TraceError("OperationCanceledException was thrown in trying to receive the message from the service bus.");

                return;
            }
            catch (Exception ex)
            {
                _trace.TraceError(ex.Message);
                receiverContext.OnError(ex);

                Thread.Sleep(RetryDelay);
                goto receive;
            }
        }
Exemplo n.º 13
0
        private void CreateSubscription(ServiceBusConnectionContext connectionContext, int topicIndex)
        {
            lock (connectionContext.SubscriptionsLock)
            {
                if (connectionContext.IsDisposed)
                {
                    return;
                }

                string topicName = connectionContext.TopicNames[topicIndex];

                // Create a random subscription
                string subscriptionName = Guid.NewGuid().ToString();

                try
                {
                    var subscriptionDescription = new SubscriptionDescription(topicName, subscriptionName);

                    // This cleans up the subscription while if it's been idle for more than the timeout.
                    subscriptionDescription.AutoDeleteOnIdle = _idleSubscriptionTimeout;

                    _namespaceManager.CreateSubscription(subscriptionDescription);

                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} in the service bus completed successfully.", subscriptionName, topicName);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // The entity already exists
                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} threw an MessagingEntityAlreadyExistsException.", subscriptionName, topicName);
                }

                // Create a receiver to get messages
                string subscriptionEntityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName);
                MessageReceiver receiver = _factory.CreateMessageReceiver(subscriptionEntityPath, ReceiveMode.ReceiveAndDelete);

                _trace.TraceInformation("Creation of a message receive for subscription entity path {0} in the service bus completed successfully.", subscriptionEntityPath);

                connectionContext.SetSubscriptionContext(new SubscriptionContext(topicName, subscriptionName, receiver), topicIndex);

                var receiverContext = new ReceiverContext(topicIndex, receiver, connectionContext);

                ProcessMessages(receiverContext);

                // Open the stream
                connectionContext.OpenStream(topicIndex);
            }
        }
Exemplo n.º 14
0
        public ServiceBusSubscription Subscribe(IList<string> topicNames,
                                                Action<int, IEnumerable<BrokeredMessage>> handler,
                                                Action<int, Exception> errorHandler)
        {
            if (topicNames == null)
            {
                throw new ArgumentNullException("topicNames");
            }

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

            _trace.TraceInformation("Subscribing to {0} topic(s) in the service bus...", topicNames.Count);

            var subscriptions = new ServiceBusSubscription.SubscriptionContext[topicNames.Count];
            var clients = new TopicClient[topicNames.Count];

            for (var topicIndex = 0; topicIndex < topicNames.Count; ++topicIndex)
            {
                string topicName = topicNames[topicIndex];

                if (!_namespaceManager.TopicExists(topicName))
                {
                    try
                    {
                        _trace.TraceInformation("Creating a new topic {0} in the service bus...", topicName);

                        _namespaceManager.CreateTopic(topicName);

                        _trace.TraceInformation("Creation of a new topic {0} in the service bus completed successfully.", topicName);
                    }
                    catch (MessagingEntityAlreadyExistsException)
                    {
                        // The entity already exists
                        _trace.TraceInformation("Creation of a new topic {0} threw an MessagingEntityAlreadyExistsException.", topicName);
                    }
                }

                // Create a client for this topic
                clients[topicIndex] = TopicClient.CreateFromConnectionString(_configuration.ConnectionString, topicName);

                _trace.TraceInformation("Creation of a new topic client {0} completed successfully.", topicName);

                // Create a random subscription
                string subscriptionName = Guid.NewGuid().ToString();

                try
                {
                    var subscriptionDescription = new SubscriptionDescription(topicName, subscriptionName);

                    // This cleans up the subscription while if it's been idle for more than the timeout.
                    subscriptionDescription.AutoDeleteOnIdle = IdleSubscriptionTimeout;

                    _namespaceManager.CreateSubscription(subscriptionDescription);

                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} in the service bus completed successfully.", subscriptionName, topicName);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // The entity already exists
                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} threw an MessagingEntityAlreadyExistsException.", subscriptionName, topicName);
                }

                // Create a receiver to get messages
                string subscriptionEntityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName);
                MessageReceiver receiver = _factory.CreateMessageReceiver(subscriptionEntityPath, ReceiveMode.ReceiveAndDelete);

                _trace.TraceInformation("Creation of a message receive for subscription entity path {0} in the service bus completed successfully.", subscriptionEntityPath);

                subscriptions[topicIndex] = new ServiceBusSubscription.SubscriptionContext(topicName, subscriptionName, receiver);

                var receiverContext = new ReceiverContext(topicIndex, receiver, handler, errorHandler);

                ProcessMessages(receiverContext);
            }

            _trace.TraceInformation("Subscription to {0} topics in the service bus Topic service completed successfully.", topicNames.Count);

            return new ServiceBusSubscription(_configuration, _namespaceManager, subscriptions, clients);
        }
Exemplo n.º 15
0
        public ServiceBusSubscription Subscribe(IList <string> topicNames,
                                                Action <int, IEnumerable <BrokeredMessage> > handler,
                                                Action <int, Exception> errorHandler)
        {
            if (topicNames == null)
            {
                throw new ArgumentNullException("topicNames");
            }

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

            _trace.TraceInformation("Subscribing to {0} topic(s) in the service bus...", topicNames.Count);

            var subscriptions = new ServiceBusSubscription.SubscriptionContext[topicNames.Count];
            var clients       = new TopicClient[topicNames.Count];

            for (var topicIndex = 0; topicIndex < topicNames.Count; ++topicIndex)
            {
                string topicName = topicNames[topicIndex];

                if (!_namespaceManager.TopicExists(topicName))
                {
                    try
                    {
                        _trace.TraceInformation("Creating a new topic {0} in the service bus...", topicName);

                        _namespaceManager.CreateTopic(topicName);

                        _trace.TraceInformation("Creation of a new topic {0} in the service bus completed successfully.", topicName);
                    }
                    catch (MessagingEntityAlreadyExistsException)
                    {
                        // The entity already exists
                        _trace.TraceInformation("Creation of a new topic {0} threw an MessagingEntityAlreadyExistsException.", topicName);
                    }
                }

                // Create a client for this topic
                clients[topicIndex] = TopicClient.CreateFromConnectionString(_configuration.ConnectionString, topicName);

                _trace.TraceInformation("Creation of a new topic client {0} completed successfully.", topicName);

                // Create a random subscription
                string subscriptionName = Guid.NewGuid().ToString();

                try
                {
                    var subscriptionDescription = new SubscriptionDescription(topicName, subscriptionName);

                    // This cleans up the subscription while if it's been idle for more than the timeout.
                    subscriptionDescription.AutoDeleteOnIdle = IdleSubscriptionTimeout;

                    _namespaceManager.CreateSubscription(subscriptionDescription);

                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} in the service bus completed successfully.", subscriptionName, topicName);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // The entity already exists
                    _trace.TraceInformation("Creation of a new subscription {0} for topic {1} threw an MessagingEntityAlreadyExistsException.", subscriptionName, topicName);
                }

                // Create a receiver to get messages
                string          subscriptionEntityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName);
                MessageReceiver receiver = _factory.CreateMessageReceiver(subscriptionEntityPath, ReceiveMode.ReceiveAndDelete);

                _trace.TraceInformation("Creation of a message receive for subscription entity path {0} in the service bus completed successfully.", subscriptionEntityPath);

                subscriptions[topicIndex] = new ServiceBusSubscription.SubscriptionContext(topicName, subscriptionName, receiver);

                var receiverContext = new ReceiverContext(topicIndex, receiver, handler, errorHandler);

                ProcessMessages(receiverContext);
            }

            _trace.TraceInformation("Subscription to {0} topics in the service bus Topic service completed successfully.", topicNames.Count);

            return(new ServiceBusSubscription(_configuration, _namespaceManager, subscriptions, clients));
        }
Exemplo n.º 16
0
        public ServiceBusSubscription Subscribe(IList <string> topicNames,
                                                Action <int, IEnumerable <BrokeredMessage> > handler,
                                                Action <int, Exception> errorHandler)
        {
            if (topicNames == null)
            {
                throw new ArgumentNullException("topicNames");
            }

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

            var subscriptions = new ServiceBusSubscription.SubscriptionContext[topicNames.Count];
            var clients       = new TopicClient[topicNames.Count];

            for (var topicIndex = 0; topicIndex < topicNames.Count; ++topicIndex)
            {
                string topicName = topicNames[topicIndex];

                if (!_namespaceManager.TopicExists(topicName))
                {
                    try
                    {
                        _namespaceManager.CreateTopic(topicName);
                    }
                    catch (MessagingEntityAlreadyExistsException)
                    {
                        // The entity already exists
                    }
                }

                // Create a client for this topic
                clients[topicIndex] = TopicClient.CreateFromConnectionString(_configuration.ConnectionString, topicName);

                // Create a random subscription
                string subscriptionName = Guid.NewGuid().ToString();

                try
                {
                    _namespaceManager.CreateSubscription(topicName, subscriptionName);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // The entity already exists
                }

                // Create a receiver to get messages
                string          subscriptionEntityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName);
                MessageReceiver receiver = _factory.CreateMessageReceiver(subscriptionEntityPath, ReceiveMode.ReceiveAndDelete);

                subscriptions[topicIndex] = new ServiceBusSubscription.SubscriptionContext(topicName, subscriptionName, receiver);

                var receiverContext = new ReceiverContext(topicIndex, receiver, handler, errorHandler);

                ProcessMessages(receiverContext);
            }

            return(new ServiceBusSubscription(_configuration, _namespaceManager, subscriptions, clients));
        }
Exemplo n.º 17
0
 public ReceiverItem(ReceiverContext <DTO> _receiver)
 {
     this._receiver = _receiver;
 }
Exemplo n.º 18
0
 public ReceiverInitialState(ReceiverContext <T> logContext)
 {
     _ctx = logContext;
 }
        private bool ContinueReceiving(IAsyncResult asyncResult, ReceiverContext receiverContext)
        {
            bool     shouldContinue = true;
            TimeSpan backoffAmount  = _backoffTime;

            try
            {
                IEnumerable <BrokeredMessage> messages = receiverContext.Receiver.EndReceiveBatch(asyncResult);

                receiverContext.OnMessage(messages);

                // Reset the receive timeout if it changed
                receiverContext.ReceiveTimeout = DefaultReadTimeout;
            }
            catch (ServerBusyException ex)
            {
                receiverContext.OnError(ex);

                // Too busy so back off
                shouldContinue = false;
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                _logger.LogError("Receiving messages from the service bus threw an OperationCanceledException, most likely due to a closed channel.");

                return(false);
            }
            catch (MessagingEntityNotFoundException ex)
            {
                receiverContext.Receiver.CloseAsync()
                .ContinueWith(t => _logger.LogInformation("{0}", t.Exception.ToString()), TaskContinuationOptions.OnlyOnFaulted);
                receiverContext.OnError(ex);

                Task.Run(async() =>
                {
                    await Task.Delay(RetryDelay);
                    Retry(() => CreateSubscription(receiverContext.ConnectionContext, receiverContext.TopicIndex));
                });

                return(false);
            }
            catch (Exception ex)
            {
                receiverContext.OnError(ex);

                shouldContinue = false;

                // TODO: Exponential backoff
                backoffAmount = ErrorBackOffAmount;

                // After an error, we want to adjust the timeout so that we
                // can recover as quickly as possible even if there's no message
                receiverContext.ReceiveTimeout = ErrorReadTimeout;
            }

            if (!shouldContinue)
            {
                Task.Run(async() =>
                {
                    await Task.Delay(backoffAmount);
                    ProcessMessages(receiverContext);
                });

                return(false);
            }

            return(true);
        }
Exemplo n.º 20
0
 public ReceiverProcessState(ReceiverContext <T> logContext)
 {
     this._ctx = logContext;
 }
        private async Task TryCreateSubscription(ReceiverContext receiverContext)
        {
            await Task.Delay(RetryDelay);

            Retry(() => CreateSubscription(receiverContext.ConnectionContext, receiverContext.TopicIndex));
        }
        private bool ContinueReceiving(IAsyncResult asyncResult, ReceiverContext receiverContext)
        {
            bool shouldContinue = true;
            TimeSpan backoffAmount = BackoffAmount;

            try
            {
                IEnumerable<BrokeredMessage> messages = receiverContext.Receiver.EndReceiveBatch(asyncResult);

                receiverContext.OnMessage(messages);

                // Reset the receive timeout if it changed
                receiverContext.ReceiveTimeout = DefaultReadTimeout;
            }
            catch (ServerBusyException ex)
            {
                receiverContext.OnError(ex);

                // Too busy so back off
                shouldContinue = false;
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                return false;
            }
            catch (Exception ex)
            {
                receiverContext.OnError(ex);

                shouldContinue = false;

                // TODO: Exponential backoff
                backoffAmount = ErrorBackOffAmount;

                // After an error, we want to adjust the timeout so that we
                // can recover as quickly as possible even if there's no message
                receiverContext.ReceiveTimeout = ErrorReadTimeout;
            }

            if (!shouldContinue)
            {
                TaskAsyncHelper.Delay(backoffAmount)
                               .Then(ctx => ProcessMessages(ctx), receiverContext);

                return false;
            }

            return true;
        }
        private void ProcessMessages(ReceiverContext receiverContext)
        {
            receive:

            try
            {
                IAsyncResult result = receiverContext.Receiver.BeginReceiveBatch(receiverContext.ReceiveBatchSize, receiverContext.ReceiveTimeout, ar =>
                {
                    if (ar.CompletedSynchronously)
                    {
                        return;
                    }

                    var ctx = (ReceiverContext)ar.AsyncState;

                    if (ContinueReceiving(ar, ctx))
                    {
                        ProcessMessages(ctx);
                    }
                },
                receiverContext);

                if (result.CompletedSynchronously)
                {
                    if (ContinueReceiving(result, receiverContext))
                    {
                        goto receive;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // This means the channel is closed
                return;
            }
            catch (Exception ex)
            {
                receiverContext.OnError(ex);

                // REVIEW: What should we do here?
            }
        }
        public ServiceBusSubscription Subscribe(IList<string> topicNames,
                                                Action<int, IEnumerable<BrokeredMessage>> handler,
                                                Action<int, Exception> errorHandler)
        {
            if (topicNames == null)
            {
                throw new ArgumentNullException("topicNames");
            }

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

            var subscriptions = new ServiceBusSubscription.SubscriptionContext[topicNames.Count];
            var clients = new TopicClient[topicNames.Count];

            for (var topicIndex = 0; topicIndex < topicNames.Count; ++topicIndex)
            {
                string topicName = topicNames[topicIndex];

                if (!_namespaceManager.TopicExists(topicName))
                {
                    try
                    {
                        _namespaceManager.CreateTopic(topicName);
                    }
                    catch (MessagingEntityAlreadyExistsException)
                    {
                        // The entity already exists
                    }
                }

                // Create a client for this topic
                clients[topicIndex] = TopicClient.CreateFromConnectionString(_configuration.ConnectionString, topicName);

                // Create a random subscription
                string subscriptionName = Guid.NewGuid().ToString();

                try
                {
                    _namespaceManager.CreateSubscription(topicName, subscriptionName);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // The entity already exists
                }

                // Create a receiver to get messages
                string subscriptionEntityPath = SubscriptionClient.FormatSubscriptionPath(topicName, subscriptionName);
                MessageReceiver receiver = _factory.CreateMessageReceiver(subscriptionEntityPath, ReceiveMode.ReceiveAndDelete);

                subscriptions[topicIndex] = new ServiceBusSubscription.SubscriptionContext(topicName, subscriptionName, receiver);

                var receiverContext = new ReceiverContext(topicIndex, receiver, handler, errorHandler);

                ProcessMessages(receiverContext);
            }

            return new ServiceBusSubscription(_configuration, _namespaceManager, subscriptions, clients);
        }
Exemplo n.º 25
0
 public void Finished()
 {
     this._ctx.MsgConnection  = null;
     this._ctx.DataConnection = null;
     this._ctx = null;
 }
Exemplo n.º 26
0
	public ReceiverContext receiver() {
		ReceiverContext _localctx = new ReceiverContext(_ctx, State);
		EnterRule(_localctx, 100, RULE_receiver);
		try {
			State = 696;
			switch ( Interpreter.AdaptivePredict(_input,62,_ctx) ) {
			case 1:
				EnterOuterAlt(_localctx, 1);
				{
				State = 693; expression();
				}
				break;

			case 2:
				EnterOuterAlt(_localctx, 2);
				{
				State = 694; class_name();
				}
				break;

			case 3:
				EnterOuterAlt(_localctx, 3);
				{
				State = 695; Match(SUPER);
				}
				break;
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			_errHandler.ReportError(this, re);
			_errHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}