The Visual Studio Solution and documentation can be found at the MSDN Code Gallery.


Original Text by:
Suren Machiraju, Principal Group Program Manager, Microsoft
Sidney Higa, Senior Programming Writer, Microsoft
The Starter Kit is designed to be a reference implementation; a secondary objective is to provide sample code that developers could use to manage the life-cycle of the .NET 4 Workflow Services on Windows Server AppFabric. It does this by providing a complete client-side application that enables design of .NET Windows Workflow Services outside of the Visual Studio IDE; deployment of these Services from the Client to the AppFabric server; versioning of the deployed service definitions; and finally management of Service Instances in a custom monitoring console. Additionally this document provides the instructions for setup, a tour of the features and implementation highlights.
The features enabled via the starter kit are:
       Re-hosting the designer to provide a design experience that’s fully integrated into the line-of-business application  
       Handling deployment from design tool to the Windows Server AppFabric
       Managing the published versions of the customer’s workflow designs
       Securing access to designed workflows
       Executing and controlling instances of custom workflows from the product
       Reporting on business metrics collected from a workflow service instance’s execution
       Troubleshooting and diagnosing issues



The scenario implemented here is a document conversion service.

1.       A document is submitted to the system in one format, and a customizable amount of processing takes place to convert it to the desired target format.

2.       The choice of using workflow services for defining the conversion logic is based on two key requirements:

a.         First, the conversions may be long running (taking days) or may have to incorporate data from multiple sources to proceed.

b.       Second, users of the system need to be able to customize the conversion logic.  


Figure 1 shows the general flow and high-level implementation of the conversion process.

Figure 1 - Conversion Process Scenario

In addition, the tooling is designed to enable both users of the product and the IT Staff to manage, troubleshoot and support the application in production

Starter Kit Components

The Starter Kit includes sample implementations that fall into four component groups:

·         Workflow Design Client

·         Custom Activities

·         A Client for Running Service Instances

·         Various Server Components

·         Sample projects that demonstrate features of Workflow Studio.

Workflow Design Client

The design client is called Workflow Studio; it is a feature-rich client application that enables users to design, configure, publish, monitor and troubleshoot workflows remotely from the Windows Server AppFabric server. The next graphic shows the UI.

Custom Activities

The solution includes three simple custom activities that demonstrate the use of custom activities and activity designers in general, and how to use promoted properties to emit business activity metrics from custom activities in particular (see the following figure).

Figure 2 - The three custom activities included with the Starter Kit.

Client for Running Service Instances

The Document Conversion Client (client.exe) is a very simple client-side application that can be used to launch instances of conversion workflows on the AppFabric server. It adds the ability to specify username and password or Windows credentials, to select from one of the provided sample services to invoke and to configure the conversion parameters.


Various server-side components are required for supporting Workflow Studio. This includes a set of extensions for working with promoted properties, as well as a customization to the WCF routing service in support of versioning deployed workflow service definitions.
Specifically, this includes code that demonstrates how to “promote” business properties of interest. The implementation demonstrates various extensibility points: creating a custom PersistenceParticipant, a custom ServiceBehavior and a custom configuration BehaviorExtensionElement.
The components that customize the WCF routing service demonstrate how create a ClientMessageInspector that can be used to control how the routing service reacts to exceptions. This necessitates the implementation of custom EndpointBehavior and another BehaviorExtensionElement for configuring this behavior.
Because these behaviors are plugged in via a configuration file (web.config), the server components also show how you define custom schemas and register them with IIS so that tools like the AppFabric Dashboard don’t generate errors when attempting to process services whose configuration includes them.


The %install dir%\Workflow Studio Samples folder contains six sample Workflow Studio projects that demonstrate various features of the Starter Kit.

§  General Conversion: A basic project, that is similar to what is created when using the New Project function in Workflow Studio. This is shown in the Quick Start below.

§  InternalErrorSample: This project contains a workflow that has an error in the middle that is useful for seeing error messages when replaying workflows. This sample attempts to parse a string value containing a file path (provided as input) into an Int32, and throws an exception when the Assign activity that attempts the parse executes. This sample is run in a fashion similar to the Reliable Sample described in detail in the Troubleshooting with Replay section that appears later in this document, except that the instance of InternalErrorSample cannot be resumed.

§  Long Delay: This project contains a workflow that has a long delay and can be used to see how the Choose Instance to Visualize list gets updated, as well as to examine a workflow at various points in its lifecycle.

§  Reliable Sample: This project shows how to leverage AppFabric resiliency (resulting from a combination of persistence and instance management) from Workflow Studio. It is described in detail in the Troubleshooting with Replay section below.

§  SecureService: This project provides a sample service that uses activities from the Workflow Services Security Pack to secure a workflow.

