private async Task GetSasUriAsync(Client.TransportType transport, string blobName, bool x509auth = false)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(
                Logger,
                _devicePrefix,
                x509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false);

            DeviceClient deviceClient;

            if (x509auth)
            {
                X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey();

                var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert);
                deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, auth, transport);
            }
            else
            {
                deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport);
            }

            using (deviceClient)
            {
                FileUploadSasUriResponse sasUriResponse = await deviceClient.GetFileUploadSasUriAsync(new FileUploadSasUriRequest { BlobName = blobName });

                await deviceClient.CloseAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 2
0
        private async Task UploadFileGranularAsync(Stream source, string filename, Http1TransportSettings fileUploadTransportSettings, bool useX509auth = false)
        {
            using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(
                      Logger,
                      _devicePrefix,
                      useX509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false);

            DeviceClient deviceClient;
            var          clientOptions = new ClientOptions()
            {
                FileUploadTransportSettings = fileUploadTransportSettings
            };

            X509Certificate2 cert = null;
            DeviceAuthenticationWithX509Certificate x509Auth = null;

            if (useX509auth)
            {
                cert     = s_selfSignedCertificate;
                x509Auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert);

                deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, x509Auth, Client.TransportType.Http1);
            }
            else
            {
                deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, Client.TransportType.Http1, clientOptions);
            }

            var fileUploadSasUriRequest = new FileUploadSasUriRequest()
            {
                BlobName = filename
            };

            using (deviceClient)
            {
                FileUploadSasUriResponse fileUploadSasUriResponse = await deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest).ConfigureAwait(false);

                var  blob       = new CloudBlockBlob(fileUploadSasUriResponse.GetBlobUri());
                Task uploadTask = blob.UploadFromStreamAsync(source);
                await uploadTask.ConfigureAwait(false);

                var notification = new FileUploadCompletionNotification
                {
                    CorrelationId = fileUploadSasUriResponse.CorrelationId,
                    IsSuccess     = uploadTask.IsCompleted
                };

                await deviceClient.CompleteFileUploadAsync(notification).ConfigureAwait(false);
            }

            x509Auth?.Dispose();
        }
Exemplo n.º 3
0
        private static async Task GetFileUploadUri(String fileName)
        {
            var fileUploadSasUriRequest = new FileUploadSasUriRequest();

            fileUploadSasUriRequest.BlobName = fileName;

            Console.WriteLine("Retrieving SAS URI for File Upload from the IoT Hub");
            sasUploadUri = await Client.GetFileUploadSasUriAsync(fileUploadSasUriRequest);

            fileUploadUri = new Uri($"https://{sasUploadUri.HostName}/{sasUploadUri.ContainerName}/{Uri.EscapeDataString(sasUploadUri.BlobName)}{sasUploadUri.SasToken}");

            Console.WriteLine($"Successfully retrieved SAS URI ({fileUploadUri}) for File upload from IoT Hub");
        }
Exemplo n.º 4
0
        private async Task UploadFileGranularAsync(Stream source, string filename, Http1TransportSettings fileUploadTransportSettings, bool x509auth = false)
        {
            await FileNotificationTestListener.InitAsync().ConfigureAwait(false);

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(
                _devicePrefix,
                x509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false);

            DeviceClient deviceClient;
            var          clientOptions = new ClientOptions()
            {
                FileUploadTransportSettings = fileUploadTransportSettings
            };

            if (x509auth)
            {
                X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey();

                var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert);

                // The X509 certificate being used for device authentication needs to be set into FileUploadTransportSettings as well,
                // so that the HttpClient created for file upload operation has access to those certificates.
                clientOptions.FileUploadTransportSettings.ClientCertificate = cert;
                deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, auth, Client.TransportType.Http1, clientOptions);
            }
            else
            {
                deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, Client.TransportType.Http1, clientOptions);
            }

            var fileUploadSasUriRequest = new FileUploadSasUriRequest()
            {
                BlobName = filename
            };

            FileUploadSasUriResponse fileUploadSasUriResponse = await deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest).ConfigureAwait(false);

            var  blob       = new CloudBlockBlob(fileUploadSasUriResponse.GetBlobUri());
            Task uploadTask = blob.UploadFromStreamAsync(source);
            await uploadTask.ConfigureAwait(false);

            var notification = new FileUploadCompletionNotification
            {
                CorrelationId = fileUploadSasUriResponse.CorrelationId,
                IsSuccess     = uploadTask.IsCompleted
            };

            await deviceClient.CompleteFileUploadAsync(notification).ConfigureAwait(false);

            await FileNotificationTestListener.VerifyFileNotification(filename, testDevice.Id).ConfigureAwait(false);
        }
