Demo Project Azure Blob Storage With ASP.NET MVC 5.0: Part 3

This is is my third article on Azure Blob Storage in this I just tried to use blob storage in ASP.NET MVC application with helping of ASP.NET Web role it’s a kind of demo project Application to store Images file to blob storage and edit update them and also get the list. Before reading this article I’ll recommend to read the following two previous articles:

So, let’s start now firstly you need Azure blob storage which I already explained in the previous articles. After that open your Visual Studio and create Azure Cloud Service with ASP.NET Web roles as in the following steps:

Step 1: Open Visual Studio, Templates, Visual C#, then Cloud.
Step 2: Select “Azure Cloud Service”.
Step 3: In the name section, I have given name to my project “AzureCloudDemoMVC”.
Step 4: Click on OK button.

azure

After clicking on “OK” button choose “ASP.NET Web Role”.

Web Role: Web Role is a font and application or we can say a user interface.

Click on (>) button (In the red circle).

Hit on “OK” button.

webrole

Click on “MVC” because I am going to create an MVC Application.

Click on “OK” button.

mvc

In the following figure, I have a Window Azure Cloud Project with name “AzureCloudDemoMVC”, you can see In Solution Explorer.

And “WebRole1” is a regular MVC project in my Solution Explorer.

solution

You can notice here, a new file with the name “WebRole.cs”. This file contains entry point settings of MVC application. You need this file while MVC running in Cloud Services. The information written in this file executes before the execution of “Global.asax” file.

WebRole

The other project is “AzureCloudDemoMVC”, this is actually a cloud project. Inside this project, you will find the “Roles” folder and in the “Roles” folder you will find “WebRole1”.

solution

Now we need to connect with Azure, so go in the “Server Explorer” and right click on “Azure (Reenter your credentials)" and go to “Connect to Microsoft Azure Subscription”.

azure

Fill the Login detail and click on “Sign in” button.

sign in

So, we have successfully connected with the Azure Account, and right click on the “Storage” and select “Attach External Storage”.

storage

In the “Account Name” section and in “Account key” section provide name and key from the Azure Storage, so go to your Azure Storage and copy name and key from account.

In the Cloud, go to “STORAGE” and click on your storage account, here my storage account is “nitindemostorage”, and click on “MANAGE ACCESS KEYS”.

access

Copy the “Storage Account Name” and "Primary Access Key” from here and paste it over there.

keys

After pasting name and key click on “OK” button.

new account

We got my storage account ”nitindemostorage” and in this we have a “Blob” and “mysample” named Blob Container.

solution

Now go in to project which is “WebRole1”, right click on project, select “Add” and then select a “Class”.

class

Give a name to your class, whatever you want, here I have given it “BlobServices”.

Then click on “Add” button.

add

Now, let’s go ahead and add a method that will get cloud blob container information. Right click near “CloudBlobContainer” and import a namespace, select “Resolve” and click on “using Microsoft.WindowsAzure.Storage.Blob”.

click

We need to write some important namespaces, so go ahead and type the namespaces.
  1. using System.IO;  
  2. using Microsoft.WindowsAzure.Storage;  
  3. using Microsoft.WindowsAzure.Storage.Blob;  
  4. using Microsoft.WindowsAzure.Storage.Auth;  
  5. using System.Configuration;  
The method will be “GetCloudBlobContainer” as in the following screenshot:

method

Here, I have creating a string to give the string of my storage account. You can copy the connection string from your Azure Explorer. So go in Azure Explorer and copy the string from Azure Storage.
  1. public CloudBlobContainer GetCloudBlobContainer()  
  2. {  
  3.     string connString = "DefaultEndpointsProtocol=https;AccountName=nitindemostorage;AccountKey=jH/5WgOZzQ7wSQv6BSZ2fbJW3sSEAzinmOUhorUWFpfJSUKPUopAD5uDIP3lvJujmnw1hBoD2RFSzHlPYt2nLw==;";  
  4.     string destContainer = "mysample";  
  5.   
  6.     // Get a reference to the storage account  
  7.     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connString);  
  8.     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
  9.     CloudBlobContainer blobContainer = blobClient.GetContainerReference(destContainer);  
  10.     if (blobContainer.CreateIfNotExists())  
  11.     {  
  12.         blobContainer.SetPermissions(newBlobContainerPermissions  
  13.         {  
  14.             PublicAccess = BlobContainerPublicAccessType.Blob  
  15.         });  
  16.   
  17.     }  
  18.     return blobContainer;  
  19.   
  20. }  