§  Versioning Sample: This project provides a starting point for creating and testing the versioning functionality. Publish it as is and run it with the Document Conversion Client. Then add an Assign between the Receive and SendReply activities that changes the value of the inputFilePath variable (for example, that capitalizes it) and run it with the Document Conversion Client. Examine the web.config on the Router for the updates, as well as the VersioningSample folder contents in IIS to see how the files are versioned. 


·         Visual Studio 2010 RTM

·         Windows Server AppFabric available for download here.

  • Ensure that the Default Web Site is running under DefaultAppPool and that DefaultAppPool is running .NET 4.
  • Monitoring - Enable application monitoring for the default web site, and ensure the database is named AppFabricMonitoring and is available at .\SQLEXPRESS.
  • Ensure the Monitoring level is set to Health Monitoring or higher
  • Persistence - Enable SQL Persistence.  Ensure the database is named AppFabricPersistence and is available at .\SQLEXPRESS.
  • Workflow Host Management - Ensure the Enable Instance Control is checked.
  • Ensure the persist and unload timeouts set to 0.
  • If your default monitoring and persistence database names are not that described above, you will need to modify the two connection strings in app.config (for WorkflowStudio.exe) to use the database names you have.

    These connection strings are named Samples.WorkflowStudio.Properties.Settings.AppFabricMonitoringConnectionString and Samples.WorkflowStudio.Properties.Settings.AppFabricPersistenceConnectionString respectively.

·         Windows Identity Foundation (WIF)

   o    Download from: Windows Identity Foundation Download.

   o    Microsoft.IdentityModel 3.5 Installed

·         Web Deploy

  o    Download from Web Deploy Download

     o    If you have VS2010 installed, you need to uninstall Web Deploy and then re-run install from download. Be sure to do a Complete installation.

   o    After installation, ensure that the required Windows services are running (preferably set to start automatically):

    §  Web Deployment Agent Service

    §  Web Management Service

                ·         The Web Management Service must be configured to allow remote connections if you intend to connect from remote machines (this is only available on Windows Server 2008 and 2008 R2). From IIS, select the Server Node, scroll down until you see Management Service Delegation (see the following graphic). Double click it and in the pane that appears check Enable remote connections.

                 ·         IIS 6 Metabase and IIS 6 Configuration Compatibility. Open the Control Panel, and click Programs And Features. Then click Turn Windows features on or off 

Setup Procedure

