Updating AppFabric Cache via SQL Service Broker External Activator

 Event Driven Updates


If I can’t have magic then I want something easy. I’d like to have changes that occur on certain tables be reflected in AppFabric Cache. I’d also like this to occur in an event based manner.  “Use SqlDependency and be done with it” you say? That’s certainly one answer but it also creates a coupling between your application and managing cache refreshes or it means you’re deploying yet another domain specific service.


External Activator is an engine designed to invoke external code in response to an event in SQL Server. This is exactly what I want. In this specific case I am using it to update my cache data but it’s not hard to imagine many use cases where this is useful and being able to do it with a simple executable rather than a full blown service has many implications in terms of xcopy deployment etc.


I want to be clear up front that this idea is in the investigatory stage. My results are encouraging but you should expect to do some analysis and tweaking if you attempt the technique for a production system.


Finally, before I jump in this example assumes you have AppFabric Cache installed and working and you have at least read about External Activator. 
If you need more information about  External Activator   and service broker before starting see the SQL Service Broker Team Blog.

 

Creating the Service Broker Queues


The first step to getting going was to download the External Activator from the feature pack  page and diligently follow all of the directions.  Be sure to download the appropriate 64 bit or 32 bit msi for your platform.


Next, I created a database called CacheUpdateSample and made sure to enable Service Broker and grant the service account that the activator would be running under the necessary access.


Once that was done I issued the following commands:

use CacheUpdateSample

CREATE MESSAGE TYPE GenericXml VALIDATION = WELL_FORMED_XML

GO

CREATE CONTRACT GenericContract

(

      GenericXml SENT BY ANY

)

GO   

CREATE QUEUE MessageQueue

GO

CREATE QUEUE UpdateCacheQueue

GO

CREATE SERVICE MessageQueueService ON QUEUE MessageQueue (GenericContract)

GO

CREATE SERVICE UpdateCacheService

ON QUEUE UpdateCacheQueue

(

      [http://schemas.microsoft.com/SQL/Notifications/PostEventNotification]

);

GO

CREATE EVENT NOTIFICATION UpdateCacheNotification

ON QUEUE MessageQueue

FOR QUEUE_ACTIVATION

TO SERVICE ‘UpdateCacheService’ , ‘current database’

GO


This set up the service broker infrastructure I needed. Now I had to figure out a way to get messages flowing.

 

Service Broker Shenanigans

The vehicle I chose to drive the updates within the database might be viewed as slightly unconventional:

create procedure [dbo].[uspSendGeneric]

(@xml xml)

as

begin

      DECLARE @dh UNIQUEIDENTIFIER;

      BEGIN DIALOG CONVERSATION  @dh

      FROM SERVICE [MessageQueueService]

      TO SERVICE ‘MessageQueueService’,‘current database’

      ON CONTRACT GenericContract

      WITH ENCRYPTION = OFF;

      SEND ON CONVERSATION @dh MESSAGE TYPE GenericXml(@xml);

end

GO


If you look closely you’ll see that it’s talking to itself!


I did this because it was easy to make the updates fire the way I wanted them to and it was easy to make sure I cleaned up my conversations. There is a lot of material out there on conversation patterns, serializing conversation handles, explaining why both sides should end the conversation and all kinds of things that are very interesting but I just wanted the thing to fire when I wanted it to and go away when I was done and this worked well in my testing.


Once I had my narcissistic procedure done I hooked it up to a simple trigger

create trigger [dbo].[sendGenericTrigger]

on [dbo].[TestTable] FOR Insert, Update

as

begin

      declare @xml xml;

      set @xml = (select * from inserted for xml auto,root(‘SSBData’),elements)

      exec uspSendGeneric @xml

end

GO

 

That Which Is Invoked

Once the database side is all hooked up it’s time to create something for the External Activator to activate. So, I quickly created a small application to drive the cache updates.


The heart of main looks like this:

using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[dbKey].ConnectionString))

{

    con.Open();

    var clean = ProcessMessages(con);

    EndConversations(con, clean);

    con.Close();

}


The ProcessMessages  function retrieves the messages , populates the cache. And returns the conversation handles. The EndConversation routine spins through the handles and closes them.


When you read the sample code that contains the body of the routines you’ll see they are very simple for demo purposes. In production you *could* develop an elaborate dispatching system using dynamic assembly loading or various validation checks etc. The one thing to keep in mind however is to not affect the simplicity of the design. Prefer creating another event and executable that you map in the config file to a monolithic solution. By doing this you’ll be more able to take advantage of the flexibilty of this aproach.

 Impressions


There were several things I liked about this technique:

  • It was faster than I expected even though External Activator is invoking the executable each time the event fires.
  • I was able to edit and recompile code without restarts/ file locking
  • Using the log file produced by external activator was easy.


