Archive for the ‘ASP.NET’ Category.

Configuring an ASP.NET Web Application to Use a Windows Server AppFabric Cache for Session State

Last week I spent some time setting up Windows Server AppFabric Cache in anticipation of additional tasks this week.  The first task is configuring an ASP.NET web application to use Windows Server AppFabric Caching for the Session State Provider.  This allows the web application to spread session objects across the entire cache cluster, resulting in greater scalability.

Below is a walkthrough on how to configure this scenario.  In addition to this post, I recommend you take a look at this article on MSDN.

  1. Thoroughly review Getting Started with Windows Server AppFabric Cache to get everything setup.
  2. Open up the Cache PowerShell console (Start –> Windows Server AppFabric –> Caching Administration Windows PowerShell).  This will automatically import the DistributedCacheAdministration module and use the CacheCluster.
  3. Start the Cache Cluster (if not already started).  Run the following command in the PowerShell console:
    Start-CacheCluster
  4. Create a new cache that you will leverage for your session state provider.  Run the following command in the PowerShell console:
    New-Cache MySessionStateCache
  5. Create a new ASP.NET Web Application in Visual Studio 2010 targeting .NET 4.0.  This will create a sample project, complete with master page which we’ll leverage later on.
  6. Add references to the Microsoft.ApplicationServer.Caching.Client and Microsoft.ApplicationServer.Caching.Core.  To do this, use the following steps (thanks to Ron Jacobs for the insight):
    1. Right-click on your project and select Add Reference.
    2. Select the Browse tab.
    3. Enter the following folder name, and press enter:
      %windir%\Sysnative\AppFabric
    4. Locate and select both Microsoft.ApplicationServer.Caching.Client and Microsoft.ApplicationServer.Caching.Core assemblies.
  7. Add the configSections element to the web.config file as the very first element element in the configuration element:
    <!--configSections must be the FIRST element -->
    
    <configSections>
    
      <!-- required to read the <dataCacheClient> element -->
    
      <section name="dataCacheClient"
    
            type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
    
              Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0,
    
              Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    
            allowLocation="true"
    
            allowDefinition="Everywhere"/>
    
    </configSections>
  8. Add the dataCacheClient element to the web.config file, after the configSections element.  Be sure to replace YOURHOSTNAME with the name of your cache host.  In the PowerShell console you can get the HostName (and CachePort) by starting or restarting your cache).
    <dataCacheClient>
    
      <!-- cache host(s) -->
    
      <hosts>
    
        <host
    
            name="YOURHOSTNAME"
    
            cachePort="22233"/>
    
      </hosts>
    
    </dataCacheClient>
  9. Add the sessionState element to the web.config file in the system.web element.  Be sure that the cacheName is the same as the cache you created in step 4.
    <sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
    
      <providers>
    
        <!-- specify the named cache for session data -->
    
        <add
    
          name="AppFabricCacheSessionStoreProvider"
    
          type="Microsoft.ApplicationServer.Caching.DataCacheSessionStoreProvider"
    
          cacheName="MySessionStateCache"
    
          sharedId="SharedApp"/>
    
      </providers>
    
    </sessionState>
  10. Now, we need a quick and easy way to test this.  There are many ways to do this, below is mine.  I loaded data into session, then created a button that writes the session data into a JavaScript alert.  Quick and easy:
    protected void Page_Load(object sender, EventArgs e)
    
    {
    
        // Store information into session
    
        Session["PageLoadDateTime"] = DateTime.Now.ToString();
    
    
    
        // Reference the ContentPlaceHoler on the master page
    
        ContentPlaceHolder mpContentPlaceHolder =
    
            (ContentPlaceHolder)Master.FindControl("MainContent");
    
        if (mpContentPlaceHolder != null)
    
        {
    
            // Register the button
    
            mpContentPlaceHolder.Controls.Add(
    
                GetButton("btnDisplayPageLoadDateTime", "Click Me"));
    
        }
    
    }
    
    
    
    // Define the button
    
    private Button GetButton(string id, string name)
    
    {
    
        Button b = new Button();
    
        b.Text = name;
    
        b.ID = id;
    
        b.OnClientClick = "alert('PageLoadDateTime defined at " +
    
            Session["PageLoadDateTime"] + "')";
    
        return b;
    
    }
  11. Now, hit control-F5 to start your project.  After it loads, click the button labeled “Click Me” – you should see the following alert:
    ASP.NET using Cache for Session State

