October 23, 2016
Hot Topics:

Creating an Azure App: Step 6 - Add Retry Logic, Page 3

  • January 18, 2012
  • By Michael Collier
  • Send Email »
  • More Articles »

Step 6 – Add Retry Logic

At this point a new Course and Round should be able to be added to the SQL Azure database via the new ASP.NET MVC3 application. However, there is at least one more step that needs to be done. Working with SQL Azure is a little different than working with a SQL Server instance on-premises. It is often assumed when working with local systems, that there will be a highly reliable connection between the application server and the SQL Server database. It is also assumed the SQL Server database will essentially allow applications to beat up on it as much as wanted without complaining. With SQL Azure, this is not the case.

While SQL Azure is a reliable source for data, it is possible to experience transient errors when working with SQL Azure. By definition, a transient error is one that will go away quickly, often on the next attempt. These errors could be related to a bad internet connection between the application and the Windows Azure data center, or they could be related to some issues internal to SQL Azure, such as throttling. In any case, when working with SQL Azure (or any service consumed over the internet for that matter), it is always wise to build retry logic into the application. Doing so will add a little time to the overall development effort, but it is time well spent.

The Microsoft Patterns & Practices team has released a framework that greatly simplifies the process of adding retry logic to any application. The Transient Fault Handling Application Block is a library that can be added to any application that needs retry capabilities. The application block implements strategies to help with SQL Azure, Windows Azure storage (tables, blobs, queues), the Windows Azure Service Bus, and Windows Azure Caching.

The Transient Fault Handling Application Block can be added to a project via NuGet. If the NuGet Package Manager extension for Visual Studio is not yet installed, please follow the guidance at http://docs.nuget.org/docs/start-here/installing-nuget.

In order to add the Transient Fault Handling Application Block from the NuGet Package Manager Console, simply enter “Install-Package EnterpriseLibrary.WindowsAzure.TransientFaultHandling”at the Package Manager prompt. This will install the Transient Fault Handling Application Block, as well as any necessary dependencies.

NuGet - Adding the Transient Fault Handling App Block (snipped and edited)

The Transient Fault Handling Application Block is intelligent about how frequently an operation should be retried, and includes a set of error detection strategies to determine what error situation should trigger a retry. The Transient Fault Handling Application Block includes a few built-in error detection strategies, which encapsulates the conditions for a transient error. The SqlAzureTransientErrorDetectionStrategy does that for SQL Azure.

It should be noted that not every action should be retried. Carefully consider the implications of retrying an action. Retries should not be done indefinitely. At some point, for the sake of application performance and stability, the action should fail and a human may need to get involved.

For the purposes of this walkthrough, create a base controller class that can be used to encapsulate the retry policy to use in the application. The retry policy used here simply states that in the event a transient SQL Azure error is detected, the action should be retried 5 times, waiting 1 second before the first retry, and increasing 2 seconds between retries. An event handler can be used to determine when a retry occurs and to make a note of that, for example.

	public abstract class BaseController : Controller
		protected RetryStrategy retryStrategy;
		protected RetryPolicy<SqlAzureTransientErrorDetectionStrategy> retryPolicy;

		protected BaseController()
			retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
			retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(retryStrategy);

			retryPolicy.Retrying += (sender, args) => LogRetry(args);

		protected virtual void LogRetry(RetryingEventArgs args)
			var msg = string.Format("Retry Count: {0}, Delay: {1}; Exception: {2}.",
                args.CurrentRetryCount, args.Delay, args.LastException);

