Azure

Add And Obtain File To Azure Blob Storage Utilizing C#

Introduction

Azure Storage is a service offered by Microsoft to retailer the information, akin to textual content or binary. You need to use this knowledge to make it out there to the general public or safe it from public entry. There are a number of methods I discovered on the web to add the content material to Azure Blob Storage like you should utilize shared keys, or use a Connection string, or a local app.

Downside

Now, right here is the issue. Suppose it’s important to create a Home windows Service that can add and obtain your information to the Azure Blob Storage. And as per the necessities, you don’t have to make use of a shared key or connection string, or just your consumer didn’t share it. The consumer needs to get it executed by Energetic Listing Authentication. With the Native app, as many of the samples are over the web, person consent is required in case your token expires and that’s why it can’t be utilized in Home windows Service.

Answer

After spending a while on it, I discovered the suitable method to add and obtain a file on Azure Blob Storage. As I didn’t discover any documentation or samples specific to this requirement over the web, I’m sharing it. Hope it can assist.

Create an utility on Azure

Create an utility of Internet app/API sort on the Azure portal.

Get Keys for Authentication

You could have the applying ID, tenant/Listing ID, and Shopper Secret key.

After utility creation, you will notice the beneath display screen the place you have got the applying ID and from the Keys part, you may generate the Shopper Secret key. See the beneath screens.

Client Secret key

To get a Listing/ Tenant ID.

Directory

Tenant ID

Function task to your Azure utility

Now, go to your storage account that you simply wish to use and assign your utility Storage Blob Knowledge Proprietor/Contributor Function.

Contributor Role

IAM

Really, the above position offers you permissions to learn/write/delete on Blob Administration and Knowledge. With Administration permission, you may learn/write/delete a container within the Blob and with Knowledge, you may learn/write/delete content material in it.

 Blob Management

Now, you have got all of the issues it’s essential construct an utility. Let’s examine the code snippets.

Authentication

The very first thing you want is to get an entry token and you may get it utilizing the beneath technique.

static string GetUserOAuthToken(string tenantId, string applicationId, string clientSecret)  
{  
    const string ResourceId = "https://storage.azure.com/";  
    const string AuthInstance = "https://login.microsoftonline.com/{0}/";  
  
    string authority = string.Format(CultureInfo.InvariantCulture, AuthInstance, tenantId);  
    AuthenticationContext authContext = new AuthenticationContext(authority);  
  
    var clientCred = new ClientCredential(applicationId, clientSecret);  
    AuthenticationResult outcome = authContext.AcquireTokenAsync(  
                                            ResourceId,  
                                            clientCred  
                                        ).End result;  
    return outcome.AccessToken;  
}

File Add and Obtain Strategies

Under is the code snippet to add and obtain the file to Azure Blob Storage.

public static class AzureOperations
{
    #area ConfigParams
    public static string tenantId;
    public static string applicationId;
    public static string clientSecret;
    #endregion

    public static void UploadFile(AzureOperationHelper azureOperationHelper)
    {
        CloudBlobContainer blobContainer = CreateCloudBlobContainer(
            tenantId,
            applicationId,
            clientSecret,
            azureOperationHelper.storageAccountName,
            azureOperationHelper.containerName,
            azureOperationHelper.storageEndPoint
        );

        blobContainer.CreateIfNotExists();
        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(azureOperationHelper.blobName);
        blob.UploadFromFile(azureOperationHelper.srcPath);
    }

    public static void DownloadFile(AzureOperationHelper azureOperationHelper)
    {
        CloudBlobContainer blobContainer = CreateCloudBlobContainer(
            tenantId,
            applicationId,
            clientSecret,
            azureOperationHelper.storageAccountName,
            azureOperationHelper.containerName,
            azureOperationHelper.storageEndPoint
        );

        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(azureOperationHelper.blobName);
        blob.DownloadToFile(azureOperationHelper.destinationPath, FileMode.OpenOrCreate);
    }

