Showing posts with label SASKey using C#. Show all posts
Showing posts with label SASKey using C#. Show all posts

Saturday, October 12, 2019

Helper class to upload file to azure blob storage container with SASKey using C#

This blog walk thorough the helper class which help us to save file to desired private azure blob storage container using shared access signatures Key(SASKey).

using System;
using System.Net.Http;

namespace JP_CloudStorageHelperClass
{
    public class JP_CloudStorageHelperLocal
    {
        HttpClient httpClient = new HttpClient();

        //_StorageAccountName:- storage account name where you would like to save the file
        //_SASKey:- Which grant limited access to Azure Storage resources using SASKey
        //_BlobName: Name of the file 
        // _stream:- file stream you would like to drop to blob

        public Boolean saveFileInBlob(string _StorageAccountName, string _Container, string _SASKey = "", string _BlobName ="" , System.IO.Stream _stream = null)
        {
            string storageAddress = string.Format("https://{0}.blob.core.windows.net/", _StorageAccountName);

            //preparing URI to drop the file to blob
            Uri containerUrl = new Uri(storageAddress + $"{_Container}/{_BlobName}" + "?" + _SASKey);

            // which returns complete URI which is prepared in previous step
            string sasUri = containerUrl.AbsoluteUri;

            //x-ms-blob-type: <BlockBlob> - Returns the blob's type.
            httpClient.DefaultRequestHeaders.Add("x-ms-blob-type", "BlockBlob");

            // Drops the specified Uri as an asynchronous operation to blob
            HttpResponseMessage response = httpClient.PutAsync(sasUri,new StreamContent(_stream)).GetAwaiter().GetResult();

            if (response.IsSuccessStatusCode)
                return true;
            else
                return false;
        }
    }
}

This project can be referenced in D365FO project  and make use of this helper class for more details please check my previous post. of course there are direct class in X++ which can be used instead of this approach. this is just another way of doing it.

Hope this helps and I will come up with another interesting blog post soon.

Happy Daxing :)

Tags
#D365FO, #Azure, #AzureBlob, #Blob, #DropFileToBlob, #UploadFileToBlob