[Sample of Mar 11th] Retry Azure Cache Operations

 

Homepage image
Sample of the Day RSS Feed

Sample Download: https://code.msdn.microsoft.com/CSAzureRetryCache-c26c894b

imageToday’s code sample is about a typical programming scenario in Windows Azure.  The sample implements retry logic to protect the application from crashing in the event of transient errors. When using cloud based services, it is very common to receive exceptions similar to below while performing cache operations such as get, put. These are called transient errors. Developer is required to implement retry logic to successfully complete their cache operations.  The code sample could reduce your effort in implementing this scenario.

The sample was developed by Microsoft Escalation Engineer - Narahari Dogiparthi.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage https://1code.codeplex.com/.

 

Introduction

When using cloud based services, it is very common to receive exceptions similar to below while performing cache operations such as get, put. These are called transient errors.

Developer is required to implement retry logic to successfully complete their cache operations.

ErrorCode<ERRCA0017>:SubStatus<ES0006>:There is a temporary failure. Please retry later. (One or more specified cache servers are unavailable, which could be caused by busy network or servers. For on-premises cache clusters, also verify the following conditions. Ensure that security permission has been granted for this client account, and check that the AppFabric Caching Service is allowed through the firewall on all cache hosts. Also the MaxBufferSize on the server must be greater than or equal to the serialized object size sent from the client.)

This sample implements retry logic to protect the application from crashing in the event of transient errors. This sample uses Transient Fault Handling Application Block to implement retry mechanism

 

Building the Sample

1) Ensure Windows Azure SDK 1.6 is installed on the machine. Download Link

2) Modify the highlighted cachenamespace, autherizataionInfo attributes under DataCacheClient section of web.config and provide values of your own cache namespace and Authentication Token. Steps to obtain the value of authentication token, cache namespace value can be found here

 <dataCacheClients> 
  <dataCacheClient name="default"> 
    <hosts> 
      <host name="skyappcache.cache.windows.net" cachePort="22233" /> 
    </hosts> 
    <securityProperties mode="Message"> 
      <messageSecurity authorizationInfo="YWNzOmh0dHBzOi8vbXZwY2FjaGUtY2FjaGUuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldC9XUkFQdjAuOS8mb3duZXImOWRINnZQeWhhaFMrYXp1VnF0Y1RDY1NGNzgxdGpheEpNdzg0d1ZXN2FhWT0maHR0cDovL212cGNhY2hlLmNhY2hlLndpbmRvd3MubmV0"> 
      </messageSecurity> 
    </securityProperties> 
</dataCacheClient> 

 

Running the Sample

Open the Project in VS 2010 and run it in debug or release mode

Click on “Add To Cache” button to add a string object to Azure cache. Up on successful operation, “String object added to cache!” message will be printed on the webpage

Click on “Read From Cache” button to read the string object from Azure Cache. Up on successful operation, value of the string object stored in Azure cache will be printed on the webpage. By default it will be “My Cache” (if no changes are made to code)

 

Using the Code

1. Define required objects globally, so that they are available for all code paths with in the module.

 // Define DataCache object 
DataCache cache; 
  
// Global variable for retry strategy 
FixedInterval retryStrategy; 
  
// Global variable for retry policy 
RetryPolicy retryPolicy;

2. This method configures strategies, policies, actions required for performing retries.

 /// <summary> 
/// This method configures strategies, policies, actions required for performing retries. 
/// </summary> 
protected void SetupRetryPolicy() 
{ 
    // Define your retry strategy: in this sample, I'm retrying operation 3 times with 1 second interval 
    retryStrategy = new FixedInterval(3, TimeSpan.FromSeconds(1)); 
  
    // Define your retry policy here. This sample uses CacheTransientErrorDetectionStrategy 
    retryPolicy = new RetryPolicy<CacheTransientErrorDetectionStrategy>(retryStrategy); 
  
    // Get notifications from retries from Transient Fault Handling Application Block code 
    retryPolicy.Retrying += (sender1, args) => 
    { 
        // Log details of the retry. 
        var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}", 
            args.CurrentRetryCount, args.Delay, args.LastException); 
  
        // Logging the notification details to the application trace. 
        Trace.Write(msg); 
    }; 
} 

3. Create the Cache Object using the DataCacheClient configuration specified in web.config and perform initial setup required for Azure cache retries

 protected void Page_Load(object sender, EventArgs e) 
{ 
   // Configure retry policies, strategies, actions 
    SetupRetryPolicy(); 
  
   // Create cache object using the cache settings specified web.config 
   cache = CacheUtil.GetCacheConfig(); 
} 

4. Add string object to Cache on a button click event and perform retries in case of transient failures

 protected void btnAddToCache_Click(object sender, EventArgs e) 
{ 
    try 
    { 
        // In order to use the retry policies, strategies defined in Transient Fault Handling 
        // Application Block , user calls to cache must be wrapped with in ExecuteAction delegate 
        retryPolicy.ExecuteAction( 
            () => 
            { 
                // I'm just storing simple string object here .. Assuming this call fails, 
                // this sample retries the same call 3 times with 1 second interval before it gives up. 
                cache.Put("MyDataSet", "My Cache"); 
                Response.Write("String object added to cache!"); 
            }); 
                                         
    } 
    catch (DataCacheException dc) 
    { 
        // Exception occurred after implementing the Retry logic. 
        // Ideally you should log the exception to your application logs and show user friendly 
        // error message on the webpage. 
        Trace.Write(dc.GetType().ToString() + dc.Message.ToString() + dc.StackTrace.ToString()); 
    } 
} 

5. Read the value of string object stored in Azure Cache on a button click event and perform retries in case of transient failures

 protected void btnReadFromCache_Click(object sender, EventArgs e) 
{ 
    try 
    { 
        // In order to use the retry policies, strategies defined in Transient Fault 
        // Handling Application Block , user calls to cache must be wrapped with in 
        // ExecuteAction delegate. 
        retryPolicy.ExecuteAction( 
            () => 
            { 
                 
                // Getting the object from azure cache and printing it on the page. 
                Response.Write(cache.Get("MyDataSet")); 
            }); 
    } 
    catch (DataCacheException dc) 
    { 
        // Exception occurred after implementing the Retry logic. 
        // Ideally you should log the exception to your application logs and show user 
        // friendly error message on the webpage. 
        Trace.Write(dc.GetType().ToString() + dc.Message.ToString() + dc.StackTrace.ToString()); 
    } 
} 

 

More Information

Refer to below blog entry for more information https://blogs.msdn.com/b/narahari/archive/2011/12/29/implementing-retry-logic-for-azure-caching-applications-made-easy.aspx