Easy Guide to Azure Blob Storage for .NET Developers
Tags: azureapril, csharp, dotnet, azure
Published: 2021-09-10 05:25:52

## What is Azure Blob Storage ?
Azure Blob storage is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn't adhere to a particular data model or definition, such as text or binary data.


## Why Azure Blob Storage ?
* Serving images or documents directly to a browser.
* Storing files for distributed access.
* Streaming video and audio.
* Writing to log files.
* Storing data for backup and restore, disaster recovery, and archiving.
* Storing data for analysis by an on-premises or Azure-hosted service.

All of above theory from [Microsoft's Documentations about Blob Storage](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction) . Now Let get into the point ,

Today we will go fast forward to see how its works rather than knowing too deep architecture, its pretty straight forward for visualize the work flow of azure blob storage. 

## What we will learn today ?
Today we will store a image to blob storage and retrieve it using NET5 web project.

## Ingredient's

* Visual Studio Code
* NET5 SDK
* Azure Account [*Its Free for 1 month](https://azure.microsoft.com/en-us/services/storage/blobs/)

To Continue further steps sign up in Azure.


## **Azure Blob Storage Setup** 
<div>

After creating Azure Account , Open Azure Portal . In the homepage will will notice a icon named "create a resource" click it. <br>
![Home Page of Azure Portal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iu6imjjlsq96wvlb4kxq.png)

<br>
You will see a search bar there you type "Blob" & hit in "Storage Account" , create a storage account & set a storage account name. here I set my storage name is "**blobazdemo**"


![Resource Creating page in Azure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bmr1iwg1p9vebjq2g5u.png)
![Resource Creating page in Azure 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqnxj5lxgln8rzf6hjk4.png)
![Resource Creating page in Azure 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0oghscsnhf9j5f3bcme.png)

<div>
So if everything goes well you will get validation passed message then create storage & waiting for deployment.
![Resource Creating page in Azure 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zkgavy3ko2unb5t0k41j.png)

![Running Deployment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kuts4f9ijldu636j878r.png)


![Deployment Complete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cc8jcxjt84yacygzwove.png)
<div>
After complete deployment, Go to resource and find container option from resource side nav options. Create a container inside it to store out images. Here I set my container name is "azdemo"
<div/>
![Container](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hty9ounegp7k5vgdeu3z.png)
 
Here the last steps, now we need connection string to connect our blob storage container to our API project. To again from your resource side nav option find out "Access key" follow the steps and copy the "connection string".

![Access Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eli09r3zrjauseli3zhv.png)

That's all for now to working with azure blob storage. 


## Web Project Setup
We mainly focus on how we can store image in blob storage not making a fancy application. I recommend you to create 'webapp' or 'webapi' using dotnet cli its up to you.

Check available command to create new project
```
dotnet new --list
```
<div>
Now you can create your dotnet project by using this command schema,
<div>
```
dotnet new <TEMPLATE> [--dry-run] [--force] [-lang|--language {"C#"|"F#"|VB}]
    [-n|--name <OUTPUT_NAME>] [-o|--output <OUTPUT_DIRECTORY>] [Template options]
```
<div>
We will make a Service for responsible to store & retrieve image in azure blob storage, so before start making service we need to add a Nuget package in our project. By following,
<div>
```
dotnet add package Azure.Storage.Blobs --version 12.10.0
``` 
[Know More About Azure Storage Blob Nuget Package]
(https://www.nuget.org/packages/Azure.Storage.Blobs)

<div>

**Let Jump into coding part 😀**

 *  Update your ``startup.cs`` by following,

  ```
  services.AddSingleton(x => new BlobServiceClient(PUT_YOUR_BLOB_CONNECTION_STRING));
  ```
<div>
<div>

*  Create a service class in my case I named it ``BlobService``. You can set any name you want. Then Inject ``BlobServiceClient`` which is provid by ``Azure.Storage.Blobs``.

```
 public class BlobService 
    {
        // BlobServiceClient from 'Azure.Storage.Blobs' package
        private readonly BlobServiceClient _blobClient;

        public BlobService(BlobServiceClient blobClient)
        {
            _blobClient = blobClient;
        }
}

```

<div>

*  Let fetch data from blob storage. its pretty straight forward.

```
 public async Task<IEnumerable<string>> AllBlobs(string containerName)
        {
            // allow us to get access to data inside container
            // in our senario 'containerName' will be 'azblob'
            var containerClient = _blobClient.GetBlobContainerClient(containerName);
            var files = new List<string>();
            var blobs = containerClient.GetBlobsAsync();
            await foreach (var item in blobs)
            {
                files.Add(item.Name);
            }
            return files;
        }
```

<div>

* Upload Image into blob storage 

```
        public async Task<bool> UploadBlob(string name, IFormFile file, string containerName)
        {
          // in our senario 'containerName' will be 'azblob'
            var containerClient = _blobClient.GetBlobContainerClient(containerName);
            // checking is current file is exit; if exit then ovverrite
            var blobClient = containerClient.GetBlobClient(name);

            var httpHeaders = new BlobHttpHeaders()
            {
                ContentType = file.ContentType
            };

            var res = await blobClient.UploadAsync(file.OpenReadStream(), httpHeaders);

            if (res != null) return true;
            return false;
        }

```
[Here The Complete Code of Service](https://gist.github.com/sefatanam/69012a05396ef4f0cc8ea70a2531597e)


* Now, We should trigger these method from controller right. Get into it, Post an image through API. [ Here I used basic mvc app to also display updated image ]

```
 [HttpPost]
        public async Task<IActionResult> AddFile(IFormFile file)
        {
            if (file == null || file.Length < 1) return View();
            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
            var res = await _service.UploadBlob(fileName, file, "azdemo");

            if (res) return RedirectToAction("Index");

            return View();
        }
```

After Successfully Posting image via API go to Azure Portal and open ``azdemo`` container you can see their a image file is created.

* Click on the view from given options.

![Click on Options](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m5hlpn46vfxnz36p0noq.png)
* Finally your image is there. 

![Image View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wi9q765t0zwv4p1rbdtp.png)

[Here The Complete Code of Controller](https://gist.github.com/sefatanam/bf48a9fdfa7fa1c344d1a5fdb3ec0726)

That's all for today. Hope now you can easily complete rest of the functionality your self.

Happy Coding
I’m Sefat Anam
Full-Stack Developer ( Angular, .NET )
Email: sefatanam@outlook.com