Service Bus on the Cloud Cover Show

WadeCloudCoverShow Ryan Dunn and Steve Marx have a great show on Channel9 called the Cloud Cover Show.  I’ve been watching it since the beginning, and have learned a lot about different features of the Windows Azure Platform, the latest news and announcements, as well as tips and tricks.  Naturally, I was honored (and a bit scared) when they asked me to join them on the show to talk about the Windows Azure AppFabric Service Bus.

Let me state this for the record – I was right to be afraid! <grin>

Let’s talk about how I was introduced – Wegner Clawed.  Watch it for yourself.  If you aren’t laughing hysterically then there’s something wrong with you.  And for the record I am not related to Joe Wegner (at least I hope not)!

Wade's Funky Fresh Beat

Next, Wade’s Funky Fresh Beat – a tribute to both Wegner Clawed and the funky beat in my post Using Social Web Providers in Less than 5 Minutes.  I’m moved that Steve took the time to put this together.

Of course, we did manage to spend some time talking about the Service Bus, and even showed a few demos (with a funky beat, I might add).

Get Microsoft Silverlight

All-in-all, I had a ton of fun (despite losing a bit of dignity).  Can’t wait to come on again!

Using the ‘TrustServerCertificate’ Property with SQL Azure and Entity Framework

I’ve spent the last few days refactoring a web application to leverage SQL Server via Entity Framework 4.0 (EF4) in preparation for migrating it to SQL Azure.  It’s a neat application, and a great example of how to fully encapsulate your data tier (the previous version had issues due to tight coupling between the data and web tier).  More on this soon.

So, when I deployed my database to SQL Azure (using the SQL Azure Migration Wizard) I was confounded by the following error:

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 – The certificate’s CN name does not match the passed value.)

I was caught off guard by this error, as I was pretty sure my connection string was valid – after all, I had copied it directly from the SQL Azure portal.  Then I realized that this was the first time I had attempted to use EF4 along with SQL Azure; my first thought was, “oh crap!”

After a little bit of frantic research I found the following question on the SQL Azure forums.  Raymond Li of Microsoft made the suggestion to set the ‘TrustServerCertificate’ property to True.  So, I updated my connection string from …

<add name="BidNowDataContext"
	connectionString="metadata=
		res://*/BidNowDataContext.csdl|res://*/BidNowDataContext.ssdl|
		res://*/BidNowDataContext.msl;
	provider=System.Data.SqlClient;
	provider connection string=&quot;
		Server=tcp:SERVERNAME.database.windows.net;Database=BidNow;
		User ID=USERNAME@SERVERNAME;Password=PASSWORD;
		Trusted_Connection=False;Encrypt=True;&quot;"
	providerName="System.Data.EntityClient" />


… to …

<add name="BidNowDataContext"
	connectionString="metadata=
		res://*/BidNowDataContext.csdl|res://*/BidNowDataContext.ssdl|
		res://*/BidNowDataContext.msl;
	provider=System.Data.SqlClient;
	provider connection string=&quot;
		Server=tcp:SERVERNAME.database.windows.net;Database=BidNow;
		User ID=USERNAME@SERVERNAME;Password=PASSWORD;
		Trusted_Connection=False;Encrypt=True;trustServerCertificate=true;
		&quot;"
	providerName="System.Data.EntityClient" />


… and voilà!  It worked!

Turns out that when Encryt=True and TrustServerCertificate=False, the driver will attempt to validate the SQL Server SSL certificate.  By setting the property TrustServerCertificate=True the driver will not validate the SQL Server SSL certificate.

Of course, once I learned tried this I came across an article on MSDN called How to: Connect to SQL Azure Using ADO.NET to says to set the TrustServerCertificate property to False and the Encrypt property to True to prevent any man-in-the-middle attacks, so I guess I should include the following disclaimer: Use at your own risk!

SQL Azure Adds Support for Database Copy

The SQL Azure team has announced SQL Azure Service Update 4, which includes database copy, an improved help system, and deployment of Microsoft Project Code-Named “Houston” to multiple data centers.  See the SQL Azure Team Blog for the formal announcement.

Customers have been asking for a way to backup databases with SQL Azure for a long time, and the new database copy capabilities will provide a lot of support.  From the SQL Azure Team Blog:

Support for database copy: Database copy allows you to make a real-time complete snapshot of your database into a different server in the data center. This new copy feature is the first step in backup support for SQL Azure, allowing you to get a complete backup of any SQL Azure database before making schema or database changes to the source database. The ability to snapshot a database easily is our top requested feature for SQL Azure, and goes above and beyond our database center replication to keep your data always available. The MSDN Documentation with more information is entitled: Copying Databases in SQL Azure.

Good stuff.  So, if you want to rename a database, you can do this …

// Rename a database
ALTER DATABASE database1 modify name=database2


… if you want to make a copy of a database, you can do this …

// Create a consistent copy of a database
CREATE DATABASE database2 AS COPY OF database1


… and finally, if you want to track the copy progress of a database, you can do this …

// Keep track of the copy progress
SELECT * FROM sys.dm_database_copies


There is also some great “How-To” documentation that’s been published to MSDN that you should take a look at:

And don’t forget about “Houston”.  Microsoft project Microsoft Project Code-Named “Houston” (Houston) is a light weight web-based database management tool for SQL Azure. Houston, which runs on top of Windows Azure is now available in multiple datacenters reducing the latency between the application and your SQL Azure database.

Enjoy!

AutoStart WCF Services to Expose them as Service Bus Endpoints

A couple months ago I wrote a post on how to host WCF services in IIS that expose themselves as endpoints on the Windows Azure AppFabric Service Bus.  The principal challenge in this scenario is that IIS/WAS relies on message-based activation and will only launch the host after the first request comes in.  However, until the host is launched the service will not connect to the Service Bus, and consequently will never receive a message.  A classic catch-22.

The solution I proposed was to leverage the Application Warm-Up Extension for IIS 7.5, which will proactively load and initialize processes before the first request arrives.  While this is acceptable, I’ve found a better solution using the Windows Server AppFabric Autostart (thanks to conversations with Ron Jacobs).

Windows Server AppFabric Autostart is a feature introduced in Windows 7 and Windows Server 2008 R2.  The primary use cases are for reducing the latency incurred by the first message and to host WCF transports/protocols for which their are no listener adapters.  As you can see, initializing the host so that it connects to the Service Bus is another benefit.

To set this up, ensure that you have installed Windows Server AppFabric on your machine.  I personally recommend you use the Web Platform Installer to do this for you (I detail how to do this in the first part of my post on Getting Started with Windows Server AppFabric Cache).  Once you have this installed, follow these steps:

  1. Open IIS Manager.  Navigate to your web application.
  2. Click on Configure in Actions pane.
  3. Configure the application to either autostart all the services by choosing Enabled or specific services by choosing Custom.
  4. If you specified Custom, navigate to the configuration panel for that specific service and turn autostart to Enabled.

Pretty straightforward.  I think you’ll like this solution, as it keeps everything within the AppFabric family.

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!