public void RemoveAmqpUnit(AmqpUnit amqpUnit)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, amqpUnit, nameof(RemoveAmqpUnit));
            }

            IDeviceIdentity deviceIdentity = amqpUnit.GetDeviceIdentity();

            if (deviceIdentity.IsPooling())
            {
                AmqpConnectionHolder amqpConnectionHolder;
                lock (_lock)
                {
                    AmqpConnectionHolder[] amqpConnectionHolders = ResolveConnectionGroup(deviceIdentity);
                    amqpConnectionHolder = ResolveConnectionByHashing(amqpConnectionHolders, deviceIdentity);

                    amqpConnectionHolder.RemoveAmqpUnit(amqpUnit);

                    // If the connection holder does not have any more units, the entry needs to be nullified.
                    if (amqpConnectionHolder.IsEmpty())
                    {
                        int index = GetDeviceIdentityIndex(deviceIdentity, amqpConnectionHolders.Length);
                        amqpConnectionHolders[index] = null;
                        amqpConnectionHolder?.Dispose();
                    }
                }
            }

            if (Logging.IsEnabled)
            {
                Logging.Exit(this, amqpUnit, nameof(RemoveAmqpUnit));
            }
        }
        internal async Task <IAmqpAuthenticationRefresher> CreateRefresherAsync(IDeviceIdentity deviceIdentity, CancellationToken cancellationToken)
        {
            if (_amqpConnection.IsClosing())
            {
                throw new IotHubCommunicationException("Amqp connection is disconnected.");
            }

            try
            {
                IAmqpAuthenticationRefresher amqpAuthenticator = new AmqpAuthenticationRefresher(deviceIdentity, _amqpIotCbsLink);
                await amqpAuthenticator.InitLoopAsync(cancellationToken).ConfigureAwait(false);

                return(amqpAuthenticator);
            }
            catch (Exception e) when(!e.IsFatal())
            {
                Exception ex = AmqpIotExceptionAdapter.ConvertToIotHubException(e, _amqpConnection);

                if (ReferenceEquals(e, ex))
                {
                    throw;
                }
                else
                {
                    throw ex;
                }
            }
        }
Ejemplo n.º 3
0
        public async Task GetDeviceIdentityTest(
            string iotHubHostName,
            string clientId,
            string username,
            string password,
            X509Certificate2 certificate,
            IList <X509Certificate2> chain,
            bool authRetVal,
            Type expectedType)
        {
            var authenticator    = new Mock <IAuthenticator>();
            var productInfoStore = Mock.Of <IProductInfoStore>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(authRetVal);
            var deviceIdentityProvider = new DeviceIdentityProvider(authenticator.Object, new ClientCredentialsFactory(new IdentityProvider(iotHubHostName)), productInfoStore, true);

            if (certificate != null)
            {
                deviceIdentityProvider.RegisterConnectionCertificate(certificate, chain);
            }

            IDeviceIdentity deviceIdentity = await deviceIdentityProvider.GetAsync(clientId, username, password, null);

            Assert.IsAssignableFrom(expectedType, deviceIdentity);
        }
Ejemplo n.º 4
0
        async void Connect(IChannelHandlerContext context, ConnectPacket packet)
        {
            try
            {
                this.stateFlags = StateFlags.ProcessingConnect;

                this.identity = await this.authProvider.GetAsync(
                    packet.DeviceId, packet.Username, packet.Password, this.capturedContext.Channel.RemoteAddress);

                if (!this.identity.IsAuthenticated)
                {
                    Console.WriteLine("ClientNotAuthenticated", $"Client ID: {packet.DeviceId}; Username: {packet.Username}", this.ChannelId);
                    ShutdownOnError(context, ConnectProcessingScope, new SocketIoTGatewayException(ErrorCode.AuthenticationFailed, "Authentication failed."));
                    return;
                }

                Console.WriteLine("ClientAuthenticated", this.identity.ToString(), this.ChannelId);

                this.messagingBridge = await this.messagingBridgeFactory(this.identity);

                this.keepAliveTimeout = this.DeriveKeepAliveTimeout(context, packet);

                this.CompleteConnect(context);
            }
            catch (Exception e)
            {
                SocketIoTHubAdapter.ShutdownOnError(context, ConnectProcessingScope, e);
            }
        }
