Working With Azure BLOB Storage in MVC

In this article you will learn the following things:

  1. Introduction to BLOB Storage

  2. Installing the Azure SDK

  3. Creating MVC Application (Web Role) to upload BLOBs (for example, images) and delete BLOBs

  4. Publishing to Windows Azure (Storage and Web Role)

Introduction to BLOB Storage

Windows Azure provides various cloud enabled storage services and BLOB is one of them. BLOB stands for Binary Large Object which means unstructured data that typically includes images, documents, audio, video or other multimedia objects.

Now a question arises here, why you use BLOB storage services in the Cloud? The BLOB storage services provided by Windows Azure is manageable, scalable and highly available data in the Cloud.

Installing the Azure SDK

In order to develop Azure Could enabled applications you need to install its SDK. There are various ways to download and install this SDK, either you can download it from http://www.windowsazure.com/en-us/downloads/ or the best way is to use your Visual Studio IDE as given here. Use the following procedure.

Step 1

Open Visual Studio and try to create a new Cloud based project. You will see the "Get Windows Azure SDK.." project template.

1.jpg

Step 2

When you select the project template shown above and click "Ok", you will get a Windows Azure project in Solution Explorer as well as an HTML page that will take you to the download page.

2.jpg

Step 3

After clicking on the "Download Windows Azure SDK for .NET" button, it will take you to another web page where you will find an "Install SDK" link.

3.jpg
 

Step 4

When you click on the "Install the SDK" link, a "Web Platform Installer" dialog will be shown prompting you for confirmation to install the required software.

4.png
 

Step 5

After clicking on the "Install" button in the dialog shown above, it will take a few minutes to install the required software for your Visual Studio IDE. This is actually a hassle-free way to install the Azure SDK, you don't need to think about version stuff.

5.png

That's it, your IDE is now ready to create cloud enabled projects.

Creating MVC Application (Web Role) to upload BLOBs (images) and delete BLOBs

This is just like a normal Web Forms or MVC Application, the only difference is that it is Web Role enabled using MVC running on the Cloud that we can scale up and down anytime to meet the requirements and much more.

Let's proceed step-by-step to build this application.

Step 1: Creating Projects

Once you have installed the Azure SDK for .NET you will see the "Windows Azure Cloud Service" project template.

7.png

Hit "Ok" in the dialog shown above, and now you will be prompted to select roles. Select "ASP.NET MVC 4 Web Role"; you could select any Worker Role, Queue and so on. (What are web role, worker role, and queue? You will see it in just a bit.) For the sake of this simple BLOB demo however, selecting "ASP.NET MVC 4 Web Role" will work. At the end hit "Ok".

8.png
 

When you hit "Ok" in the dialog shown above, it will ask you to select whichever MVC Application template that may be familiar to you. Select "Internet Application" and hit "Ok".

Here are a few quick definitions of common terms that you should know.

Web Role: Web roles in Windows Azure are special purpose, and provide a dedicated Internet Information Services (IIS) web-server used for hosting front-end web applications. You can quickly and easily deploy web applications to Web Roles and then scale your compute capabilities up or down to meet demands.

Worker Role: Worker roles are processes that can do some work. For example, automatically compress uploaded images, do stuff whenever something changes in your database, and get new messages from queues and processes.

Queue: A Queue is something that contains a set of messages and all messages must be in the queue.

Note: Web Roles, Worker Roles and Queue are actually VMs.

The definitions above may be insufficient to make your point crystal clear but that's okay, you will not work on them in this article, you just need to understand Web Role here.

Step 2: Overviewing MVC (Web Role) Project and Windows Azure Project

Now you will have two projects in Solution Explorer, here they are.

9.png
 

1. MVC Project (MvcWebRole1): this is just a regular MVC with Internet Application template project, you will notice a new file WebRole.cs here.

10.png
 

This file contains the entry point settings of the MVC application. You need this file when the MVC is running in the Cloud. The information written in this file executes before the execution of the Global.asax file. So, we use this file to configure what to do before starting the web app (OnStart()) or what to do on stop (OnStop()). The remainder of what is in this project will be familiar to you.

2. Windows Azure Project (Windows Azure2): this is actually our Cloud project. This file contains all the information required to run the application (web role) on the local development server and also to take it to the Cloud. Double-click to open the "MvcWebRole1" file.

11.png
 

In the preceding image you can see all the sections Configuration, Settings, Endpoints, Local Storage, Certificates, and Caching. Look at the "Settings" section, here you can add a Connection String (Storage Connection String) or normal string as name-type-value pairs. Currently you will see a value that points to Local Development Storage, we will modify this value before publishing the application to the Cloud so that it maps the correct storage account.

Step 3: Adding Development Connection String

Double-click to open the "MvcWebRole1" file and add a new setting by name "ImageStorageAccountConn" and select type as "Connection String" and then follow the instruction given in the image to select storage to store BLOBs in the Azure storage emulator. Remember, before publishing the application to the Cloud this needs to be modified.

12.jpg
 

At the end hit "Ok". Now you have a setting named "ImageStorageAccountConn" with the value "UseDevelopmentStorage=true".

Step 4: BLOB Storage Service

In order to call the storage account and create the container you need a class in the MVC Project. Add a class "BlobStorageService.cs" and a method "GetCloudBlobContainer()" of type CloudBlobContainer.

13.jpg
 

You need to import a couple of namespaces here, so make sure you have all of them. Now, let's understand the code written for the method.

Line Number 15, 16: Connecting to the storage account using the Connection String that we provided in Step 3 and then creating the Cloud BLOB service client.

