Azure

Manage Azure Blob Storage Using The Azure SDK

Introduction

The Azure cloud has many possibilities and ways of working and making everything easier for us through computing in the cloud, one of them is the famous blob storage. But then what is a blob storage? … Azure blob storage is designed to store unstructured data, which does not have a defined structure that includes text files, images, videos, documents, and much more. An entity stored in blob storage is called a blob. There are many ways to work a blob storage, in this article we are going to develop a simple way to upload content from a multimedia file such as an image, sound, video, to very heavy files using all the power of the Azure SDK.

Manage Azure Blob storage using the Azure SDK

What you will learn in this article,

  1. Basic concepts of a blob storage in Azure
  2. Create a blob storage container
  3. Connect an application in C # to Azure using its SDK
  4. Upload media files using the Azure SDK

Basic requirements

  1. Visual Studio 2019
  2. An Azure account (For this you can create a new account at no cost)
  3. Net Core 5 installed
  4. Basic knowledge of C #
  5. Willingness to learn

Create a blob storage container

The first thing we must do to put into practice is to start preparing all the necessary resources in the Azure cloud, but for this, we must first create our Azure account (Create an Azure account – Learn | Microsoft Docs). If you already have it then you can skip this step and enter the main Azure portal (https://portal.azure.com) where we are going to select the hamburger button in the upper left corner of the main portal and clicking on the first option as it appears in the following image

Manage Azure Blob storage using the Azure SDK

Once we have clicked, a new page will be displayed, and we will write the word blob in the search bar as shown in the following image

Manage Azure Blob storage using the Azure SDK

By clicking, it will send us to a new page where it will detail all the information related to this resource, introducing the price plans, use of support information, and reviews of this, as well as a suggestion of resources like the storage account that we are going to create, Next, we are going to click the create button as shown in the following image

Manage Azure Blob storage using the Azure SDK

Once the create button is clicked, it will take us to a page where we are going to start configuring our storage account where the first value that it asks us is the subscription. We select the subscription then the resource associated with that subscription. If you do not have a resource you can create a new one by clicking on the “Create New” below the text box. Then in the details section of the instance, we are now going to give a name to our storage account for this article “demostorageazhugh“. The name of the storage account must be in lowercase letters and the name must be accepted by Azure. In the next step we are going to select the region, in this case, I will select ” US South Central US“. In the last step we are going to select the performance and redundancy for this demo. We are going to leave it as default values ​​and we are going to select click the review and create button as shown in the following image

Manage Azure Blob storage using the Azure SDK

Once the validation of all this configuration that we have generated has been successful, what we do is simply click the create button as shown in the following image

Manage Azure Blob storage using the Azure SDK

After waiting for that resource to be created, we will now go to access it by clicking on the go to resource button.

Manage Azure Blob storage using the Azure SDK

Now accessing the page where the resource that we have just generated shows us, we are going to go to the data storage section in the left menu. We are going to see a section called containers and we are going to create a new container by clicking on the symbol of more as the following picture shows

Manage Azure Blob storage using the Azure SDK

Then we are going to go to a window that is displayed on the right side where we are going to write the name of the container where we are going to store our blog files. For this, we are going to determine a name in lowercase and that it is accepted by Azure as such then in the next section we are going to see the access levels of this container. For this, we are going to select the second option for this article as such in order to be able to give public output to the files that we are going to upload later and that can be consumed both read and unloaded dynamically through the Azure SDK, we leave the other options as default and click the create button.

Manage Azure Blob storage using the Azure SDK

To ensure that the files that we are going to upload can be viewed correctly through an Azure URL, we are going to upload a file directly by clicking the upload button, selecting the file and then clicking the upload button. After uploading the file we are going to select it and a window or a page will appear where it will explain the detail directly of everything related to that file itself. There is a property called URL which is where we are going to copy that value and we are going to paste into the browser directly to see if we can already access the container itself as shown in the following images

Manage Azure Blob storage using the Azure SDK

Manage Azure Blob storage using the Azure SDK

In this way, we can already access our files publicly from any browser and we can now generate the application to consume either its life or download our blob files.

Build the console application in Visual Studio 2019

To continue with the development of this article we are going to open visual Studio 2019, then we are going to go to the first dialog window that visual Studio offers us and we are going to select the option to create a new project as shown in the following image

Manage Azure Blob storage using the Azure SDK

Then we are going to go to the search bar and we are going to write console then this is going to filter the types of applications supported in Visual Studio and we are going to select the first option that filters us which is called console application. Note that there are several types of applications with the same name the only thing that varies is the type of language and platform in which they are going to be configured and prepared in the Visual Studio environment. For the purposes of this example, we are going to work with C#, therefore, we are going to select the project corresponding to the C# and .Net Core development platform as shown in the following image

Manage Azure Blob storage using the Azure SDK

We click the next button and a next window will appear where we are going to specify the name of the project, the location of the project and we are going to select the next button again.

Manage Azure Blob storage using the Azure SDK

Then we will see additional information about the framework that we are going to use for development in this case we are going to select .Net 5.0 and we are going to click on the create button as shown in the following image

Manage Azure Blob storage using the Azure SDK

Up to this point we have already configured the cloud storage; we have the necessary permissions, and we already have our console application created in the visual Studio 2019 environment.

Install and configure the Azure SDK

To install the Azure SDK our previously created console solution to be able to either consume files through a download, as well as place or upload these objects to a blog storage container, what we do is simply right-click on the project, and we select the option to handle the NuGets packages as shown in the following image.

Manage Azure Blob storage using the Azure SDK

Once the option is selected, it will show us on the left side a tab where the NuGets package manager will be displayed, where we will then select and type in the Azure search bar.Storage.Blogs and we are going to select the first option and click the install button as shown in the following image

Manage Azure Blob storage using the Azure SDK

Once this step is done well, we can work directly with the Azure SDK, we only have to go back to the Azure portal and bring us the corresponding configuration.

Implementation of the solution

To start consuming the Azure SDK we are going to perform an exercise to download the file that we tested when creating the blob storage container in Azure, then upload a new image and finally we are going to list the files that already exist in blob storage container to confirm that it already exists in the cloud. As a first step to implement, let’s go back to the Azure portal and go to the section of the storage account that we had already generated, and we are going to go to the security section and click on the Access keys option as shown in the following image

Manage Azure Blob storage using the Azure SDK

Next, a new page will open where the access and rotation keys will be displayed, as well as some relevant data in accordance with the security of these keys. We will click on the first option to show the keys that at first glance will be hidden and to be able to copy the information, for this article we are going to copy the Connection String, I took the first key, but without problem, you can take either of the two as shown below in the following image

Manage Azure Blob storage using the Azure SDK

This information of the connection string is necessary to bring it to our application and we are going to create a variable where we are going to paste this connection string and we also need the name of the container that we named when creating the storage account in this case we call it ” demoshugh“, these two values are important to be able to access these cloud resources through the Azure SDK.

static string storageconnstring = "<connection string>";
static string containerName = "demoshugh";
static string fileToDownload = "azure.png";
static string fileToUpload = "azurelogo.png";
static string filepath = @ "C:DemoFiles";

In addition to these 2 values, we will create 3 more variables, fileToDownload variable for name of the file that is already up in the blob container, the fileToUpload variable that refers to the value of the file name that is locally on the pc and we want to upload to that blob container, and finally, the filePath variable is the path where the file is to be uploaded and it will also serve to download the file that we have in said blob container. We need to initialize the BlobServiceClient objects where we are going to pass the storageconnstring variable and we are also going to specify the name of the container through the function inside the blobServiceClient called GetBlobContainerClient and we pass the name of the containerName variable

private static void InitializeBlob() {
    try {
        blobServiceClient = new BlobServiceClient(storageconnstring);
        containerClient = blobServiceClient.GetBlobContainerClient(containerName);
    } catch (Exception) {
        throw;
    }
}

We are going to implement the DownloadBlob method where we are going to specify with the use of the Azure SDK which file we want to download and save on our pc using the following source code fragment below.

private static async Task DownloadBlob() {
    try {
        BlobClient blobClient = containerClient.GetBlobClient(fileToDownload);
        //Download data content of blob and copy to the disc
        using FileStream stream = File.Create(filepath + fileToDownload);
        var result = await blobClient.DownloadToAsync(stream);
        if (result.Status > 200 || result.Status < 300) {
            Console.WriteLine("File downloaded sucessfully!");
            return;
        }
        Console.WriteLine("Error to download file!");
    } catch (Exception) {
        throw;
    }
}

We have already created the method to download an item from the blob container, we are fine no! Now we will proceed to create the UploadBlob method where we are going to upload the file that we have on our computer to store it in the blob storage container as shown in the following code fragment.

private static async Task UploadBlob() {
    try {
        BlobClient blobClient = containerClient.GetBlobClient(fileToUpload);
        var result = await blobClient.UploadAsync(filepath + fileToUpload, true);
        if (result.GetRawResponse().Status == 201) {
            Console.WriteLine("File uploaded sucessfully!");
            return;
        }
        Console.WriteLine("Error to upload file!");
    } catch (Exception) {
        throw;
    }
}

Once the method to download an image has been created, as well as a method to upload an image, to ensure that all the elements exist in our container we are going to create a method to list or obtain the items or files saved in the container using the following code snippet below.

private static void ListBlobs() {
    try {
        Console.WriteLine($ "List of all items in blob {containerName} container");
        Console.WriteLine("----------------------------------------------------");
        // Print out all the blob names
        foreach(BlobItem blob in containerClient.GetBlobs()) {
            Console.WriteLine(blob.Name);
        }
    } catch (Exception) {
        throw;
    }
}

Now let’s put all the pieces together at the starting point of the application in the Main method of the console application.

static void Main(string[] args) {
    InitializeBlob();
    DownloadBlob().Wait();
    UploadBlob().Wait();
    ListBlobs();
}

And in this way we compile and execute the application, to see the entire process in more detail, It is advisable to execute the application by applying breakpoints in each method so that you can see the application flow more closely.

Conclusion

In this way, as we saw in the previous steps, we can quickly demonstrate the use of this Azure SDK to handle a blob storage container dynamically either to upload elements to that container or to be able to download directly by adding a solution database where we could save the information that is generated through a path or URL generated in the blob storage as a good practice for managing multimedia content or file content in our applications. The Azure cloud has a large number of resources and tools that any developer can simply manage from a command console through an SDK as well as its interactive use directly through its web portal, for better management of the information and resources that we want to work in the cloud either from a database to a virtual machine or simply a save of relevant information to be used in any of our applications.

Tags
Show More

Related Articles

Leave a Reply

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

Close