And “mysample” is my Blob Container in the Cloud.

mysample

Now go into Azure Explorer and copy the connection string from storage account.

Go into search box and type Azure Explorer.

apps

Now right click on Azure Storage account that is “nitindemostorage” and select “Copy Connection string” to copy it. Paste the connection string in the “string connString”.

explorer

Now I am going to use here,

CloudBlobClient:- To create the cloud blob service client.

CloudBlobContainer:
To check if there is any Blob Container of “mysample” named in the storage account.

And here I have used if condition to check if there is any Blob Container, so just go in to the storage account and create a Blob Storage of name “mysample”.

And finally it will return Blob Container. Container is nothing but just a folder in the cloud.

If there is a blob container then it will use existing.

webrole
Now go ahead and use this setup in my Controller.

Go to “HomeController.cs”.

I’m going to add a new Action method inside this “HomeController”.

Blob Services class is nothing but a “BlobServices.cs” class which is used in the previous “BlobServices.cs” class.

We have created a “Upload()” method with ActionResult Return type.

Inside the “Upload()”, create “CloudBlobContainer” and list name all the blobs and “_blobServices” is object of my class.

Inside this Action Result, list available blobs, Uri in the container and return it to the view page to display all the blobs.

Means if you upload the blobs which is image it will list all the images and look through the images and return the Uri of the images to the view page.
  1. BlobServices _blobServices = newBlobServices();  
  2. publicActionResult Upload()  
  3. {  
  4.     CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();  
  5.     List < string > blobs = newList < string > ();  
  6.     foreach(var blobItem in blobContainer.ListBlobs())  
  7.     {  
  8.         blobs.Add(blobItem.Uri.ToString());  
  9.   
  10.     }  
  11.     return View(blobs);  
  12. }  
Now, I’m going to implement its post version means user will be able to upload his Blob also,
publicActionResult Upload(FormCollectionimage)- It will collect the posted file image information, and upload it to the Blob Container and at the end this will redirect to the same view to make recently image visible to user.
  1. [HttpPost]  
  2. public ActionResult Upload(FormCollection image)  
  3. {  
  4.     foreach(string item in Request.Files)  
  5.     {  
  6.         HttpPostedFileBase file = Request.Files[item] asHttpPostedFileBase;  
  7.         if (file.ContentLength == 0)  
  8.             continue;  
  9.   
  10.         if (file.ContentLength > 0)  
  11.         {  
  12.   
  13.             CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();  
  14.             CloudBlockBlob blob = blobContainer.GetBlockBlobReference(file.FileName);  
  15.             blob.UploadFromStream(file.InputStream);  
  16.         }  
  17.     }  
  18.     return RedirectToAction("Upload");  
  19. }  
When we write “CloudBlobContainer” we need to resolve it by right clicking near”CloudBlobContainer”. So simply go to Resolve and select “using Microsft.WindowsAzure.Storage.Blob;”

resolve

resolve

Now we need to create one more method to delete the blobs, so let’s go ahead and create a method for deleting the blob.

You can see, this method will accept name as a parameter and return stream message which is String and will return “File Successfully Deleted”.

“Name” is nothing but “uri” of the images, uri means the complete address of the image.

“uri.LocalPath” is a path that contains the actual description of the images.
  1. [HttpPost]  
  2. public string DeleteImg(string Name)  
  3. {  
  4.     Uri uri = newUri(Name);  
  5.     string filename = System.IO.Path.GetFileName(uri.LocalPath);  
  6.     CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();  
  7.     CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);  
  8.     blob.Delete();  
  9.     return "File Successfully Deleted";  
  10.   
  11. }  


code


Now we need to add a view for the design that design will be shown on our browser, means that we want to show in the browser.
 
Simply go near to foreach statement and click right over there and go to “Add View”, for adding a view.

view





In the following image, in the view name section, give any name to view whatever you want, here I have given it “Upload”.

Click on “Add” button to add a view.
add

After adding a view, in the paragraph tag <P></P>, I am creating a form section and using Razor syntax here.

Upload: My ActionResult