1.             From the directory where you extracted the starter kit files, run Setup.cmd as an administrator. (You will get three security warnings for three scripts that create databases or directories. Type “R” and press ENTER each time to run the scripts.

2.             Open AppFabricApps.sln.


The following errors may occur with an incorrect setup. Here are the common solutions:
·         Publish Failed.
      ·         First, ensure that the Web Deployment Agent Service and Web Management Service windows services are both running.
      ·         If the error you get is specifically: Microsoft.Web.Deployment.DeploymentException: Unknown factory 'versionedPublish'.
             ·     This error can appear as the result of a configuration problem on a remote deployment source client or on the deployment target server.
     ·         Ensure that the Extensibility folder has been created and contains the WebDeployUtilities.dll. It must exist on both client machines and the target server.
      o    On x86 machines, this is C:\Program Files (x86)\IIS\Microsoft Web Deploy\Extensibility
      o    On x64 machines, this is C:\Program Files\IIS\Microsoft Web Deploy\Extensibility. You will also need to add the dll to the x86 path mentioned previously.
      ·         If you created the folder, you will need to restart a few processes
      o    Restart IIS.
      o    Restart the Web Deployment Agent Service.
      o    Restart Workflow Studio.
      ·         Workflow Studio crashes when starting.
               ·         Ensure that the loading of assemblies from other network locations is permitted. This is done by modifying the  WorkflowStudio.exe.config to have the following entry within the configuration element:
      <loadFromRemoteSources enabled="true"/>




In the following sections we break out a feature of the Starter Kit and highlight where you can look in the solution files to observe the implementation.
The Starter Kit offers sample solutions for the following:

·         Re-hosting the Workflow designer

Load activity libraries, using custom glyphs, activity designers, and the workflow debugger

·         Handling WF deployment

Use WebDeploy APls for remote deployment of services

·         Managing versions

Configuring a WCF routing service with Web Deploy, versioning workflow service endpoints

·         Executing and controlling instances

Uses AppFabric instance control

·         Reporting on instance business metrics

Implements a WCF service behavior, using promoted properties & querying for them in SQL

·         Diagnostic tooling

Query SQL monitoring tables, loading monitoring tables, correlating event records with activities in the designer to provide for replay of executed workflow instances

We begin with an end–to-end tour that helps to provide context to the feature sets detailed in the sections that follow and demonstrates the bulk of the Starter Kit features in action.

Quick Tour

In this tour, we show publishing a workflow designed with Workflow Studio, running it and monitoring its execution.

§  Open the AppFabricApps.sln solution (from %install dir%\) and build it.

§  Run Workflow Studio by navigating to %install dir%\WorkflowStudio\bin\debug and double clicking on WorkflowStudio.exe.

§  Within Workflow Studio, select File->Open Project…  

§  Browse to the General Conversion project folder under %install dir%\Workflow Studio Samples folder, select it and click OK

§  The General Conversion workflow will load in Workflow Studio.

§  Select File->Publish Project to Server…

§  Assuming you are publishing to your local server, leave the Service URL as localhost and username/password fields blank.

§  Click OK to begin the publish operation. If you get an exception while publishing, see the Troubleshooting section above.

§  Click OK to the Publish Succeeded message box.

§  Open the Document Conversion Client (%install dir%\Client\bin\Debug\Client.exe).

§  General Conversion should be selected by default, so just click Start Conversion.

§  Verify you get a message with a file path back indicating that the conversion has started.

§  Do not click OK, keep the Document Conversion Client open.

§  Return to Workflow Studio.

§  With the GeneralConversion project still, open, select Visualization->Visualize Instance Execution…

§  The Choose Visualization Instance dialog will appear. If you get an error here, ensure that your monitoring and persistence databases are configured and named as described in the Pre-Requisites section of this document.

§  In the list, choose the latest instance. If you have multiple instances, note that the LastModifiedTime is in UTC. If your instance does not appear in the list, it may take about 10 seconds for AppFabric to update the monitoring database, click the Refresh button.

§  Click OK.

§  The designer will begin replaying the execution of the selected instance.

§  Hover over the green circles to view the additional tracking event details surfaced. The replay data is fed from tracking records stored in the AppFabric monitoring database.

§  From the Visualization menu, choose Dashboard…

§  The Dashboard will appear, summarizing all conversions performed and their average duration (on the right). Your screenshot will differ from the below depending on how many instances you have run and what conversion parameters you used. The data which feeds this dashboard is collected from promoted properties (stored in the persistence database) whose values are set by the execution of the CaptureAnalyticProperty activities in the workflow design.



The Quick Tour demonstrated how Workflow Studio enables users to load projects consisting of workflow services and configuration files (web.config). Workflow Studio allows you to design workflow services by dragging and dropping activities from the toolbox and configuring activities on the design surface using the property grid. It also provides a rudimentary project system, which supports defining a project that can contain one or more XAMLX files and a web.config. (XAMLX is the file type (.xamlx) used by the workflow framework to declaratively create workflows.) The project is named from the folder used to contain it. Once published to IIS, the project becomes an IIS Web Application.
Workflow Studio provides project system functionality similar to Visual Studio: New Project (creates a copy of a project from a template consisting of a single service XAMLX and a web.config), Open Project (opens a project folder and displays the available service XAMLX files) and Close Project. Once a project has been created or opened services can be added or deleted by a right-clicking in the Project tree. The activity library assemblies required by the workflow design are maintained in the bin directory of the project.

Where is it implemented in theStarter Kit?

To support the workflow service editing experience, the .NET 4 Workflow Designer has been re-hosted to provide the bulk of the functionality for the editing experience.
WorkflowStudio->MainWindow.cs: actions from the menu system such as New Project and Open Project are implemented as commands within this file, with the suffix Executed (e.g., NewCmdExecuted and OpenCmdExecuted). Both of these ultimately call into the OpenInitialXamlx method that instructs the re-hosted workflow designer to load and display the first XAMLX in the project, as well as to load the toolbox with a hard-coded list of activities (via the LoadDefaultToolbox method). The selection of a XAMLX from the Project tree also triggers the re-hosted workflow designer to load the selected definition (DisplaySelectedItem). The actual loading of the designer from the file system is performed by the WorkflowDesignerHost control discussed next.            
WorkflowStudio-> WorkflowDesignerHost.xaml.cs: The loading and display of a XAMLX happens by means of a call to the LoadWorkflow overload that takes a string with the file path as a parameter within the WorkflowDesignerHost control. This control wraps access to and manages an instance of the .NET 4 System.Activities.Presentation.WorkflowDesigner. Some of the logic used in the LoadWorkflow method is designed to support the visualization replay of an executed instance, which is covered later. The crux of the loading and display in this method is the call to this.WorkflowDesigner.Load(filename) which actually creates the visual tree of the XAMLX file, and the assignment to of the resulting visual tree to the Content property of the WorkflowDesignerHost control in the line this.Content = this.WorkflowDesigner.View. The View property at this point contains a WPF Grid that represents the complete design surface with the workflow loaded. Once loaded, the WorkflowDesignerHost raises the WorkflowLoaded event. The instance of MainWindow hosting the WorkflowDesignerHost control listens for this event with the WfDesignerHost_WorkflowLoaded method. When triggered, it retrieves the PropertyGrid instance created by the WorkflowDesigner (accessed by the WorkflowDesigner.PropertyInspectorView) and sets it as the content of PropertyGridHost control on the surface of the MainWindow to display it. This property grid is bound to the WorkflowDesigner to respond to selection changed events, so it will automatically display the properties of the selected activity.


Let’s dive into the use of promoted properties within the Starter Kit. Recall from the Quick Tour the Dashboard summarized the average duration of a conversion for each source (Convert From) and destination type (Convert To) pair. The rationale for choosing to use promoted properties for such values is that they are guaranteed to be in sync with the state of the persisted workflow service instance. This is in contrast to custom tracking records or variables extracted with tracking profiles which are monitoring records not guaranteed to reflect the persisted state of the instance.

Where is it implemented in the Starter Kit?

The values of promoted properties are written to the InstancePromotedProperties table in the AppFabric SQL Persistence Database (the figure below shows the table in SQL Server Management Studio).

Promoted properties represent a set of 64 properties (32 value columns of type sql_variant and 32 value columns of binary type varbinary(max)) whose values are updated when a workflow service instance is persisted, and read when a workflow service instance is loaded. The meaning of an individual value column is defined by the program logic. There is only ever one row per promoted properties set per instance, and that row simply gets updated as the workflow persists and the values change. The Workflow Studio Dashboard simply queries this table to generate the summary report and chart.
There are two major steps to using promoted properties.
First, to promote a property, call the Promote method on an instance of a SqlWorkflowInstanceStoreBehavior class. You will need access to the instance of this instance store used by the WorkflowServiceHost that will be running the workflow service definition (XAMLX) of interest. 
Second, to actually be able to read and write promoted property values from your workflow service instances, you will need to add a custom persistence participant to the WorkflowExtensions collection of a WorkflowServiceHost instance before it is opened.
The following describes how we accomplished the aforementioned steps.
ServiceExtensions->PromotePropertiesBehavior.cs: The approach to do both, at the right time, for a workflow service hosted in AppFabric, is to define a custom Service Behavior and register it with the service via web.config. The PromotePropertiesBehavior class creates the schema of the promoted properties set and registers a custom persistence participant within its ApplyDispatchBehavior method.
ServiceExtensions->CustomPropertiesParticipant.cs: The persistence participant that collects the values from the workflow to persist, as well as makes the values of or promoted properties available to workflow activities is defined in the CustomPropertiesParticipant class.
ServiceExtensions->PromotePropertiesBehaviorElement.cs: Service behaviors are applied to workflow services hosted in AppFabric by configuration, either via the web.config of the service or a web.config higher up in the hierarchy (at the site or server level). The configuration runtime needs to understand how to translate the XML element found in the serviceBehaviors element of the web.config into a type that instantiates the service behavior. For example, the following is an excerpt of the configuration used in the Workflow Studio Samples to attach the PromotePropertiesBehavior:





      <serviceMetadata httpGetEnabled="true" />

      <serviceDebug includeExceptionDetailInFaults="true" />

      <sqlWorkflowInstanceStore connectionStringName="ApplicationServerWorkflowInstanceStoreConnectionString" hostLockRenewalPeriod="00:00:30" runnableInstancesDetectionPeriod="00:00:05" instanceEncodingOption="None" instanceCompletionAction="DeleteNothing" instanceLockedExceptionAction="NoRetry" />

      <promoteProperties />







    <add name="promoteProperties" type="ServiceExtensions.PromotePropertiesBehaviorElement, ServiceExtensions, Version=, Culture=neutral, PublicKeyToken=null" />



To accomplish this a BehaviorExtensionElement needs to be created. The PromotedPropertiesBehaviorElement class performs this function for the PromotePropertiesBehavior.
ServiceExtensions->ServiceExtensions_Schema.xml: If you were to use the web.config containing the promoteProperties behavior now and looked at the AppFabric Dashboard for that application in IIS Manager you would see an error telling you that the element promoteProperties is not recognized. This is because AppFabric uses the Microsoft.Web.Administration library to process configuration files, and it requires all elements to be described by a registered schema. If an element is not registered then such an error will occur. The ServiceExtensions_Schema.xml contains the xml necessary to describe both the promoteProperties element and the peristenceFaultToClientException element (introduced later).  To “register” this schema with IIS, you simply need to copy the xml file into %windows%\system32\intesrv\config\schema. The file name is irrelevant so long as it is unique.
ConversionActivities->CaptureAnalyticProperty.cs: Access to the values stored in a promoted properties set is performed via the custom properties participant that is made available to activities as an extension. The CaptureAnalyticProperty activity’s Execute method shows how to access the CustomPropertiesParticipant from the context, and use it to both read and write values of a promoted properties set.


Workflow Studio not only enables users to visualize the replay of successfully executed instances (as shown in the Quick Start)—it also enables you to use the replay as an means to diagnose problems by showing errors encountered during an execution directly on the design surface. Moreover, Workflow Studio enables these diagnostic replays to be packaged up as Snapshots and sent to other Workflow Studio users for assistance. For example, a customer using Workflow Studio can create a snapshot and sent it to the organization’s technical support team for analysis.
In addition to diagnosing services, in some situations the diagnosis may indicate that there was an environmental failure that occurred while running the workflow (e.g., a required drive could not be accessed or the network was down). In these cases, once the environmental issue has been corrected it may be valid to simply resume the workflow from the last persistence point just before the failure occurred. Workflow Studio enables the user to do this remotely by leveraging the Instance Control functionality provided by AppFabric and without having to issue the Resume command with IIS Manager. The following walk thru shows these features in action.

§  In Workflow Studio, open the Reliable Service sample project.

§  Publish the project to the server.

§  As a part of the Starter Kit installation, the Default Web Site has been configured to abandon (effectively rollback to that last persist point) and suspend (wait for an administrative action before re-running) workflow service instances that have unhandled exceptions. To see this,

§  Load IIS Manager.

§  Right click on the Default Web Site and click Manage WCF and WF Services, then click Configure.

§  Click Workflow Host Management. You should see the Action on unhandled exception already set to Abandon and suspend.

§  Run the Document Conversion Client as an administrator. (%/AppFabricApps/Client/Client.exe)

§  In the list of Services, select Reliable Service.

§  Click Start Conversion. This will launch an instance of the Reliable Service with the path to the document specified in Input File Path. The problem is that this file doesn’t exist (yet)!

§  In the Conversion Started dialog, click OK.

§  Let’s see the error that resulted from our not having the file in place. Return to Workflow Studio and select Visualization->Visualize Instance Execution.

§  Select the instance just run. From the list of instances, look for the most recent instance whose LastEventStatus is Aborted.

§  Click OK.

§  Allow the replay to run, and then hover over the red circled exclamation above the Throw activity. Observe the error text.

We can correct this issue without losing the progress of the workflow service instance. When the error occurred, AppFabric abandoned the in memory state of the running workflow service instance. This means that the current state of the instance is at the Persist just before the If activity. AppFabric normally resumes the execution of this workflow automatically since the If activity is not waiting on anything. However, when the workflow was abandoned it was also set to have a suspended state. This tells AppFabric to not automatically resume execution of the workflow until an explicit resume command for that instance has been received from an administrator. Let’s first correct the problem by creating the file.

§  Return to the Document Conversion Client, and from the Input File Path text box, copy just the file name e.g., MyFileXXXX.docx. Do not include the path.

§  Open explorer and navigate to C:\Pending

§  Create a Word Document in that folder. Name it with the file name you just copied.

§  Return to Workflow Studio.

§  From the Visualization menu choose Resume Instance Execution

§  You should see the following confirmation message:

§  The instance has now resumed, and executed successfully, which you can confirm by going back to the Visualization menu and selecting Visualize Instance Execution.

§  Click Cancel to exit the Visualization dialog, but keep Workflow Studio and the faulted replay open.

§  Another aspect of the replay feature offered by Workflow Studio is the ability to send the replay to another Workflow Studio user by creating and loading Snapshots. A Snapshot captures all of the monitoring records that drive the replay and serializes them to disk, along with the project files. Another user can load the replay file, which loads the monitoring records into a separate, private copy of the AppFabric monitoring database, and view the animated replay as if it were local.

To create a Snapshot from this replay execution, follow these steps:

§  On the Help menu click Create Snapshot for Support…

§  Choose a folder where you want the replay files saved:

§  Click OK.

§  Click OK to the Snapshot Created message box.

§  You now have a snapshot ready for exchange with another Workflow Studio user.

§  Run a new instance of Workflow Studio.

§  From the Help menu, choose Load Snapshot for Troubleshooting…

§  Browse to the replay folder created (it will have the name of the project).

§  Open that folder, and within it select the *.BIN file and click Open.

§  The replay will execute just as before, however this time the monitoring records were not loaded directly from the submitter’s instance of AppFabric, so the user viewing the replay does not need direct access to submitters environment in order to assist with troubleshooting.


The replay and snapshot support is one of the most involved features of the Starter Kit. The following will serve as a guide as you explore the implementation.
WorkflowStudio->MainWindow.xaml.cs: When you go Visualize->Visualize Instance Execution… this is running the VisualizeCmdExecuted method which displays the selection dialog and after selection makes a call to the VisualizeInstanceExecution method of the WorkflowDesignerHost. It is this method that retrieves the monitoring records from the AppFabric monitoring database and iterates over them, displaying the appropriate status glyphs for each record above the activity it describes. This is covered in more depth the next segment that describes the WorkflowDesignerHost.xaml.cs.


When you create a snapshot, the CreateSnapshotCmdExecuted method is invoked, which in turn runs CreateSnapshotOfInstance method handing it the GUID instance ID of the selected instance. CreateSnapshotOfInstance makes a copy of the open project to the save location. Then it builds a DataSet containing records from multiple tables in the monitoring database. This data set is defined by the AppFabricMonitoringDataSet.xsd if you’re curious as to what queries are executed. Finally it uses a BinaryFormatter to serialize the DataSet to a binary file on the file system.  LoadSnapshotCmdExecuted, which runs when you go to Help->Load Snapshot for Troubleshooting…, does almost the exact opposite. It deserializes the data set and bulk inserts the records into an isolated copy of the AppFabric monitoring database that was created during installation of the Starter Kit. It then uses the records from this database to drive the replay execution.
Finally, the ResumeCmdExecuted method (called when selecting Visualization->Resume Instance Execution) implements the call to the WorkflowControlEndpoint that all Workflow Studio designed services expose. It makes use of the WorkflowControlClient to call the Unsuspend method, passing in the instance id of the service instance which will be resumed.

 Creating the Visualization

WorkflowStudio->WorkflowDesignerHost.xaml.cs: The visualization of an instance execution is performed in a unique way. One initial approach would be to iterate over the received monitoring records and add a new status glyph to the design surface at the coordinates for the activity to which it applies. In reality, this approach becomes problematic because a user can drill down into composite workflow activities. This would necessitate removing any status glyphs for activities no longer shown, as well as for adding new glyphs for activities that were not visible before.
Instead, we take a more comprehensive approach that requires less management of the visual state. We override the default WPF Activity Designer Template that is applied to all activities loaded in the designer surface. We modify this template to add a placeholder for where the status glyphs should appear (to the left of the DisplayName) as well as the tooltip (so that status details can be displayed). We then bind the value of this placeholder to attached properties which we add on the model item (the object that represents the activity visually on the design surface). The values of these attached properties determine the actual glyph and tooltip content.
When VisualizeInstanceExecution is run, it retrieves the all of the monitoring records for the selected instance in a datatable. It then creates a timer that animates the selection of an activity, updating its status and then waiting for 1 second before updating the status of the next activity. The selection of the activity is performed using the WorkflowDebugger, which automatically highlights the “active” activity in yellow.
The selection of the activity by the WorkflowDebugger also causes the selection to change on the design surface, which is handled by the SelectionChanged method. This method sets the values of the attached properties from the data present in the record, which causes the display to update with the new status glyphs.
WorkflowStudio->App.xaml: in order to override the default activity designer template with our own, we define a resource dictionary that references ours, and apply it to the ActivityDesigner class using a style. The OnStartup method in App.xaml.cs ensures that all .NET WF activities and our own custom activities use this template, so that the glyph display process is universal.
WorkflowStudio-> StatusEnabledActivityDesignerTemplate.xaml: this is the modified Activity Designer Template that is applied to any workflow loaded on the design surface. It provides for displaying the status glyphs used during replay. The interesting sections to examine in this file is the DataTemplate with the x:Key=”toolTipTemplate” which controls how the tool tip renders status data, and the Viewbox with x:Uid=”errorBox”, which controls the display of the error status glyph, and the Viewbox with x:Uid=”checkBox” which displays the OK status glyph. 


Versioning is accomplished using the Web Deploy service and the WCF Routing Service technology.
What happens when a service definition is published? When you select Publish Project from the File menu in Workflow Studio (and click OK on the credentials dialog), the process shown below in Figure 3 is starts.

                                                             Service Publishing Process

In brief, the deployment process uses Web Deploy in both the Workflow Studio client and on the AppFabric server. The actual transmission of the XAMLX files, the web.config and supporting assemblies is handled completely by Web Deploy and happens using an HTTPS transport.
The deployment happens in two phases,

§  Web Deploy “synchronizes” the destination files with the source files. This means creating the IIS Web Application, and copying over new or updated files (files present on only one side are never deleted from either end).

§  In phase 2 we version the copied files by invoking a custom deployment provider called versionedPublish. In Workflow Studio the versioning strategy is file name based, where it appends the string _wfs<versionNumber>. So if Service1.xamlx was deployed, the original version will have the name  Service1_wfs1.xamlx and if published again, that new one will be named Service1_wfs2.xamlx on the server.

In addition to versioning the deployed files this provider also ensures that the Web Application has the NET.PIPE protocol enabled, as is required for workflow instance management.
The key operation performed by versionedPublish however, is configuring the WCF Routing Service to 1) route to the correct service (canonical version, such as Service1.xamlx) when requests for all services come to the router directly and 2) route to the correct version of that service (such as Service1_wfs3.xamlx). This is accomplished by protocol. Clients, such as the Document Conversion Client, are configured with an address that includes both the router endpoint and the path to the correct service, for example the General Conversion service uses this address:

Notice that the endpoint is actually that of Routing.svc (which is our WCF Routing Service implementation’s endpoint name). The portion following Routing.svc provides the IIS Application Path and name of the canonical service endpoint. The canonical service endpoint is never actually communicated with, it is simply used to identify which service (without regard to version) within an application should be targeted.
During the versioning phase of publishing, the versionedPublish deployment provider updates the configuration of the WCF Routing Service (which is described in the web.config next to Routing.svc) so that requests to the canonical service endpoint go to the version just deployed. That is to say, new requests always go to the latest deployed version.
The handling of routing service requests to older versions is performed in a unique fashion and is based on correlation failures. Basically, the routing service will attempt to route the message to the latest version. If it receives a correlation failure there it assumes that it was the wrong version, and will route it to the next oldest version. This retry pattern continues until either the correlation succeeds and a service accepts the message, or all versions have been tried. This is a pattern we call routing because the client does not see an exception unless every attempt at finding a service has been made. The advantage of this approach is that the clients do not need to include any version information in the message header or body, the versioning works transparently albeit at a slight performance overhead.


The versionedPublish deployment provider is implemented in the WebDeployUtilities project and compiles to the WebDeployUtilities.dll. For Web Deploy to plug this custom provider in, the dll must be placed in a folder called Extensibility beneath the Web Deploy installation directory. It must exist on both client machines and the target server.
o On x86 machines, this is C:\Program Files (x86)\IIS\Microsoft Web Deploy\Extensibility
o On x64 machines, this is C:\Program Files\IIS\Microsoft Web Deploy\Extensibility. You will also need to add the dll to the x86 path mentioned previously.
 WorkflowStudio->MainWindow.xaml.cs: The PublishCmdExecuted method implements the behavior just described, making use of Web Deploy intrinsic providers as well as the versionedPublish custom deployment provider.
