/// <summary>
        ///   Performs the actions needed to open an AMQP object, such
        ///   as a session or link for use.
        /// </summary>
        ///
        /// <param name="target">The target AMQP object to open.</param>
        /// <param name="timeout">The timeout to apply when opening the link.</param>
        protected virtual async Task OpenAmqpObjectAsync(
            AmqpObject target,
            TimeSpan timeout)
        {
            try
            {
                await target.OpenAsync(timeout).ConfigureAwait(false);
            }
            catch
            {
                switch (target)
                {
                case AmqpLink linkTarget:
                    linkTarget.Session?.SafeClose();
                    break;

                case RequestResponseAmqpLink linkTarget:
                    linkTarget.Session?.SafeClose();
                    break;

                default:
                    break;
                }

                target.SafeClose();
                throw;
            }
        }
        private static async Task OpenLinkAsync(AmqpObject link, TimeSpan timeout)
        {
            Logging.Enter(link, link.State, timeout, nameof(OpenLinkAsync));

            try
            {
                var timeoutHelper = new TimeoutHelper(timeout);
                try
                {
                    await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    Logging.Error(link, exception, nameof(OpenLinkAsync));

                    if (exception.IsFatal())
                    {
                        throw;
                    }

                    link.SafeClose(exception);

                    throw;
                }
            }
            finally
            {
                Logging.Exit(link, link.State, timeout, nameof(OpenLinkAsync));
            }
        }
Exemple #3
0
        protected override async Task OpenLinkAsync(AmqpObject link, IotHubConnectionString connectionString, string audience, TimeSpan timeout, CancellationToken token)
        {
            var timeoutHelper = new TimeoutHelper(timeout);

            token.ThrowIfCancellationRequested();
            try
            {
                // this is a device-scope connection string. We need to send a CBS token for this specific link before opening it.
                var iotHubLinkTokenRefresher = new IotHubTokenRefresher(this.FaultTolerantSession.Value, connectionString, audience);

                if (this.iotHubTokenRefreshers.TryAdd(link, iotHubLinkTokenRefresher))
                {
                    link.SafeAddClosed((s, e) =>
                    {
                        if (this.iotHubTokenRefreshers.TryRemove(link, out iotHubLinkTokenRefresher))
                        {
                            iotHubLinkTokenRefresher.Cancel();
                        }
                    });

                    // Send Cbs token for new link first
                    // This will throw an exception if the device is not valid or if the token is not valid
                    await iotHubLinkTokenRefresher.SendCbsTokenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
                }

                token.ThrowIfCancellationRequested();
                // Open Amqp Link
                await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
            }
            catch (Exception exception) when(!exception.IsFatal())
            {
                link.SafeClose(exception);
                throw;
            }
        }
        public async Task <AmqpObject> CreateAndOpenAmqpLinkAsync()
        {
            TimeoutHelper  timeoutHelper = new TimeoutHelper(this.serviceBusConnection.OperationTimeout);
            AmqpConnection connection    = await this.serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            // Authenticate over CBS
            AmqpCbsLink cbsLink  = connection.Extensions.Find <AmqpCbsLink>();
            Uri         address  = new Uri(this.serviceBusConnection.Endpoint, this.entityPath);
            string      audience = address.AbsoluteUri;
            string      resource = address.AbsoluteUri;
            await cbsLink.SendTokenAsync(this.cbsTokenProvider, address, audience, resource, this.requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false);

            AmqpSession session = null;

            try
            {
                // Create our Session
                AmqpSessionSettings sessionSettings = new AmqpSessionSettings {
                    Properties = new Fields()
                };
                session = connection.CreateSession(sessionSettings);
                await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                // Create our Link
                AmqpObject link = this.OnCreateAmqpLink(connection, this.amqpLinkSettings, session);
                await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                return(link);
            }
            catch (Exception)
            {
                session?.Abort();
                throw;
            }
        }
        protected override async Task OpenLinkAsync(AmqpObject link, IotHubConnectionString doNotUse, string doNotUse2, TimeSpan timeout, CancellationToken token)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, timeout, token, $"{nameof(IotHubSingleTokenConnection)}.{nameof(OpenLinkAsync)}");
            }

            token.ThrowIfCancellationRequested();
            try
            {
                await link.OpenAsync(timeout).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);

                throw;
            }
            finally
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, timeout, token, $"{nameof(IotHubSingleTokenConnection)}.{nameof(OpenLinkAsync)}");
                }
            }
        }
