Category Archives: Azure

Extracting and Using Facebook OAuth Token from ACS

A couple of my previous blog posts have shown how AppFabric ACS (Access Control Service) can be used as part of the Windows Azure Toolkit for iOS to enable federated authentication with Facebook, Google, Yahoo, and other providers.

I was recently asked whether it’s possible to extract an OAuth token as part of the ACS sign in process that can then be presented to Facebook’s Graph API in order to access details such as friends lists, photos, etc. In this post, I’ll cover how this can be done.

The first step is of course to display the authentication page. As you’ve seen in previous posts, this can be achieved using the following:

WACloudAccessControlClient *acsClient = [WACloudAccessControlClient accessControlClientForNamespace:@“iostest-walkthrough” realm:@“uri:wazmobiletoolkit”];

[acsClient showInViewController:self allowsClose:NO withCompletionHandler:^(BOOL authenticated) { if (!authenticated) { NSLog(@"Error authenticating"); } else { WACloudAccessToken *token = [WACloudAccessControlClient sharedToken]; NSString *securityToken = [token securityToken]; ... }

In the application, this will display the federated login dialog, and prompt the user to enter their Facebook credentials.

myWPEdit Image

You’ll notice that the ACS client returns a cloud access token, of which a security token can be extracted. This security token is a set of claims returned from ACS. Here’s an example:

If we want to make follow on calls to Facebook’s Graph API, we are going to need to present the Facebook User ID and an OAuth Token. Fortunately both of these can be extracted from the token.

To extract this, we first HTTP encode the token:

NSMutableArray *httpEncoding = [NSMutableArray arrayWithObjects:[NSArray arrayWithObjects:@"%3a",@":",nil], [NSArray arrayWithObjects:@"%2f",@"/",nil], nil];

while ([httpEncoding count] >= 1) { securityToken = [securityToken stringByReplacingOccurrencesOfString:[[httpEncoding objectAtIndex:0] objectAtIndex:0] withString:[[httpEncoding objectAtIndex:0] objectAtIndex:1]]; [httpEncoding removeObjectAtIndex:0]; }

NSError *error = NULL;

Using a simple RegEx search we can extract the Facebook User ID:

NSRegularExpression regex = [NSRegularExpression regularExpressionWithPattern:@“[0-9])” options:0 error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:securityToken options:0 range:NSMakeRange(0, [securityToken length])]; firstRange = [match rangeAtIndex:1]; fbuserId = [securityToken substringWithRange:firstRange];

And the required OAuthToken:

regex = [NSRegularExpression regularExpressionWithPattern:@“[A-Za-z0-9]*)” options:0 error:&error];

match = [regex firstMatchInString:securityToken options:0 range:NSMakeRange(0, [securityToken length])];
NSRange firstRange = [match rangeAtIndex:1];
oauthToken = [securityToken substringWithRange:firstRange];

Now it’s just a case of calling the Graph API using these credentials:

NSString *graphURL = [NSString stringWithFormat:@“”,fbuserId,oauthToken];

For the purposes of this post, let’s take a quick look at my list of friends.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:graphURL]];
NSURLResponse *response = NULL;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *friendsList = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
regex = [NSRegularExpression regularExpressionWithPattern:@“id” options:0 error:&error];
NSUInteger friendCount = [regex numberOfMatchesInString:friendsList options:0 range:NSMakeRange(0, [friendsList length])];

Displaying the friend count in a UIAlertView on the screen shows how popular (or not!) I am:

myWPEdit Image

A simple example, but hopefully this shows not only that you can authenticate against Facebook using AppFabric ACS, but also how the returned Facebook User ID and OAuth Token can be used to make further calls to Facebook using the user’s credentials.

Working with the Windows Azure Toolkit for Android

At the end of August, Microsoft published the Windows Azure Toolkit for Android. At Neudesic, the partner behind developing the both toolkits for iOS and Android, we’ve been working with customers that use the toolkit to connect mobile applications to the cloud. One of the recent requests however has been to provide a walkthrough of getting started with the toolkit. The current build on GitHub was released for a specific version of Eclipse and the Android tools, and as a result, can be a little challenging getting the library and sample code up and running.