Home:
 My HomeController, and form method will be Post,
  1. @using(Html.BeginForm("Upload""Home", FormMethod.Post, new  
  2. {  
  3.     enctype = "multipart/form-data"  
  4. }))  
  5.   
  6. {  
  7.     enctype = "multipart/form-data"  
  8. } - This code defines;  
  9. //we can select the multi part of the image.  
  10. Now in the < div > section, I’ m going to print a message that is“ Upload Image”.  
  11. Now I’ m going to create some Html tags. < inputtype = "file"  
  12. name = "avatar" / > -This will allows us to upload an image. < inputtype = "submit"  
  13. value = "upload" / > -This is upload a button.  
I have created a table also for image and delete, image for Images and Delete for the Delete. So create a table class and in the “style” you can give the widths according to your choice. I have given 50% to image and 25% to delete.

Here, I’m going to create also a script to delete button. So create a function “deleteimage(item)” and in the URL section give the Url of DeleteImage.
  1. @ {  
  2.     ViewBag.Title = "Upload";  
  3. } < h2 > Upload The Image < /h2> < p >  
  4.     @using(Html.BeginForm("Upload""Home", FormMethod.Post, new  
  5.      {  
  6.         enctype = "multipart/form-data"  
  7.     })) { < div > Upload Image < /div> < inputtype = "file"  
  8.         name = "avatar" / >  
  9.             < inputtype = "submit"  
  10.         value = "upload" / >  
  11.     } < /p> < table >  
  12.     < tr > < td >  
  13.     < tableclass = "table"  
  14. style = "width:200px; " >  
  15.     < tr >  
  16.     < tdstyle = "width:50%" > Image < /td> < tdstyle = "width:25%" > Delete < /td> < /tr>  
  17. @foreach(var item in Model) { < tr >  
  18.             < td > < imgsrc = "@item"  
  19.         alt = "image here is"  
  20.         width = "100"  
  21.         height = "100" / > < /td> < td > < inputtype = "button"  
  22.         id = "@item"  
  23.         onclick = "deleteImage('@item');"  
  24.         value = "Delete" / > < /td> < /tr>  
  25.     } < /table></td > < tdstyle = "width:100px" > < /td> < /table> < script >  
  26.     function deleteImage(item) {  
  27.         var url = "/Home/DeleteImg";  
  28.         $.post(url,  
  29.          {  
  30.             Name: item  
  31.         }, function(data)  
  32.           {  
  33.             window.location.href = "/Home/Upload";  
  34.         });  
  35.     } < /script>  
code


Finally, we successfully created a “Delete” button to delete the image and “upload” button to upload an image. Now let’s check our output, Build your project by Ctrl+Shift+B and after successful build you can run it by pressing F5 key.

Finally, I got my Output. Click on “Choose file” button and click on “upload” button.
And choose your favorite image which you want to upload in the cloud as well as in the Azure Explorer and to show it on the browser.

browser
I have successfully uploaded my image, now go ahead and check on its changes on cloud and as well as Azure Explorer.

upload

Sign In Azure Portal and go into Storage Account and select the Blob Container.

Go to “STORAGE”, and select “nitindemostroage”.

Storage

In the “nitindemostorage”, select the “CONTAINERS”.

Containers

After clicking on the “CONTAINERS”, you will see your Blob Container, my Blob Container is “mysample”.

Click on “mysample”.

mysample

Finally, we can see the changes in my Cloud account, I got my output simply. We can see there ARE three images which can be seen in the browser as well.

mysample

Now go in to the Azure Explorer to see the above changes.

Explorer


In the following figure, we can check our output as well. Here also three images with the same name means all changes on the browser will be made on cloud as well as Azure Explorer.

Explorer

Now we can check the same output in Server Explorer as well in Visual Studio.

In the Server Explorer, select your storage accounts, my account is “nitindemostorage”, go in Blobs and then “mysample” Container.

Double click on “mysample” container to see the changes.

mysample

Now here also you can see the same output as well.

output

In the “Upload.cshtml”, now we have to create an edit button to edit an image.
  1. <td style="width:25%">  
  2.     Edit</td>  
  3.     <td>  
  4.         <input type="button" id="@item" onclick="EditImage('@item');" value="Edit" />  
  5.     </td>  
This Html Code will create an “Edit” button to the browser and just a div to load a partial view for Editing an image by jQuery.
  1. <td>  
  2.     <div id="ForEdit">  
  3.         </div>  
  4. </td>  
