Overview Of Microsoft Azure Storage - Part Three

This is the third part of the series on Azure storage. In this article, you’ll see how we can perform different operations on storage such as creating container, uploading blobs to the container, listing of blobs and deleting of blobs through the code. For this, you have to follow the prerequisites given below.

  • Microsoft Visual Studio 2015(.NET Framework 4.5.2).
  • Microsoft Azure Account.

Hence, let’s start and follow the steps in the order to perform one of the best Azure storage, which is Blob Storage. I think there is no need to tell you, what Blob Storage in Azure is? If you want to learn and start with Azure, you can go with my series. In order to work, you’ve got to create a storage account by signing in to Azure Portal.

After creating a storage account on Azure portal, open Visual Studio 2015 and create a new project.

Azure

Select MVC template and click OK button.

Azure

Here, my AzureCloudStorage project is ready for use. I need some references of Azure storage in my project and Azure storage account connection string. Right click on the project, add the Connected Service.

Azure

We are going to work with Azure storage account, so select Azure storage and click Configure button to configure your account.
Azure

This will ask you to enter your Azure credentials. After successful login, your storage account is automatically configured by it. If you don’t have any storage account, you can create a new storage account from the given option.

Azure

All is set now. I have to write all the necessary code in my controller. To create a controller, right click on to Controller's folder and add a controller.

Azure

My Controller has been created. Here, add a method, which will return ActionResult. Under this method, create a Container for an existing storage account.

Azure

Create a Container in storage aAccount

Create an object of storage account, which represents our storage account information such as storage account name and key. The setting exists in Web Config file. To get all information, we parse a connection string from Cloud Configuration Manager. To create the Service client object, use CloudBlobClient credentials access to the blob Service. Now, create an object for CloudBlobContainer, which retrieves a reference to a container. Give a name to the container, which you want to create, unless a container already exists.

Azure

Azure

I’ve used ViewBag to show, if container doesn’t exist, then show container is created, else it's not created on view. Also, I've used ViewBag to show container name on view. 

  1. namespace AzureCloudStorage.Controllers  
  2. {  
  3.     public class MyStorageController : Controller  
  4.     {  
  5.         // Create a Container for existing Storage Account  
  6.         public ActionResult CreateStorageContainer()  
  7.         {  
  8.             CloudStorageAccount userstorageAccount = CloudStorageAccount.Parse(  
  9.             CloudConfigurationManager.GetSetting("mystorageazure01_AzureStorageConnectionString"));  
  10.   
  11.             CloudBlobClient myBlobClient = userstorageAccount.CreateCloudBlobClient();  
  12.   
  13.             CloudBlobContainer myContainer = myBlobClient.GetContainerReference("mystoragecontainer001");  
  14.   
  15.             ViewBag.UploadSuccess = myContainer.CreateIfNotExists();  
  16.   
  17.             ViewBag.YourBlobContainerName = myContainer.Name;  
  18.   
  19.             return View();  
  20.         }  
  21.     }  
  22. }   

Resolve to references and the main references are given below. 

  1. using Microsoft.Azure;  
  2. using Microsoft.WindowsAzure.Storage;  
  3. using Microsoft.WindowsAzure.Storage.Blob;   

Azure

Perhaps, you know that views are used to display the data. Let’s create a view for the CreateStorageContainer method by right clicking it.

Azure

View Name would be as it is and use this view along with layout page.

Azure

Here is the some code snippet on view to display a result on the browser that if container has uploaded, then show a message of success, else the same name container already exists. The screenshot given below is for CreateStorageContainer.chtml.

Azure

Open _Layout.cshtml file and add an Action Link is required to create a storage account.

Azure

Run the Application by CTRL+F5. The Action Link text is available, so just click on to it to create a Container in your Storage Account (mystoragecontainer001).

Azure

After clicking it, you’ll be redirected to your controller method and container should be created on Azure portal successfully.

Azure

Let’s move to Azure portal and you will find Container has successfully been created under given storage account.

Azure

Now, again go back to dashboard and click Action Link to check, whether it will upload same name Container or not.

Azure

No, it shows Container already exists in your storage account.

Azure
Upload a Block Blob or Page Blob into Selected Container

As explained earlier in the articles, Azure storage supports a different kind of blob types such as page blob, block blob and append blob. In this demo, I am going to explain only block blob. I need to upload a blob from my local file. Here, I am creating an object of CloudBlockBlob and retrieving a reference of block blob. From the myblob reference object’s UploadFromStream, you can upload your data stream and create a blob, if there any blob does not exist.

Here, I’m using session, which would be accessed into another ActionResult through the string and string object would be accessed into our View to display blob name.

Create a method to upload blob