WebDeployUtilities->VersionedPublishProviderFactory.cs: When the versionedPublish provider is requested, it is requested by a string name. A deployment provider factory serves to both label the provider it exposes (to clients like IIS, the command MSDeploy.exe, and to requests from code) and provides the logic to return an instance of the provider. This file demonstrates how to create a factory for our versionedPublish provider.
WebDeployUtilities->VersionedPublishProvider.cs: Within this file is the implementation of the versionedPublish provider. The Add method orchestrates the process described previously.
Routing->Routing.svc: This is the WCF Routing Service endpoint that we have configured to understand our versioning protocol.
Routing->Web.config: On every publish, it is this web.config that will get updated by the versionedPublish.
ServiceExtensions->PersistenceFaultToClientExceptionInspector.cs: The routing approach protocol leverages the WCF Routing Service’s backup lists, which are designed to provide a list of backup service endpoints to try in case a service is offline. By default this behavior is only triggered by exceptions related to this cause, like EndPointNotFoundException. If another error, such as a correlation exception, occurs, that error is sent back directly to the client and the fallback list is not used.  In order to get the WCF Routing Service to use the backup list on a correlation error, we plug into it a ClientMessageInspector that examines the fault and if it is a correlation error. If the error is a correlation error, then we re-throw the Exception as an EndpointNotFoundException to trigger the backup list mechanism. For more information about routing service backup lists, see Routing Service and <backupLists>.
ServiceExtensions->PersistenceFaultToClientExceptionBehavior.cs: The PersistenceFaultToClientExceptionInspector is plugged in as an IEndpointBehavior. This file provides the implementation of that endpoint behavior.
ServiceExtensions->PersistenceFaultToClientExceptionBehaviorElement.cs: The PersistenceFaultToClientExceptionBehavior is added through configuration (web.config); this file describes the element that can read the XML configuration and return an instance of the behavior.