Line Number 17: In the Cloud BLOB service client, we are looking for a container by the name "myimages"; you will see the container in just a bit.

Line Number 18 to 21: Using an if block, determine if the "myimage" named container exists. If it does not exist then create one and set all the required public access permissions.

Line Number 22: Finally, returning the blobContainer object that has everything, like account information, container information and appropriate permissions.

What is Container? Roughly speaking, this is just like a folder in the Cloud that will contain our BLOBs.

Step 5: Working on ActionResult to Upload, Display and Delete Images

Once you have a storage account and container set up, you can proceed to use them inside controllers.

I will add action methods inside the Home controller. Here is the code that will upload and display the images.

14.png

Look at the line number 33, I've created the object of BLOB storage service class (BlobStorageService). There are two Upload action results, the first one will list all the available BLOB's URIs in the container and return them in the view to be displayed, and the second one is labeled "[HttpPost]" so this will accept the posted image file and upload it to the BLOB container. In the end this will redirect to the same view page to make the recently uploaded image visible.

There is one more method with the "[HttpPost]" label that we are left with, which will delete the image, here it is.

15.png

In the code above, you can see this is just a normal method that will accept Name as a parameter and return a string message. "Name" is nothing but the URI of the image (for example: "http://127.0.0.1:10000/devstoreaccount1/myimages/scene.jpg") so in order to know the actual name of the image ("scene.jpg") we need to use "uri.LocalPath". Then, we will use this filename to get the reference of BLOB and then delete it. At the end we will return the string result "File Deleted.".

Step 6: Creating View Page

In the above step we created all the required ActionResults and a method inside the Home controller. Now, let's add a view page for the Upload ActionResult and use the following code.

16.png
 

In the code above, look at the first block, here we have created a regular form using Razor syntax with a file input and submited the input control. In the second block, we are looping through the Model returned by the GET version of the "Upload" action result. In the body of the loop attaching the Model item data (which is the URI of the image) to the image control and link control. Inside the link control, I'm making a JS function called with a URI parameter. Now, this JS function will call the method "DeleteImage" with a URI (which is, Name: item) as a parameter, then it will redirect the browser to the Home/Upload location and display the alert message "File Deleted.".

Now, we are all set to run the application and do everything to upload and delete images.

17.png
 

That's all for building the application. Now, let's proceed to push this application and BLOB storage to the Cloud.

Publishing to Windows Azure (Storage and Web Role)

Before pushing the storage and MVC application (web role) to the Cloud, let's look at the local development server and see what's happening here.

When you open the Server Explorer, you will notice many Azure services are running.

18.jpg

In the above image, notice a "Windows Azure Storage" service, if you expand it you will find "Development" server storage services. Inside "Development" you will find BLOBs, Queues and Tables. If you expand BLOBs you will find "myimages", which is our container that we created in "Step 4: BLOB Storage Service". If you right-click on "myimages" and click to select "View BLOB Container", it will open a nice document based list of BLOBs (images). So, all these are running on the local development server.

In the same way, if you look at the running applications (maybe hidden, click the little icon on the Taskbar to open it) you will see an Azure Storage Emulator running with all three services.

19.png

Now, let's proceed to open the Azure Portal and create a storage account and return here to modify/update the Connection String setting and then we will push the application and BLOB storage to the Cloud.

Step 1: Create Storage Account on Azure Portal

Let's go quickly to the Windows Azure portal and quickly create a storage account by the name "blobstoragedemo". Here is an image of that.

20.jpg

Once you have created the storage account, you will see "Manage Access Keys", let's copy "Storage Account Name" and "Primary Access Key".

21.png

Step 2: Modify Connection String

Once you have "Storage Account Name" and "Primary Access Key", you can open your development application and modify the Connection String settings to point to the Cloud Storage Account which is "blobstoragedemo".

22.jpg

After filling in all the information displayed on the Azure portal, click "Ok" at the end. That's it. Now this will store all the BLOBs in the Storage Account in the Cloud rather than in the Azure emulator (on the local machine).

Run the application and try to upload any image here, before proceeding to the next step.

Step 3: Connecting to Azure Storage Account from Server Explorer

You can check it in the Server explorer by adding the storage account and by entering "Storage Account Name" and "Primary Access Key". Look at the image given below.

23.jpg

In the above image, look in the Server Explorer; you will see another storage account connected to the Cloud storage account. Also, look at the image that we uploaded in the above step, it is right there uploaded, you will see the URL of the BLOB accessible by browsers.

Step 4: Publishing MVC Web Role Application

As of now, we have connected our application to Azure Storage in the Cloud. There is only one thing left here, the publishing of the MVC Application. Please note, this is not just a MVC Application, it is more than a "Cloud enabled application", so publishing it like regular "Azure Websites" will not work. So, right-click on "MvcWebRole1" and select "Publish to Windows Azure".

24.png

After clicking on "Publish to Windows Azure" you will be asked to select your subscription, you can download it just by clicking on the given link. An image showing that is given below.

25.png

When you have downloaded the credentials, import it and click on the "Next" button. You will get the following dialog. You can either pick the "Cloud Service" you have created or create a new one. Let's create a new one, "BlobCloudService". Select the location and hit "Ok".

26.png

Leave all the other information as it is for now and click the "Next" button. Then click to publish it. You will see the deployment process running in Visual Studio.

27.png

Once the deployment process finishes, you can browse it and try to upload images, it will work smoothly, now everything is in the Cloud.

28.png

I hope this helps. Thanks.


Similar Articles