Ejemplo n.º 5
0
        public AmqpUnit CreateAmqpUnit(
            IDeviceIdentity deviceIdentity,
            Func <MethodRequestInternal, Task> onMethodCallback,
            Action <Twin, string, TwinCollection, IotHubException> twinMessageListener,
            Func <string, Message, Task> onModuleMessageReceivedCallback,
            Func <Message, Task> onDeviceMessageReceivedCallback,
            Action onUnitDisconnected)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, deviceIdentity, nameof(CreateAmqpUnit));
            }

            var amqpUnit = new AmqpUnit(
                deviceIdentity,
                this,
                onMethodCallback,
                twinMessageListener,
                onModuleMessageReceivedCallback,
                onDeviceMessageReceivedCallback,
                onUnitDisconnected);

            lock (_unitsLock)
            {
                _amqpUnits.Add(amqpUnit);
            }

            if (Logging.IsEnabled)
            {
                Logging.Exit(this, deviceIdentity, nameof(CreateAmqpUnit));
            }

            return(amqpUnit);
        }
Ejemplo n.º 6
0
        public async Task SetAsync(IDeviceIdentity identity, ISessionState sessionState)
        {
            var state = sessionState as BlobSessionState;

            if (state == null)
            {
                throw new ArgumentException("Cannot set Session State object that hasn't been acquired from provider.", "sessionState");
            }

            if (state.IsTransient)
            {
                return;
            }

            CloudBlockBlob blob = this.container.GetBlockBlobReference(identity.Id);

            using (var memoryStream = new MemoryStream())
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
                    serializer.Serialize(streamWriter, state);
                    streamWriter.Flush();

                    memoryStream.Position = 0;
                    AccessCondition accessCondition = state.ETag == null
                    ? AccessCondition.GenerateIfNoneMatchCondition("*")     // create
                    : AccessCondition.GenerateIfMatchCondition(state.ETag); // update

                    await blob.UploadFromStreamAsync(memoryStream, accessCondition, null, null);

                    state.ETag = blob.Properties.ETag;
                }
        }
Ejemplo n.º 7
0
 public AmqpConnectionHolder(IDeviceIdentity deviceIdentity)
 {
     _deviceIdentity   = deviceIdentity;
     _amqpIotConnector = new AmqpIotConnector(deviceIdentity.AmqpTransportSettings, deviceIdentity.IotHubConnectionString.HostName);
     if (Logging.IsEnabled)
     {
         Logging.Associate(this, _deviceIdentity, nameof(_deviceIdentity));
     }
 }
 public async Task<IQos2MessageDeliveryState> GetMessageAsync(IDeviceIdentity deviceIdentity, int packetId)
 {
     string rowKey = CalculateRowKey(deviceIdentity.Id, packetId);
     TableQuery<TableMessageDeliveryState> query = new TableQuery<TableMessageDeliveryState>()
         .Where(TableQuery.CombineFilters(
             TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, CalculatePartitionKey(rowKey)),
             TableOperators.And,
             TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey)));
     return await this.ReadRowAsync(query, CancellationToken.None);
 }
        public async Task OpenAsync(string deviceId, string deviceKey)
        {
            this.deviceIdentity = this.GetDeviceIdentity(deviceId, deviceKey);
            if (this.deviceIdentity != UnauthenticatedDeviceIdentity.Instance)
            {
                this.deviceClient = await this.deviceClientFactory(this.deviceIdentity);

                this.deviceClient.BindMessagingChannel(this);
            }
        }