That’s it!  You have now configured your ASP.NET web application to leverage Windows Server AppFabric Cache to store all Session State. 

While I was putting this together, I encountered two errors.  I figured I’d share them here, along with resolution, in case any of you encounter the same problems along the way.

    Configuration Error
    
      
    Description: An error occurred during the processing of a configuration
    
    file required to service this request. Please review the specific error
    
    details below and modify your configuration file appropriately.
    
    Parser Error Message: ErrorCode<ERRCA0009>:SubStatus<ES0001>:Cache
    
    referred to does not exist. Contact administrator or use the Cache
    
    administration tool to create a Cache.


    If you received the above error message, it’s likely that the cacheName specified in the sessionState element is wrong.  Update the cacheName to reflect the cache you created in step #4.

    Configuration Error
    
      
    Description: An error occurred during the processing of a configuration
    
    file required to service this request. Please review the specific error
    
    details below and modify your configuration file appropriately.
    
    Parser Error Message: 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. Ensure that security permission has been granted for this
    
    client account on the cluster and that the AppFabric Caching Service
    
    is allowed through the firewall on all cache hosts. Retry later.)


    If you received the above error message, it’s likely that the host name specified in the dataCacheClient is wrong.  Update the dataCacheClient host name to reflect the name of your host.  Note: it’s likely that it’s just your machine name.

Hope this help!

Getting Started with Windows Server AppFabric Cache

I struggled today to find a good “Getting started with Windows Server AppFabric Cache” tutorial – either my search fu failed me or it simply doesn’t exist.  Nevertheless, I was able to piece together the information I needed to get started.

I recommend you break this up into three steps:

  • Installing Windows Server AppFabric
  • Configuring Windows Server AppFabric Cache
  • Testing Windows Server AppFabric Cache with Sample Apps

I think this article will serve as a good tutorial on getting started, and we can refer back to it as the basis for more advanced scenarios.

Installing Windows Serve AppFabric

  1. Get the Web Platform Installer.
  2. Once it is installed and opened, select Options.
    Options
  3. Under Display additional scenarios select Enterprise.
    Enterprise
  4. Now you’ll see an Enterprise tab.  Select it, and choose Windows Server AppFabric.  Click Install.  This will start a multi-step process for installing Windows Server AppFabric (which in my case required two reboots to complete).
    Windows Server AppFabric

Configuring Windows Server AppFabric Cache

  1. Open the Windows Server AppFabric Configuration Wizard (Start –> Windows Server AppFabric –> Configure AppFabric).
  2. Click Next until you reach the Caching Service step.  Check Set Caching Service configuration, select SQL Server AppFabric Caching Service Configuration Store Provider for the configuration provider, and click Configure.
    Set Caching Service
  3. Check Create AppFabric Caching Service configuration database, confirm the Server name, and specify a Database name. Click OK.
    Specify Database
  4. When asked if you want to continue, click Yes.
    Configuration Database confirmation
  5. You will receive confirmation that your database was created and registered.
    Success
  6. On the Cache Node step, confirm the selected port nodes.
    Cache Node ports
  7. You will be asked to continue and apply the configuration settings; select Yes.
    Continue
  8. On the last step you’ll click Finish.
  9. Open up an elevated Windows PowerShell window.
  10. Add the Distributed Cache administration module
    Import-Module DistributedCacheAdministration
  11. Set the context of your Windows PowerShell session to the desired cache cluster with Use-CacheCluster.  You can run this without parameters to use the connection parameters provided during configuration.
    Use-CacheCluster
  12. Grant your user account access to the cache cluster as a client.  Specify your user and domain name.
    Grant-CacheAllowedClientAccount domain\username
  13. Verify your user account has been granted access.
    Get-CacheAllowedClientAccounts
  14. Start the cluster.
    Start-CacheCluster

Testing Windows Server AppFabric Cache with Sample Apps

  1. Grab a copy of the Microsoft AppFabric Samples, which are a series of very short examples.
  2. Extract the samples locally.
  3. Open up CacheSampleWebApp.sln (..\Samples\Cache\CacheSampleWebApp).
  4. Right-click the CreateOrder.aspx file and select Set As Start Page.
  5. Hit F5 to start the solution.
  6. Confirm that the cache is functioning by creating a sample order, getting the sample order, and updating the sample order.

Once you accomplish these three steps, you’ll have the basis for building more complex caching solutions.

I hope this helps!