With the base controller in place, modify our other controllers to use this new BaseController to take advantage of the retry logic. Any actions that execute against the SQL Azure database will need to have retry logic applied. This can be done by using the RetryPolicy.ExecuteAction() method and an anonymous function to carry out the database work.

	public class CourseController : BaseController
		private GolfContext db = new GolfContext();

		public ViewResult Index()
			var courses = retryPolicy.ExecuteAction(() =>
				var items = db.Courses.ToList();
				return items;
			return View(courses);
		// . . . .

The retry policy demonstrated in the image above will need to be done in both the CourseController and the RoundController – essentially any place that works with the GolfContext class (and thus SQL Azure). Please download the application source code for a full example.

Step 7 – Deploy the Application

The My Golf Story application is nearly complete. The final step is to deploy it to Windows Azure. In order to deploy the application to Windows Azure, the application needs to be associated with a Windows Azure deployment project. Fortunately, Visual Studio makes this very easy.

  1. Right click on the MyGolfStory ASP.NET MVC3 web project in Solution Explorer and then click on “Add Windows Azure Deployment Project”.

    Add Windows Azure Deployment Project

    Doing so will add a new MyGolfStory.Azure project to the solution and associate the MyGolfStory application with a Windows Azure web role.

    MyGolfStory.Azure Added to Solution

  2. With the deployment project in place, it is now time to publish the application to Windows Azure. To start that process, right click on the MyGolfStory.Azure project in Solution Explorer and select “Publish”.

    Publish Azure Project

    Note: The same can be accomplished by right clicking on the MyGolfStory project and selecting “Publish to Windows Azure”.

  3. This will bring up a wizard to guide your through the steps of publishing the application to Windows Azure. The first time a Windows Azure application is published from a new machine, a publish settings file will need to be downloaded. Subsequent publishes (of any Windows Azure solution) from that same machine should not need to that file again.

    Publish - Download Credentials

  4. Clicking on the “Sign in to download credentials” link should open a web page which will prompt you to sign in using the Windows Live ID associated with the Windows Azure subscription to be used.
  5. Download the publish profile (.publishsettings) file to your computer. This file will be needed in the next steps.

    Download PublishSettings File

  6. The publishing wizard should still be open. Click on the “Import” button and then browse and select the publish profile (the .publishsettings) file previously downloaded.

    Publish - Import Credentials

  7. Select the Windows Azure subscription to publish the application to and then click “Next”.
  8. It is here that a new hosted service can be created if one doesn’t already exist. The hosted service is a container for an application in Windows Azure. Enter a name that identifies the application, along with a Window Azure data center to publish to.

    New Hosted Service Dialog

  9. For the purposes of this walkthrough, leave the other options to their defaults, but feel free to explore them later. Clicking on the “Advanced Settings” tab will display options for creating a new storage account to use with the hosted service. The Windows Azure deployment package will be temporarily uploaded to Windows Azure blob storage (in the "vsdeploy" container") in that storage account. Click “Next” to proceed.

    Publish - New Hosted Service Complete

  10. The final page of the wizard will display a summary of the deployment that is about to take place. Clicking the Save icon to the right of the Target profile dropdown box will allow the current settings to be saved for future use. Clicking on “Publish” will start the deployment process.

    Publish - New Hosted Service Final Step

    The first time a new hosted service is deployed to Windows Azure, the process can take 10-15 minutes. Windows Azure is performing several steps to prepare the service, including provisioning a new virtual machine, configuring the operating system, creating the web role, deploying application code, and configuring the load balancer and networking.

    Subsequent deployments to Windows Azure will take much less time. By default Visual Studio will perform an update to your existing application, instead of a completely new deployment.

  11. To monitor the Windows Azure deployment progress, do so from the Windows Azure Activity Log window in Visual Studio.

    Start of deployment - MyGolfStory

  12. Once the deployment is complete, clicking on the Website URL in the deployment monitor window will launch the site.

    Completed Deployment - MyGolfStory

What Was Just Accomplished

This walkthrough demonstrated how simple it is to create an ASP.NET MVC3 application that uses SQL Azure for the database, and Entity Framework as the ORM. While SQL Azure works in many ways like SQL Server on-premises, there are some special considerations that need to be accounted for – primarily the need for retries. Finally, the necessary steps were taken to deploy the new application to Windows Azure.

The My Golf Story application is a good starting point to explore the features available with Windows Azure. For example, pictures of the course, scorecard or snapshots from the round could easily be stored in Windows Azure blob storage and then displayed on the site. Another area to explore would be securing access with Windows Azure Access Control Services or even creating a Windows Phone application to supplement the web front-end.

Next Steps

Proceed to www.windowsazure.com to learn more about Windows Azure and to get the development tools. The Windows Azure Developer Center contains SDKs for many popular languages or frameworks such as .NET, Java, PHP, and node.js.

With the developer tools in place, it’s time to set up a new Windows Azure account. A free 90-day trial account can be obtained at https://www.windowsazure.com/en-us/pricing/free-trial/.

The full solution source code for this project can be found at http://bit.ly/MyGolfStoryAzure.

Microsoft Platform Ready

Thank you to the following technical experts for reviewing this article: Ted Neward, Chad Thomas, Samidip Basu, Jared Faris, Sean Kelly, Mike Wood and Brett Carlson.


This article was sponsored by Microsoft Corporation, but written independently by the author.

Tags: cloud computing, Azure, cloud development, Azure Cloud, Microsoft Platform Ready

Page 3 of 3

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel