How to Build Your First Azure-Powered ASP.NET MVC App

The Visual Studio project templates included with the Azure Tools provide a quick way to get started with a cloud-hosted web application.  Unfortunately, it only supports classic ASP.NET web projects by default.  This tutorial will get you going on deploying an ASP.NET MVC web application to Azure.

PreRequisites

To get started, you’ll need to have the following tools installed on your machine:

Installing the Azure SDK will install the two important local development components – Development Fabric, which simulates the cloud on your local machine, and Development Storage, which simulates the Azure Storage components (table, blob, and queue) using SQL Server.

In addition to the listed components, you will reuse code from the Azure Samples.  These are included with the Azure SDK in a samples.zip file, which can be found in the installation directory (C:\Program Files\Windows Azure SDK\v1.0 by default).  Unzip this file to a folder on your local machine, such as C:\Azure Samples.

Create Your Cloud Project

To get started, start up a session of Visual Studio 2008.  If you are using Windows 7 or Vista, make sure you start it with administrator privileges or you will run into permission problems later:

Azure Development Fabric Permissions Error

Click File -> New -> Project and select “Cloud Service” from the list of Project Types on the left.  Then choose “Cloud Service” from the list of templates, give your project a name, and click OK.

Cloud Service Project Role Selection

You’ll need to choose one or more Roles to add to your cloud service.  Roles are the basic managed-code, scalable components in an Azure-based application.  Web Roles are web applications accessed by HTTP or HTTPS endpoints, while Worker Roles are background-processing applications with no external endpoints (although they communicate with storage and other internet-enabled services).  The third option, FastCGI, allows developers to easily incorporate third-party programming languages into the Azure-enabled application.  Since we will be writing an ASP.NET MVC application accessed over HTTP, add a single ASP.NET Web Role and click OK.

Let’s take a look at the Solution Explorer.  You’ll see two projects have been created from the template: the Cloud Service project, consisting of two Azure configuration files and the WebRole association; and the classic ASP.NET project named WebRole1.

