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.
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.
Click on “
MVC” because I am going to create an MVC Application.
Click on “
OK” button.
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.
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.
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”.
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”.
Fill the Login detail and click on “
Sign in” button.
So, we have successfully connected with the Azure Account, and right click on the “
Storage” and select “
Attach External 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”.
Copy the “
Storage Account Name” and "
Primary Access Key” from here and paste it over there.
After pasting name and key click on “OK” button.
We got my storage account ”
nitindemostorage” and in this we have a “Blob” and “mysample” named Blob Container.
Now go in to project which is “
WebRole1”, right click on project, select “
Add” and then select a “
Class”.
Give a name to your class, whatever you want, here I have given it “
BlobServices”.
Then click on “
Add” button.
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”.
We need to write some important namespaces, so go ahead and type the namespaces.
- using System.IO;
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Blob;
- using Microsoft.WindowsAzure.Storage.Auth;
- using System.Configuration;
The method will be “GetCloudBlobContainer” as in the following screenshot:
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.
- public CloudBlobContainer GetCloudBlobContainer()
- {
- string connString = "DefaultEndpointsProtocol=https;AccountName=nitindemostorage;AccountKey=jH/5WgOZzQ7wSQv6BSZ2fbJW3sSEAzinmOUhorUWFpfJSUKPUopAD5uDIP3lvJujmnw1hBoD2RFSzHlPYt2nLw==;";
- string destContainer = "mysample";
-
-
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connString);
- CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
- CloudBlobContainer blobContainer = blobClient.GetContainerReference(destContainer);
- if (blobContainer.CreateIfNotExists())
- {
- blobContainer.SetPermissions(newBlobContainerPermissions
- {
- PublicAccess = BlobContainerPublicAccessType.Blob
- });
-
- }
- return blobContainer;
-
- }
And “
mysample” is my Blob Container in the Cloud.
Now go into Azure Explorer and copy the connection string from storage account.
Go into search box and type Azure Explorer.
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”.
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.
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.
- BlobServices _blobServices = newBlobServices();
- publicActionResult Upload()
- {
- CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
- List < string > blobs = newList < string > ();
- foreach(var blobItem in blobContainer.ListBlobs())
- {
- blobs.Add(blobItem.Uri.ToString());
-
- }
- return View(blobs);
- }
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.
- [HttpPost]
- public ActionResult Upload(FormCollection image)
- {
- foreach(string item in Request.Files)
- {
- HttpPostedFileBase file = Request.Files[item] asHttpPostedFileBase;
- if (file.ContentLength == 0)
- continue;
-
- if (file.ContentLength > 0)
- {
-
- CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
- CloudBlockBlob blob = blobContainer.GetBlockBlobReference(file.FileName);
- blob.UploadFromStream(file.InputStream);
- }
- }
- return RedirectToAction("Upload");
- }
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;”
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.
- [HttpPost]
- public string DeleteImg(string Name)
- {
- Uri uri = newUri(Name);
- string filename = System.IO.Path.GetFileName(uri.LocalPath);
- CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
- CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);
- blob.Delete();
- return "File Successfully Deleted";
-
- }
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.
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.
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,
- @using(Html.BeginForm("Upload", "Home", FormMethod.Post, new
- {
- enctype = "multipart/form-data"
- }))
-
- {
- enctype = "multipart/form-data"
- } - This code defines;
- //we can select the multi part of the image.
- Now in the < div > section, I’ m going to print a message that is“ Upload Image”.
- Now I’ m going to create some Html tags. < inputtype = "file"
- name = "avatar" / > -This will allows us to upload an image. < inputtype = "submit"
- 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.
- @ {
- ViewBag.Title = "Upload";
- } < h2 > Upload The Image < /h2> < p >
- @using(Html.BeginForm("Upload", "Home", FormMethod.Post, new
- {
- enctype = "multipart/form-data"
- })) { < div > Upload Image < /div> < inputtype = "file"
- name = "avatar" / >
- < inputtype = "submit"
- value = "upload" / >
- } < /p> < table >
- < tr > < td >
- < tableclass = "table"
- style = "width:200px; " >
- < tr >
- < tdstyle = "width:50%" > Image < /td> < tdstyle = "width:25%" > Delete < /td> < /tr>
- @foreach(var item in Model) { < tr >
- < td > < imgsrc = "@item"
- alt = "image here is"
- width = "100"
- height = "100" / > < /td> < td > < inputtype = "button"
- id = "@item"
- onclick = "deleteImage('@item');"
- value = "Delete" / > < /td> < /tr>
- } < /table></td > < tdstyle = "width:100px" > < /td> < /table> < script >
- function deleteImage(item) {
- var url = "/Home/DeleteImg";
- $.post(url,
- {
- Name: item
- }, function(data)
- {
- window.location.href = "/Home/Upload";
- });
- } < /script>
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.
I have successfully uploaded my image, now go ahead and check on its changes on cloud and as well as Azure Explorer.
Sign In Azure Portal and go into Storage Account and select the Blob Container.
Go to “
STORAGE”, and select “
nitindemostroage”.
In the “
nitindemostorage”, select the “
CONTAINERS”.
After clicking on the “
CONTAINERS”, you will see your Blob Container, my Blob Container is “
mysample”.
Click on “
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.
Now go in to the Azure Explorer to see the above changes.
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.
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 Blo
bs and then “
mysample” Container.
Double click on “mysample” container to see the changes.
Now here also you can see the same output as well.
In the “
Upload.cshtml”, now we have to create an edit button to edit an image.
- <td style="width:25%">
- Edit</td>
- <td>
- <input type="button" id="@item" onclick="EditImage('@item');" value="Edit" />
- </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.
- <td>
- <div id="ForEdit">
- </div>
- </td>
And write a jQuery function to call on that edit button click for requesting that partial view to edit a record.
- function EditImage(item)
- {
- $("#ForEdit").load("/Home/Edit?Name=" + item, function()
- {
-
- }).css
- ({
- "border-color": "red",
- "border-width": "5px",
- "border-style": "solid"
- });
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:
-
- [HttpGet]
- publicActionResult Edit(string Name)
- {
- return PartialView("Edit", Name);
- }
-
-
-
- [HttpPost]
- publicActionResult Edit(FormCollection images)
- {
- try {
- Uri uri = newUri(images["ImageName"]);
- string filename = System.IO.Path.GetFileName(uri.LocalPath);
- CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
- CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);
- blob.Delete();
-
- foreach(string item in Request.Files)
- {
- HttpPostedFileBase file = Request.Files[item] asHttpPostedFileBase;
- if (file.ContentLength == 0)
- continue;
-
- if (file.ContentLength > 0)
- {
- string nn = file.FileName;
- CloudBlobContainer blobContainer1 = _blobServices.GetCloudBlobContainer();
- string[] arr = images["ImageName"].Split('/');
- CloudBlockBlob blob1 = blobContainer1.GetBlockBlobReference(arr[arr.Length - 1]);
- blob1.UploadFromStream(file.InputStream);
- }
- }
-
-
- return RedirectToAction("Upload");
- } catch (Exception)
- {
- return PartialView("Edit", images["ImageName"]);
-
- }
-
- }
Also can be seen in the following image:
Now go in “
Views” folder and add another view.
Here, I gave “Edit” name to my view. I’m adding a “Partial View”.
Click on “
Add” button to add a partial view.
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
- @model System.String < p >
- @using(Html.BeginForm("Edit", "Home", FormMethod.Post, new
- {
- enctype = "multipart/form-data"
- })) { < div > Edit Image: < imgsrc = @Model alt = "image here is"
- width = "100"
- height = "100" / > < /div> < inputtype = "hidden"
- value = @Model name = "ImageName" / >
- < inputtype = "file"
- name = "avatar" / >
- < inputtype = "submit"
- value = "upload" / >
- } < /p>
Can also show as in the following image:
Now, finally we can edit our image; click on your favorite image which you want to change.
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.
Select your favorite image what you want to replace from old one.
Click on “
Open” button to open that image.
After clicking on “
Open” button, you will see the selected image name (
Nitinpandit.jpg).
Click “
Upload” button.
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).
To check our changes, just go in to Azure Explorer and right click on the top image and select “
Open”.
Below is my editable image and final output.
Enjoy the Azure and cloud services by Microsoft.
Thanks again for reading this article and following me too.
Connect(“Nitin Pandit”);