With activities from the Workflow Services Security Pack, creating a workflow service with Workflow Studio becomes largely a matter of adjusting configuration, and Workflow Studio provides a tool that does just that. In the sample that follows we show how configure the same service for either username and password authentication or Windows authentication.
Before proceeding with this sample in Workflow Studio, we will perform some steps to set up username and password authentication.

§  Run Workflow Studio.

§  Open the SecureService sample (AppFabricApps\Workflow Studio Samples\SecureService).

§  Observe that the “Convert” operation is entirely contained within the PrincipalPermissionScope activity.

§  The Role property is set to the value “Super Users”. In the case of Windows principals, this would ensure that the caller is a member of the “Super Users” group. In the case of user name and password authentication and authorization, this requires that the user is a member of the “Super Users” role.  To see what security mode is in use, right-click the web.config node in the Project tree and select Edit Security Configuration. 

§  The Web.Config Security Configuration dialog appears. You can use this dialog to switch between SQL Membership and Roles for username and password credentials, Windows Authentication or None (no authentication).

§  Change the Authentication Credentials to Windows Authentication and Click OK. Workflow Studio will update the web.config of the active project.

§  Publish the project to the server.

§  Run the Document Conversion Client.

§  In the list of services, select Secure Service.

§  Click Start Conversion. This will launch an instance of the Secure Service. The problem is that this client is not in the Super Users group of Windows Authentication. You will get an error message telling you access to the service was denied. This is a confirmation that Windows Authentication is working.