Exemple #6
0
        public async Task <Tuple <AmqpObject, DateTime> > CreateAndOpenAmqpLinkAsync()
        {
            var timeoutHelper = new TimeoutHelper(this.serviceBusConnection.OperationTimeout);

            MessagingEventSource.Log.AmqpGetOrCreateConnectionStart();
            var amqpConnection = await this.serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(this.entityPath, amqpConnection.ToString(), amqpConnection.State.ToString());

            // Authenticate over CBS
            var cbsLink = amqpConnection.Extensions.Find <AmqpCbsLink>();

            var resource = this.endpointAddress.AbsoluteUri;

            MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(this.endpointAddress, resource, resource, this.requiredClaims);
            var cbsTokenExpiresAtUtc = await cbsLink.SendTokenAsync(this.cbsTokenProvider, this.endpointAddress, resource, resource, this.requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false);

            MessagingEventSource.Log.AmqpSendAuthenticationTokenStop();

            AmqpSession session = null;

            try
            {
                // Create Session
                var amqpSessionSettings = new AmqpSessionSettings {
                    Properties = new Fields()
                };
                session = amqpConnection.CreateSession(amqpSessionSettings);
                await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                MessagingEventSource.Log.AmqpSessionCreationException(this.entityPath, amqpConnection, exception);
                session?.Abort();
                throw AmqpExceptionHelper.GetClientException(exception, null, session.GetInnerException());
            }

            AmqpObject link = null;

            try
            {
                // Create Link
                link = this.OnCreateAmqpLink(amqpConnection, this.amqpLinkSettings, session);
                await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                return(new Tuple <AmqpObject, DateTime>(link, cbsTokenExpiresAtUtc));
            }
            catch (Exception exception)
            {
                MessagingEventSource.Log.AmqpLinkCreationException(
                    this.entityPath,
                    session,
                    amqpConnection,
                    exception);

                session.SafeClose(exception);
                throw AmqpExceptionHelper.GetClientException(exception, null, link?.GetInnerException(), session.IsClosing());
            }
        }
        protected override async Task OpenLinkAsync(AmqpObject link, IotHubConnectionString doNotUse, string doNotUse2, TimeSpan timeout)
        {
            try
            {
                await link.OpenAsync(timeout);
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);

                throw;
            }
        }
        protected override async Task OpenLinkAsync(AmqpObject link, IotHubConnectionString doNotUse, string doNotUse2, TimeSpan timeout)
        {
            try
            {
                await link.OpenAsync(timeout);
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);

                throw;
            }
        }
        protected override async Task OpenLinkAsync(AmqpObject link, IotHubConnectionString doNotUse, string doNotUse2, TimeSpan timeout, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();
            try
            {
                await link.OpenAsync(timeout).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);

                throw;
            }
        }
        static async Task OpenLinkAsync(AmqpObject link, TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);

            try
            {
                await link.OpenAsync(timeoutHelper.RemainingTime());
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);

                throw;
            }
        }
