コード例 #1
0
        async Task <ReceivingAmqpLink> CreateTwinReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceTwinPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId));

            ReceivingAmqpLink twinReceivingLink = await this.IotHubConnection.CreateReceivingLinkAsync(path, this.iotHubConnectionString, this.twinConnectionCorrelationId, IotHubConnection.ReceivingLinkType.Twin, this.prefetchCount, timeout, cancellationToken);

            MyStringCopy(twinReceivingLink.Name, out twinReceivingLinkName);
            this.SafeAddClosedTwinReceivingLinkHandler = this.linkClosedListener;
            twinReceivingLink.SafeAddClosed(async(o, ea) =>
                                            await Task.Run(async() =>
            {
                await this.SafeAddClosedTwinReceivingLinkHandler(
                    o,
                    new ConnectionEventArgs
                {
                    ConnectionType               = ConnectionType.AmqpTwinReceiving,
                    ConnectionStatus             = ConnectionStatus.Disconnected_Retrying,
                    ConnectionStatusChangeReason = ConnectionStatusChangeReason.No_Network
                });
            }
                                                           ));

            twinReceivingLink.RegisterMessageListener(message => this.HandleTwinMessage(message, twinReceivingLink));

            return(twinReceivingLink);
        }
コード例 #2
0
ファイル: TheClient.cs プロジェクト: Bigsby/PoC
        public static void Start()
        {
            try
            {
                var connection = AmqpConnection.Factory.OpenConnectionAsync("amqp://localhost:5672/").Result;

                var sessionSettings = new AmqpSessionSettings
                {
                };
                //AmqpSessionSettings.Create(new Begin())
                var session = connection.CreateSession(sessionSettings);

                var linkSettings = new AmqpLinkSettings
                {
                    LinkName = "theExchange",
                    Handle   = 1234,
                    Role     = false,
                    Source   = new Source
                    {
                        Address = "theQueue",
                        Durable = 1
                    }
                };
                var receiver = new ReceivingAmqpLink(session, linkSettings);

                receiver.RegisterMessageListener(message =>
                {
                    var stop = "here";
                });
            }
            catch (System.Exception ex)
            {
                var s = ex.Message;
            }
        }
コード例 #3
0
        async Task <ReceivingAmqpLink> CreateMethodReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceMethodPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId));

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

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

            MyStringCopy(methodReceivingLink.Name, out methodReceivingLinkName);
            this.SafeAddClosedMethodReceivingLinkHandler = this.linkClosedListener;
            methodReceivingLink.SafeAddClosed(async(o, ea) =>
                                              await Task.Run(async() =>
            {
                await this.SafeAddClosedMethodReceivingLinkHandler(
                    o,
                    new ConnectionEventArgs
                {
                    ConnectionType               = ConnectionType.AmqpMethodReceiving,
                    ConnectionStatus             = ConnectionStatus.Disconnected_Retrying,
                    ConnectionStatusChangeReason = ConnectionStatusChangeReason.No_Network
                });
            }
                                                             ));

            return(methodReceivingLink);
        }
コード例 #4
0
        public async Task EnableEventReceiveAsync(TimeSpan timeout)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, timeout, $"{nameof(EnableEventReceiveAsync)}");
            }

            try
            {
                Debug.Assert(_eventReceivingLink == null);
                _eventReceivingLink = await AmqpLinkHelper.OpenEventsReceiverLinkAsync(
                    _deviceIdentity,
                    _amqpSession,
                    timeout
                    ).ConfigureAwait(false);

                _eventReceivingLink.RegisterMessageListener(OnEventsReceived);
                _eventReceivingLink.Closed += OnLinkDisconnected;

                if (Logging.IsEnabled)
                {
                    Logging.Associate(this, this, _eventReceivingLink, $"{nameof(EnableEventReceiveAsync)}");
                }
            }
            finally
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, timeout, $"{nameof(EnableEventReceiveAsync)}");
                }
            }
        }
コード例 #5
0
            public AmqpLink CreateLink(AmqpSession session, AmqpLinkSettings settings)
            {
                AmqpLink link;

                if (settings.Role.Value)
                {
                    var receiver = new ReceivingAmqpLink(session, settings);
                    receiver.RegisterMessageListener(m =>
                    {
                        this.messages.Enqueue(m.Clone());
                        receiver.AcceptMessage(m, true, true);
                        m.Dispose();
                    });
                    link = receiver;
                }
                else
                {
                    var sender = new SendingAmqpLink(session, settings);
                    sender.RegisterCreditListener((credit, drain, tx) =>
                    {
                        AmqpMessage message = this.messages.Dequeue();
                        message.DeliveryAnnotations.Map["x-opt-sequence-number"] = 1;
                        sender.SendMessageNoWait(message, EmptyBinary, NullBinary);
                    });
                    sender.RegisterDispositionListener(d =>
                    {
                        sender.DisposeDelivery(d, true, d.State);
                    });
                    link = sender;
                }

                return(link);
            }