In order to test Username and Password Authentication with Workflow Studio, you need to first set up a database and add configure it accordingly. The following instructions will guide you through this.
Note: if you switch to using SQL Membership and Roles, the current version of the Routing service will be unable to route the message. This limitation is due in part to the point-to-point nature of username credentials encrypted with certificates. Therefore if you want to test using the Document Conversion Client, you will need to provide the direct address of the deployed service, not the routing endpoint.

1.   Run ASPNET_REGSQL.EXE (ASP.NET SQL Setup Wizard) to install the needed databases to the local machine. ASPNET_REGSQL.EXE is located in the %windir%\Microsoft.NET\Framework\version folder.

2.   When this Setup Wizard opens, Click Next.

3.   Choose ‘Configure SQL Server for Application Purposes’ and Click Next.

4.   Enter your server configuration settings and Click Next. Leaving the database set to <default> will result in this database being named aspnetdb.

5.   On the following window Click Next one more time to confirm the settings and create the database. If everything goes successfully, you will see confirmation that the database was successfully created or modified. Click Finish to exit this program.

6.   Next, use MSSM to execute the following three commands in order to create the user, create the role and add the user to this role in the newly created database. This user will have a username of JohnDoe and the password JD.

SQL – Create a user in the membership DB

            USE [aspnetdb]
            DECLARE     @return_value int,
                        @UserId uniqueidentifier
            EXEC  @return_value = [dbo].[aspnet_Membership_CreateUser]
                        @ApplicationName = N'/',
                        @UserName = N'JohnDoe',
                        @Password = N'JD',
                        @PasswordSalt = '',
                        @Email = '',
                        @PasswordQuestion = 'who',
                        @PasswordAnswer = 'you',
                        @IsApproved = 1,
                        @CurrentTimeUtc = '1/1/2010',
                        @UserId = @UserId OUTPUT           
            SELECT      @UserId as N'@UserId' 
            SELECT      'Return Value' = @return_value 

