Skip to content

Commit 6a968cc

Browse files
committed
Edits
1 parent 1466f94 commit 6a968cc

File tree

4 files changed

+84
-124
lines changed

4 files changed

+84
-124
lines changed

includes/iot-hub-howto-file-upload-dotnet.md

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Follow this procedure to upload a file from a device to IoT Hub:
2525
* Connect to IoT Hub
2626
* Get a SAS URI from IoT Hub
2727
* Upload the file to Azure storage
28-
* Notify IoT Hub that it completed the upload
28+
* Notify IoT hub of the file upload status
2929

3030
### Connect to IoT Hub
3131

@@ -38,7 +38,7 @@ deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
3838

3939
### Get a SAS URI from IoT Hub
4040

41-
Call [GetFileUploadSasUriAsync](/dotnet/api/microsoft.azure.devices.client.deviceclient.getfileuploadsasuriasync) to get a file upload SAS URI, which the Azure Storage SDK can use to upload a file from a device to Blob Storage.
41+
Call [GetFileUploadSasUriAsync](/dotnet/api/microsoft.azure.devices.client.deviceclient.getfileuploadsasuriasync) to get a file upload details. The SAS URI is used in the next step to upload a file from a device to Blob Storage.
4242

4343
```csharp
4444
const string filePath = "TestPayload.txt";
@@ -53,26 +53,28 @@ FileUploadSasUriResponse sasUri = await _deviceClient.GetFileUploadSasUriAsync(f
5353
Uri uploadUri = sasUri.GetBlobUri();
5454
```
5555

56-
### Upload the file to Azure storage
56+
### Upload a file to Azure storage
5757

58-
Create a [blockBlobClient](/dotnet/api/azure.storage.blobs.specialized.blockblobclient) object, passing a file upload URI.
58+
To upload a file to Azure storage:
5959