Now, access previous sessions in string and ViewBag represents the string as its object and for container as well. 

  1. //Upload Blobs To selected Container  
  2.         public ActionResult UploadYourBlob( )  
  3.         {  
  4.   
  5.             CloudStorageAccount userstorageAccount = CloudStorageAccount.Parse(  
  6.             CloudConfigurationManager.GetSetting("mystorageazure01_AzureStorageConnectionString"));  
  7.   
  8.             CloudBlobClient myBlobClient = userstorageAccount.CreateCloudBlobClient();  
  9.   
  10.             CloudBlobContainer myContainer = myBlobClient.GetContainerReference("mystoragecontainer001");  
  11.   
  12.             //get blob reference by entering its name  
  13.             CloudBlockBlob myBlob = myContainer.GetBlockBlobReference("lion3.jpg");  
  14.   
  15.             //directory name from where you want to upload your blob.  
  16.             using (var fileStream = System.IO.File.OpenRead(@"D:\Amit Mishra\lion3.jpg"))  
  17.             {  
  18.                 myBlob.UploadFromStream(fileStream);  
  19.   
  20.                 ViewBag.BlobName = myBlob.Name;  
  21.             }  
  22.             //hold container in viewbag using string that we will used to get container name onto browser  
  23.             string getcontainer = Session["getcontainer"].ToString();  
  24.             ViewBag.YourBlobContainerName = getcontainer;  
  25.   
  26.             return View();  
  27.         }   

Right click near ActionResult method and add View for it.

Azure

Create a view to display the data.

Azure