SQL – Create Role in Roles DB

            USE [aspnetdb]
            DECLARE     @return_value int            
            EXEC  @return_value = [dbo].[aspnet_Roles_CreateRole]
                        @ApplicationName = N'/',
                        @RoleName = N'Super Users'           
            SELECT      'Return Value' = @return_value

SQL – Add User to the Role

            USE [aspnetdb]
            DECLARE     @return_value int
            EXEC  @return_value = [dbo].[aspnet_UsersInRoles_AddUsersToRoles]
                        @ApplicationName = N'/',
                        @UserNames = N'j',
                        @RoleNames = N'Super Users',
                        @CurrentTimeUtc = N'1/1/2010'
            SELECT      'Return Value' = @return_value

7.    Now that username and password authentication has been set up, return to Workflow Studio with the SecureService sample open.  

8.   Right-click the web.config node in the Project tree and click Edit Security Configuration.

9.   In the Web.Config Security Configuration dialog box, select SQL Membership and Roles.

10.   Set the Connection String value to “Data Source=.Data Source=.\sqlexpress;Integrated Security=SSPI;Initial Catalog=aspnetdb;”

11.   Set the Membership Provider Connection String Name value to “SqlConn”

12.   Set the Membership Provider Application Name value to “MembershipAndRoleProviderSample”

13.   Set the Role Provider Connection String Name value to “SqlConn”

14.   Set the Role Provider Application Name value to “MembershipAndRoleProviderSample”

15.   Click OK and Workflow Studio will update the web.config of the SecureService sample.

16.   Publish the project to the server.

17.   Run the Document Conversion Client.

18.   In the list of services, select Secure Service.

19.  In the Authentication Credentials area at the top of the Document Conversion Client dialog box, click Username and enter “JohnDoe” for the Username value and “JD” for the password value.

20.   Click Start Conversion. This will launch a new instance of the Secure Service which will attempt to communicate with the newly published version that has been configured for Username and Password Authentication. SQL Authentication should now deny access to the service. You will see a slightly different error message informing you access was denied, confirming SQL Membership and Roles is active in the service.


WorkflowStudio->MainWindow.xaml.cs: The EditConfigSecurityCmdExecuted method controls the display of the dialog and applies the requisite configuration changes to the local web.config.