Ejemplo n.º 10
0
        public override async Task SetAsync(IDeviceIdentity identity, ISessionState sessionState)
        {
            using (await this.setLock.LockAsync())
            {
                await base.SetAsync(identity, sessionState);

                await this.PersistToStore(identity.Id, sessionState);

                Events.SetSessionStateSuccess(identity);
            }
        }
        public async Task <IQos2MessageDeliveryState> GetMessageAsync(IDeviceIdentity deviceIdentity, int packetId)
        {
            string rowKey = CalculateRowKey(deviceIdentity.Id, packetId);
            TableQuery <TableMessageDeliveryState> query = new TableQuery <TableMessageDeliveryState>()
                                                           .Where(TableQuery.CombineFilters(
                                                                      TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, CalculatePartitionKey(rowKey)),
                                                                      TableOperators.And,
                                                                      TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey)));

            return(await this.ReadRowAsync(query, CancellationToken.None));
        }
        public AmqpUnit CreateAmqpUnit(
            IDeviceIdentity deviceIdentity,
            Func <MethodRequestInternal, Task> onMethodCallback,
            Action <Twin, string, TwinCollection, IotHubException> twinMessageListener,
            Func <string, Message, Task> onModuleMessageReceivedCallback,
            Func <Message, Task> onDeviceMessageReceivedCallback,
            Action onUnitDisconnected)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, deviceIdentity, nameof(CreateAmqpUnit));
            }

            if (deviceIdentity.IsPooling())
            {
                AmqpConnectionHolder amqpConnectionHolder;
                lock (_lock)
                {
                    AmqpConnectionHolder[] amqpConnectionHolders = ResolveConnectionGroup(deviceIdentity);
                    amqpConnectionHolder = ResolveConnectionByHashing(amqpConnectionHolders, deviceIdentity);
                }

                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, deviceIdentity, nameof(CreateAmqpUnit));
                }

                return(amqpConnectionHolder.CreateAmqpUnit(
                           deviceIdentity,
                           onMethodCallback,
                           twinMessageListener,
                           onModuleMessageReceivedCallback,
                           onDeviceMessageReceivedCallback,
                           onUnitDisconnected));
            }
            else
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, deviceIdentity, nameof(CreateAmqpUnit));
                }

                return(new AmqpConnectionHolder(deviceIdentity)
                       .CreateAmqpUnit(
                           deviceIdentity,
                           onMethodCallback,
                           twinMessageListener,
                           onModuleMessageReceivedCallback,
                           onDeviceMessageReceivedCallback,
                           onUnitDisconnected));
            }
        }
        public Task DeleteMessageAsync(IDeviceIdentity deviceIdentity, int packetId, IQos2MessageDeliveryState message)
        {
            Contract.Requires(message != null);

            TableMessageDeliveryState tableMessage = ValidateMessageType(message);

            if (tableMessage.ETag == null)
            {
                throw new ArgumentException("Transient message cannot be deleted.");
            }

            return(this.table.ExecuteAsync(TableOperation.Delete(tableMessage)));
        }
        internal AmqpAuthenticationRefresher(IDeviceIdentity deviceIdentity, AmqpIotCbsLink amqpCbsLink)
        {
            _amqpIotCbsLink          = amqpCbsLink;
            _connectionString        = deviceIdentity.IotHubConnectionString;
            _audience                = deviceIdentity.Audience;
            _amqpIotCbsTokenProvider = new AmqpIotCbsTokenProvider(_connectionString);

            if (Logging.IsEnabled)
            {
                Logging.Associate(this, deviceIdentity, nameof(DeviceIdentity));
                Logging.Associate(this, amqpCbsLink, nameof(_amqpIotCbsLink));
            }
        }
        public Task DeleteMessageAsync(IDeviceIdentity deviceIdentity, int packetId, IQos2MessageDeliveryState message)
        {
            Contract.Requires(message != null);

            TableMessageDeliveryState tableMessage = ValidateMessageType(message);

            if (tableMessage.ETag == null)
            {
                throw new ArgumentException("Transient message cannot be deleted.");
            }

            return this.table.ExecuteAsync(TableOperation.Delete(tableMessage));
        }
Ejemplo n.º 16
0
        private static string BuildLinkAddress(IDeviceIdentity deviceIdentity, string deviceTemplate, string moduleTemplate)
        {
            string path = string.IsNullOrEmpty(deviceIdentity.IotHubConnectionString.ModuleId)
                ? string.Format(
                CultureInfo.InvariantCulture,
                deviceTemplate,
                WebUtility.UrlEncode(deviceIdentity.IotHubConnectionString.DeviceId))
                : string.Format(
                CultureInfo.InvariantCulture,
                moduleTemplate,
                WebUtility.UrlEncode(deviceIdentity.IotHubConnectionString.DeviceId), WebUtility.UrlEncode(deviceIdentity.IotHubConnectionString.ModuleId));

            return(deviceIdentity.IotHubConnectionString.BuildLinkAddress(path).AbsoluteUri);
        }