One facet I will investigate further to see if there is a more elegant way to do things is having the queue talk to itself. While this makes conversation cleanup easy it does result in an extra invocation of the executable. Another might be a detailed measurment of cache misses/hits % using this method vs. deploying a dedicated service. 

Code for the sample can be found here.

 

 

 

Thanks to teammates Mark Simms, Emil Velinov, Jaime Alva Bravo and James Podgorski for their review

Windows Azure AppFabric SDK October Release available for download

A new version of the Windows Azure AppFabric SDK V1.0 is available for download starting 10/27. The new version introduces a fix to an issue which causes the SDK to rollback on 64 bit Windows Server machines with BizTalk Server installed.

The fix is included in the updated SDK download.  If you are not experiencing this issue, there is no need to download the new version of the SDK.

The Windows Azure AppFabric Team

AppFabric’s AutoStart feature: great news for BizTalk

Any of you who have been writing WCF front-ends for BizTalk services will know about one of ASP.NET’s failings: first request latency. A service (or application) hosted in IIS doesn’t start-up and JIT itself fully until the first request is received.

And if low-latency is important to you, this isn’t acceptable, as the first request can incur delays ranging anywhere from 2 secs to 60 secs!

There are many common ways to…

Server AppFabric for the BizTalk Developer Video Session

If you consider yourself a hard core BizTalk Developer, then this session is for you!

A few weeks ago I presented a session on Server AppFabric to the BizTalk User Group in Sweden.  This session was geared to showing how similar Workflow 4.0 and AppFabric are to BizTalk – conceptually at least.  The goal of this session was to show how us BizTalk guys and gals can quickly pick up Workflow 4 and AppFabric because we already understand the concepts.

I would highly recommend this 60 minute session to all fellow BizTalkers out there!

This session is available on Channel 9 – http://channel9.msdn.com/Blogs/MSCOMSWE/Tech-Overview-WCFWF-Server-AppFabric-BizTalk-Conference-Stockholm

The code and slides are available for download at http://www.biztalkgurus.com/media/p/29973.aspx.

At the same conference, I gave a session which covered Windows Azure Platform AppFabric.  This 30 minute session covers a real-world service bus solution and a walk through of the code behind the solution.  It is available at http://channel9.msdn.com/Blogs/MSCOMSWE/Pattern-5–Remote-Message-Broadcast-BizTalk-Conference-Stockholm and the code and slides can be downloaded at http://www.biztalkgurus.com/media/p/29975.aspx.

 

If you are looking for other sessions from the multi-day conference in Sweden, below is a full list.  We covered a wide-range of technologies from AppFabric to StreamInsight.

Day 1 (Sessions from September 8th, 2010)

Welcome and Introduction

Choosing The Right Tool in the Application Platform
Discuss the challenge of choosing the right technology for a given situation and present a decision framework for guiding evaluation.

Tech Overview: SQL Server
Look at the core components of SQL Server that are used to build applications (e.g. SSIS) and when to use them.

Tech Overview: BizTalk Server
Discuss what BizTalk is and when to use it.

Tech Overview: WCF/WF, Server AppFabric
Highlight key capabilities in WCF and WF and benefits offered by Windows Server AppFabric.

Tech Overview: Windows Azure Platform
Discuss Microsoft’s cloud offering and best usage scenarios.

Pattern #1 – Simple Workflow
Evaluate scenario that involves aggregating data from multiple sources and presenting a unified response.

Day 2 (Sessions from September 9th, 2010)

Pattern #2 – Content Based Routing
Consider options for effectively transmitting data to multiple systems that perform similar functions.

Pattern #3 – Human Workflow with Repair and Resubmit
Showcase using workflow 3.5 to send customer details to an AppFabric hosted workflow 4.0 Workflow Service.  This workflow service controls the payment collection process and allows for updated information on a user to be sent back into the same running workflow instance from SharePoint.

Pattern #4 – Cross Organization Supply Chain
Evaluate how to build a supply chain to integrate systems in a PO scenario.

Pattern #5 – Remote Message Broadcast
Demonstrates a scenario where a traditional polling solution is augmented to support real-time updates.

Pattern #6 – Complex Event Processing
Addresses click stream analysis and creating actionable events from user and system behavior.

What are the Workflow Authoring Modes?

WF enables you to separate workflow definition from business logic. You can develop your entire workflow by using code, where you specify the workflow structure and logic in the Microsoft Visual C# development tool or the Microsoft Visual Basic development system. The typical workflow-authoring scenario in Visual Studio provides a designer to specify the workflow definition and then uses code in Visual C# or Visual Basic to represent business logic in separate code-behind pages.

read more

What Is Windows Workflow Foundation?

WF includes visual designers for use in Visual Studio 2008, which enable you to quickly design and develop workflow applications. By using workflow classes and custom data types, you can also define your workflow structure programmatically and develop the entire solution in code.

The following table shows some of the commonly used namespaces in WF.

read more