When writing code for Dynamics 365 online plugins, you are limited to assemblies you can use within the sandbox. Luckily you can use the HTTPClient, which allows you to upload a file to an Azure Blob Storage Container without using any of the Azure Blob Storage Nuget Packages found here. This blog will show you how to achieve this while using a SAS (shared access signature), you can find more information on SAS tokens here.
To do this, you will need your SAS token as mentioned above and a Blob Storage Container setup. My URL for the blob container is, ‘https://example.blob.core.windows.net/test-container’ while my SAS token example is ‘sv=2019-12-12&ss=b&srt=o&sp=rwdlacx&se=2025-10-08T06:00:03Z&st=2020-10-07T22:00:03Z&spr=xxxxx’.
Let’s say you want to upload a file ‘test.txt’ to your blob storage container using the SAS token above. The request URL is broken down like this:
Blob Storage Authenticated URL structure: {blobStorageUrl}/{blobContainer}/{fileName}?{sasToken}
Blob Storage Authenticated URL: https://example.blob.core.windows.net/test-container/test.txt?sv=2019-12-12&ss=b&srt=o&sp=rwdlacx&se=2025-10-08T06:00:03Z&st=2020-10-07T22:00:03Z&spr=xxxxx
To use this authenticated URL code, you simply pass the byteArray of the file you want to upload with the mimeType within the ‘Content-Type’ header and viola! You have successfully uploaded your file into the blob storage. Now check out the code below:
byte[] dataByteArray = Convert.FromBase64String(base64Data); string blobAuthenticatedPath = "https://example.blob.core.windows.net/test-container/test.txt?sv=2019-12-12&ss=b&srt=o&sp=rwdlacx&se=2025-10-08T06:00:03Z&st=2020-10-07T22:00:03Z&spr=xxxxx"; Uri blobUri = new Uri(blobAuthenticatedPath); try { using (HttpClient client = new HttpClient()) { var content = new StreamContent(new MemoryStream(dataByteArray)); content.Headers.Add("x-ms-blob-type", "BlockBlob"); string mimeType = "text/plain"; content.Headers.Add("Content-Type", mimeType); var response = client.PutAsync(blobUri, content).Result; if (!response.IsSuccessStatusCode) { throw new InvalidPluginExecutionException("Put request wasn't a success."); } } } catch (Exception e) { throw new InvalidPluginExecutionException("Your file upload wasn't successful."); }
This is a simple example of how to upload any file to a blob storage container. To access the file you simply use the URL without the sasToken, i.e. https://example.blob.core.windows.net/test-container/test.txt. I hope this helps when you’re working with Azure Blob Storage in Dynamics 365.