Ejemplo n.º 17
0
 internal async Task <AmqpIotReceivingLink> OpenEventsReceiverLinkAsync(
     IDeviceIdentity deviceIdentity,
     CancellationToken cancellationToken)
 {
     return(await OpenReceivingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                null,
                (byte)ReceiverSettleMode.First,
                CommonConstants.DeviceEventPathTemplate,
                CommonConstants.ModuleEventPathTemplate,
                AmqpIotConstants.EventsReceiverLinkSuffix,
                null,
                cancellationToken)
            .ConfigureAwait(false));
 }
Ejemplo n.º 18
0
 internal async Task <AmqpIotReceivingLink> OpenMessageReceiverLinkAsync(
     IDeviceIdentity deviceIdentity,
     CancellationToken cancellationToken)
 {
     return(await OpenReceivingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                null,
                (byte)ReceiverSettleMode.Second,
                CommonConstants.DeviceBoundPathTemplate,
                CommonConstants.ModuleBoundPathTemplate,
                AmqpIotConstants.TelemetryReceiveLinkSuffix,
                null,
                cancellationToken)
            .ConfigureAwait(false));
 }
Ejemplo n.º 19
0
 internal async Task <AmqpIotSendingLink> OpenTelemetrySenderLinkAsync(
     IDeviceIdentity deviceIdentity,
     CancellationToken cancellationToken)
 {
     return(await OpenSendingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                null,
                null,
                CommonConstants.DeviceEventPathTemplate,
                CommonConstants.ModuleEventPathTemplate,
                AmqpIotConstants.TelemetrySenderLinkSuffix,
                null,
                cancellationToken)
            .ConfigureAwait(false));
 }
Ejemplo n.º 20
0
        public async Task GetDeviceIdentityTest(
            string iotHubHostName,
            string clientId,
            string username,
            string password,
            bool authRetVal,
            Type expectedType)
        {
            var authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(authRetVal);

            IDeviceIdentityProvider deviceIdentityProvider = new DeviceIdentityProvider(authenticator.Object, new ClientCredentialsFactory(iotHubHostName), false);
            IDeviceIdentity         deviceIdentity         = await deviceIdentityProvider.GetAsync(clientId, username, password, null);

            Assert.IsAssignableFrom(expectedType, deviceIdentity);
        }
Ejemplo n.º 21
0
 internal async Task <AmqpIotSendingLink> OpenTwinSenderLinkAsync(
     IDeviceIdentity deviceIdentity,
     string correlationIdSuffix,
     CancellationToken cancellationToken)
 {
     return(await OpenSendingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                (byte)SenderSettleMode.Settled,
                (byte)ReceiverSettleMode.First,
                CommonConstants.DeviceTwinPathTemplate,
                CommonConstants.ModuleTwinPathTemplate,
                AmqpIotConstants.TwinSenderLinkSuffix,
                AmqpIotConstants.TwinCorrelationIdPrefix + correlationIdSuffix,
                cancellationToken)
            .ConfigureAwait(false));
 }
Ejemplo n.º 22
0
        public AmqpUnit CreateAmqpUnit(
            IDeviceIdentity deviceIdentity,
            Func <MethodRequestInternal, Task> onMethodCallback,
            Action <Twin, string, TwinCollection, IotHubException> twinMessageListener,
            Func <string, Message, Task> onModuleMessageReceivedCallback,
            Func <Message, Task> onDeviceMessageReceivedCallback,
            Action onUnitDisconnected)
        {
            IAmqpUnitManager amqpConnectionPool = ResolveConnectionPool(deviceIdentity.IotHubConnectionString.HostName);

            return(amqpConnectionPool.CreateAmqpUnit(
                       deviceIdentity,
                       onMethodCallback,
                       twinMessageListener,
                       onModuleMessageReceivedCallback,
                       onDeviceMessageReceivedCallback,
                       onUnitDisconnected));
        }
Ejemplo n.º 23
0
        public async Task <AmqpIotSession> OpenSessionAsync(IDeviceIdentity deviceIdentity, CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, deviceIdentity, nameof(OpenSessionAsync));
            }

            AmqpIotConnection amqpIotConnection = await EnsureConnectionAsync(cancellationToken).ConfigureAwait(false);

            AmqpIotSession amqpIotSession = await amqpIotConnection.OpenSessionAsync(cancellationToken).ConfigureAwait(false);

            if (Logging.IsEnabled)
            {
                Logging.Associate(amqpIotConnection, amqpIotSession, nameof(OpenSessionAsync));
                Logging.Exit(this, deviceIdentity, nameof(OpenSessionAsync));
            }

            return(amqpIotSession);
        }
Ejemplo n.º 24
0
        public async Task DeleteAsync(IDeviceIdentity identity, ISessionState sessionState)
        {
            var state = sessionState as BlobSessionState;

            if (state == null)
            {
                throw new ArgumentException("Cannot set Session State object that hasn't been acquired from provider.", "sessionState");
            }

            CloudBlockBlob blob = this.container.GetBlockBlobReference(identity.Id);
            await blob.DeleteAsync(
                DeleteSnapshotsOption.None,
                new AccessCondition
            {
                IfMatchETag = state.ETag
            },
                null,
                null);
        }
Ejemplo n.º 25
0
        public async Task GetIdentityCertAuthNotEnabled()
        {
            string iotHubHostName = "foo.azure-devices.net";
            var    authenticator  = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(true);
            var deviceIdentityProvider = new DeviceIdentityProvider(authenticator.Object, new ClientCredentialsFactory(new IdentityProvider(iotHubHostName)), false);

            deviceIdentityProvider.RegisterConnectionCertificate(new X509Certificate2(), new List <X509Certificate2> {
                new X509Certificate2()
            });
            IDeviceIdentity deviceIdentity = await deviceIdentityProvider.GetAsync(
                "Device_2",
                $"127.0.0.1/Device_2/api-version=2016-11-14&DeviceClientType={Uri.EscapeDataString("Microsoft.Azure.Devices.Client/1.2.2")}",
                null,
                null);

            Assert.Equal(UnauthenticatedDeviceIdentity.Instance, deviceIdentity);
        }
        public void AmqpConnectionPool_Add_Remove_ConnectionHolderIsRemoved()
        {
            string          sharedAccessKeyName = "HubOwner";
            uint            poolSize            = 10;
            IDeviceIdentity testDevice          = CreatePooledSasGroupedDeviceIdentity(sharedAccessKeyName, poolSize);
            IDictionary <string, AmqpConnectionHolder[]> injectedDictionary = new Dictionary <string, AmqpConnectionHolder[]>();

            AmqpConnectionPoolTest pool = new AmqpConnectionPoolTest(injectedDictionary);

            AmqpUnit addedUnit = pool.CreateAmqpUnit(testDevice, null, null, null, null, null);

            injectedDictionary[sharedAccessKeyName].Count().Should().Be((int)poolSize);

            pool.RemoveAmqpUnit(addedUnit);

            foreach (object item in injectedDictionary[sharedAccessKeyName])
            {
                item.Should().BeNull();
            }
        }
Ejemplo n.º 27
0
        public async Task <IAmqpAuthenticationRefresher> CreateRefresherAsync(IDeviceIdentity deviceIdentity, CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, deviceIdentity, nameof(CreateRefresherAsync));
            }

            AmqpIotConnection amqpIotConnection = await EnsureConnectionAsync(cancellationToken).ConfigureAwait(false);

            IAmqpAuthenticationRefresher amqpAuthenticator = await amqpIotConnection
                                                             .CreateRefresherAsync(deviceIdentity, cancellationToken)
                                                             .ConfigureAwait(false);

            if (Logging.IsEnabled)
            {
                Logging.Exit(this, deviceIdentity, nameof(CreateRefresherAsync));
            }

            return(amqpAuthenticator);
        }
        public Task SetMessageAsync(IDeviceIdentity deviceIdentity, int packetId, IQos2MessageDeliveryState message)
        {
            Contract.Requires(message != null);

            TableMessageDeliveryState tableMessage = ValidateMessageType(message);
            TableOperation            tableOperation;

            if (tableMessage.ETag == null)
            {
                string rowKey = CalculateRowKey(deviceIdentity.Id, packetId);
                tableMessage.PartitionKey = CalculatePartitionKey(rowKey);
                tableMessage.RowKey       = rowKey;
                tableOperation            = TableOperation.Insert(tableMessage);
            }
            else
            {
                tableOperation = TableOperation.Replace(tableMessage);
            }
            return(this.table.ExecuteAsync(tableOperation));
        }