Exemplo n.º 5
0
        private async Task GetSasUriAsync(Client.TransportType transport, string blobName, bool useX509auth = false)
        {
            using TestDevice testDevice = await TestDevice
                                          .GetTestDeviceAsync(
                      Logger,
                      _devicePrefix,
                      useX509auth
                      ?TestDeviceType.X509
                      : TestDeviceType.Sasl)
                                          .ConfigureAwait(false);

            DeviceClient     deviceClient;
            X509Certificate2 cert = null;
            DeviceAuthenticationWithX509Certificate x509Auth = null;

            if (useX509auth)
            {
                cert     = s_selfSignedCertificate;
                x509Auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert);

                deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, x509Auth, transport);
            }
            else
            {
                deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport);
            }

            using (deviceClient)
            {
                FileUploadSasUriResponse sasUriResponse = await deviceClient.GetFileUploadSasUriAsync(new FileUploadSasUriRequest { BlobName = blobName });

                await deviceClient.CloseAsync().ConfigureAwait(false);
            }

            x509Auth?.Dispose();
        }
Exemplo n.º 6
0
        public async Task RunSampleAsync()
        {
            const string filePath = "TestPayload.txt";

            using var fileStreamSource = new FileStream(filePath, FileMode.Open);
            var fileName = Path.GetFileName(fileStreamSource.Name);

            Console.WriteLine($"Uploading file {fileName}");

            var fileUploadTime = Stopwatch.StartNew();

            var fileUploadSasUriRequest = new FileUploadSasUriRequest
            {
                BlobName = fileName
            };

            // Note: GetFileUploadSasUriAsync and CompleteFileUploadAsync will use HTTPS as protocol regardless of the DeviceClient protocol selection.
            Console.WriteLine("Getting SAS URI from IoT Hub to use when uploading the file...");
            FileUploadSasUriResponse sasUri = await _deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest);

            Uri uploadUri = sasUri.GetBlobUri();

            Console.WriteLine($"Successfully got SAS URI ({uploadUri}) from IoT Hub");

            try
            {
                Console.WriteLine($"Uploading file {fileName} using the Azure Storage SDK and the retrieved SAS URI for authentication");

                // Note that other versions of the Azure Storage SDK can be used here. For the latest version, see
                // https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/storage#azure-storage-libraries-for-net
                var blobClient = new BlobClient(uploadUri);
                await blobClient.UploadAsync(fileStreamSource, overwrite : true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to upload file to Azure Storage using the Azure Storage SDK due to {ex}");

                var failedFileUploadCompletionNotification = new FileUploadCompletionNotification
                {
                    // Mandatory. Must be the same value as the correlation id returned in the sas uri response
                    CorrelationId = sasUri.CorrelationId,

                    // Mandatory. Will be present when service client receives this file upload notification
                    IsSuccess = false,

                    // Optional, user-defined status code. Will be present when service client receives this file upload notification
                    StatusCode = 500,

                    // Optional, user defined status description. Will be present when service client receives this file upload notification
                    StatusDescription = ex.Message
                };

                // Note that this is done even when the file upload fails. IoT Hub has a fixed number of SAS URIs allowed active
                // at any given time. Once you are done with the file upload, you should free your SAS URI so that other
                // SAS URIs can be generated. If a SAS URI is not freed through this API, then it will free itself eventually
                // based on how long SAS URIs are configured to live on your IoT Hub.
                await _deviceClient.CompleteFileUploadAsync(failedFileUploadCompletionNotification);

                Console.WriteLine("Notified IoT Hub that the file upload failed and that the SAS URI can be freed");

                fileUploadTime.Stop();
                return;
            }

            Console.WriteLine("Successfully uploaded the file to Azure Storage");

            var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
            {
                // Mandatory. Must be the same value as the correlation id returned in the sas uri response
                CorrelationId = sasUri.CorrelationId,

                // Mandatory. Will be present when service client receives this file upload notification
                IsSuccess = true,

                // Optional, user defined status code. Will be present when service client receives this file upload notification
                StatusCode = 200,

                // Optional, user-defined status description. Will be present when service client receives this file upload notification
                StatusDescription = "Success"
            };

            await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification);

            Console.WriteLine("Notified IoT Hub that the file upload succeeded and that the SAS URI can be freed.");

            fileUploadTime.Stop();

            Console.WriteLine($"Time to upload file: {fileUploadTime.Elapsed}.");
        }
        public async Task RunSampleAsync()
        {
            const string filePath = "TestPayload.txt";

            using var fileStreamSource = new FileStream(filePath, FileMode.Open);
            var fileName = Path.GetFileName(fileStreamSource.Name);

            Console.WriteLine($"Uploading file {fileName}");

            var fileUploadTime = Stopwatch.StartNew();

            var fileUploadSasUriRequest = new FileUploadSasUriRequest
            {
                BlobName = fileName
            };

            // Note: GetFileUploadSasUriAsync and CompleteFileUploadAsync will use HTTPS as protocol regardless of the DeviceClient protocol selection.
            Console.WriteLine("Getting SAS URI from IoT Hub to use when uploading the file...");
            FileUploadSasUriResponse sasUri = await _deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest);

            Uri uploadUri = sasUri.GetBlobUri();

            Console.WriteLine($"Successfully got SAS URI ({uploadUri}) from IoT Hub");

            try
            {
                Console.WriteLine($"Uploading file {fileName} using the Azure Storage SDK and the retrieved SAS URI for authentication");

                // Note that other versions of the Azure Storage SDK can be used here. For the latest version, see
                // https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/storage#azure-storage-libraries-for-net
                // NOTE: The UploadAsync operation overwrites the contents of the blob, creating a new block blob if none exists.
                // Overwriting an existing block blob replaces any existing metadata on the blob.
                // Set <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations">
                // access conditions through BlobRequestConditions to avoid overwriting existing data.
                // See https://github.com/Azure/azure-sdk-for-net/blob/66d8ab97081a35ebc50c98278110dcac0e4d763e/sdk/storage/Azure.Storage.Blobs/src/BlockBlobClient.cs#L570 for more details.
                var blockBlobClient = new BlockBlobClient(uploadUri);
                await blockBlobClient.UploadAsync(fileStreamSource, new BlobUploadOptions());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to upload file to Azure Storage using the Azure Storage SDK due to {ex}");

                var failedFileUploadCompletionNotification = new FileUploadCompletionNotification
                {
                    // Mandatory. Must be the same value as the correlation id returned in the sas uri response
                    CorrelationId = sasUri.CorrelationId,

                    // Mandatory. Will be present when service client receives this file upload notification
                    IsSuccess = false,

                    // Optional, user-defined status code. Will be present when service client receives this file upload notification
                    StatusCode = 500,

                    // Optional, user defined status description. Will be present when service client receives this file upload notification
                    StatusDescription = ex.Message
                };

                // Note that this is done even when the file upload fails. IoT Hub has a fixed number of SAS URIs allowed active
                // at any given time. Once you are done with the file upload, you should free your SAS URI so that other
                // SAS URIs can be generated. If a SAS URI is not freed through this API, then it will free itself eventually
                // based on how long SAS URIs are configured to live on your IoT Hub.
                await _deviceClient.CompleteFileUploadAsync(failedFileUploadCompletionNotification);

                Console.WriteLine("Notified IoT Hub that the file upload failed and that the SAS URI can be freed");

                fileUploadTime.Stop();
                return;
            }

            Console.WriteLine("Successfully uploaded the file to Azure Storage");

            var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
            {
                // Mandatory. Must be the same value as the correlation id returned in the sas uri response
                CorrelationId = sasUri.CorrelationId,

                // Mandatory. Will be present when service client receives this file upload notification
                IsSuccess = true,

                // Optional, user defined status code. Will be present when service client receives this file upload notification
                StatusCode = 200,

                // Optional, user-defined status description. Will be present when service client receives this file upload notification
                StatusDescription = "Success"
            };

            await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification);

            Console.WriteLine("Notified IoT Hub that the file upload succeeded and that the SAS URI can be freed.");

            fileUploadTime.Stop();

            Console.WriteLine($"Time to upload file: {fileUploadTime.Elapsed}.");
        }
