How to apply caching in existing windows azure project?

Proposed Answer How to apply caching in existing windows azure project?

  • Thursday, July 05, 2012 4:12 AM
     
     
    I create a new web role windows azure project and add my existing project as an asp.net windows azure project.  In this project i do caching separately. There is no performance diifference after launching in cloud. I apply caching in my asp.net project. But how to apply windows azure caching in my existing project and how to check windows azure caching is enable in my existing project?

    P.Mythili

All Replies

  • Thursday, July 05, 2012 4:37 AM
     
     Proposed Answer Has Code

    Are you trying to do page caching, or have you written code that uses a cache object explicitly?  If it's page caching you're after, take a look at http://www.windowsazure.com/en-us/develop/net/how-to-guides/cache/#store-page .

    If you're trying to accomplish something with a cache referred to in code, then look at the rest of the page (http://www.windowsazure.com/en-us/develop/net/how-to-guides/cache/) , and use the DataCacheFactory and DataCache objects.  (Note that all of this advice assumes you're using the latest version of the SDK, 1.7).

    My recommendation to see what the performance changes are is to simply add some timer code to your page, and dump out the results before and after using the caching.  For example, in a project of mine, I had two versions of the code that I ran and checked:

    		protected void Page_Load(object sender, EventArgs e)
    		{
    			// Version 1 : uncached
    			DateTime startTime = DateTime.Now;
    			
    			List<Twitter.UserStatus> statuses = Twitter.Utility.GetUserTimeLine("twitteruser");
    			
    			DateTime endTime = DateTime.Now;
    			TimeSpan elapsedTime = endTime - startTime;
    
    			GridView1.DataSource = statuses;
    			GridView1.DataBind();
    		}

    and then:

    		protected void Page_Load(object sender, EventArgs e)
    		{
    			// Version 2 : with caching
    			DateTime startTime = DateTime.Now;
    			
    			List<Twitter.UserStatus> statuses;
    			Microsoft.ApplicationServer.Caching.DataCache cache =
    				new Microsoft.ApplicationServer.Caching.DataCache("default");
    			statuses = (List<Twitter.UserStatus>)cache.Get("twitteruser");
    			if (statuses == null)
    			{
    				statuses = Twitter.Utility.GetUserTimeLine("twitteruser");
    				cache.Add("twitteruser", statuses);
    			}
    			
    			DateTime endTime = DateTime.Now;
    			TimeSpan elapsedTime = endTime - startTime;
    
    			this.startTime.Text = startTime.ToString();
    			this.endTime.Text = endTime.ToString();
    			this.elapsedTime.Text = elapsedTime.TotalMilliseconds.ToString();
    
    			GridView1.DataSource = statuses;
    			GridView1.DataBind();
    		}

    The first version of my code averaged about 600-1000 ms. to run and render the page. The second version (with caching) averages about 1-2 ms. to run and render the page - a 300-1000x improvement.

    Oh, one other thing to remember (as it's a common mistake with the new caching).  Remember to update the connection string settings in the cache config to use a "real" storage account when you deploy it to the cloud.  By default, it's configured to use DevelopmentStorage (which works in the emulator), but will cause problems after you upload it.

    -adam

    Windows Azure Blog - http://stratospher.es

    Twitter - http://twitter.com/stratospher_es




  • Friday, July 06, 2012 4:50 AM
     
     

    The role is not yet started after am doing the above steps.

    But for my web.config file the follwing code added but cacheName attribute is not allowed. After a very long time the role is started and shows the 500 internal server error. At final cachestatusemulator.exe is stopped working error message shown.

    <sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
          <providers>
            <add name="AppFabricCacheSessionStoreProvider"
                 type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
                 cacheName="default" />
          </providers>
        </sessionState>

    in config sectionsi paste this code.

     <configSections>
        <!-- Append below entry to configSections. Do not overwrite the full section. -->
        <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
      </configSections>

    The following code is added:

    <dataCacheClients>
        <tracing sinkType="DiagnosticSink" traceLevel="Error" />
        <dataCacheClient name="default">
          <autoDiscover isEnabled="true" identifier="CacheWorkerRole1" />
          <!--<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />-->
          <localCache isEnabled="true" objectCount="100000" ttlValue="300" />
          <hosts>
            <host name="MYTCache.cache.windows.net" cachePort="22233" />
          </hosts>
          <securityProperties mode="Message">
            <messageSecurity authorizationInfo="YWNzOmh0dHBzOi8vbXl0Y2FjaGUtY2FjaGUuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldC9XUkFQdjAuOS8mb3duZXImQmtFTjdEL1NrVlFLSWJaaDI4eHlVZU93VVViNjgzbkE4aTVSM1lmcDdVYz0maHR0cDovL01ZVENhY2hlLmNhY2hlLndpbmRvd3MubmV0"></messageSecurity>
          </securityProperties>
        </dataCacheClient>

    Solution to the above error.


    P.Mythili

  • Wednesday, July 18, 2012 9:13 AM
     
     

    Hi,

    Are you using SDK 1.7? Is there a Caching tab on the WebRole properties page? And is it enabled?

    Marcel

  • Monday, July 23, 2012 6:09 AM
     
     

    s am using azure sdk 1.7. I have caching tab and it is working. I choose the co-;ocated topology. But if am applying caching by enabling the check box then the WebRole is working in local and while am publishing in cloud not yet starting and busy like more than 5 hrs and re cycling. If am not enable caching the Role is working perfectly..The example mentioned dll's are added in my references. Now am applying caching(Preview).

    • Microsoft.ApplicationServer.Caching.Client.dll
    • Microsoft.ApplicationServer.Caching.Core.dll
    • Microsoft.WindowsFabric.Common.dll
    • Microsoft.WindowsFabric.Data.Common.dll

    Solution to this error message..

    Instance 1 of role WebRole1 is in an unknown state
    3:01:47 PM - Instance 0 of role WebRole1 is starting the virtual machine
    3:01:47 PM - Instance 1 of role WebRole1 is starting the virtual machine
    3:03:57 PM - Instance 0 of role WebRole1 is busy
    3:03:57 PM - Instance 1 of role WebRole1 is busy

     Instance 1 of role WebRole1 is cycling atlast..


    P.Mythili


  • Monday, July 23, 2012 6:49 AM
     
     

    Mythil, 

    Can you upload your code somewhere ?

    Thanks,

    V

  • Monday, July 23, 2012 7:14 AM
     
     

    in Cloud configuration file looks like,

       <Setting name="Microsoft.WindowsAzure.Plugins.Caching.NamedCaches" value="" />
          <Setting name="Microsoft.WindowsAzure.Plugins.Caching.Loglevel" value="" />
          <Setting name="Microsoft.WindowsAzure.Plugins.Caching.CacheSizePercentage" value="30" />
          <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString" value="UseDevelopmentStorage=true" />

    In service definition file looks like,

     <Import moduleName="Caching" />

      <LocalResources>
          <LocalStorage name="Microsoft.WindowsAzure.Plugins.Caching.FileStore" sizeInMB="1000" cleanOnRoleRecycle="false" />
        </LocalResources>

    In a default.asox page i have one textbox and button.In button click i put this code to check while it is working correct or not.

    namespace for this page as

    using System.Web.Caching;
    using System.Diagnostics;
    using System.Threading;
    using Microsoft.ApplicationServer.Caching;

     protected void btnsubmit_Click(object sender, EventArgs e)
            {
                var name = txtName.Text;
                if (string.IsNullOrWhiteSpace(name))
                {
                    lblResult.Text = "Error. Please specify name.";
                    return;
                }
                bool cached;
                var sw = new Stopwatch();
                sw.Start();

                // create the cache factory and cache
                var factory = new DataCacheFactory();
                var cache = factory.GetDefaultCache();

                // check if the name specified is in cache

                // var email = cache.Get(name) as string;
                var email = "mm@gmail.com";
                if (email != null)
                {
                    cached = true;
                    sw.Stop();
                }

                else
                {

                    cached = false;

                    // simulate the letancy

                    Thread.Sleep(2000);

                    email = string.Format("{0}@igt.com", name);

                    // add to cache

                    cache.Add(name, email);

                }



                sw.Stop();

                lblResult.Text = string.Format(

                 "Cached = {0}. Duration: {1}s. {2} => {3}",

                 cached, sw.Elapsed.TotalSeconds.ToString("0.00"), name, email);
            }
        }

    In web.config file it looks like,

    Session state and outputcache as follows,

     <sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
          <providers>
            <add name="AppFabricCacheSessionStoreProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" useBlobMode="false" />
          </providers>
        </sessionState>
        <caching>
          <outputCache defaultProvider="DistributedCache">
            <providers>
              <add name="DistributedCache" type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" />
            </providers>
          </outputCache>
        </caching>

    In Configsections of the web.config file,<configSections>
        <!-- Append below entry to configSections. Do not overwrite the full section. -->
        <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
      </configSections>

    and in configuration section as looks,

    <dataCacheClients>
        <tracing sinkType="DiagnosticSink" traceLevel="Error" />
        <dataCacheClient name="default">
          <autoDiscover isEnabled="true" identifier="WebRole1" />
          <!--<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />-->
        </dataCacheClient>
      </dataCacheClients>

    I apply Caching(Preview) and sdk version 1.7.Without caching applying its working fine. After applying Caching it shown when deploying

    Instance 0 of role WebRole1 is busy
    11:56:58 AM - Instance 1 of role WebRole1 is busy
    12:44:35 PM - Instance 0 of role WebRole1 is cycling
    12:44:35 PM - Instance 1 of role WebRole1 is cycling

    more than 4 hours.how should i resolve this. Anyone help me as soon as possible. Am stuck more than one week.


    P.Mythili

  • Monday, July 30, 2012 3:13 PM
     
     

    I supect there is something not related to the caching is the problem.

    In the web.config there is also a Connection string. Is this one correct?

    And are you sure there are no errors?

    Marcel