Creating Blob Storage In Microsoft Azure Using C# ASP.NET

Introduction

This article will discuss how we can create/use MS Azure storage in ASP.NET Web application using MS Libraries. I am not an expert to discuss all the parts of Azure Storage but I am sharing information about Blob Storage.

What is Microsoft Azure Storage?

It is a Microsoft managed cloud storage service that provides storage of the user data. Azure storage consists of Blob storage, File Storage, and Queue storage. Using this service, we can store any kind of data such as text, image, files etc.

What is Blob Storage?

Blob storage is used to store unstructured data in Microsoft managed cloud service. We can access the data from anywhere where we  have an internet connection 😛 in HTTP and HTTPS mode. Also, we can restrict the access to the blob storage as public or private.

We are storing the data in file system and we will have a main folder called container and inside that, we can keep the items in folders or as it is.

Microsoft Azure Storage

Let's start with Azure Account

Create Azure Account

Those who have a Microsoft account can sign in using those account details and use the service free for 30 days. To learn about blob storage this is enough; if you need to use this for your application then you need to buy a subscription.

Microsoft Azure Storage

Property Name Description
NameThe name must be unique. Minimum of 3 letters long and a maximum of 24.
Note: -lowercase letters and numbers are allowed.
Deployment modelClassic:-In this mode; the resources will be independent, will not treat it as a group. We need to manage each resource separately.Resource manager (ARM): - it a new feature in Azure storage, it will consider all the resource as a group, using power shell commands we can manage the resource easily.
PerformanceStandard:-It is storing the Data in magnetic drives, if your application frequently accesses the data or bulk data storage then we can choose this.Premium:-It is mainly used with azure virtual machines, if it is best for intensive applications like database
ReplicationHow/where the data replicates.  Replication copies the data in the storage and keep it in same data center or in different. Please see the table of data below from Microsoft about replication strategy.
Secure Transfer RequiredIt is about HTTP and HTTPS transfer.
SubscriptionPlease select your subscription.
Resource GroupIt is to group different services in single group. You can create different resource group for different application.
LocationYou can select the Data Center location.
Virtual networks (Preview)You can use virtual network to access this storage.

Microsoft Azure Storage

Select Blob Storage

Select the storage account and choose the storage type "Blobs" from the list.

Microsoft Azure Storage

Lets Start to Store data.

You have many options to use /manage the storage accounts. Here we are going to discuss how we can achieve the same using C# code.

In brief, in this application I am using the blob storage to store the images generated and the images uploaded from the client system via my web application.

Before we start Writing code

  1. Create a new web application in Visual studio (I am using Visual Studio 2015).

    Microsoft Azure Storage

  2. Using NuGet we can install required Assembly packages.

Go to "Manage Package for Solution Menu" and search for WindowsAzure.Storage and WindowsAzure.ConfigurationManager and click on install.

Now two packages are installed in your application, see the screenshot below.

Microsoft Azure Storage

  1. Add the following Azure Connection string to the web.config file. Don't forget to update the "AccountName" and "AccountKey". These two items you can get from the Azure portal itself,  you can even get the entire connection string from there. See the screenshot below.

    Microsoft Azure Storage

  1. <configuration>  
  2.     <startup>  
  3.         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup>  
  4.     <appSettings>  
  5.         <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key" /> </appSettings>  
  6. </configuration>  

Now your Development Environment is Ready, Let's Start with blob storage.

See below screen shot for how I designed my web application to complete this task. Here the Business Logic and Models I have created, you can choose your way of coding standards, that’s your choice.

Microsoft Azure Storage

Should include the below assemblies in the code.

  1. using Microsoft.WindowsAzure; // Namespace for CloudConfigurationManager  
  2. using Microsoft.WindowsAzure.Storage; // Namespace for CloudStorageAccount  
  3. using Microsoft.WindowsAzure.Storage.Blob; // Namespace for Blob storage types  
  4. using Microsoft.Azure; // Namespace for CloudConfigurationManager  

Create Container

As I mentioned above, Blob items will reside inside a container in Azure Blob Storage. If we check the blob item URL then the container will be a part of the URL. It's like if we are accessing the file from file explorer then the path will contain the base folder.

Eg.

Microsoft Azure Storage

Rules to Create Container Name

Name should be in lower case

Must be at least 3 letters long and max 63 character allowed

Should start with letter or number no special character except "-"

The below sample code will create a new container using C# code while creating the object of the AzureBlobHelper class.

  1. public class AzureBlobHelper   
  2. {  
  3.     CloudStorageAccount storageAAccountConnection {  
  4.         get {  
  5.             return CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));  
  6.         }  
  7.     } //Getting Blob Connection string  
  8.     CloudBlobClient _blobClient {  
  9.         get {  
  10.             return storageAAccountConnection.CreateCloudBlobClient();  
  11.         }  
  12.     }  
  13.     CloudBlobContainer _blobcontainer {  
  14.         get {  
  15.             return _blobClient.GetContainerReference("sampl");  
  16.         }  
  17.     }  
  18.     public AzureBlobHelper() {  
  19.         _blobcontainer.CreateIfNotExists();  
  20.     }  
  21. }  

Now, check your storage account, you can see the container sample generated.

By default, the container will be private, no one can access from outside. To set the permissions we should use the SetPermission method as below.

  1. CloudBlobContainer .SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });  

Please try different permissions in the list.

Upload a file(Blob) to container

Just now we created container in our storage account, now we need a file inside that container

Before uploading the file to blob we need to get the reference on the container. Once the container is available in the storage account then only we can upload the files to the storage account.

As per my design while creating the object of the AzureHelper class we will get the reference to the container. Check Create Container part.

To upload the file, I have created the following function in the AzureHelper class.

  1. public void SaveDataToAzureBlob(postedFileModel filemodel)  
  2. {  
  3.     Stream _streamContent;  
  4.     HttpWebRequest _requestPage = (HttpWebRequest) WebRequest.Create(filemodel.filePath);  
  5.     HttpWebResponse _responseRequest = (HttpWebResponse) _requestPage.GetResponse();  
  6.     CloudBlockBlob _blockblob = _blobcontainer.GetBlockBlobReference(filemodel.filename); //Createing a Blob  
  7.     // Create or overwrite the blob with contents from a local file.  
  8.     _blockblob.UploadFromStream(_responseRequest.GetResponseStream());  
  9. }  

You can upload the file to blob from Stream, File,ByteArray,Text etc. Try to find out the proper upload function for your requirement from the CloudBlockBlob  class.

If the file name contains any directory name then those directories will create automatically in container.

Eg./Image/Barcode/image.png

Get List of Items from Blob

We created the container, uploaded the files to the blob. Now we are trying to get the list of items from the blob. For this also we need the reference of the container, and with the help of CloudBlobContainer.ListBlobs() function we can retrieve the all the items from the container.

The first parameter is will be the name of the blob object or you need all the file then just pass "null" as parameter. See the example code below.

  1. public List < BlobList > GetListOfata(postedFileModel filemodel) {  
  2.     List < BlobList > _blobList = new List < BlobList > ();  
  3.     if (filemodel != null) {  
  4.         CloudBlockBlob _blobpage = (CloudBlockBlob) _blobcontainer.ListBlobs(filemodel.filename, false).FirstOrDefault();  
  5.         _blobList.Add(new BlobList() {  
  6.             URI = _blobpage.Uri.ToString(), length = _blobpage.Properties.Length  
  7.         });  
  8.     } else {  
  9.         foreach(IListBlobItem item in _blobcontainer.ListBlobs(nullfalse)) {  
  10.             if (item.GetType() == typeof(CloudBlockBlob)) {  
  11.                 CloudBlockBlob _blobpage = (CloudBlockBlob) item;  
  12.                 _blobList.Add(new BlobList() {  
  13.                     URI = _blobpage.Uri.AbsoluteUri.ToString(), length = _blobpage.Properties.Length  
  14.                 });  
  15.             }  
  16.         }  
  17.     }  
  18.     return _blobList;  
  19. }  

In first condition, only the blob has the given name and in the else condition, we are getting all the list of items.

Conclusion

It's your turn to check, find out and use the remaining functions and services by Azure blob storage. I just discussed about Save and List the items from the Blob storage. You will get more help from the URL mentioned in the Reference part.

Reference

  • https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-deployment-model
  • https://docs.microsoft.com/en-us/azure/storage/blobs/storage-dotnet-how-to-use-blobs


Similar Articles