upload


And write a jQuery function to call on that edit button click for requesting that partial view to edit a record.
  1. function EditImage(item)   
  2. {  
  3.     $("#ForEdit").load("/Home/Edit?Name=" + item, function()  
  4.     {  
  5.   
  6.     }).css  
  7.     ({  
  8.         "border-color""red",  
  9.         "border-width""5px",  
  10.         "border-style""solid"  
  11.     });  
You can edit your image in the browser as well, now go for code,

Here we created a new Action “Edit” with ActionResult Return type for both type of request [httpget] and also for [httppost]. First one only return a partial view with a string type of Model binder object which contain the image uri which I need to edit and second Action with [httppost] will use when a user will submit the request to server for image editing.

Code:
  1. //First Action for [httpGet] request:  
  2. [HttpGet]  
  3. publicActionResult Edit(string Name)  
  4. {  
  5.     return PartialView("Edit", Name);  
  6. }  
  7.   
  8. //Second Action for [HttpPost] request:   
  9.   
  10. [HttpPost]  
  11. publicActionResult Edit(FormCollection images)  
  12. {  
  13.     try {  
  14.         Uri uri = newUri(images["ImageName"]);  
  15.         string filename = System.IO.Path.GetFileName(uri.LocalPath);  
  16.         CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();  
  17.         CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);  
  18.         blob.Delete();  
  19.   
  20.         foreach(string item in Request.Files)  
  21.         {  
  22.             HttpPostedFileBase file = Request.Files[item] asHttpPostedFileBase;  
  23.             if (file.ContentLength == 0)  
  24.                 continue;  
  25.   
  26.             if (file.ContentLength > 0)  
  27.             {  
  28.                 string nn = file.FileName;  
  29.                 CloudBlobContainer blobContainer1 = _blobServices.GetCloudBlobContainer();  
  30.                 string[] arr = images["ImageName"].Split('/');  
  31.                 CloudBlockBlob blob1 = blobContainer1.GetBlockBlobReference(arr[arr.Length - 1]);  
  32.                 blob1.UploadFromStream(file.InputStream);  
  33.             }  
  34.         }  
  35.   
  36.   
  37.         return RedirectToAction("Upload");  
  38.     } catch (Exception)  
  39.     {  
  40.         return PartialView("Edit", images["ImageName"]);  
  41.   
  42.     }  
  43.   
  44. }  
Also can be seen in the following image:

controller

Now go in “Views” folder and add another view.

view

Here, I gave “Edit” name to my view. I’m adding a “Partial View”.

Click on “Add” button to add a partial view.

add

And now just write that minimum code in which I have to used the previous image and 1 fileupload control to upload new image and a submit button and a hidden control to store the previous image id/URI to change that with new image.

Code
  1. @model System.String < p >  
  2.     @using(Html.BeginForm("Edit""Home", FormMethod.Post, new   
  3.         {  
  4.         enctype = "multipart/form-data"  
  5.     })) { < div > Edit Image: < imgsrc = @Model alt = "image here is"  
  6.         width = "100"  
  7.         height = "100" / > < /div> < inputtype = "hidden"  
  8.         value = @Model name = "ImageName" / >  
  9.             < inputtype = "file"  
  10.         name = "avatar" / >  
  11.             < inputtype = "submit"  
  12.         value = "upload" / >  
  13.     } < /p>  
Can also show as in the following image:

image

Now, finally we can edit our image; click on your favorite image which you want to change.

edit

Here, I’m going to edit first image.

Click on “Edit” button.

After Clicking on “Edit” button, you will see that image will open near “Delete” button.

Click on “Choose file” button.

edit

Select your favorite image what you want to replace from old one.

Click on “Open” button to open that image.

open

After clicking on “Open” button, you will see the selected image name (Nitinpandit.jpg).

Click “Upload” button.

upload

Finally, I got my output. That image successfully edits and updated, as well as in my cloud, Azure Explorer, and in Server Explorer (in Visual Studio).

upload



To check our changes, just go in to Azure Explorer and right click on the top image and select “Open”.

open

Below is my editable image and final output.

output

Enjoy the Azure and cloud services by Microsoft.

Thanks again for reading this article and following me too.

Connect(“Nitin Pandit”);

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now