Ejemplo n.º 1
0
 private void OnDesiredPropertyReceived(AmqpMessage amqpMessage)
 {
     if (Logging.IsEnabled) Logging.Enter(this, amqpMessage, $"{nameof(OnDesiredPropertyReceived)}");
     try
     {
         _twinReceivingLink?.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome);
         _twinMessageListener?.Invoke(amqpMessage);
     }
     finally
     {
         if (Logging.IsEnabled) Logging.Exit(this, amqpMessage, $"{nameof(OnDesiredPropertyReceived)}");
     }
 }
Ejemplo n.º 2
0
 private void OnMethodReceived(AmqpMessage amqpMessage)
 {
     if (Logging.IsEnabled) Logging.Enter(this, amqpMessage, $"{nameof(OnMethodReceived)}");
     try
     {
         MethodRequestInternal methodRequestInternal = MethodConverter.ConstructMethodRequestFromAmqpMessage(amqpMessage, new CancellationToken(false));
         _methodReceivingLink?.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome);
         _methodHandler?.Invoke(methodRequestInternal);
     }
     finally
     {
         if (Logging.IsEnabled) Logging.Exit(this, amqpMessage, $"{nameof(OnMethodReceived)}");
     }
 }
        private void HandleTwinMessage(AmqpMessage message, ReceivingAmqpLink link)
        {
            // Test code.  Will be reworked in future commits.
            using (StreamReader reader = new StreamReader(message.BodyStream, System.Text.Encoding.UTF8))
            {
                string body = reader.ReadToEnd();
                System.Diagnostics.Debug.WriteLine(body);
            }
            link.DisposeDelivery(message, true, AmqpConstants.AcceptedOutcome);

            // TODO: deserialize and call one of the following:
            // this.messageListener(twinRequestInternal);
            // twinResponseEvent(message);
            // this.onReportedStatePatchListener(props);
        }
Ejemplo n.º 4
0
        protected override async Task <IList <BrokeredMessage> > OnReceiveAsync(int maxMessageCount)
        {
            try
            {
                TimeoutHelper     timeoutHelper = new TimeoutHelper(this.OperationTimeout, true);
                ReceivingAmqpLink receiveLink   = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                IEnumerable <AmqpMessage> amqpMessages = null;
                bool hasMessages = await Task.Factory.FromAsync(
                    (c, s) => receiveLink.BeginReceiveRemoteMessages(maxMessageCount, AmqpMessageReceiver.DefaultBatchFlushInterval, timeoutHelper.RemainingTime(), c, s),
                    a => receiveLink.EndReceiveMessages(a, out amqpMessages),
                    this).ConfigureAwait(false);

                if (receiveLink.TerminalException != null)
                {
                    throw receiveLink.TerminalException;
                }

                if (hasMessages && amqpMessages != null)
                {
                    IList <BrokeredMessage> brokeredMessages = null;
                    foreach (var amqpMessage in amqpMessages)
                    {
                        if (brokeredMessages == null)
                        {
                            brokeredMessages = new List <BrokeredMessage>();
                        }

                        if (this.ReceiveMode == ReceiveMode.ReceiveAndDelete)
                        {
                            receiveLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome);
                        }

                        BrokeredMessage brokeredMessage = AmqpMessageConverter.ClientGetMessage(amqpMessage);
                        brokeredMessage.Receiver = this; // Associate the Message with this Receiver.
                        brokeredMessages.Add(brokeredMessage);
                    }

                    return(brokeredMessages);
                }

                return(null);
            }
            catch (AmqpException amqpException)
            {
                throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error);
            }
        }
Ejemplo n.º 5
0
        async Task <ReceivingAmqpLink> CreateMethodReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            string path = this.BuildPath(CommonConstants.DeviceMethodPathTemplate, CommonConstants.ModuleMethodPathTemplate);

            ReceivingAmqpLink methodReceivingLink = await IotHubConnection.CreateReceivingLinkAsync(path, iotHubConnectionString, methodConnectionCorrelationId, IotHubConnection.ReceivingLinkType.Methods, prefetchCount, timeout, productInfo, cancellationToken).ConfigureAwait(false);

            methodReceivingLink.RegisterMessageListener(amqpMessage =>
            {
                MethodRequestInternal methodRequestInternal = MethodConverter.ConstructMethodRequestFromAmqpMessage(amqpMessage, cancellationToken);
                methodReceivingLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome);
                this.methodReceivedListener(methodRequestInternal);
            });

            MyStringCopy(methodReceivingLink.Name, out methodReceivingLinkName);

            methodReceivingLink.SafeAddClosed(OnAmqpConnectionClose);

            return(methodReceivingLink);
        }
Ejemplo n.º 6
0
        private void StartReceiver()
        {
            Task.Run(async() =>
            {
                var tfactory   = new AmqpConnectionFactory();
                var connection = await tfactory.OpenConnectionAsync("amqp://localhost:5672", TimeSpan.FromSeconds(10));

                var session = connection.CreateSession(CreateSessionSettings());

                var receicerSettings = new AmqpLinkSettings
                {
                    LinkName = $"receiver-{DateTime.UtcNow.Ticks}",
                    Role     = true,
                    Source   = new Source
                    {
                        Address = QueueName,
                        //DynamicNodeProperties = CreateProperties(),
                        //Value = "sourceValue",
                        Durable = 1
                    },
                    Properties = CreateProperties()
                };

                var receiver = new ReceivingAmqpLink(session, receicerSettings);
                await Task.WhenAll(
                    session.OpenAsync(session.DefaultOpenTimeout),
                    receiver.OpenAsync(receiver.DefaultOpenTimeout));

                while (true)
                {
                    AmqpMessage message = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(20));

                    if (message != null)
                    {
                        receiver.DisposeDelivery(message, true, AmqpConstants.AcceptedOutcome);
                        ReceiveMessage(message);
                    }
                }
            });
        }
Ejemplo n.º 7
0
        private static void TestLocalReceiver()
        {
            var tfactory   = new AmqpConnectionFactory();
            var connection = tfactory.OpenConnectionAsync("amqp://localhost:5672", TimeSpan.FromSeconds(10)).Result;

            var session = connection.CreateSession(new AmqpSessionSettings());

            var receicerSettings = new AmqpLinkSettings
            {
                LinkName        = $"receiver-{DateTime.UtcNow.Ticks}",
                Role            = true,
                TotalLinkCredit = 300,
                Source          = new Source
                {
                    Address = QueueName
                },
                Target = new Target()
            };

            var receiver = new ReceivingAmqpLink(session, receicerSettings);

            Task.WhenAll(
                session.OpenAsync(TimeSpan.FromSeconds(30)),
                receiver.OpenAsync(TimeSpan.FromSeconds(30))).Wait();

            Console.WriteLine("Listening");
            while (true)
            {
                AmqpMessage message = receiver.ReceiveMessageAsync(receiver.DefaultOpenTimeout).Result;

                if (message != null)
                {
                    receiver.DisposeDelivery(message, true, AmqpConstants.AcceptedOutcome);
                    DisplayMessage(new StreamReader(message.BodyStream).ReadToEnd());
                }
            }
        }
 private void DisposeDelivery(AmqpMessage amqpMessage, bool settled, Accepted acceptedOutcome)
 {
     _receivingAmqpLink.DisposeDelivery(amqpMessage, settled, acceptedOutcome);
 }
Ejemplo n.º 9
0
        protected override async Task <IList <EventData> > OnReceiveAsync(int maxMessageCount, TimeSpan waitTime)
        {
            bool shouldRetry;
            int  retryCount = 0;

            var timeoutHelper = new TimeoutHelper(waitTime, true);

            do
            {
                shouldRetry = false;

                try
                {
                    try
                    {
                        // Always use default timeout for AMQP sesssion.
                        ReceivingAmqpLink receiveLink =
                            await this.ReceiveLinkManager.GetOrCreateAsync(
                                TimeSpan.FromSeconds(AmqpClientConstants.AmqpSessionTimeoutInSeconds)).ConfigureAwait(false);

                        IEnumerable <AmqpMessage> amqpMessages = null;
                        bool hasMessages = await Task.Factory.FromAsync(
                            (c, s) => receiveLink.BeginReceiveMessages(maxMessageCount, timeoutHelper.RemainingTime(), c, s),
                            a => receiveLink.EndReceiveMessages(a, out amqpMessages),
                            this).ConfigureAwait(false);

                        if (receiveLink.TerminalException != null)
                        {
                            throw receiveLink.TerminalException;
                        }

                        if (hasMessages && amqpMessages != null)
                        {
                            IList <EventData> eventDatas = null;
                            foreach (var amqpMessage in amqpMessages)
                            {
                                if (eventDatas == null)
                                {
                                    eventDatas = new List <EventData>();
                                }

                                receiveLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome);
                                eventDatas.Add(AmqpMessageConverter.AmqpMessageToEventData(amqpMessage));
                            }

                            return(eventDatas);
                        }
                    }
                    catch (AmqpException amqpException)
                    {
                        throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error);
                    }
                }
                catch (Exception ex)
                {
                    // Evaluate retry condition?
                    TimeSpan?retryInterval = this.RetryPolicy.GetNextRetryInterval(ex, timeoutHelper.RemainingTime(), ++retryCount);
                    if (retryInterval != null && !this.EventHubClient.IsClosed)
                    {
                        await Task.Delay(retryInterval.Value).ConfigureAwait(false);

                        shouldRetry = true;
                    }
                    else
                    {
                        // Handle EventHubsTimeoutException explicitly.
                        // We don't really want to to throw EventHubsTimeoutException on this call.
                        if (ex is EventHubsTimeoutException)
                        {
                            break;
                        }

                        throw;
                    }
                }
            } while (shouldRetry);

            // No messages to deliver.
            return(null);
        }
Ejemplo n.º 10
0
        protected override async Task <IList <EventData> > OnReceiveAsync(int maxMessageCount, TimeSpan waitTime)
        {
            bool shouldRetry;

            var timeoutHelper = new TimeoutHelper(waitTime, true);

            do
            {
                shouldRetry = false;

                try
                {
                    try
                    {
                        ReceivingAmqpLink receiveLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                        IEnumerable <AmqpMessage> amqpMessages = null;
                        bool hasMessages = await Task.Factory.FromAsync(
                            (c, s) => receiveLink.BeginReceiveMessages(maxMessageCount, timeoutHelper.RemainingTime(), c, s),
                            a => receiveLink.EndReceiveMessages(a, out amqpMessages),
                            this).ConfigureAwait(false);

                        if (receiveLink.TerminalException != null)
                        {
                            throw receiveLink.TerminalException;
                        }

                        this.EventHubClient.RetryPolicy.ResetRetryCount(this.ClientId);

                        if (hasMessages && amqpMessages != null)
                        {
                            IList <EventData> eventDatas = null;
                            foreach (var amqpMessage in amqpMessages)
                            {
                                if (eventDatas == null)
                                {
                                    eventDatas = new List <EventData>();
                                }

                                receiveLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome);
                                eventDatas.Add(AmqpMessageConverter.AmqpMessageToEventData(amqpMessage));
                            }

                            return(eventDatas);
                        }
                    }
                    catch (AmqpException amqpException)
                    {
                        throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error);
                    }
                }
                catch (Exception ex)
                {
                    // Evaluate retry condition?
                    this.EventHubClient.RetryPolicy.IncrementRetryCount(this.ClientId);
                    TimeSpan?retryInterval = this.EventHubClient.RetryPolicy.GetNextRetryInterval(this.ClientId, ex, timeoutHelper.RemainingTime());
                    if (retryInterval != null)
                    {
                        await Task.Delay(retryInterval.Value).ConfigureAwait(false);

                        shouldRetry = true;
                    }
                    else
                    {
                        throw;
                    }
                }
            } while (shouldRetry);

            // No messages to deliver.
            return(null);
        }