Click here to Skip to main content
Click here to Skip to main content

Dynamic Blob creation and Uploading files

, 16 Apr 2014
Rate this:
Please Sign up or sign in to vote.
Check for the containers, add them and create dynamic blobs and upload files, Also check the Exceptions from blobs.

Please note

This article is an entry in our DnB Developer Challenge. Articles in this sub-section are not required to be full articles so care should be taken when voting.

Introduction

Windows Azure provides various cloud enabled storage services and Blob storage 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. The main purpose for using BLOB cloud services is it has a many advantages over storing files in local file systems.

As the msdn suggests the advantages are:

  • It is highly Scalable : that is a single storage account(will be discussed ahead) can store hundreds of terabytes of data and one can have multiple storage accounts.

  • It is Durable : that is every file(images, documents, audio, video or other) stored, automatically has a backup.

And many more, for the time these are of more focus.

Concept Behind

Storage Account: All access to Azure Storage is done through a storage account.


Container: A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs.

Blob: A file of any type and size. There are two types of blobs that can be stored in Azure Storage: block and page blobs. Most files are block blobs. A single block blob can be up to 200GB in size. This tutorial uses block blobs. Page blobs, another blob type, can be up to 1TB in size, and are more efficient when ranges of bytes in a file are modified frequently.

Background

  • This article mainly focuses on use of cloud services as here is Azure, checking for containers in our development storage and creating blobs dynamically into it and uploading files to it, as its being used in almost every sites.

    In order to develop Azure Cloud enabled applications, we need to install SDK(Software Development Kit-A software development tool required to create application for specific software) first. The best way to develop SDK is :

    It will then redirect you to download the SDK.

Using the code

  • Lets follow the steps (I will follow with the Screenshots for better understanding)

  • Step 1: Navigate to Visual Studio-->

  • Step 2: After selecting a new project, we select cloud and then Windows Azure Cloud Service. After clicking Ok you get a popup as shown below:

    As I have mentioned we can select any web/worker roles, but here I select ASP.NET MVC4 Web Role.

  • Step 3: Now your solution looks like the image below

    Now our architecture looks like the above. Now we might notice in the MVCWebRole project there is a class WebRole.cs, this class executes before the execution of the Global.asax, we can configure what to do before the starting of the project in the OnStart() method. You can check the code provided for download.

    The second project as you can see in the figure is UploadTrial1 ,that is basically the cloud sevice. It contains a Roles folder that contains MvcWebRole. When we open the file a dialog comes up that contains all the Configuratins Settings required for our cloud services and even local settings. The dialog is shown below.

    In the settings, we prescribe a setting name and then select the storage for us. "UseDevelopmentStorage=true", this directs to the local storage. You can navigate into the Server Explorer-->Windows Azure-->Development-->Blobs-->You find your container there with its contents. We can opt for Manually entered credentials during deployment. Here I have chosen local storage.

    We then add our Class for checking for the container blobs and dynamically creating it. Below are the codes

    //namespaces used
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace MvcWebRole1
    {
        //Container information
        public class BlobStorageServices
        {
            public CloudBlobContainer GetCloudBlobContainer()
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("ImageUploadSetting"));//gets settings value
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();//activates the storage account on local
                CloudBlobContainer blobContainer = blobClient.GetContainerReference("imagesupload");
                if(blobContainer.CreateIfNotExists())
                {
                    blobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });//Allowing public Access
                    
                }
                return blobContainer;
    
            }
    
        }
    }

    Check for the namespaces correctly as the assemblies are required in the reference. Now its time for coding our Controller(HomeController.cs), we write the codes here for the Upload action method-[Httpget]/[HttpPost]. Below are the codes

     BlobStorageServices blobStorageServices = new BlobStorageServices();
    //Instantiate object of the class we just created.
    
            /// summary///
            /// Uploads this blobs.
            /// summary///
            /// <returns>Views of blobs<returns>
            public ActionResult Upload()
            {
                CloudBlobContainer blobContainer = blobStorageServices.GetCloudBlobContainer();
                List<string> blobs=new List<string>();
                foreach(var blobItem in blobContainer.ListBlobs())
                {
                    blobs.Add(blobItem.Uri.ToString());//Returns all the blobs Uri in the container.
    
                }
                return View(blobs);//Returns to view to display all blobs.
    
            }
     
            ///summary///
            /// Uploads the specified image.
            /// 
            /// <param name="image"/>The image.
            /// <returns>Redirected to Upload Action</returns>
            [HttpPost]
            public ActionResult Upload(HttpPostedFileBase image) //Accept the posted file
            {
                try
                {
                    if (image.ContentLength > 0)
                    {
                        CloudBlobContainer blobContainer = blobStorageServices.GetCloudBlobContainer();
                        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(image.FileName);                 
                        
              // Upload content to the blob, which will create the blob if it does not already exist.
                        blob.UploadFromStream(image.InputStream);
                    }
                }
                catch(Exception ex)
                {
                    CloudBlobContainer blobContainer = blobStorageServices.GetCloudBlobContainer();
                    CloudBlockBlob blob2 = blobContainer.GetBlockBlobReference("myfile.txt");
                    blob2.UploadText(ex.ToString());
                }
                return RedirectToAction("Upload");
            }

    Then our work is to create/add a view to the upload action(remember to the get method) Smile | :) Below is the image that follows our view page(upload.cshtml), one thing to inform I have used Razor view engine here

    And Done we are up with uploading files. One important thing you can check in the codes I have written or the download the code given, is that I have implemented one thing i.e. to upload the exception if occurs in a ".txt"format.

Points of Interest

Web Role in Windows Azure are special purpose services and provide a dedicated IIS used for hosting web application, we can easily add and deploy application to webrole and scale as per our compatibility as per requirement.It is basically front-end that appears to the users.

Worker Role are processes that can do some work as the name suggests. For example, compressing an uploaded image automatically or on the fly, any changes in the database, best is notifications that are received.

Queue contain set of messages and those messages should be queue. The main thing is that Web Role, Worker Role and Queues are Virtual Machines running on cloud.

History

First Article published in April 12th.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Suraj Sahoo Mindfiresolutions
Software Developer (Junior) Mindfire Solutions
India India

I am currently a Software Developer at Mindfire Solutions,India.Working currently on ASP.NET MVC4 Web Applications.



I am passionate and enthusiastic to learn more about softwares and coding.Code Project is the best platform to feed me what i want.



I would love to know queries and questions from all of you specially beginners like me so that we could share some Code stuffs and make new recipes.Drop into suraj.0241@gmail.com.

I am Microsoft MVC4(70-486) certified.

Follow on   Twitter   Google+

Comments and Discussions

 
QuestionCode provided for download? Pinmemberavous19-Apr-14 7:34 
AnswerRe: Code provided for download? PingroupSuraj Sahoo Mindfiresolutions19-Apr-14 8:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 16 Apr 2014
Article Copyright 2014 by Suraj Sahoo Mindfiresolutions
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid