Exemple #1
0
        static async Task <Exception> MapToExceptionAsync(
            HttpResponseMessage response,
            IDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > > errorMapping)
        {
            Func <HttpResponseMessage, Task <Exception> > func;

            if (!errorMapping.TryGetValue(response.StatusCode, out func))
            {
                return(new IotHubException(
                           await ExceptionHandlingHelper.GetExceptionMessageAsync(response),
                           isTransient: true));
            }

            var mapToExceptionFunc = errorMapping[response.StatusCode];
            var exception          = mapToExceptionFunc(response);

            return(await exception);
        }
        public AmqpServiceClient(IotHubConnectionString iotHubConnectionString)
        {
            var iotHubConnection = new IotHubConnection(iotHubConnectionString, AccessRights.ServiceConnect);

            this.iotHubConnection         = iotHubConnection;
            this.openTimeout              = IotHubConnection.DefaultOpenTimeout;
            this.operationTimeout         = IotHubConnection.DefaultOperationTimeout;
            this.sendingPath              = "/messages/deviceBound";
            this.faultTolerantSendingLink = new FaultTolerantAmqpObject <SendingAmqpLink>(this.CreateSendingLinkAsync, this.iotHubConnection.CloseLink);
            this.feedbackReceiver         = new AmqpFeedbackReceiver(this.iotHubConnection);
            this.iotHubName       = iotHubConnectionString.IotHubName;
            this.httpClientHelper = new HttpClientHelper(
                iotHubConnectionString.HttpsEndpoint,
                iotHubConnectionString,
                ExceptionHandlingHelper.GetDefaultErrorMapping(),
                DefaultOperationTimeout,
                client => {});
        }
        public AmqpServiceClient(IotHubConnectionString iotHubConnectionString, bool useWebSocketOnly, ServiceClientTransportSettings transportSettings)
        {
            var iotHubConnection = new IotHubConnection(iotHubConnectionString, AccessRights.ServiceConnect, useWebSocketOnly, transportSettings);

            Connection                = iotHubConnection;
            OpenTimeout               = IotHubConnection.DefaultOpenTimeout;
            OperationTimeout          = IotHubConnection.DefaultOperationTimeout;
            _sendingPath              = "/messages/deviceBound";
            _faultTolerantSendingLink = new FaultTolerantAmqpObject <SendingAmqpLink>(CreateSendingLinkAsync, Connection.CloseLink);
            _feedbackReceiver         = new AmqpFeedbackReceiver(Connection);
            _fileNotificationReceiver = new AmqpFileNotificationReceiver(Connection);
            _iotHubName               = iotHubConnectionString.IotHubName;
            _httpClientHelper         = new HttpClientHelper(
                iotHubConnectionString.HttpsEndpoint,
                iotHubConnectionString,
                ExceptionHandlingHelper.GetDefaultErrorMapping(),
                s_defaultOperationTimeout,
                transportSettings.HttpProxy);
        }
        public override Task <Device> UpdateDeviceAsync(Device device, bool forceUpdate, CancellationToken cancellationToken)
        {
            this.EnsureInstanceNotClosed();

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

            if (string.IsNullOrWhiteSpace(device.Id))
            {
                throw new ArgumentException(ApiResources.DeviceIdNotSet);
            }

            if (string.IsNullOrWhiteSpace(device.ETag) && !forceUpdate)
            {
                throw new ArgumentException(ApiResources.ETagNotSetWhileUpdatingDevice);
            }

            // auto generate keys if not specified
            if (device.Authentication == null)
            {
                device.Authentication = new AuthenticationMechanism();
            }

            ValidateDeviceAuthentication(device);

            var errorMappingOverrides = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >();

            errorMappingOverrides.Add(HttpStatusCode.PreconditionFailed, async(responseMessage) => new PreconditionFailedException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)));
            errorMappingOverrides.Add(HttpStatusCode.NotFound, async responseMessage =>
            {
                var responseContent = await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage);
                return((Exception) new DeviceNotFoundException(responseContent, (Exception)null));
            });

            PutOperationType operationType = forceUpdate ? PutOperationType.ForceUpdateEntity : PutOperationType.UpdateEntity;

            return(this.httpClientHelper.PutAsync(GetRequestUri(device.Id), device, operationType, errorMappingOverrides, cancellationToken));
        }
