This is an amazing experience for me to work with Azure Blob Storage in ASP.NET MVC application. I am going to share some advanced part which I have learned.
As we all know Azure Blob Storage is used to store the Binary Large Objects [Blobs]. Here we can store and retrieve different kinds of data like images, documents, media files, etc.
Agenda of this Article
- What is Blob Storage?
- Why Blob Storage?
- Create Blob Storage Account.
- Install and use Azure Explorer.
- Create ASP.NET MVC Application.
- Install Storage Client Library and Configuration through NuGet.
- Upload Image through ASP.NET MVC Application.
What is Blob Storage
Windows Azure Blob Storage can store the hundreds of terabytes data in one account. As you know you can create multiple blob storage account, so definitely you can store multiple hundreds of terabytes data with Windows Azure Blob Storage.
We don’t require taking tension about the backup of the data which is stored on blob storage. It is because it automatically takes the backed up data. You can increase your storage as per requirement and you need to pay only which you have used and what you have used.
One more thing, I want to consider here that you don’t need to take headache about how to manage your data, your VM or any other things; actually Windows Azure manages everything automatically.
You can use Blob Storage as REST API and can use with any language like Java, .NET, etc. Actually technology doesn’t matter with blob storage. It means all kinds of client can be accessible to this storage.
You can also visit this article for brief about Windows Azure Storage.
Why Blob Storage
Persistency is the main advantage because we use Blob Storage. Actually there are many ways to share your static content or files to someone. You can store it on Hard Drive but these instances are not persistent. If you are going to use VMs then it is managed automatically by Windows Azure and you don’t need to worry about this.
So, basically you are going to put your data in persistent store for long term uses then you need to go with Blob Storage.
Create Blob Storage Account
There are different kinds of storage with Windows Azure like Tables Storage, Queue Storage as well as Blob Storage. Today we are going to work with Blob Storage.
To start with Blob Storage, first you should have a Azure Account as well as Blob Storage account. If you don’t have the Windows Azure Account, you can try with Free Trial.
If you have MSDN subscription then you can take benefits to your credit limits.
To login with Windows Azure Portal, you just need to go with Azure portal. Provide your credentials to login and enter the Portal.
When you complete you successful login with Azure Portal then you will go to the following page [See the following image].
To create a Blob Storage account, click to New option which is resided in the following,
When you click to NEW then choose Data Service option then choose Storage, then Quick Create.
It will give you the window where you can enter your blob storage URL and location [which region you want to create your blob storage]. So, here you need to provide the storage name in URL textbox. One thing you need to consider here that name is globally unique. When you are going to choose your blob storage location, please note that it will be your primary location where your blob storage data center will be resided.
Below you will find one more option “Geo Replication”. If you select this option, the replica of your data will be stored on different location in same region. Now it is time to create your Blob Storage. So, click on CREATE STORAGE ACCOUNT.
It will take few minutes to create and configure your storage account. Actually it create all types of setting for your storage account.
After few minutes, you will find that your storage account has created successfully. You will get a successfully created message in status bar.
From the below status bar menu, you can find one more option there and it is “MANAGE ACCESS KEYS”. Actually we need access key to work with storage account.
So, click on the MANAGE ACCESS KEYS which is resided at bottom of the screen.
Here you will see two types of the access key, one is primary and other one is secondary corresponding to your storage account. You can copy your storage account access key to click on Copy icon at the right side. If you think that someone knows the storage access key then you can regenerate the access key using the “regenerate” option.
So, finally we have successfully created the storage account on Windows Azure. Now it is time to access the account. There are different types of way to access your blob storage.
Install and Use Azure Explorer
If you are working with Windows Azure Blob Storage and storing some files then you need to view, rename, and delete the files. So, you can use the Azure Explorer to access your blob storage.
You have to install Azure Explorer to your system to direct access to your blob storage. So, you can use link to download your azure explorer.
Click on Download, within few seconds, you will get the setup file for Azure Explorer. Click on the setup file to run the setup and it will be going to install the Azure Explorer for you.
When it will be installed successfully, an application icon will be set inside the program menu. Go to start and find Azure Explorer and click on it.
It will ask for license terms and conditions. You need to check on checkbox and click on I Accept.
So, you have installed Azure Explorer successfully. It will open the azure explorer for you as in the following. Here you will find the Azure Storage Account option where you will be finding the entire containers which contain the blob for you.
To add your account with Azure Explorer, Right click on Azure Storage Account and choose Add Connection to Azure Storage.
It will provide you different way to connect with storage account. You need to choose “Connect to Azure with an Storage Account Name and an Access Key”. As we know that we have got access key earlier and click to Next.
In the next “Add Windows Azure Storage Account”, provides you storage account name and storage access key.
If you want to test your connection, you can use “Test Connection” button.
So, finally we have added our account with Azure Explorer. You can see my storage account “mukeshdemostorage” added successfully.
As we all know that there should be a container to store the blob inside storage account. So, for creating the new container for blob, Right click on your storage account “mukeshdemostorage” and choose New Blob Container.
It will open a dialog window where you can specify the name of the Blob Container and Access Level. I am going to provide the name as “sampleimage” [Name always should be in small letters] and there access level as Private.
So, it will create a blob container “sampleimage” for me. As it is an azure explorer. You can directly paste the documents or files inside it. I am going to paste [Upload] one of my images directly inside the “sampleimage” blob container.
So, you can see that one image is available with name “Mukesh Kumar”. Right click on the image and click on Copy Path. It will directly copy the path of image which is resided on the server.
Going to access the image, you can paste the URL inside the browser and press enter. You will see the following error which says that you can’t access this file because the access level of this file is Private and you can’t access it from outside as publicly.
So, you need to change the access level of your blob container.
When you again try to access the same URL inside the browser, you will find the image is uploaded through the Azure Explorer.
Create ASP.NET MVC Application
We have successfully uploaded and access the same image from Azure Explorer. It is very easy. But how it is possible through an application, so, complete this task I am going to create an MVC application from where I will try to upload an image inside the blob storage and access it.
So, create an MVC application “BlobStorageDemo” with No Authentication.
As I am going to upload an image, so create a controller “ImageController” from where we will perform all the activity of the image. Right Click on the Controllers, Add, then Controller.
Provide the name of the Controller as “ImageController” and click to Add.
- using System.Web.Mvc;
- namespace BlobStorageDemo.Controllers
- {
- public class ImageController: Controller
- {
- ImageService imageService = new ImageService();
-
- public ActionResult Upload()
- {
- return View();
- }
- }
- }
Install Storage Client Library and Configuration through NuGet
Generally when we create a simple application there is no reference of the
Storage Client Library. So to add this I am going to use
NuGet Package Manager.
Right Click on the project and choose
Manage NuGet Packages. It will open
NuGet Package Manager for you. Type the
azure storage inside the search and it will give you the following package which can be installed. You need to choose
WindowsAzureStorage and click to
Install.
It will give you some preview what it is going to install packages.
It will take few minutes to install. When it will install successfully, you will be finding lots of extra references inside the
Reference section along with
WindowsAzure.Storage.
You can also install
Azure Configuration to access the configuration setting in application.
Upload Image through ASP.NET MVC Application
So, going to access the blob storage through your services or controller, you need to use
blob storage access key. So, for the security purpose you can store it inside the configuration files. Later we can access it anytime from anywhere.
I am going to create a class “
ConnectionString.cs” from where I will access the storage account name and storage access key and create the connection string for blob storage. Please make sure you need to use two namespaces.
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
ConnectionString.cs
- using Microsoft.Azure;
- using Microsoft.WindowsAzure.Storage;
- using System;
- namespace BlobStorageDemo
- {
- public static class ConnectionString
- {
- static string account = CloudConfigurationManager.GetSetting("StorageAccountName");
- static string key = CloudConfigurationManager.GetSetting("StorageAccountKey");
- public static CloudStorageAccount GetConnectionString()
- {
- string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", account, key);
- return CloudStorageAccount.Parse(connectionString);
- }
- }
- }
To accessing the Storage Account, You can access it through the
CloudStorageAccount class which can be accessed by account name and access key. Using the instance of the
CloudStorageAccount, you can access and create the instance of the
CloudBlobClient. But without accessing the blob container you can’t access the resource which is resided in container. So, in this case, we need to use the
CloudBlobContainer.
- CloudStorageAccount cloudStorageAccount = ConnectionString.GetConnectionString();
- CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
- CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("sampleimage");
To access these Storage classes, you make sure you are adding the following namespace.
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Blob;
ImageService.cs
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Blob;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web;
-
- namespace BlobStorageDemo
- {
- public class ImageService
- {
- public async Task<string> UploadImageAsync(HttpPostedFileBase imageToUpload)
- {
- string imageFullPath = null;
- if (imageToUpload == null || imageToUpload.ContentLength==0)
- {
- return null;
- }
- try
- {
- CloudStorageAccount cloudStorageAccount = ConnectionString.GetConnectionString();
- CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
- CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("sampleimage");
-
- if(await cloudBlobContainer.CreateIfNotExistsAsync())
- {
- await cloudBlobContainer.SetPermissionsAsync(
- new BlobContainerPermissions {
- PublicAccess = BlobContainerPublicAccessType.Blob
- }
- );
- }
- string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);
-
- CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
- cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;
- await cloudBlockBlob.UploadFromStreamAsync(imageToUpload.InputStream);
-
- imageFullPath = cloudBlockBlob.Uri.ToString();
- }
- catch (Exception ex)
- {
-
- }
- return imageFullPath;
- }
- }
- }
As we are going to upload and show the latest uploaded image on the view, we need to make changes in the controller as in the following. I am going to upload image through the “
Upload” Action and showing the latest image through the action “
LatestImage”,
ImageController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Mvc;
-
- namespace BlobStorageDemo.Controllers
- {
- public class ImageController : Controller
- {
- ImageService imageService = new ImageService();
-
-
- public ActionResult Upload()
- {
- return View();
- }
-
- [HttpPost]
- public async Task<ActionResult> Upload(HttpPostedFileBase photo)
- {
- var imageUrl= await imageService.UploadImageAsync(photo);
- TempData["LatestImage"] = imageUrl.ToString();
- return RedirectToAction("LatestImage");
- }
-
- public ActionResult LatestImage()
- {
- var latestImage = string.Empty;
- if (TempData["LatestImage"] != null)
- {
- ViewBag.LatestImage = Convert.ToString(TempData["LatestImage"]);
- }
-
- return View();
- }
- }
- }
To upload and show the latest image, I have created two different views. For uploading you can use
upload.cshtml and for showing the latest image use
LatestImage.cshtml. Upload.cshtml - @{
- ViewBag.Title = "Upload";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h2>Upload Image</h2>
- <br />
-
- @using (Html.BeginForm("Upload", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
- {
- <fieldset class="form-horizontal">
- <div class="form-group">
- <label class="control-label col-md-2" for="Photo">Photo</label>
- <div class="col-md-10">
- <input type="file" name="photo" />
- </div>
- </div>
- <div class="form-group">
-
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Submit" class="btn" />
- </div>
-
- </div>
- </fieldset>
-
- }
LatestImage.cshtml
- @model string
- @
- {
- ViewBag.Title = "Latest Image";
- Layout = "~/Views/Shared/_Layout.cshtml";
- } < br / > < h3 > Latest Uploaded Image < /h3> < br / > < img src = "@ViewBag.LatestImage"
- title = "Latest Uploaded" / >
It is time to run the project. So, runt the project to press F5 and go to the following page to upload the image, here you can choose a image which is going to upload and click to submit.
When you click submit, it will upload your image inside the
sampleimage blob storage container. And redirect to latest image page with latest uploaded image.
You can check your uploaded image to refresh the
Azure Explorer. Conclusion
So, today we have learned what blob storage is and why we need to use it. We have used blob storage to create an account with ASP.NET MVC application.
Suggest, what do you think?
Thanks for reading this article, hope you have enjoyed it. Please share your valuable feedback and suggestion through comments.