Exemplo n.º 8
0
        static async Task UploadImage(byte[] pictureBytes, string fileName)
        {
            var fileUploadSasUriRequest = new FileUploadSasUriRequest
            {
                BlobName = fileName
            };
            FileUploadSasUriResponse sasUri = await _deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest);

            // Pass URL encoded device name and blob name to support special characters
            Uri uploadUri = new Uri($"https://{sasUri.HostName}/{sasUri.ContainerName}/{Uri.EscapeDataString(sasUri.BlobName)}{sasUri.SasToken}");
            //Console.WriteLine($"Successfully got SAS URI ({uploadUri}) from IoT Hub");
            MemoryStream memStream = new MemoryStream();

            memStream.Write(pictureBytes, 0, pictureBytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            try
            {
                //Console.WriteLine($"Uploading file {fileName} using the Azure Storage SDK and a SAS URI for authentication");
                // Note that other versions of the Azure Storage SDK can be used here. For the latest version, see
                // https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/storage#azure-storage-libraries-for-net
                var blob = new CloudBlockBlob(uploadUri);
                await blob.UploadFromStreamAsync(memStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to upload file to Azure Storage using the Azure Storage SDK due to {ex}");

                var failedFileUploadCompletionNotification = new FileUploadCompletionNotification
                {
                    // Mandatory. Must be the same value as the correlation id returned in the sas uri response
                    CorrelationId = sasUri.CorrelationId,
                    // Mandatory. Will be present when service client receives this file upload notification
                    IsSuccess = false,
                    // Optional, user-defined status code. Will be present when service client receives this file upload notification
                    StatusCode = 500,
                    // Optional, user defined status description. Will be present when service client receives this file upload notification
                    StatusDescription = ex.Message
                };

                // Note that this is done even when the file upload fails. IoT Hub has a fixed number of SAS URIs allowed active
                // at any given time. Once you are done with the file upload, you should free your SAS URI so that other
                // SAS URIs can be generated. If a SAS URI is not freed through this API, then it will free itself eventually
                // based on how long SAS URIs are configured to live on your IoT Hub.
                await _deviceClient.CompleteFileUploadAsync(failedFileUploadCompletionNotification);

                //Console.WriteLine("Notified IoT Hub that the file upload failed and that the SAS URI can be freed");
                return;
            }

            //Console.WriteLine("Successfully uploaded the file to Azure Storage");

            var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
            {
                // Mandatory. Must be the same value as the correlation id returned in the sas uri response
                CorrelationId = sasUri.CorrelationId,
                // Mandatory. Will be present when service client receives this file upload notification
                IsSuccess = true,
                // Optional, user defined status code. Will be present when service client receives this file upload notification
                StatusCode = 200,
                // Optional, user-defined status description. Will be present when service client receives this file upload notification
                StatusDescription = "Success"
            };
            await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification);

            //Console.WriteLine("Notified IoT Hub that the file upload succeeded and that the SAS URI can be freed.");
        }