如何从Xamarin PCL项目通过IOT集线器将文件上传到Azure Blob存储 [英] How to upload a file to azure Blob storage through IOT hub from a Xamarin PCL project

查看:57
本文介绍了如何从Xamarin PCL项目通过IOT集线器将文件上传到Azure Blob存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要将此json文件从IotHub上传到AzureBlob存储.到目前为止,我有一个存储帐户和一个链接到我的IoT HUb的容器.我有一个PCL项目,该项目链接到3个平台项目(Android,iOS和UWP).在我的PCL项目中,我有一个deviceClient,否则将发送遥测数据.

So I need to upload this json file to my AzureBlob storage from my IotHub. So far I have a storage account and a container linked to my IoT HUb. I have a PCL project that is linked to 3 platform projects(Android, iOS, and UWP). In my PCL project, I have a deviceClient that otherwise sends telemetry data.

我尝试使用 https://docs.microsoft.com/zh-cn/azure/iot-hub/iot-hub-csharp-csharp-file-upload

private static async void SendToBlobAsync()
{
    string fileName = "data.json";
    Console.WriteLine("Uploading file: {0}", fileName);
    var watch = System.Diagnostics.Stopwatch.StartNew();

    using (var sourceData = new FileStream(@"image.jpg", FileMode.Open))
    {
        await deviceClient.UploadToBlobAsync(fileName, sourceData);
    }

    watch.Stop();
    Console.WriteLine("Time to upload file: {0}ms\n",batch.ElapsedMilliseconds);
}

但是我没有在IntelliSense上获得方法"UploadToBlobAsync".

But I don't get the method "UploadToBlobAsync" on the IntelliSense.

我正在使用VS2017.

I am using VS2017.

已添加NuGet软件包:Microsoft.Azure.Devices.Client.PCL

NuGet packages added: Microsoft.Azure.Devices.Client.PCL

我的IOTHubHelper类具有对Microsoft.Azure.Devices.Client的引用;

My IOTHubHelper Class has the reference to Microsoft.Azure.Devices.Client;

推荐答案

方法 Microsoft.Azure.Devices.Client.DeviceClient.UploadToBlobAsync 基本上是用于blob上传会话的REST API调用的包装通过Azure IoT中心.该会话的顺序分为3个步骤,例如:第1步.从Azure IoT中心获取上传信息参考(公开会话)第2步.根据收到的参考信息上传Blob第3步.关闭发布上传过程结果的会话.

The method Microsoft.Azure.Devices.Client.DeviceClient.UploadToBlobAsync is basically a wrapper around the REST API calls for blob uploading session via the Azure IoT Hub. The sequence of this session is divided into the 3 steps such as: Step 1. Get the upload info reference from the Azure IoT Hub (open session) Step 2. uploading a blob based on the received reference info Step 3. Close the session posting a result of the upload process.

以下代码段显示了在PCL项目中实现的上述步骤的示例:

The following code snippet shows an example of the above steps implemented in PCL project:

    private async Task UploadToBlobAsync(string blobName, Stream source, string iothubnamespace, string deviceId, string deviceKey)
    {
        using(HttpClient client = new HttpClient())
        {
            // create authorization header
            string deviceSasToken = GetSASToken($"{iothubnamespace}.azure-devices.net/devices/{deviceId}", deviceKey, null, 1);
            client.DefaultRequestHeaders.Add("Authorization", deviceSasToken);

            // step 1. get the upload info
            var payload = JsonConvert.SerializeObject(new { blobName = blobName }); 
            var response = await client.PostAsync($"https://{iothubnamespace}.azure-devices.net/devices/{deviceId}/files?api-version=2016-11-14", new StringContent(payload, Encoding.UTF8, "application/json"));                
            var infoType = new { correlationId = "", hostName = "", containerName = "", blobName = "", sasToken = "" };
            var uploadInfo = JsonConvert.DeserializeAnonymousType(await response.Content.ReadAsStringAsync(), infoType);

            // step 2. upload blob
            var uploadUri = $"https://{uploadInfo.hostName}/{uploadInfo.containerName}/{uploadInfo.blobName}{uploadInfo.sasToken}";
            client.DefaultRequestHeaders.Add("x-ms-blob-type", "blockblob");
            client.DefaultRequestHeaders.Remove("Authorization");
            response = await client.PutAsync(uploadUri, new StreamContent(source));

            // step 3. send completed
            bool isUploaded = response.StatusCode == System.Net.HttpStatusCode.Created;
            client.DefaultRequestHeaders.Add("Authorization", deviceSasToken);
            payload = JsonConvert.SerializeObject(new { correlationId = uploadInfo.correlationId, statusCode = isUploaded ? 0 : -1, statusDescription = response.ReasonPhrase, isSuccess = isUploaded });
            response = await client.PostAsync($"https://{iothubnamespace}.azure-devices.net/devices/{deviceId}/files/notifications?api-version=2016-11-14", new StringContent(payload, Encoding.UTF8, "application/json"));
        }
    }

对于授权标头,我们需要一个sasToken,因此以下代码段显示了其实现:

for authorization header we need a sasToken, so the following code snippet shows its implementation:

    private string GetSASToken(string resourceUri, string key, string keyName = null, uint hours = 24)
    {
        var expiry = Convert.ToString((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds + 3600 * hours);
        string stringToSign = System.Net.WebUtility.UrlEncode(resourceUri) + "\n" + expiry;
        HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        var sasToken = keyName == null ?
            String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", System.Net.WebUtility.UrlEncode(resourceUri), System.Net.WebUtility.UrlEncode(signature), expiry) :
            String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", System.Net.WebUtility.UrlEncode(resourceUri), System.Net.WebUtility.UrlEncode(signature), expiry, keyName);
        return sasToken;
    }

请注意,上述实现在第2步中不处理重试机制.

Note, that the above implementation doesn't handle a retrying mechanism in the step 2.

这篇关于如何从Xamarin PCL项目通过IOT集线器将文件上传到Azure Blob存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