As basic as it is, this simple solution is a fully-functional cloud-based web application.  Hit F5 to launch the debugger instance.  If all goes well, the Development Fabric will start in the background (you should see an icon for it appear in the system tray) and your default web browser will launch to your local cloud-enabled application (usually something like http://127.0.0.1:85).

If you get some funky errors messages, make sure your CloudService project is selected as the StartUp Project.  It should be the bold name in your list of projects in the Solution Explorer.  If it’s not, right-click on the project name, choose “Set as StartUp Project” from the menu, and try again.

Change Your Web Project to an ASP.NET MVC Application

Now we need to change our Web Role to an MVC application.  First, remove the ASP.NET application from the solution by right-clicking the project name in the Solution Explorer window and selecting “Remove.”  Next, add a new ASP.NET MVC project by right-clicking on the solution name and selecting Add -> New Project. From the list of project types on the left, choose “Web” under the “Visual C#” category.  Select “ASP.NET MVC Web Application” from the list of installed templates.  Give your web project a name, and click okay.  A unit test project will be created by default, although we won’t utilize it in this tutorial.

Attempt to build the solution, or hit F5 to start the debugger.  You’ll get an error: “A Web or Worker project is required but could not be found.”  Tassociate mvc app with azure web rolehe CloudService project needs to know what web application is associated with the Web Role; without it, it doesn’t know how to configure the HTTP endpoint.  In the solution explorer, the Roles folder in the CloudService project will display “No project associated (WebRole1)”.  To create this association, right click on that role, select Associate with -> Web Role Project in solution.  In the dialog that appears, choose your newly added ASP.NET MVC project and click OK.  The solution explorer will now show the MVC application under the Roles subfolder.

Hit F5 to start the debugger.  Looking good!  Your MVC application is now running on your local Azure fabric.  Although the application is up and running, try clicking on the “Log On” link in the top right corner of the page.  Try to register for an account.  Uh oh.  You’ll get an exception indicating the membership provider couldn’t connect to the database.

While we could modify the connection string in our web.config to configure the ASP.NET SQL Membership Provider, this would completely defeat the purpose of deploying our app to the cloud.  Instead, we’ll utilize Azure Storage to enable the membership functionality.

Configure the Membership Provider

The Azure SDK ships with great samples that demonstrate the various features of Azure Storage.  These samples include two incredibly useful projects: StorageClient, a wrapper around the Azure Storage functions, and AspProviders, which implement the Membership, Profile, Role, and Session State Providers using Azure Table storage.  We’ll utilize these two projects to enable the remaining features of our basic MVC application.

Navigate to the folder where you unzipped the Azure samples and go to the StorageClient\Lib directory.  Select everything in this folder and copy it to the clipboard.  Create a new folder in your solution folder and name it StorageClient.  Paste all of the files in your clipboard to this new folder.  Repeat the process for the AspProviders folder – copy all of the AspProviders\Lib files to a new AspProviders folder in your solution directory.

Add these two new projects to your solution.  Right-click on the solution and select Add -> Existing project.  Choose the StorageClient.proj file from your solution directory’s newly-created StorageClient folder.  Repeat the process for the AspProviders project.

At this point, you should have five projects in your solution:

  • AspProviders
  • AzureMVCSample (StartUp project)
  • <Your MVC web project>
  • <Your MVC web project>.Tests (if you selected to create unit tests)
  • StorageClient

Looking good?  Great.  We have a few last steps before we can utilize the Azure-enabled membership provider.  First, we need to tell our MVC application where the provider exists.  To do this, add a reference to the AspProviders project in your MVC application.

We also need to configure Azure storage  to work on your local machine.  First, you need to configure the required keys in your cloud service configuration files: ServiceDefinition.csdef and ServiceConfiguration.cscfg.  The StorageClient project has three configuration settings that it uses to connect and authenticate to Azure Storage.  In ServiceDefinition.csdef, add the following three setting keys to the ConfigurationSettings node:

<ConfigurationSettings>
<Setting name="AccountName" />
<Setting name="AccountSharedKey" />
<Setting name="TableStorageEndpoint" />
</ConfigurationSettings>

Then, in ServiceConfiguration.cscfg, we need to set the values of those settings.  For simplicity’s sake, we’ll use the same values used by the Azure sample projects.  If you were to deploy this solution to the cloud, you would need to change these values to match your production (or staging) configuration.

<ConfigurationSettings >
<Setting name="AccountName" value="devstoreaccount1"/>
<Setting name="AccountSharedKey" value="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="/>
<Setting name="TableStorageEndpoint" value="http://127.0.0.1:10002"/>
</ConfigurationSettings>

Now, we need to initialize our local SQL Server with the required tables so wcreate test azure storage tablese can simulate Azure Storage.  There are two ways to do this.  If you are running SQL Server Express, you can right-click on your cloud service project and select “Create Test Storage Tables.” If you are using SQL Server 2008, you will need to use the DevTableGen command-line tool.  From  an Azure Command Prompt (found in the Start Menu), run the following command:

devtablegen <path-to-your-cloud-service-assembly> /server localhost

At this point, your Azure configuration is ready to go.  All we have left is to configure your application to use the Azure Storage Membership provider.  In your MVC application’s web.config file, scroll down to the membership section.  The default configuration will be using the SqlMembershipProvider.  Delete that line, add your TableStorageMembershipProvider, and set the defaultProvider property as shown below:

<membership defaultProvider="TableStorageMembershipProvider">
<providers>
<clear/>
<add name="TableStorageMembershipProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageMembershipProvider" description="Membership provider using Azure table storage" applicationName="AzureMVCSample" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" requiresUniqueEmail="true" passwordFormat="Hashed"/>
</providers>
</membership>

Save the file, hit F5, and try registering for an account and logging on.  All of the basic site features should work – enjoy your Azure-hosted MVC application!

Next steps

While it may feel like you’ve put in a lot of work just to get a basic “Hello World” site up and running, you are now in a very good position to easily extend your application and quickly add features that utilize Azure functionality.  The StorageClient project allows you to easily access Table, Blob, and Queue storage, and all of your initial configuration to get that up and running has already been completed. Similarly, you can now implement the Role and Profile providers just by modifying the web.config file in the same way as the membership provider – no extra configuration required.

The sky (the cloud?) is the limit from here – explore the features of Azure and how you can integrate them into your MVC application!

Windows Azure Tools for Microsoft Visual Studio July 2009 CTPW

13 Comments

  1. I want to say – thank you for this!

  2. I agree – this was very helpful. Just a couple of tweaks since I didn’t follow this right from the beginning so not everything in my solution was exactly as here. I had already created an Azure MVC app an modified it a bit. The ApplicationName in the membership provider has to match your application name – here it is shown as AzureMVCSample. If you go to Development Storage in the tray and look at what database is running, you’ll know what to set it to (in my case, I had renamed my application). But thanks, this is a very helpful start.

  3. Great work! I’ll let you know how I get on with it… Btw, any way to run local C#-written processes where the browser is running?

  4. Hi Rob – I think what you are referring to by “local C#-written processes” is a different type of Role. In this tutorial, we added a “Web Role” to our project when we created it. If you want background processing, such as an engine, to run in your cloud deployment (or locally with the Development Fabric), you can use a “Worker Role.” Sounds like a good tutorial to post here – I’ll write one a sample app and post it this week!

  5. FYI: to create the storage tables, I actually had to run the following command (localhost\sqlserver is my SQL 2008 instance):

    devtablegen “\AspProviders\bin\Debug\AspProviders.dll” /server:localhost\sqlserver

  6. forgot to say: thanks for the excellent explanation :-)

  7. Thanks, this is very useful post. It helped me to resolve error i was getttings.I was keeping ApplicationName is aspprover different.

  8. Sehr interessanter Artikel den du da geschrieben hast. Endlich hab ich das gefunden was ich gesucht habe. Ich wuerde auch gerne den RSS Feed von deinem Blog abonieren aber leider finde ich diesen nicht. Wo muss ich denn danach suchen?

  9. very amazing thank you all

  10. Hah Kümmert euch nicht drum, das ist nur ‘n Fehlalarm

  11. Thanks. One note, the samples are now located in a separate download, and are not included in the SDK as of version 1.2: They can be downloaded from http://code.msdn.microsoft.com/windowsazuresamples from the file “Additional C# Samples”

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>