In this post, I’ll explain what it takes to download the toolkit, create a brand new environment in Eclipse, and get started quickly with the toolkit.

Getting Started – What You’ll Need

Firstly, there is a list of tools that you’ll need to download.

1. Eclipse. Download from – we’ll be using Helios in this tutorial.

2. JDK. We’ll be using the default that ships with Mac OSX, but if you are on a PC, you’ll need JDK 1.6 or higher.

3. Android SDK and Eclipse Tooling. Download the Android SDK from (we are using r14 for this walkthrough). Also follow the instructions for configuring the Android tooling within Eclipse. After you have installed everything, use the AVD manager to setup a new AVD for an Android 2.3.3 device.

Setting Up the Library in Eclipse

To import and build the library in Eclipse, perform the following steps.

1. Download the Windows Azure Toolkit for Android from GitHub. If you have the Git client installed, you can use this command:

git clone

Otherwise, go to the site and pull down the zip file of the repo.

2. Create a new directory for your Eclipse workspace:

mkdir wa-toolkit-android-workspace

3. Launch Eclipse, and point the default workspace to this newly created directory:

myWPEdit Image

  1. Create a new Android project called AzureLibrary, set the target to Android 2.3.3, use as the package name, but do not create an activity or test project.

myWPEdit Image

  1. Right click on the AzureLibrary project and select Import. Choose General / File System as the import source, and click on Next.
  2. Browse to the /library/src/com folder in the toolkit folder that you downloaded from GitHub.
  3. Click on the Browse (into folder) button and select the src folder under your project. Expand the src folder, and check the com folder as shown in this screenshot:

myWPEdit Image

  1. Click on the Finish button. The import will complete.

myWPEdit Image

  1. Right click on the project, select properties, and change the Java compiler version from 1.5 to 1.6. (The default is 1.5, yet the toolkit uses many constructs only supported in 1.6)

myWPEdit Image

  1. Click OK, and say yes to rebuilding the project. The project should now build with no errors.
  2. Assuming everything builds correctly, right click on the project, and select Properties again. Go to the Android setting, and click on the Is Library check box.

myWPEdit Image

Setting Up the Sample Application in Eclipse

To import and build the sample application in Eclipse, perform the following steps:

  1. Create a new Android project called AzureSample. Select Android 2.3.3, set the namespace to com.windowsazure.samples.sample, and choose not to create an activity.

myWPEdit Image

  1. As you did with the library, right click on the project, and select Import. Select the /samples/simple/src as the source and import into the AzureSample/src folder.

myWPEdit Image

  1. Right click on the project, select Properties, select Android and add a reference to the AzureLibrary project:

myWPEdit Image

  1. Right click on the project, select Import. Import from the /samples/simple/res folder into the AzureSample/res folder. This will import the resources required for the sample application.

myWPEdit Image

Answer yes when prompted to overwrite the main.xml file.

  1. Right click on project, select Import and select the file system again. Select the AndroidManifest.xml from the root of the source directory and import into the root of the destination project.

myWPEdit Image

The Sample project should now build with no errors.

Configuring your Windows Azure Account Name and Key