コード例 #6
0
        public async Task EnsureTwinLinksAreOpenedAsync(TimeSpan timeout)
        {
            if (Volatile.Read(ref _twinLinksOpened) == true) return;
            if (Logging.IsEnabled) Logging.Enter(this, timeout, $"{nameof(EnsureTwinLinksAreOpenedAsync)}");

            try
            {
                await _twinLinksLock.WaitAsync().ConfigureAwait(false);
                if (_twinLinksOpened) return;

                Debug.Assert(_twinSendingLink == null);
                Debug.Assert(_twinReceivingLink == null);

                string correlationIdSuffix = Guid.NewGuid().ToString();

                Task<ReceivingAmqpLink> receiveLinkCreator =
                    AmqpLinkHelper.OpenTwinReceiverLinkAsync(
                        _deviceIdentity,
                        _amqpSession,
                        correlationIdSuffix,
                        timeout);

                Task<SendingAmqpLink> sendingLinkCreator =
                    AmqpLinkHelper.OpenTwinSenderLinkAsync(
                        _deviceIdentity,
                        _amqpSession,
                        correlationIdSuffix,
                        timeout);

                await Task.WhenAll(receiveLinkCreator, sendingLinkCreator).ConfigureAwait(false);

                _twinSendingLink = sendingLinkCreator.Result;
                _twinSendingLink.Closed += OnLinkDisconnected;

                _twinReceivingLink = receiveLinkCreator.Result;
                _twinReceivingLink.RegisterMessageListener(OnDesiredPropertyReceived);
                _twinReceivingLink.Closed += OnLinkDisconnected;

                _twinLinksOpened = true;

                if (Logging.IsEnabled) Logging.Associate(this, this, _twinReceivingLink, $"{nameof(EnsureTwinLinksAreOpenedAsync)}");
                if (Logging.IsEnabled) Logging.Associate(this, this, _twinSendingLink, $"{nameof(EnsureTwinLinksAreOpenedAsync)}");
            }
            catch (Exception ex) when (!ex.IsFatal())
            {
                _twinReceivingLink?.Abort();
                _twinSendingLink?.Abort();
                _twinReceivingLink = null;
                _twinSendingLink = null;

                throw;
            }
            finally
            {
                _twinLinksLock.Release();
                if (Logging.IsEnabled) Logging.Exit(this, timeout, $"{nameof(EnsureTwinLinksAreOpenedAsync)}");
            }
        }
コード例 #7
0
 public void AddCoordinator(ReceivingAmqpLink link)
 {
     link.RegisterMessageListener(this.OnMessage);
     link.Closed += this.link_Closed;
     lock (this.coordinators)
     {
         this.coordinators.Add(link.Identifier, link);
     }
 }
コード例 #8
0
        async Task <ReceivingAmqpLink> CreateTwinReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            string path = this.BuildPath(CommonConstants.DeviceTwinPathTemplate, CommonConstants.ModuleTwinPathTemplate);

            ReceivingAmqpLink twinReceivingLink = await this.IotHubConnection.CreateReceivingLinkAsync(path, this.iotHubConnectionString, this.twinConnectionCorrelationId, IotHubConnection.ReceivingLinkType.Twin, this.prefetchCount, timeout, this.productInfo, cancellationToken).ConfigureAwait(false);

            MyStringCopy(twinReceivingLink.Name, out twinReceivingLinkName);
            twinReceivingLink.SafeAddClosed(OnAmqpConnectionClose);
            twinReceivingLink.RegisterMessageListener(message => this.HandleTwinMessage(message, twinReceivingLink));

            return(twinReceivingLink);
        }
コード例 #9
0
        private async Task <ReceivingAmqpLink> CreateEventReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            string path = this.BuildPath(CommonConstants.DeviceEventPathTemplate, CommonConstants.ModuleEventPathTemplate);

            ReceivingAmqpLink messageReceivingLink = await this.IotHubConnection.CreateReceivingLinkAsync(path, this.iotHubConnectionString, this.deviceId, IotHubConnection.ReceivingLinkType.Events, this.prefetchCount, timeout, this.productInfo, cancellationToken).ConfigureAwait(false);

            messageReceivingLink.RegisterMessageListener(amqpMessage => this.ProcessReceivedEventMessage(amqpMessage));

            MyStringCopy(messageReceivingLink.Name, out eventReceivingLinkName);
            messageReceivingLink.SafeAddClosed(OnAmqpConnectionClose);

            return(messageReceivingLink);
        }
コード例 #10
0
        public async Task EnableMethodsAsync(TimeSpan timeout)
        {
            if (Logging.IsEnabled) Logging.Enter(this, timeout, $"{nameof(EnableMethodsAsync)}");

            try
            {
                Debug.Assert(_methodSendingLink == null);
                Debug.Assert(_methodReceivingLink == null);

                string correlationIdSuffix = Guid.NewGuid().ToString();
                Task<ReceivingAmqpLink> receiveLinkCreator =
                    AmqpLinkHelper.OpenMethodsReceiverLinkAsync(
                        _deviceIdentity,
                        _amqpSession,
                        correlationIdSuffix,
                        timeout);

                Task<SendingAmqpLink> sendingLinkCreator =
                    AmqpLinkHelper.OpenMethodsSenderLinkAsync(
                        _deviceIdentity,
                        _amqpSession,
                        correlationIdSuffix,
                        timeout);

                await Task.WhenAll(receiveLinkCreator, sendingLinkCreator).ConfigureAwait(false);

                _methodReceivingLink = receiveLinkCreator.Result;
                _methodSendingLink = sendingLinkCreator.Result;

                _methodReceivingLink.RegisterMessageListener(OnMethodReceived);
                _methodSendingLink.Closed += OnLinkDisconnected;
                _methodReceivingLink.Closed += OnLinkDisconnected;

                if (Logging.IsEnabled) Logging.Associate(this, _methodReceivingLink, $"{nameof(_methodReceivingLink)}");
                if (Logging.IsEnabled) Logging.Associate(this, _methodSendingLink, $"{nameof(_methodSendingLink)}");
            }
            catch (Exception)
            {
                _methodReceivingLink?.Abort();
                _methodReceivingLink = null;

                _methodSendingLink?.Abort();
                _methodSendingLink = null;

                throw;
            }
            finally
            {
                if (Logging.IsEnabled) Logging.Exit(this, timeout, $"{nameof(EnableMethodsAsync)}");
            }
        }
コード例 #11
0
        public async Task <ReceivingAmqpLink> CreateMethodReceivingLinkAsync(
            string path, IotHubConnectionString connectionString, TimeSpan timeout, uint prefetchCount, CancellationToken cancellationToken,
            string deviceId, Action <AmqpMessage, ReceivingAmqpLink> messageListenerAction)
        {
            this.OnCreateReceivingLink(connectionString);

            var timeoutHelper = new TimeoutHelper(timeout);

            AmqpSession session;

            if (!this.FaultTolerantSession.TryGetOpenedObject(out session))
            {
                session = await this.FaultTolerantSession.GetOrCreateAsync(timeoutHelper.RemainingTime(), cancellationToken);
            }

            var linkAddress = this.BuildLinkAddress(connectionString, path);

            var linkSettings = new AmqpLinkSettings()
            {
                Role            = true,
                TotalLinkCredit = prefetchCount,
                AutoSendFlow    = prefetchCount > 0,
                Source          = new Source()
                {
                    Address = linkAddress.AbsoluteUri
                },
                SndSettleMode = (byte)SenderSettleMode.Settled,
                RcvSettleMode = (byte)ReceiverSettleMode.First,
                LinkName      = Guid.NewGuid().ToString("N") // Use a human readable link name to help with debuggin
            };

            SetLinkSettingsCommonProperties(linkSettings, timeoutHelper.RemainingTime());
            SetLinkSettingsCommonPropertiesForMethod(linkSettings, deviceId);

            var link = new ReceivingAmqpLink(linkSettings);

            link.AttachTo(session);
            link.RegisterMessageListener(amqpMessage => messageListenerAction(amqpMessage, link));

            var audience = this.BuildAudience(connectionString, path);

            await this.OpenLinkAsync(link, connectionString, audience, timeoutHelper.RemainingTime(), cancellationToken);

            return(link);
        }
コード例 #12
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);
        }
コード例 #13
0
 internal void RegisterReceiveMessageListener(Action <Message> onDeviceMessageReceived)
 {
     _onDeviceMessageReceived = onDeviceMessageReceived;
     _receivingAmqpLink.RegisterMessageListener(OnDeviceMessageReceived);
 }
コード例 #14
0
 internal void RegisterEventListener(Action <Message> onEventsReceived)
 {
     _onEventsReceived = onEventsReceived;
     _receivingAmqpLink.RegisterMessageListener(OnEventsReceived);
 }
コード例 #15
0
ファイル: TestAmqpBroker.cs プロジェクト: Azure/azure-amqp
 public void AddCoordinator(ReceivingAmqpLink link)
 {
     link.RegisterMessageListener(this.OnMessage);
     link.Closed += this.link_Closed;
     lock (this.coordinators)
     {
         this.coordinators.Add(link.Identifier, link);
     }
 }