Ejemplo n.º 29
0
        public async Task <ISessionState> GetAsync(IDeviceIdentity identity)
        {
            // todo: handle server busy (throttle?)

            CloudBlockBlob blob       = this.container.GetBlockBlobReference(identity.Id);
            JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);

            try
            {
                using (Stream stream = await blob.OpenReadAsync())
                {
                    using (var memoryStream = new MemoryStream(new byte[blob.Properties.Length])) // we don't expect it to be big (i.e. bigger than 85KB leading to LOH alloc)
                    {
                        await stream.CopyToAsync(memoryStream);

                        memoryStream.Position = 0;
                        using (var streamReader = new StreamReader(memoryStream))
                            using (var jsonReader = new JsonTextReader(streamReader))
                            {
                                var sessionState = serializer.Deserialize <BlobSessionState>(jsonReader);
                                sessionState.ETag = blob.Properties.ETag;

                                return(sessionState);
                            }
                    }
                }
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode == 404)
                {
                    return(null);
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 30
0
        public AmqpUnit(
            IDeviceIdentity deviceIdentity,
            IAmqpConnectionHolder amqpConnectionHolder,
            Func <MethodRequestInternal, Task> onMethodCallback,
            Action <Twin, string, TwinCollection, IotHubException> twinMessageListener,
            Func <string, Message, Task> onModuleMessageReceivedCallback,
            Func <Message, Task> onDeviceMessageReceivedCallback,
            Action onUnitDisconnected)
        {
            _deviceIdentity                  = deviceIdentity;
            _onMethodCallback                = onMethodCallback;
            _twinMessageListener             = twinMessageListener;
            _onModuleMessageReceivedCallback = onModuleMessageReceivedCallback;
            _onDeviceMessageReceivedCallback = onDeviceMessageReceivedCallback;
            _amqpConnectionHolder            = amqpConnectionHolder;
            _onUnitDisconnected              = onUnitDisconnected;

            if (Logging.IsEnabled)
            {
                Logging.Associate(this, _deviceIdentity, nameof(_deviceIdentity));
            }
        }
        private AmqpConnectionHolder[] ResolveConnectionGroup(IDeviceIdentity deviceIdentity)
        {
            if (deviceIdentity.AuthenticationModel == AuthenticationModel.SasIndividual)
            {
                if (_amqpSasIndividualPool == null)
                {
                    _amqpSasIndividualPool = new AmqpConnectionHolder[deviceIdentity.AmqpTransportSettings.AmqpConnectionPoolSettings.MaxPoolSize];
                }

                return(_amqpSasIndividualPool);
            }
            else
            {
                string scope = deviceIdentity.IotHubConnectionString.SharedAccessKeyName;
                GetAmqpSasGroupedPoolDictionary().TryGetValue(scope, out AmqpConnectionHolder[] amqpConnectionHolders);
                if (amqpConnectionHolders == null)
                {
                    amqpConnectionHolders = new AmqpConnectionHolder[deviceIdentity.AmqpTransportSettings.AmqpConnectionPoolSettings.MaxPoolSize];
                    GetAmqpSasGroupedPoolDictionary().Add(scope, amqpConnectionHolders);
                }

                return(amqpConnectionHolders);
            }
        }
Ejemplo n.º 32
0
        public async Task <ISessionState> GetAsync(IDeviceIdentity identity)
        {
            // todo: handle server busy (throttle?)

            CloudBlockBlob blob       = this.container.GetBlockBlobReference(identity.Id);
            JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);

            try
            {
                using (var stream = new RecyclableMemoryStream(StreamMemoryManager))
                {
                    await blob.DownloadToStreamAsync(stream);

                    stream.Position = 0;
                    using (var streamReader = new StreamReader(stream))
                        using (var jsonReader = new JsonTextReader(streamReader))
                        {
                            var sessionState = serializer.Deserialize <BlobSessionState>(jsonReader);
                            sessionState.ETag = blob.Properties.ETag;

                            return(sessionState);
                        }
                }
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode == 404)
                {
                    return(null);
                }
                else
                {
                    throw;
                }
            }
        }
 public Task DeleteAsync(IDeviceIdentity identity, ISessionState sessionState)
 {
     return TaskEx.Completed;
 }
 public Task<ISessionState> GetAsync(IDeviceIdentity identity)
 {
     return Task.FromResult((ISessionState)null);
 }
        public Task SetMessageAsync(IDeviceIdentity deviceIdentity, int packetId, IQos2MessageDeliveryState message)
        {
            Contract.Requires(message != null);

            TableMessageDeliveryState tableMessage = ValidateMessageType(message);
            TableOperation tableOperation;
            if (tableMessage.ETag == null)
            {
                string rowKey = CalculateRowKey(deviceIdentity.Id, packetId);
                tableMessage.PartitionKey = CalculatePartitionKey(rowKey);
                tableMessage.RowKey = rowKey;
                tableOperation = TableOperation.Insert(tableMessage);
            }
            else
            {
                tableOperation = TableOperation.Replace(tableMessage);
            }
            return this.table.ExecuteAsync(tableOperation);
        }
        /// <summary>
        ///     Performs complete initialization of <see cref="MqttIotHubAdapter" /> based on received CONNECT packet.
        /// </summary>
        /// <param name="context"><see cref="IChannelHandlerContext" /> instance.</param>
        /// <param name="packet">CONNECT packet.</param>
        async void Connect(IChannelHandlerContext context, ConnectPacket packet)
        {
            bool connAckSent = false;

            Exception exception = null;
            try
            {
                if (!this.IsInState(StateFlags.WaitingForConnect))
                {
                    ShutdownOnError(context, "CONNECT has been received in current session already. Only one CONNECT is expected per session.");
                    return;
                }

                this.stateFlags = StateFlags.ProcessingConnect;
                this.identity = await this.authProvider.GetAsync(packet.ClientId,
                    packet.Username, packet.Password, context.Channel.RemoteAddress);
                if (!this.identity.IsAuthenticated)
                {
                    connAckSent = true;
                    await Util.WriteMessageAsync(context, new ConnAckPacket
                    {
                        ReturnCode = ConnectReturnCode.RefusedNotAuthorized
                    });
                    PerformanceCounters.ConnectionFailedAuthPerSecond.Increment();
                    ShutdownOnError(context, "Authentication failed.");
                    return;
                }

                this.messagingServiceClient = await this.messagingFactory.CreateIotHubClientAsync(this.identity);

                bool sessionPresent = await this.EstablishSessionStateAsync(packet.CleanSession);

                this.keepAliveTimeout = this.DeriveKeepAliveTimeout(packet);

                if (packet.HasWill)
                {
                    var will = new PublishPacket(packet.WillQualityOfService, false, packet.WillRetain);
                    will.TopicName = packet.WillTopicName;
                    will.Payload = packet.WillMessage;
                    this.willPacket = will;
                }

                connAckSent = true;
                await Util.WriteMessageAsync(context, new ConnAckPacket
                {
                    SessionPresent = sessionPresent,
                    ReturnCode = ConnectReturnCode.Accepted
                });

                this.CompleteConnect(context);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                if (!connAckSent)
                {
                    try
                    {
                        await Util.WriteMessageAsync(context, new ConnAckPacket
                        {
                            ReturnCode = ConnectReturnCode.RefusedServerUnavailable
                        });
                    }
                    catch (Exception ex)
                    {
                        if (MqttIotHubAdapterEventSource.Log.IsVerboseEnabled)
                        {
                            MqttIotHubAdapterEventSource.Log.Verbose("Error sending 'Server Unavailable' CONNACK.", ex.ToString());
                        }
                    }
                }

                ShutdownOnError(context, "CONNECT", exception);
            }
        }