Exemple #5
0
        public override Task <Twin> UpdateTwinAsync(string deviceId, Twin twinPatch, string etag, CancellationToken cancellationToken)
        {
            this.EnsureInstanceNotClosed();

            if (twinPatch != null)
            {
                twinPatch.DeviceId = deviceId;
            }

            ValidateTwinId(twinPatch);

            if (string.IsNullOrEmpty(etag))
            {
                throw new ArgumentNullException(nameof(etag));
            }

            var errorMappingOverrides = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >
            {
                {
                    HttpStatusCode.PreconditionFailed,
                    async responseMessage => new PreconditionFailedException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage))
                },
                {
                    HttpStatusCode.NotFound,
                    async responseMessage => new DeviceNotFoundException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage), (Exception)null)
                }
            };

            return(this.httpClientHelper.PatchAsync <Twin, Twin>(
                       GetTwinUri(deviceId),
                       twinPatch,
                       etag,
                       etag == WildcardEtag ? PutOperationType.ForceUpdateEntity : PutOperationType.UpdateEntity,
                       errorMappingOverrides,
                       cancellationToken));
        }
Exemple #6
0
        Task RemoveDeviceAsync(string deviceId, IETagHolder eTagHolder, CancellationToken cancellationToken)
        {
            var errorMappingOverrides = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >
            {
                { HttpStatusCode.NotFound, async responseMessage =>
                  {
                      string responseContent = await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage);

                      return(new DeviceNotFoundException(responseContent, (Exception)null));
                  } },
                { HttpStatusCode.PreconditionFailed, async responseMessage => new PreconditionFailedException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)) }
            };

            return(this.httpClientHelper.DeleteAsync(GetRequestUri(deviceId), eTagHolder, errorMappingOverrides, null, cancellationToken));
        }
Exemple #7
0
        public override Task <Twin> GetTwinAsync(string deviceId, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                throw new ArgumentException(IotHubApiResources.GetString(ApiResources.ParameterCannotBeNullOrWhitespace, "deviceId"));
            }

            this.EnsureInstanceNotClosed();
            var errorMappingOverrides = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >()
            {
                { HttpStatusCode.NotFound, async responseMessage => new DeviceNotFoundException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)) }
            };

            return(this.httpClientHelper.GetAsync <Twin>(GetTwinUri(deviceId), errorMappingOverrides, null, false, cancellationToken));
        }
Exemple #8
0
        Task <T> BulkDeviceOperationsAsync <T>(IEnumerable <ExportImportDevice> devices, string version, CancellationToken cancellationToken)
        {
            this.BulkDeviceOperationSetup(devices);

            var errorMappingOverrides = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >
            {
                { HttpStatusCode.PreconditionFailed, async responseMessage => new PreconditionFailedException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)) },
                { HttpStatusCode.RequestEntityTooLarge, async responseMessage => new TooManyDevicesException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)) },
                { HttpStatusCode.BadRequest, async responseMessage => new ArgumentException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)) }
            };

            return(this.httpClientHelper.PostAsync <IEnumerable <ExportImportDevice>, T>(GetBulkRequestUri(version), devices, errorMappingOverrides, null, cancellationToken));
        }
Exemple #9
0
        public override Task <Device> UpdateDeviceAsync(Device device, bool forceUpdate, CancellationToken cancellationToken)
        {
            this.EnsureInstanceNotClosed();

            ValidateDeviceId(device);

            if (string.IsNullOrWhiteSpace(device.ETag) && !forceUpdate)
            {
                throw new ArgumentException(ApiResources.ETagNotSetWhileUpdatingDevice);
            }

            ValidateDeviceAuthentication(device.Authentication, device.Id);

            NormalizeDevice(device);

            var errorMappingOverrides = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >()
            {
                { HttpStatusCode.PreconditionFailed, async(responseMessage) => new PreconditionFailedException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)) },
                {
                    HttpStatusCode.NotFound, async responseMessage =>
                    {
                        string responseContent = await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage).ConfigureAwait(false);

                        return((Exception) new DeviceNotFoundException(responseContent, (Exception)null));
                    }
                }
            };

            PutOperationType operationType = forceUpdate ? PutOperationType.ForceUpdateEntity : PutOperationType.UpdateEntity;

            return(this.httpClientHelper.PutAsync(GetRequestUri(device.Id), device, operationType, errorMappingOverrides, cancellationToken));
        }
Exemple #10
0
        Task <string[]> BulkDeviceOperationsAsync(IEnumerable <ExportImportDevice> devices, CancellationToken cancellationToken)
        {
            this.EnsureInstanceNotClosed();

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

            foreach (var device in devices)
            {
                // auto generate keys if not specified
                if (device.Authentication == null)
                {
                    device.Authentication = new AuthenticationMechanism();
                }

                ValidateDeviceAuthentication(device.Authentication);
            }

            var errorMappingOverrides = new Dictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >();

            errorMappingOverrides.Add(HttpStatusCode.RequestEntityTooLarge, async(responseMessage) => new TooManyDevicesException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)));
            errorMappingOverrides.Add(HttpStatusCode.BadRequest, async(responseMessage) => new ArgumentException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage)));

            return(this.httpClientHelper.PostAsync <IEnumerable <ExportImportDevice>, string[]>(GetRequestUri(string.Empty), devices, errorMappingOverrides, null, cancellationToken));
        }