Here, I am writing simple scripts in UploadYourBlob.chtml. 

  1. @{  
  2.     ViewBag.Title = "UploadYourBlob";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6.     <h3>Uploaded.....☺</h3><br />  
  7.     <h2>This Blob <b style="color:purple""@ViewBag.BlobName" </b>has Uploaded into your <b style="color:red""@ViewBag.YourBlobContainerName" </b> </h2>   

Here, I want to show a simple demo. I want to show all the information on CreateStorageContainer.chstml view. Go to CreateStorageContainer.chstml and write some snippet, as shown below.

Azure

The code snippet given above shows the result given below.

Azure

If you click on blue text, it represents an action link. It will redirect to UploadYourBlob .cshtml view.

Azure

If you try to upload it again into the portal, then it shows the blob named Lion3.jpg, which already exists, as shown.

Get List of Your available blobs in Container

Now, the time of get list of blobs has come, which are available in your Container. Create an ActionResult, which will return the string of listblob in Container. Here, I am using blob list as a string 

  1. public ActionResult ListingBlobs()  
  2.         {  
  3.             CloudStorageAccount userStorageAccount = CloudStorageAccount.Parse(  
  4.              CloudConfigurationManager.GetSetting("mystorageazure01_AzureStorageConnectionString"));  
  5.             CloudBlobClient myBlobClient = userStorageAccount.CreateCloudBlobClient();  
  6.             CloudBlobContainer myContainer = myBlobClient.GetContainerReference("mystoragecontainer001");  
  7.   
  8.             List<string> listblob = BlobList(myContainer);  
  9.   
  10.             return View("CreateStorageContainer", listblob);  
  11.         }   

Here, I am creating a common function, which returns list of blobs in string, which can be used in different methods. For list, we’ll use CloudBlobContainer.ListBlobs method, which should return IListBlobItem, according to your object. 

  1. private static List<string> BlobList(CloudBlobContainer myContainer)  
  2.         {  
  3.             List<string> listblob = new List<string>();  
  4.   
  5.             foreach (IListBlobItem item in myContainer.ListBlobs(nullfalse))  
  6.             {  
  7.                 if (item.GetType() == typeof(CloudBlockBlob))  
  8.                 {  
  9.   
  10.                     CloudBlockBlob myblob = (CloudBlockBlob)item;  
  11.                     listblob.Add(myblob.Name);  
  12.                 }  
  13.                 else if (item.GetType() == typeof(CloudPageBlob))  
  14.                 {  
  15.                     CloudPageBlob myblob = (CloudPageBlob)item;  
  16.                     listblob.Add(myblob.Name);  
  17.                 }  
  18.                 else if (item.GetType() == typeof(CloudBlobDirectory))  
  19.                 {  
  20.                     CloudBlobDirectory dir = (CloudBlobDirectory)item;  
  21.                     listblob.Add(dir.Uri.ToString());  
  22.                 }  
  23.             }  
  24.   
  25.             return listblob;  
  26.         }   

Common function, which returns list of blobs as in string is CreateStorageContainer method.

  1. List<string> listblob = BlobList(myContainer);  

Now, right click on to ListingBlobs and add a view.

Azure

In view, write the code snippet given below, as shown below.

Azure

Open CreateStorageContianer.cshtml file and add get list from Model. Update your View from the code given below.

  1. @model List<string>  
  2. @{  
  3.     ViewBag.Title = "CreateStorageContainer";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6.   
  7. <h2>Create Storage Container Into Storage Account</h2>  
  8.   
  9. <h3>  
  10.     Hey This Container <b style="color:red""@ViewBag.YourBlobContainerName" </b>  
  11.     @(ViewBag.UploadSuccess == true ?   
  12.         "Has Been Successfully Created." : "Already Exist Into Your Storage Account.☻")  
  13. </h3><br />  
  14.   
  15. @if (ViewBag.UploadSuccess == true)  
  16. {  
  17.     <h4>  
  18.         Your Container has been created now ☺ You can Upload Blobs(photos, videos, music, blogs etc..)<br /> into your Container by clicking on it.  
  19.         @Html.ActionLink("Click Me To Upload a Blob""UploadYourBlob""MyStorage")  
  20.     </h4>  
  21. }  
  22. else  
  23. {  
  24.     <h4>  
  25.         Your Container already exist ☺ You can Upload Blobs(photos, videos, music, blogs etc..)<br /> into your Container by clicking on it.  
  26.         <b>@Html.ActionLink("Click Me To Upload a Blob""UploadYourBlob""MyStorage")</b>   
  27.     </h4>  
  28. }  
  29. @Html.Partial("~/Views/MyStorage/ListingBlobs.cshtml", Model.ToList())   

Azure

Run the Application. If there is any blob available in your container, then you can see the list of blobs.

Azure

Download Your Blob from Container

Add download and delete the link to the ListingBlobs.cshtml View.

Azure

When you’ll click on file, the blob should be downloaded.

Azure

Let’s write the code for Download blob and myBlob.DownloadToStream method transfers content of blob to the stream object. Give a path, where you want to download the blob. 

  1. public ActionResult DownloadYourBlob()  
  2.         {  
  3.             CloudStorageAccount userstorageAccount = CloudStorageAccount.Parse(  
  4.             CloudConfigurationManager.GetSetting("mystorageazure01_AzureStorageConnectionString"));  
  5.   
  6.             CloudBlobClient myBlobClient = userstorageAccount.CreateCloudBlobClient();  
  7.   
  8.             CloudBlobContainer myContainer = myBlobClient.GetContainerReference("mystoragecontainer001");  
  9.             CloudBlockBlob myBlob = myContainer.GetBlockBlobReference("lion1.jpg");  
  10.               
  11.             //for delete blob  
  12.               
  13.   
  14.             using (var fileStream = System.IO.File.OpenWrite(@"D:\downloads\"))   
  15.             {  
  16.                 myBlob.DownloadToStream(fileStream);  
  17.   
  18.                 ViewBag.Name = myBlob.Name;  
  19.             }  
  20.             string getcontainer = Session["getcontainer"].ToString();  
  21.             ViewBag.YourBlobContainerName = getcontainer;  
  22.             return View();  
  23.         }   

Add a view of the current method.

Azure

Click Add.

Azure

In the DownloadYourBlob.chtml, write the snippets given below. 

  1. @{  
  2.     ViewBag.Title = "DownloadYourBlob";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6. <h2>Blob has downloaded</h2>  
  7.   
  8. <b style="color:purple""@ViewBag.Name" </b>downloaded to The Folder   

Run your Application once again and click to download from the list of blobs.

Azure

The blob should be downloaded.

Azure

If you want to delete the blob,which you downloaded recently, you have to make another ActionResult for deleting blobs.

Write the same code, find the object of CloudBlobClient and call its delete method. 

  1. public ActionResult DeleteYourBlob()  
  2.         {  
  3.             CloudStorageAccount userstorageAccount = CloudStorageAccount.Parse(  
  4.             CloudConfigurationManager.GetSetting("mystorageazure01_AzureStorageConnectionString"));  
  5.   
  6.             CloudBlobClient myBlobClient = userstorageAccount.CreateCloudBlobClient();  
  7.   
  8.             CloudBlobContainer myContainer = myBlobClient.GetContainerReference("mystoragecontainer001");  
  9.             CloudBlockBlob myBlob = myContainer.GetBlockBlobReference("lion1.jpg");  
  10.   
  11.             myBlob.Delete();  
  12.             ViewBag.DeleteBlob = myBlob.Name;  
  13.   
  14.             return View();  
  15.         }   

Add a view for this ActionResult and write the snippets given below. 

  1. @{  
  2.     ViewBag.Title = "DeleteYourBlob";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6. <h2>Blob has Deleted</h2>  
  7.   
  8. <b style="color:purple""@ViewBag.DeleteName" </b>Deleted from The Folder   

Click Delete the lion1.jpg blob.

Azure

The downloaded blob has been deleted successfully.

Azure

If you want to upload more containers and blobs into your Azure storage account, then you can only change the name of container and blob into the code.

Up Next
    Ebook Download
    View all
    Learn
    View all