60-
Use the [UploadAsync](/dotnet/api/azure.storage.blobs.specialized.blockblobclient.uploadasync?#azure-storage-blobs-specialized-blockblobclient-uploadasync(system-io-stream-azure-storage-blobs-models-blobuploadoptions-system-threading-cancellationtoken)) method to upload a file to Blob Storage, passing the SAS URI.
60+
* Create a [blockBlobClient](/dotnet/api/azure.storage.blobs.specialized.blockblobclient) object, passing a file upload URI
61+
62+
* Use the [UploadAsync](/dotnet/api/azure.storage.blobs.specialized.blockblobclient.uploadasync?#azure-storage-blobs-specialized-blockblobclient-uploadasync(system-io-stream-azure-storage-blobs-models-blobuploadoptions-system-threading-cancellationtoken)) method to upload a file to Blob Storage, passing the SAS URI
6163

6264
The Azure Blob client always uses HTTPS as the protocol to upload the file to Azure Storage.
6365

64-
In this example, `BlockBlobClient` is passed the SAS URI to create an Azure Storage block blob client and uploads the file:
66+
In this example, `BlockBlobClient` is passed the SAS URI to create an Azure Storage block Blob client and uploads the file:
6567

6668
```csharp
6769
var blockBlobClient = new BlockBlobClient(uploadUri);
6870
await blockBlobClient.UploadAsync(fileStreamSource, new BlobUploadOptions());
6971
```
7072

71-
### Notify IoT hub that it completed the upload
73+
### Notify IoT hub of the file upload status
7274

73-
Use [CompleteFileUploadAsync](/dotnet/api/microsoft.azure.devices.client.deviceclient.completefileuploadasync) to notify IoT Hub that the device client completed the upload. After being notified, IoT Hub will release resources associated with the upload (the SAS URI).
75+
Use [CompleteFileUploadAsync](/dotnet/api/microsoft.azure.devices.client.deviceclient.completefileuploadasync) to notify IoT Hub that the device client completed the upload, passing a [FileUploadCompletionNotification](/dotnet/api/microsoft.azure.devices.client.transport.fileuploadcompletionnotification) object. The `IsSuccess` flag indicates whether or not the upload was successful. After being notified, IoT Hub will release resources associated with the upload (the SAS URI).
7476

75-
If file upload notifications are enabled, IoT Hub sends a notification message to backend services.
77+
If file upload notifications are enabled, IoT Hub sends a file upload notification message to backend services that are configured for file upload notification.
7678

7779
```csharp
7880
var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
@@ -97,22 +99,7 @@ await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotifi
9799

98100
You can create a backend service to receive file upload notification messages from IoT Hub.
99101

100-
### Add the connection string
101-
102-
Replace the `{IoT Hub connection string}` placeholder value with the IoT Hub connection string.
103-
104-
```csharp
105-
using Microsoft.Azure.Devices;
106-
static ServiceClient serviceClient;
107-
static string connectionString = "{IoT Hub connection string}";
108-
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
109-
```
110-
111-
### Receive file upload notification in a backend application
112-
113-
You can create a separate backend application to receive file upload notifications.
114-
115-
The [ServiceClient](/dotnet/api/microsoft.azure.devices.serviceclient) class contains methods that services can use to receive file upload notification.
102+
The [ServiceClient](/dotnet/api/microsoft.azure.devices.serviceclient) class contains methods that services can use to receive file upload notifications.
116103

117104
To receive file upload notification:
118105

@@ -121,12 +108,20 @@ To receive file upload notification:
121108
* Use a loop with [ReceiveAsync](/dotnet/api/microsoft.azure.devices.receiver-1.receiveasync?#microsoft-azure-devices-receiver-1-receiveasync(system-threading-cancellationtoken)) to wait for the file upload notification.
122109

123110
```csharp
124-
// Define the cancellation token.
111+
using Microsoft.Azure.Devices;
112+
static ServiceClient serviceClient;
113+
static string connectionString = "{IoT Hub connection string}";
114+
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
115+
116+
// Define the cancellation token
125117
CancellationTokenSource source = new CancellationTokenSource();
126118
CancellationToken token = source.Token;
127119

120+
// Create a notification receiver
128121
var notificationReceiver = serviceClient.GetFileNotificationReceiver();
129122
Console.WriteLine("\nReceiving file upload notification from service");
123+
124+
// Check for file upload notifications
130125
while (true)
131126
{
132127
var fileUploadNotification = await notificationReceiver.ReceiveAsync(token);

includes/iot-hub-howto-file-upload-java.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
3737

3838
### Connect to IoT Hub
3939

40-
Instantiate the DeviceClient to connect to IoT hub using the connection string and protocol parameters.
40+
Instantiate the DeviceClient to connect to IoT hub using the Iot hub primary connection string and protocol parameters.
4141

4242
```java
4343
String connString = "IoT hub connection string";
@@ -71,7 +71,7 @@ System.out.println("Blob Uri: " + sasUriResponse.getBlobUri());
7171

7272
### Upload the file to Azure Storage
7373

74-
Pass the blob URI endpoint to [BlobClientBuilder](/java/api/com.azure.storage.blob.blobclientbuilder?#com-azure-storage-blob-blobclientbuilder-buildclient()) to create the [BlobClient](/java/api/com.azure.storage.blob.blobclient) object.
74+
Pass the blob URI endpoint to [BlobClientBuilder.buildclient](/java/api/com.azure.storage.blob.blobclientbuilder?#com-azure-storage-blob-blobclientbuilder-buildclient()) to create the [BlobClient](/java/api/com.azure.storage.blob.blobclient) object.
7575

7676
```java
7777
BlobClient blobClient =
@@ -130,6 +130,8 @@ ServiceClient sc = ServiceClient.createFromConnectionString(connectionString, pr
130130

131131
### Check for file upload status
132132

133+
To check for file upload status:
134+
133135
* Create a [getFileUploadNotificationReceiver](/java/api/com.microsoft.azure.sdk.iot.service.fileuploadnotificationreceiver) object.
134136
* Use [open](/java/api/com.microsoft.azure.sdk.iot.service.fileuploadnotificationreceiver?#com-microsoft-azure-sdk-iot-service-fileuploadnotificationreceiver-open()) to connect to IoT Hub.
135137
* Call [receive](/java/api/com.microsoft.azure.sdk.iot.service.fileuploadnotificationreceiver?#com-microsoft-azure-sdk-iot-service-fileuploadnotificationreceiver-receive()) to check for the file upload status. This method returns a [fileUploadNotification](/java/api/com.microsoft.azure.sdk.iot.service.fileuploadnotification) object. If an upload notice is received, you can view upload status fields using [fileUploadNotification](/java/api/com.microsoft.azure.sdk.iot.service.fileuploadnotification) methods.

includes/iot-hub-howto-file-upload-node.md

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -129,51 +129,52 @@ You can create a backend application to check the IoT Hub service client for dev
129129

130130
### Connect to the IoT Hub service client
131131

132-
Create the [Client](/javascript/api/azure-iothub/client) using [fromConnectionString](/javascript/api/azure-iothub/client?#azure-iothub-client-fromconnectionstring).
132+
Create the [ServiceClient](/javascript/api/azure-iothub/client) using [fromConnectionString](/javascript/api/azure-iothub/client?#azure-iothub-client-fromconnectionstring).
133133

134134
```javascript
135135
const Client = require('azure-iothub').Client;
136136
const connectionString = "{IoT hub connection string}";
137137
const serviceClient = Client.fromConnectionString(connectionString);
138138
```
139139

140+
[Open](/javascript/api/azure-iothub/client?#azure-iothub-client-open-1) the connection to IoT hub.
141+
142+
```javascript
143+
//Open the connection to IoT hub
144+
serviceClient.open(function (err) {
145+
if (err) {
146+
console.error('Could not connect: ' + err.message);
147+
} else {
148+
console.log('Service client connected');
149+
```
150+
140151
### Check for a file upload notification
141152
142153
To check for file upload notifications:
143154
144-
* [Open](/javascript/api/azure-iothub/client?#azure-iothub-client-open-1) the connection to IoT hub.
145155
* Call [getFileNotificationReceiver](/javascript/api/azure-iothub/client?#azure-iothub-client-getfilenotificationreceiver). Supply the name of a file upload callback method that will be called when notification messages are received.
146156
* Process file upload notifications in the callback method.
147157
148158
This example sets up a `receiveFileUploadNotification` notification callback receiver. The receiver interprets the file upload status information and prints a status messsage to the console.
149159
150160
```javascript
151-
//Open the connection to IoT hub
152-
serviceClient.open(function (err) {
153-
if (err) {
154-
console.error('Could not connect: ' + err.message);
155-
} else {
156-
console.log('Service client connected');
157-
//Set up the receiveFileUploadNotification notification message callback receiver
158-
serviceClient.getFileNotificationReceiver(function receiveFileUploadNotification(err, receiver){
161+
//Set up the receiveFileUploadNotification notification message callback receiver
162+
serviceClient.getFileNotificationReceiver(function receiveFileUploadNotification(err, receiver){
163+
if (err) {
164+
console.error('error getting the file notification receiver: ' + err.toString());
165+
} else {
166+
receiver.on('message', function (msg) {
167+
console.log('File upload from device:')
168+
console.log(msg.getData().toString('utf-8'));
169+
receiver.complete(msg, function (err) {
159170
if (err) {
160-
console.error('error getting the file notification receiver: ' + err.toString());
171+
console.error('Could not finish the upload: ' + err.message);
161172
} else {
162-
receiver.on('message', function (msg) {
163-
console.log('File upload from device:')
164-
console.log(msg.getData().toString('utf-8'));
165-
receiver.complete(msg, function (err) {
166-
if (err) {
167-
console.error('Could not finish the upload: ' + err.message);
168-
} else {
169-
console.log('Upload complete');
170-
}
171-
});
172-
});
173+
console.log('Upload complete');
173174
}
174175
});
175-
}
176-
});
176+
});
177+
}
177178
```
178179
179180
### SDK file upload sample

includes/iot-hub-howto-file-upload-python.md

Lines changed: 34 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Follow this procedure to upload a file from a device to IoT hub:
3434
* Upload the file to Blob Storage
3535
* Notify IoT hub of upload status
3636

37-
### Connect to IoT hub
37+
### Import libraries
3838

3939
```python
4040
import os
@@ -43,31 +43,30 @@ from azure.core.exceptions import AzureError
4343
from azure.storage.blob import BlobClient
4444
```
4545

46-
Call [create_from_connection_string](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-create-from-connection-string) to connect to IoT hub.
46+
### Connect to IoT hub
47+
48+
Call [create_from_connection_string](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-create-from-connection-string) to add the connection string. Then call [connect](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-connect) to connect the device client to an Azure IoT hub.
4749

4850
For example:
4951

5052
```python
53+
# Add your IoT hub primary connection string
5154
CONNECTION_STRING = "{IoT hub connection string}"
5255
device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
53-
```
54-
55-
Call [connect](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-connect) to connect the device client to an Azure IoT hub.
5656

57-
```python
5857
# Connect the client
5958
device_client.connect()
6059
```
6160

6261
### Get Blob Storage information
6362

64-
Call [get_storage_info_for_blob](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-get-storage-info-for-blob) to get information from an IoT hub about a linked Storage Account. This information includes the hostname, container name, blob name, and a SAS token. The storage info is passed to the `store_blob` function (created in the previous step), so that the `BlobClient` in that function can authenticate with Azure storage. The `get_storage_info_for_blob` method also returns a `correlation_id`, which is used in the notify_blob_upload_status method. The correlation_id is IoT Hub's way of marking which blob you're working on.
63+
Call [get_storage_info_for_blob](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-get-storage-info-for-blob) to get information from an IoT hub about a linked Azure Storage account. This information includes the hostname, container name, blob name, and a SAS token. The `get_storage_info_for_blob` method also returns a `correlation_id`, which is used in the `notify_blob_upload_status` method. The `correlation_id` is IoT Hub's way of marking which Blob you're working on.
6564

6665
```python
6766
# Get the storage info for the blob
6867
PATH_TO_FILE = "[Full path to local file]"
6968
blob_name = os.path.basename(PATH_TO_FILE)
70-
storage_info = device_client.get_storage_info_for_blob(blob_name)
69+
blob_info = device_client.get_storage_info_for_blob(blob_name)
7170
```
7271

7372
### Upload a file into Blob Storage
@@ -77,41 +76,40 @@ To upload a file into Blob Storage:
7776
* Use [from_blob_url](/python/api/azure-storage-blob/azure.storage.blob.blobclient?#azure-storage-blob-blobclient-from-blob-url) to create a [BlobClient](/python/api/azure-storage-blob/azure.storage.blob.blobclient?#azure-storage-blob-blobclient-from-blob-url) object from a blob URL.
7877
* Call [upload_blob](/python/api/azure-storage-blob/azure.storage.blob.blobclient?#azure-storage-blob-blobclient-upload-blob) to upload the file into the Blob Storage.
7978

80-
This example function parses the passed `blob_info` structure to create a URL that it uses to initialize an [BlobClient](/python/api/azure-storage-blob/azure.storage.blob.blobclient). Then it calls `upload_blob` to upload the file into Blob Storage.
79+
This example parses the `blob_info` structure to create a URL that it uses to initialize an [BlobClient](/python/api/azure-storage-blob/azure.storage.blob.blobclient). Then it calls `upload_blob` to upload the file into Blob Storage.
8180

8281
```python
83-
def store_blob(blob_info, file_name):
84-
try:
85-
sas_url = "https://{}/{}/{}{}".format(
86-
blob_info["hostName"],
87-
blob_info["containerName"],
88-
blob_info["blobName"],
89-
blob_info["sasToken"]
90-
)
91-
92-
print("\nUploading file: {} to Azure Storage as blob: {} in container {}\n".format(file_name, blob_info["blobName"], blob_info["containerName"]))
93-
94-
# Upload the specified file
95-
with BlobClient.from_blob_url(sas_url) as blob_client:
96-
with open(file_name, "rb") as f:
97-
result = blob_client.upload_blob(f, overwrite=True)
98-
return (True, result)
99-
100-
except FileNotFoundError as ex:
101-
# catch file not found and add an HTTP status code to return in notification to IoT Hub
102-
ex.status_code = 404
103-
return (False, ex)
104-
105-
except AzureError as ex:
106-
# catch Azure errors that might result from the upload operation
107-
return (False, ex)
82+
try:
83+
sas_url = "https://{}/{}/{}{}".format(
84+
blob_info["hostName"],
85+
blob_info["containerName"],
86+
blob_info["blobName"],
87+
blob_info["sasToken"]
88+
)
89+
90+
print("\nUploading file: {} to Azure Storage as blob: {} in container {}\n".format(file_name, blob_info["blobName"], blob_info["containerName"]))
91+
92+
# Upload the specified file
93+
with BlobClient.from_blob_url(sas_url) as blob_client:
94+
with open(file_name, "rb") as f:
95+
result = blob_client.upload_blob(f, overwrite=True)
96+
return (True, result)
97+
98+
except FileNotFoundError as ex:
99+
# catch file not found and add an HTTP status code to return in notification to IoT Hub
100+
ex.status_code = 404
101+
return (False, ex)
102+
103+
except AzureError as ex:
104+
# catch Azure errors that might result from the upload operation
105+
return (False, ex)
108106
```
109107

110108
### Notify IoT hub of upload status
111109

112110
Use [notify_blob_upload_status](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-notify-blob-upload-status) to notify IoT hub of the status of the Blob Storage operation. Pass the `correlation_id` obtained by the `get_storage_info_for_blob` method. The `correlation_id` is used by IoT Hub to notify any service that might be listening for a notification regarding the status of the file upload task.
113111

114-
For example:
112+
This example notifies IoT hub of a successful file upload:
115113

116114
```python
117115
device_client.notify_blob_upload_status(storage_info["correlationId"], True, 200, "OK: {}".format(PATH_TO_FILE)
@@ -125,43 +123,7 @@ Shut down the client. Once this method is called, any attempts at further client
125123
device_client.shutdown()
126124
```
127125

128-
### Error handling example
129-
130-
This example shows a function that contains the previous steps including error handling logic.
131-
132-
```python
133-
def run_sample(device_client):
134-
# Connect the client
135-
device_client.connect()
136-
137-
# Get the storage info for the blob
138-
blob_name = os.path.basename(PATH_TO_FILE)
139-
storage_info = device_client.get_storage_info_for_blob(blob_name)
140-
141-
# Upload to blob
142-
success, result = store_blob(storage_info, PATH_TO_FILE)
143-
144-
if success == True:
145-
print("Upload succeeded. Result is: \n")
146-
print(result)
147-
print()
148-
149-
device_client.notify_blob_upload_status(
150-
storage_info["correlationId"], True, 200, "OK: {}".format(PATH_TO_FILE)
151-
)
152-
153-
else :
154-
# If the upload was not successful, the result is the exception object
155-
print("Upload failed. Exception is: \n")
156-
print(result)
157-
print()
158-
159-
device_client.notify_blob_upload_status(
160-
storage_info["correlationId"], False, result.status_code, str(result)
161-
)
162-
```
163-
164-
### Sample
126+
### SDK file upload sample
165127

166128
The SDK includes two file upload samples:
167129

0 commit comments

Comments
 (0)