Working with Azure BLOB Storage in MVC
In this post you will learn following things:
i) Introduction to BLOB Storage
ii) Installing the Azure SDK
iii) Creating MVC Application (Web Role) to upload BLOBs (for example, images) and delete BLOBs
iv) 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 image, document, audio, video or other multimedia objects.
Now a question arises here, why we 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 here http://www.windowsazure.com/en-us/downloads/ or the best way using Visual Studio IDE is given here. Follow the steps.
Open Visual Studio and try to create a new Cloud based project. You will notice ‘Get Windows Azure SDK..’ project template.
When you select above project template and click ok, you will get a Windows Azure project in solution explorer as well as an html page that will take you to download page.
Once you click on the ‘Download Windows Azure SDK for .NET’ button, it will take you to another web page where you will find ‘install SDK’ link.
When you click on ‘install the SDK’ link, a ‘Web Platform Installer’ dialog will come up asking you for the confirmation to install the required software.
Once you click on the ‘Install’ button in above dialog, it will take 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 stuffs.
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
Before you start looking at steps, I would like to show you an 8 seconds video clip, so that you get the idea what we are going to build.
This is just like a normal Web Forms or MVC Application, the only major difference is that it is Web Role using MVC running on the Cloud that we can scale up and down anytime to meet the requirements and much more.
Let’s go step by step to build this application.
Step 1 - Creating Projects
Once you have installed the 'Azure SDK for .NET' you will be able to see ‘Windows Azure Cloud Service’ project template.
Hit ok in above dialog, and now you will be prompted to select roles. Select ASP.NET MVC 4 Web Role, you could select any Worker Role, Queue etc (What are web role, worker role, and queue? You will see it in just a bit.) but for the sake of simple BLOB demo selecting ASP.NET MVC 4 Web Role will work. At the end hit ok.
When you hit ok in above dialog, it will ask you to select MVC Application template which may be familiar to you. Select Internet Application and hit ok.
Here are few common terms that you should quickly know, just quick definitions.
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 demand.
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 queue and process.
Queue - Queue is something that contains set of message and all messages must be in queue.
Note: Web Roles, Worker Roles and Queue are actually VMs.
Above definitions may be not sufficient to make your point crystal clear but that’s okay, you are not going to see them in this post, 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 it is.
1. MVC Project (MvcWebRole1) – this is just a regular MVC with Internet Application template project, you will notice a new file WebRole.cs here.
This file contains the entry point settings of MVC application. You need this file when MVC running in the Cloud Service. The information written in this file executes before the execution of 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()). Rest everything in the 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 local development server and also to take it to the Cloud Services. Double click to open ‘MvcWebRole1’ file.
In the above image you can see all the sections Configuration, Settings, Endpoints, Local Storage, Certificates, and Caching. Look at the ‘Settings’ section, here you can add Connection String (Storage Connection String) or normal string name-type-value pairs. Currently you can see a value which points Local Development Storage, we will modify this value before publishing the application to the Cloud so that it maps the right storage account.
Step 3 - Adding Development Connection String
Double click to open ‘MvcWebRole1’ file and add a new setting by name ‘ImageStorageAccountConn’ and select type as ‘Connection String’ and then follow the instruction given in image to select storage to store blobs on Azure storage emulator. Remember, before publishing the application up on the Cloud this needs to be modify.
At the end hit ok. Now you will have a setting name ‘ImageStorageAccountConn’ with value ‘UseDevelopmentStorage=true’.
Step 4 - Blob Storage Service
In order to call the storage account and create the container you need a class in MVC Project. Add a class ‘BlobStorageService.cs’ and a method ‘GetCloudBlobContainer()’ of type CloudBlobContainer as given in the image (click to enlarge image).
You need to import couple of namespace here, so make sure you have all. Now, let’s understand the codes written in the method.
Line Number 15, 16 - Connecting to storage account using Connection String we created in step 3 and then creating Cloud blob service client.
Line Number 17 - In Cloud blob service client, we are looking for a container by name ‘myimages’, what is container you will see it in just a bit.
Line Number 18 to 21 - Using if block, checking is ‘myimage’ named container exist. If not exist, 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? - In rough word, this is just like a folder on Cloud that will contain our blobs.
Step 5 - Working on ActionResult to Upload, Display and Delete Images
Once you have storage account and container setup, you can go ahead and use them inside controllers.
I am going to add action methods inside Home controller. Here is the code that will upload and display the images.
Look at the line number 33, I’ve created the object of blob storage service class (BlobStorageService). There are two Upload action results, first one will list all the available blob’s URI in the container and return it on the view to display, and second one is labeled with [HttpPost] so this will accept the posted image file and upload it to blob container. At the end this will redirect to same view page to make the recently uploaded image visible.
One more method we need to delete the BLOB. We need this with [HttpPost] label, here it is.
In above code, you can see this is just a normal method that will accept Name as a parameter and return 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 write uri.LocalPath. Then, we will use this filename to get the reference of blob and then delete it. At the end we will return string result ‘File Deleted.’.
Step 6 - Creating View Page
In above step we created all the required methods inside Home controller. Now, let’s add a view page for Upload ActionResult and use following code.
In above code, look at the first block, here we have created a regular form using Razor syntaxes with a file input and submit input control. In second block, we are looping through the Model returned by the GET version of ‘Upload’ action result. In the body of the loop attaching the Model item data (which is URI of image) to image control and link control. Inside the link control, I’m making a JS function call with URI parameter. Now, this JS function will call the method ‘DeleteImage’ with URI (which is, Name: item) as a parameter, then it will redirect the browser to Home/Upload location and display the alert message ‘File Deleted.’.
Now, we are all set to run the application and do all the stuff, upload image and delete image.
That’s all in building application. Now, let’s go ahead and push this application (web role) and blob storage on the cloud.
Publishing to Windows Azure (Storage and Web Role)
Before pushing Storage and MVC application (web role) on the Cloud, let’s look at local development server and see what’s happening here.
When you open Server Explorer, you will notice many Azure services are running.
In 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 have 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 local development server.
In the same way, if you look at running applications (maybe hidden, click little icon on taskbar to open it) you will notice an Azure Storage Emulator is running with all three services.
Now, let’s go ahead and open Azure Portal and create an storage account and come back here to modify/update the Connection String setting and then we will push the application and blob storage on Cloud.
Step 1 - Create Storage Account on Azure Portal
Let’s go quickly on Windows Azure portal and quick create a storage account by name ‘blobstoragedemo’. Here is image.
Once you create the storage account, you will see ‘Manage Access Keys’, let’s copy ‘Storage Account Name’ and ‘Primary Access Key’.
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 Cloud Storage Account which is ‘blobstoragedemo’.
After filling all the information displayed on the Azure portal, click ok at the end. That’s it. Now this will store all the blobs in Storage Account which is on the Cloud rather than on Azure emulator (on local machine).
Run the application and try to upload any image here, before proceeding 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.
In above image, look in the Server Explorer you will see another storage account which is connected to Cloud storage account. Also, look at the image that we uploaded in above step, it is right there uploaded, you can see the URL of the blob accessible by browsers.
Step 4 - Publishing MVC Web Role Application
As of now, we connected our application to Azure Storage on the Cloud. Only one thing left here is publishing the MVC Application. Please note, this not just MVC Application, it is more than that – ‘Cloud enabled application’, so publishing it like regular ‘Azure Websites’ will not work. So, right click on ‘MvcWebRole1’ and select ‘Publish to Windows Azure’.
Once you click on ‘Publish to Windows Azure’ you will be asked to select your subscription, you can download it just by clicking on given link. Image given below.
When you downloaded the credentials, import it and click on next button. You will get following dialog, here you can either pick ‘Cloud Service’ you been created or create a new one. Let’s create a new one ‘BlobCloudService’, select location and hit ok.
Leave all the rest information as it is for now and click on next button and then click to publish it. You will notice the deployment process in running in Visual Studio.
Once the deployment process finishes, you can browse it and try to upload images, it will work smoothly, now everything in the Cloud.
Hope this helps. Thanks.