In order to setup the sample project, you need to supply your account name and key, as provided by Windows Azure. You can obtain this by logging into the Windows Azure Portal ( and navigating to Storage Accounts to obtain the details.

When you have the name and key, perform the following:

  1. In the sample project, open from the src/com.windowsazure.samples.sample package.
  2. At the top of the file replace the ACCOUNT and ACCESS_KEY values with the account name and access key for your Azure storage account.


Running the Sample

1. To run the sample, right click on the sample project, select Run As / Android Application.

  1. Once the emulator is up and running, unlock the device.
  2. Refer to the LogCat/Console window in Eclipse if there are any errors.
  3. Click on the Start button in the sample application.
  4. Select either table, blob, or queue storage and browse the storage associated with your Windows Azure account.

myWPEdit Image

That’s it! Your sample application is now up and running, and you are able to browse Windows Azure storage!

Using Federated Identity for iOS Applications

Last week, Microsoft released v1.2 of the Windows Azure Toolkit for iOS.  As development partner for the toolkit, Neudesic has been working with several customers on implementing ACS for iPhone and iPad applications.  Due to popular demand, I wanted to share a short overview of how simple it is to get this up and working for your own iOS projects.

First, some background…

Many iPhone and iPad applications have a need to authenticate.  Maybe it’s to access sensitive information or record a particular high score against your name.  Implementing an authentication scheme for iOS can however be time consuming and tricky – you often have to create an authentication service, host it, expose the service through REST, and consume it on the device.  And afterwards you are responsible for backing up the user database and dealing with lost passwords, etc.

To help overcome this many applications are now turning to external providers.  For example, to identify yourself when playing Zynga Poker, instead of creating a new account, you simply sign into Facebook (when launching the application for the first time) and the game uses these credentials as you play. This type of sign in method is called federated identity. This prevents Zynga from having to maintain a complex and large set of user accounts and passwords, and also prevents the player from having to remember yet another username and password. 

Adding federated identity to your iPhone or iPad application can be difficult, requiring knowledge of exchange secure tokens with a set of providers, and creating and sending the right OAuth headers in your application.  Removing this difficultly is exactly what we are trying to address in v1.2 of the Windows Azure Toolkit for iOS. 

Sounds great – how do I use it?

To implement ACS in your application, you’ll first need to access the Windows Azure portal by navigating to and signing in with your credentials.


Click on the Service Bus, Access Control & Caching menu item and select the Access Control menu item under the AppFabric folder.  Select an active Windows Azure subscription and click on the New button in the toolbar.


The new service namespace dialog will open.  Ensure that Access Control is selected, and enter a unique namespace and country/region for the service.


The ACS namespace will now be created.  This might take a few minutes.  Wait until the namespace is showing in an Active state.


Once this is complete, highlight the newly created service and click on the Access Control Service button in the toolbar.  This will launch the Access Control Service portal.

Within the portal, click on Identity Providers and add the identity providers you would like to use for your application.


The default is Windows Live ID, but you can add other preconfigured providers (such as Google and Yahoo!) as well as external identity systems configured to use WS-Federation.

Once you have added the required providers, click on the Relying Parties section of the portal.


Click on the Add button and enter the following information for the relying party application:

Name – a given name for your application

Realm – a unique ID for your application.  For this walkthrough, we’ll be using uri:wazmobiletoolkit

Return URL – you can leave this blank

Error URL – you can leave this blank

Token Format – select SWT

Token Lifetime – Feel free to change the default from 600 seconds.

Select the identity providers that you would like to use, and then under the Token Signing Settings section, click on the Generate button to create a new symmetric key that will be used for this application.

Finally, click on the Save button.  This will create the Relying Party Application.

Next, go into the Rule Groups section of the portal and select the default rule group that was created for the application.


Click on the Generate link in order to generate a set of default rules for this rule group.


Select the providers that you wish to use, and click on the Generate button.  Once this is complete, you should see a set of rules.


After this step is complete, ACS has now been configured correctly to be used with your iOS application.  Make a note of your Service Namespace (found at the top of the portal) and Realm.

Ok, the service is now setup.  How do I use it in my Xcode project?

To start, launch Xcode (4.02 or higher) and create a new project.


From the project template dialog, select a View-based application and click on the Next button.  Enter a Product Name and Company Identifier and click on the Next button to continue.  Select a directory to use for the project file and return to the IDE.

Next, download the latest version of the Windows Azure Toolkit for iOS library from In the download will be a zip file containing two versions of the library (one for the device, one for the simulator) and some header files for the project.

Right click on your project and select the Add Files to… menu option.


Locate the .a file (for the simulator) and header files and add them to your project.  You may want to create a new group (called lib) to store these in.


Now we need to add a reference to a library required for XML parsing.  To do this, click on the top most project file, click on the target in the 2nd column of the IDE, and select Build Phases from the tab menu.


In the main window, expand the Link Binary with Libraries option.

Ensure that the libwatoolkitios.a file has been automatically added as a reference, click the + button to add a new library, and select the libxml2.dylib library from the drop down list.


Click on the Add button to add a reference to this library for your project.

Before we start adding any code, we need to add a couple of required linker flags to the project.  To do this, click on the Build Settings tab (next to Build Phases).

In the search box, type “other linker” to filter the settings.


You should see a setting called Other Linker Flags.  Double click on the right side of this row to add new flags.

Click on the + button to add two flags.  The first is –ObjC and the second is –all_load.  Once complete, your linker flags should look like the following screenshot:


Click on the Done button to save these settings.  The project is now configured correctly to reference the Windows Azure Toolkit library.

To test that the library works, click on the project’s [ProjectName]AppDelegate.m file.  Add the following #import statement at the top of the class:

#import "WACloudAccessControlClient.h"

Next, search for a method called didFinishLaunchingWithOptions and after the [self.window makeKeyAndVisible] line, enter the following code.

NSLog(@"Intializing the Access Control Client...");

WACloudAccessControlClient *acsClient = [WACloudAccessControlClient accessControlClientForNamespace:@"iostest-walkthrough" realm:@"uri:wazmobiletoolkit"];

[acsClient showInViewController:self.viewController allowsClose:NO withCompletionHandler:^(BOOL authenticated) {

if (!authenticated)


NSLog(@"Error authenticating");




NSLog(@"Creating the authentication token...");

WACloudAccessToken *token = [WACloudAccessControlClient sharedToken];

/* Do something with the token here! */



Replace the namespace and realm in the first line with the service namespace and realm for your own service.

As you can see from the above, the code creates a new instance of the access control client, requests that the client shows itself in the current view controller, and then extracts a token.

Build and run the application in the iOS Simulator.

Once the application starts, you should be prompted to select an identity provider from the list that you configured in your ACS service.


Pick one of the providers, and enter a valid set of credentials.


Click on the Remember me checkbox if you want to skip this step when running this application again, and click on the Sign in button.

The first time the application is run, you’ll be prompted to authorize the application to access your provider data.


Click on the Allow button to continue.  The login window will now disappear and you’ll be returned to your application.

In the debug window, you should see the following two logs:

2011-07-22 10:12:26.284 iostest-walkthrough[25838:207] Intializing the Access Control Client…

2011-07-22 10:12:36.359 iostest-walkthrough[25838:207] Creating the authentication token…

If you are seeing this, congratulations!  You’ve successfully setup federated identity for your application.  The final message indicates that the access token was retrieved and can be used for further use.  The WACloudAccessToken (derived from [WACloudAccessControlClient sharedToken]) contains an NSDictionary of claims and other properties that can be stored within your application.  Using these properties on future calls can be used to identify returning users to your application.

Developing iPhone and iPad apps that leverage Windows Azure

Thanks to all that came to my session at MIX11 last week – it was a lot of fun to put together despite a couple of demo glitches!  You can now view the recording of this online, as well as browse and download the slides below. 

I’ll be sharing the source code for the demos in the next couple of posts.

Vote For Me!

No, I’m not running for President…!

Instead, I’m asking for your help in voting for my session at MIX11 this year:

Using iPhone, iPad and Android devices with Windows Azure

You have invested a lot learning how to build applications on Microsoft’s Windows Azure platform. But your customers are asking for solutions that target iPhone, iPad, and Android devices. Now What? How do you leverage your Microsoft skills, while supporting this new user base? How do you connect these devices to services hosted on Windows Azure? What strategies do you need for data sync between the two? Is it possible to develop applications using Microsoft technology that spans all devices? In this session you’ll learn how to integrate iPhone, iPad, and Android platforms into an existing Windows Azure infrastructure. You’ll walk away confident in knowing how to extend your existing applications to take advantage of this new wave of mobile devices, working together with the cloud.

If you would like to see me present this at MIX this year, click here and follow the cats (you’ll see what I mean!)

My esteemed colleagues at Neudesic also have submitted sessions.  If you would like to know about Black Belt Windows 7 Development, follow Steve Saxon’s link and click here.  If you would prefer to hear our UX director Chris McCurry talk about How to build a Showcase Windows Phone 7 Application, click here.

We are doing some great work in the mobility practice here at Neudesic, and we hope that you’ll vote us in!  Voting ends on February 4th, so cast your ballots now!


JavaOne Tutorial: Apache Tomcat on Windows Azure

As I mentioned in my previous post, I’ll be participating in a panel at JavaOne on Monday.  With a similar format to last year, each panelist is given 5 – 10 minutes before it opens up for general discussion. Rather than showing a bunch of marketing slides, I thought it would be more interesting to put together a short tutorial for running Apache Tomcat on Windows Azure.  When I speak with Java developers interested in Windows Azure, this is often the #1 request.

Here is an overview of what I will be showing:

Step 1 – What you’ll need to get started

As you might imagine, you are going to first need a Windows Azure account.  I would recommend going to and signing up for the introductory special, which will allow you to test your application for free.  The introductory offer gives you the first 25 hours at no cost, which should be more than enough time to get up and running.

If you are at JavaOne however, I have a limited quantity (100) of tokens that give you 30 days worth of access with no need to submit any registration or credit card information.  See me at the end of the panel session or throughout the conference, and in exchange for a business card, I’ll be happy to give you one at no cost!

After you have your account, you’ll want to download and install the Windows Azure SDK.  After installation, set your PATH environment to include the location of the SDK binaries (typically C:Program FilesWindows Azure SDKv1.1bin).  This is important to ensure that the SDK is accessible from the command line.

Finally, you’ll need to install the Windows Azure Tomcat Solution Accelerator.  Feel free to install this in any directory you’d like – I’m using c:devjavaone2010tomcatazure for the purposes of this tutorial.

Step 2 – Building and running your site

With all of the pre-requisites downloaded and installed, it’s time to build and test your site.  To do this, open a command prompt, and navigate to the directory that you chose for the solution accelerator.  From this directory, run buildme.cmd.  You’ll be prompted to provide the installation path of your Tomcat installation and a JRE on your machine.


After a successful build, run the runme.cmd file. This will run Tomcat using the Windows Azure Desktop Execution Tool – also known as the local development fabric.



This is a great way to test that your application is going to work when deployed to production.  Navigate to the URL provided at the end  (replace the tcp with http) to ensure that the Tomcat instance is working correctly on your local machine.


You can open the development fabric tool (found running in your system tray) if you want to stop and/or investigate the service.

Step 3 – Packaging and deploying your site

Once you are satisfied that everything looks good, it’s time to package the application ready for deployment to the cloud.  To do this, run the packme.cmd script.  This will invoke the Windows Azure Packaging Tool, and pull together everything needed into one package file for deployment.


When this has completed, you should see a Tomcat.cspkg file and a ServiceConfiguration.cscfg file in the directory.  The .cspkg file is quite large as it contains your application, the Tomcat instance, and JRE binaries.  Despite the size, this format makes it convenient if you prefer to use a different version of Tomcat or a different JRE in the future.


To deploy to the cloud, log on to the portal ( and create a new hosted service.  Walk through the wizard to specify the name, description, URL, and location where you want the service to be deployed.  Next, hit the “Deploy” button and specify the location of the previous package and configuration file.


You have two options when it comes to deploying – either a file from your local storage (i.e. your local disk) or a file from an Azure storage account (blob storage).  If you have issues with the local storage (many http connections timeout before the package can be uploaded in time), I would recommend using Neudesic’s Azure Storage Explorer to upload your files to a blob storage container.


Hit Deploy, and your package will be uploaded to Windows Azure – this will likely take a few minutes because of the size of the deployment.

Once this has been completed, hit the Run button to bring your site to life.



Once you have a site up and running, feel free to explore some of the ways that you can either scale your application to multiple nodes or explore some of the other features on Windows Azure available to Java developers.

There are many ways that this could be improved by integrating with existing build environments (I think Maven integration would be fascinating), but hopefully this short tutorial gives you a starting point for getting a simple Tomcat site up and running on Windows Azure.

Moving VHDs to the Cloud

When I speak with customers about cloud computing, a common question is often “how do I migrate an application to the cloud?”  While this is a multi-part answer, one of the hurdles for migration is often storage. 

Many applications store data using the file system (e.g. read / write a file to d:dataconfig.xml).  Moving these types of applications to the cloud can be difficult as the storage mechanisms in the cloud are somewhat different. 

To help address this problem, in Feb 2010 we released v1.1 of the Windows Azure SDK which supports a new feature call Cloud Drives.  A Cloud Drive is the ability to mount a virtual drive in the cloud so that applications can write to it as they would a local drive.  This cloud drive is persisted so that even if the machine goes down, the data is not lost.

What many people don’t realize however is that the format that the Cloud Drive uses is interchangeable with the VHD (Virtual Hard Drive) format used by virtualization products such as Hyper-V, Virtual PC, Windows Server, and Windows 7.  What this means is that you can create a single VHD, use it locally on a Windows PC, attach it to a virtualized image, and now copy it to the cloud and access it there also.  As you can imagine, for anyone looking to migrate applications to the cloud, this opens up a world of possibilities.

In this post, I’ll walk through a series of steps that show creating a VHD from scratch, copying it to the cloud, and accessing it from a web role running in Azure.

Before you begin

You’ll of course need an Azure account.  If you don’t have one, you can go here to sign up.

Once you have your account, you’ll need to setup two new services. 


You’ll need to create a storage account – this is where the VHDs will be stored – and a hosted service to run your application from.  When you set them up, make sure that they are created in the same geography (i.e. don’t have your storage account in Asia, and your hosted service in the US as the drive mounting has to be in the same region).

Once you have your storage account and service created, you are ready to create and upload your VHD. 

Step 1.  You’ll need a VHD

If you already have a VHD file that you would like to use, you can skip to Step 2.  You’ll be copying this VHD to the cloud, so you may want to choose a smaller VHD file for test purposes.

If you are running Windows 7, creating a new VHD is easy. 

Firstly, go to the start menu and type disk management

From the start menu click on Create and format hard disk partitions


This will open up the disk management tool.  From the Action menu, select Create VHD.


Enter a location for the VHD file and a size.  The minimum is 16Mb and the maximum is likely the amount of free disk space on your machine. 


When your disk appears in the management tool, right click on the disk name and select Initialize Disk.  Select the default (MBR) and select OK.


After initialization, right click on the disk and create a New Simple Volume.  Walk through the wizard, accepting the defaults and assign a drive letter to the VHD.  Finally, format the disk using NTFS (a quick format is fine).  If a dialog box appears asking you to format the disk (sometimes the disk gets detected just before formatting has begun), just hit cancel.

After this is done, you can open the drive and access it as you would any other drive. Add some files and folders, etc.


When you are ready to upload to the cloud, you’ll need to detach the drive.  To do this, go back in to the disk management tool, right click on the disk name and select Detach VHD.


(Do not select the Delete the virtual hard disk file checkbox – otherwise, they’ll be nothing to upload!)

Step 2.  Upload it to Azure Storage

The next step is to upload the VHD to the cloud.  The VHD will be stored in something called Blob (Binary Large OBject) storage.  You may have heard of blob storage if you’ve seen any of the introductory Azure presentations.  It’s the type of storage that is used for binary data such as images, videos, and the like.

In February we enabled support for Page Blobs.  Page Blobs are binary objects stored in the cloud that support random read/writes through pages.  This makes them ideal for dealing with VHD type of access, and this is the format that we’ll be using to upload our VHD to the cloud.

The one caveat of this is that you must use a tool that supports page blobs (most of the tools available today only support regular blobs).  The tool I would recommend is Cloud Storage Studio by Cerebrata as it supports page blobs through a nice interface.


Open the tool and access the storage account that you created in the “Before you begin” section earlier in this post. 

I would recommend creating a new container for your VHD images to keep them separate from other content.  As shown in the screenshot above, I’ve created a container called vhd.


Select the container, and click on the Upload Page Blob button.  There are two upload buttons – you need the one with the icon that includes the page and the up arrow.

Point to the location of your VHD file and click on the Upload button.


This might take a little way depending on the size of your VHD and the speed of your network.

Once you have uploaded the file, validate that it exists by hitting the refresh button.


With the VHD uploaded, we can now move on to creating the cloud application that accesses it.

Step 3.  Accessing the VHD from Windows Azure

I’m going to assume that you have some knowledge of creating an ASP.NET application and uploading it to Windows Azure.  If you haven’t done this before, I would recommend checking out the Windows Azure Training Kit.

To access the VHD in the cloud, we create a webrole and use the following code.

Add reference to the Microsoft.WindowsAzure.CloudDrive DLL that can be found in the GAC (assuming that you have the v1.1 SDK installed).  Then, in your webrole, you’ll need to add the following using statements:

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

Here is the code that you should run in your web role.  (You can place this behind a button or something…)

// Setup the account details
String accountName = "";  // insert your storage account name here
String accountKey = "”;  // insert your storage account primary key here

StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(accountName, accountKey);

CloudStorageAccount storageAccount = new CloudStorageAccount(credentials, new Uri(String.Format("http://{0}",accountName)),
                                                                            new Uri(String.Format("http://{0}", accountName)),
                                                                            new Uri(String.Format("http://{0}", accountName))

// initialize the local cache - need to trim the end backslash otherwise, HRESULT=D0000033
LocalResource localCache = RoleEnvironment.GetLocalResource("LocalCache");
CloudDrive.InitializeCache(localCache.RootPath.TrimEnd(''), localCache.MaximumSizeInMegabytes);

// Create and mount the drive
CloudDrive c = storageAccount.CreateCloudDrive("vhd/myvhd.vhd");
String driveLetter = c.Mount(localCache.MaximumSizeInMegabytes, DriveMountOptions.None);

// do regular System.IO.File and System.IO.Directory operations here against driveLetter
Response.Write(System.IO.Directory.GetFiles(driveLetter + "").Count() + " files found on the root of the mounted drive.");

// unmount the drive

There are five main pieces to the code.

Firstly, the storage account reference is created using the account name and key that you retrieve when you setup your Azure account.

After that we need to initialize a local cache used by the cloud drive.  To create this, insert the following code into your ServiceDefinition.csdef file on your webrole.

  <LocalStorage name="LocalCache" cleanOnRoleRecycle="false" sizeInMB="100" />

We then create and mount the drive using the CreateCloudDrive and Mount methods.  Make sure that the path and name to your VHD matches what you uploaded in Step 2.

Once the drive is mounted we get a drive letter (as a string – e.g. “f:”).  You can then make calls to that drive letter using the regular calls (e.g. System.IO.File and System.IO.Directory).  In a worker role you can even launch applications from the VHD by spawning a new process. 

Finally, to unmount the drive, just call the Unmount method to release the VHD image.


There are a lot of details behind the scenes that I’m not going to go into here (e.g. read and read/write access to the VHD)  – if you want to learn more, I would recommend checking out this PDC session by Brad Calder

Appendix.  Running this in a local development environment.

You should note that uploading a VHD only works using a live deployment in the cloud.  In the local development fabric, you’ll find that you cannot access a remote VHD (you’ll get a HRESULT = 80070003 error).  Also, you can’t upload a page blob to local development storage.

However, you can still duplicate the same functionality in the local development environment by using this code:

// Setup the account details
CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
// initialize the local cache - need to trim the end backslash otherwise, HRESULT=D0000033
LocalResource localCache = RoleEnvironment.GetLocalResource("LocalCache");
CloudDrive.InitializeCache(localCache.RootPath.TrimEnd(''), localCache.MaximumSizeInMegabytes);

// Create and mount the drive
CloudDrive c = storageAccount.CreateCloudDrive("vhd/myvhd.vhd");

// try creating the drive if it doesn't exist
        catch (Exception)
         // ignore - VHD folder already exists

String driveLetter = c.Mount(localCache.MaximumSizeInMegabytes, DriveMountOptions.None);

// do regular System.IO.File and System.IO.Directory operations here against driveLetter
Response.Write(System.IO.Directory.GetFiles(driveLetter + "").Count() + " files found on the root of the mounted drive.");

// unmount the drive

There are a couple of differences from the live environment.

Firstly, instead of using the public account details, we can just make a call to CloudStorageAccount.DevelopmentStorageAccount

Secondly, just before we mount the drive we actually try to create it using the c.Create(16) command.  If it already exists, then it throws an exception that we just ignore.

It’s important to know that this doesn’t actually create a VHD file. Instead, it creates a new directory in this folder:


You can now access this folder through Windows Explorer, go into the .vhd folder and add/remove files as you wish.  Once you are ready to move to a production environment you simply copy the files from this directory in to a new VHD (as created in Step 1), upload, and switch to the production code.