Exemple #11
0
        protected override async Task OpenLinkAsync(AmqpObject link, IotHubConnectionString connectionString, string audience, TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);

            try
            {
                // this is a device-scope connection string. We need to send a CBS token for this specific link before opening it.
                var iotHubLinkTokenRefresher = new IotHubTokenRefresher(
                    this.FaultTolerantSession.Value,
                    connectionString,
                    audience
                    );

                if (this.iotHubTokenRefreshers.TryAdd(link, iotHubLinkTokenRefresher))
                {
                    link.SafeAddClosed((s, e) =>
                    {
                        if (this.iotHubTokenRefreshers.TryRemove(link, out iotHubLinkTokenRefresher))
                        {
                            iotHubLinkTokenRefresher.Cancel();
                        }
                    });

                    // Send Cbs token for new link first
                    await iotHubLinkTokenRefresher.SendCbsTokenAsync(timeoutHelper.RemainingTime());
                }

                // Open Amqp Link
                await link.OpenAsync(timeoutHelper.RemainingTime());
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);
                throw;
            }
        }
 /// <summary>
 ///   Performs the actions needed to open a generic AMQP object, such
 ///   as a session or link for use.
 /// </summary>
 ///
 /// <param name="target">The target AMQP object to open.</param>
 /// <param name="timeout">The timeout to apply when opening the link.</param>
 ///
 protected virtual Task OpenAmqpObjectAsync(
     AmqpObject target,
     TimeSpan timeout) =>
 target.OpenAsync(timeout);
        static async Task OpenLinkAsync(AmqpObject link, TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);
            try
            {
                await link.OpenAsync(timeoutHelper.RemainingTime());
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);

                throw;
            }
        }
        public async Task <Tuple <AmqpObject, DateTime> > CreateAndOpenAmqpLinkAsync()
        {
            var timeoutHelper = new TimeoutHelper(this.serviceBusConnection.OperationTimeout, true);

            MessagingEventSource.Log.AmqpGetOrCreateConnectionStart();
            var amqpConnection = await this.serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(this.entityPath, amqpConnection.ToString(), amqpConnection.State.ToString());

            // Authenticate over CBS
            var      cbsLink = amqpConnection.Extensions.Find <AmqpCbsLink>();
            DateTime cbsTokenExpiresAtUtc = DateTime.MaxValue;

            foreach (var resource in this.audience)
            {
                MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(this.endpointAddress, resource, resource, this.requiredClaims);
                cbsTokenExpiresAtUtc = TimeoutHelper.Min(
                    cbsTokenExpiresAtUtc,
                    await cbsLink.SendTokenAsync(this.cbsTokenProvider, this.endpointAddress, resource, resource, this.requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false));
                MessagingEventSource.Log.AmqpSendAuthenticationTokenStop();
            }

            AmqpSession session = null;

            try
            {
                // Create Session
                var amqpSessionSettings = new AmqpSessionSettings {
                    Properties = new Fields()
                };
                if (this.amqpLinkSettings.IsReceiver())
                {
                    // This is the maximum number of unsettled transfers across all receive links on this session.
                    // This will allow the session to accept unlimited number of transfers, even if the recevier(s)
                    // are not settling any of the deliveries.
                    amqpSessionSettings.IncomingWindow = uint.MaxValue;
                }

                session = amqpConnection.CreateSession(amqpSessionSettings);
                await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                MessagingEventSource.Log.AmqpSessionCreationException(this.entityPath, amqpConnection, exception);
                session?.Abort();
                throw AmqpExceptionHelper.GetClientException(exception, null, session.GetInnerException(), amqpConnection.IsClosing());
            }

            AmqpObject link = null;

            try
            {
                // Create Link
                link = this.OnCreateAmqpLink(amqpConnection, this.amqpLinkSettings, session);
                await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                return(new Tuple <AmqpObject, DateTime>(link, cbsTokenExpiresAtUtc));
            }
            catch (Exception exception)
            {
                MessagingEventSource.Log.AmqpLinkCreationException(
                    this.entityPath,
                    session,
                    amqpConnection,
                    exception);

                session.SafeClose(exception);
                throw AmqpExceptionHelper.GetClientException(exception, null, link?.GetInnerException(), amqpConnection.IsClosing());
            }
        }
        protected override async Task OpenLinkAsync(AmqpObject link, IotHubConnectionString connectionString, string audience, TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);
       
            try
            {
                // this is a device-scope connection string. We need to send a CBS token for this specific link before opening it.
                var iotHubLinkTokenRefresher = new IotHubTokenRefresher(
                    this.FaultTolerantSession.Value, 
                    connectionString, 
                    audience
                    );

                if (this.iotHubTokenRefreshers.TryAdd(link, iotHubLinkTokenRefresher))
                {
                    link.SafeAddClosed((s, e) =>
                    {
                        if (this.iotHubTokenRefreshers.TryRemove(link, out iotHubLinkTokenRefresher))
                        {
                            iotHubLinkTokenRefresher.Cancel();
                        }
                    });

                    // Send Cbs token for new link first
                    await iotHubLinkTokenRefresher.SendCbsTokenAsync(timeoutHelper.RemainingTime());
                }

                // Open Amqp Link
                await link.OpenAsync(timeoutHelper.RemainingTime());
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                link.SafeClose(exception);
                throw;
            }
        }