    personal static CloudBlobContainer CreateCloudBlobContainer(
        string tenantId,
        string applicationId,
        string clientSecret,
        string storageAccountName,
        string containerName,
        string storageEndPoint
    )
    {
        string accessToken = GetUserOAuthToken(tenantId, applicationId, clientSecret);
        TokenCredential tokenCredential = new TokenCredential(accessToken);
        StorageCredentials storageCredentials = new StorageCredentials(tokenCredential);
        CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(
            storageCredentials,
            storageAccountName,
            storageEndPoint,
            useHttps: true
        );

        CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
        CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
        return blobContainer;
    }

    static string GetUserOAuthToken(string tenantId, string applicationId, string clientSecret)
    {
        const string ResourceId = "https://storage.azure.com/";
        const string AuthInstance = "https://login.microsoftonline.com/{0}/";
        string authority = string.Format(CultureInfo.InvariantCulture, AuthInstance, tenantId);
        AuthenticationContext authContext = new AuthenticationContext(authority);
        var clientCred = new ClientCredential(applicationId, clientSecret);
        AuthenticationResult outcome = authContext.AcquireTokenAsync(ResourceId, clientCred).End result;
        return outcome.AccessToken;
    }
}

Take a look at it in a Console utility.

class Program
{
    static void Most important(string[] args)
    {
        // Set Ids of your Azure account
        AzureOperations.applicationId = "";
        AzureOperations.clientSecret = "";
        AzureOperations.tenantId = "";

        // Demo Add File
        string srcPathToUpload = @"C:Usersabdul.rehmanDesktopAzureFileUploadmyfile.txt";
        UploadFile(srcPathToUpload);

        // Demo Obtain File
        string azurePathInBlob = "dev/information/myfile.txt";
        string destinationPath = @"C:Usersabdul.rehmanDesktopAzureFileDownloadmyfile.txt";
        DownloadFile(destinationPath, azurePathInBlob);
    }

    public static void UploadFile(string srcPath)
    {
        AzureOperationHelper azureOperationHelper = new AzureOperationHelper();
        // your Storage Account Title
        azureOperationHelper.storageAccountName = "dbpoc";
        azureOperationHelper.storageEndPoint = "core.home windows.internet";
        // File path to add
        azureOperationHelper.srcPath = srcPath;
        // Your Container Title
        azureOperationHelper.containerName = "filecontainer";
        // Vacation spot Path you may set it file identify or if you wish to put it in folders do it like beneath
        azureOperationHelper.blobName = $"dev/information/{Path.GetFileName(srcPath)}";
        AzureOperations.UploadFile(azureOperationHelper);
    }

    public static void DownloadFile(string destinationPath, string srcPath)
    {
        AzureOperationHelper azureOperationHelper = new AzureOperationHelper();
        // your Storage Account Title
        azureOperationHelper.storageAccountName = "dbpoc";
        azureOperationHelper.storageEndPoint = "core.home windows.internet";
        // Vacation spot Path the place you wish to obtain file
        azureOperationHelper.destinationPath = destinationPath;
        // Your Container Title
        azureOperationHelper.containerName = "filecontainer";
        // Blob Path in container the place to obtain File
        azureOperationHelper.blobName = srcPath;

        AzureOperations.DownloadFile(azureOperationHelper);
    }
}

NuGet Dependencies

  1. WindowsAzure.Storage (I’ve put in v9.3.3).
  2. Microsoft.IdentityModel.Shoppers.ActiveDirectory (I’ve put in v4.4.2).

There are some things it’s essential verify.

  1. The container identify needs to be in lowercase. I do not know why it isn’t dealt with however on this model, it isn’t working with uppercase.
  2. Permissions are very essential. Your utility position should have learn/write/delete permissions on Blob Administration and Knowledge as effectively.

Abstract

On this above pattern, we realized tips on how to handle our information on Azure Blob Storage with Energetic Listing Authentication utilizing the applying Secret Key. And just like the Native app, no popup will probably be proven to enter the credentials with a purpose to get the entry token.

I’ve additionally uploaded the pattern console utility that you may obtain and take a look at along with your Azure credentials. Be happy to contact me in case of a difficulty.

Obtain Full Pattern

References

Know extra about our firm at Skrots. Know extra about our providers at Skrots Companies, Additionally checkout all different blogs at Weblog at Skrots

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button