Windows WorkFlow Foundation

Posted: June 11, 2008 in General Tech

Windows Workflow:
This is a framework for building workflow into applications. Workflow are set of activities that co-ordinate work or activities. Activities are the basic building blocks of Workflows. The primary activity or root activity which mainly comprises of basic workflow activity is called WorkFlow definition which inturn maintains activity tree comprising of all other activities. The root activity can be sequential activity or a state machine activity.
Remoting concepts :
· Marshal by value: the server creates a copy of the object passes the copy to the client.
· Marshal by reference: the client creates a proxy for the object and then uses the proxy to access the object.
Workflows are :
1. Stateful – Application state is maintained.
2. Long running
3. Flexible Control Flow – can be sequential or rule based.
4. Transparent
Biztalk is used for B2B scenarios. It is a Server.
WF is a programming framework and is used for defining workflow and is exposed via WinFx.
Future version of BizTalk will use WF for orchestration. Orchestration in BizTalk refers to defining business processes or workflows. BizTalk is designed for multiple applications (B2B scenarios) use while BizTalk is designed for single application use.
Workflows run in a Host process (Application or Server).
WF Components:
1. Base Activity Library : Out of box activities as well as base classes for building custom acitivites.
2. Runtime Engine : State management and workflow execution environment. Have Instance Manager, Tracking infrastructure and Activity scheduler.
3. Runtime Services : Hosting flexibility and communication. Out of Box runtime services support transactions, persistence, tracking and require SQL Server.

· Timer Services : Manages timers (Ex: delay)
· Persistence Services : Stores and retrieves instance state.
· Tracking Services : Manages profiles and stores tracked information.
· Threading Services
· Transaction Services

4. Visual Designer : VS.Net IDE
WorkFlows may be defined in code or XAML.
· There are two main kinds of workflows:
o Sequential: Its actions are executed in some predefined order with a beginning and an end. Examples of sequential workflows may include installations.
o State machines: These workflows don’t have a path, but it’s represented as a set of states and transitions between states. External events and rules drive processing order.
o Rule Based : Is rule based. Can have sequential or state machines as root activity. These have conditions and based on that decision will be taken,
WorkFlow Authoring Modes :
1. Code
2. Xaml
3. Xaml and Code
WorkFlow Compiler (wfc.exe) – Workflow constructor defines structure of the workflow.
Code / Xaml à WorkFlow Compiler à Dotnet Language compiler -àWorkFlow Runtime
Activity Class : Initialize(), Execute(), Cancel() and Close() methods. When WorkFlow runtime loads, it has Activity tree in memory.
By default, the WF runtime engine will execute the workflow asynchronously, which is not desirable in this simple example. To avoid that, you block that thread through a AutoResetEvent object and wait for workflow to complete.
Workflow can accept parameters in the form of a Dictionary object.
Out-of-box services are provided that support SQL Server. SQL Persistence and SQL tracking services are examples for this.
Exceptions are handled using FaultHandlers. We need to implement FaultHandler Activity.
Sequence Activity is a Composite activity. Delay activity is an example of Basic activity.
WF Runtime : There can be one workflow instance per App Domain. WorkFlow Instance will interact with WorkFlow Service Layer and has WorkFlowRuntime within (which has Activites tree in memory and also manages state management). WorkFlows are identied by a GUID and we can use GetWorkFlow() method and get a WorkFlow if we supply the GUID. WorkFlow Instance will have WorkFlowRuntime within it.
WorkFlow events :
Started, Stopped, WorkFlowCompleted, WorkFlowTerminated, WorkFlowIdled.
WorkFlowInstance :
WorkFlowRuntime.GetWorkFlow(instanceid) – Will get the WorkFlow Instance.
WorkFlow Instance methods : Start, Suspend, Terminate, ApplyWorkflowChanges, GetWorkflowDefinition, Resume
WorkFlow Instance Status :
The Base activity class exposed ActivityExecutionStatus enum which determines the status of the entire WorkFlow instance.
ActivityExecutionStatus : Cancelling, Closed, Compensating (Transaction has failed and compensation has to be initiated), Executing, Faulting and Initialized.
ExecutionResult : Gives the status of the last run of the WorkFlow. Possible values are Canceled, Faulted, Succeeded, Compensated and None.
Dehydration and Rehydration : If a workflow has large number of tasks executing, you can unload tasks and store the necessary context information in SQL Server. The goal is to unload some tasks and store them in SQL server temporarily and reload them when time is right.
Activities :
Single task within workflow. Grouped into Basic and Composite.
ActivityExecutonContext Object : Provide activity with methods and services tied to WorkFlow instance such as initialization, timers and general execution flow. It represents the execution environment of the Activity. It is similar to HttpContext object of ASP.Net which (Encapsulates all HTTP-specific information about an individual HTTP request.).
Dependency properties :
Allow different activites to reference to the same property.WF ActivityBind class facilitates the same for us. .Net Runtime gives us platform to use Dependency Property.
State Machines : Consists of State Activity. Each State Activity is a composite activity. State Machines need to have InitialState and FinalState. Completed State do not have any events. Event driven Activity can only have a receive event or a delay.
Events can be attached to composite State as well.
StateMachineWorkFlowInstance is wrapper around WorkFlowInstance class which gives details about StateMachine.

Make use of “SetState” activity (SetState API) to reset to any state within the StateMachine. This is WF way of dynamically changing State Activity.
WorkFlow Tracking :
There are certaing pluggable and optional services which can be used with WorkFlows such as Tracking Service, Queuing Service, Runtime Service, Scheduler Service, Transaction Service.
WorkFlow can be tracked using SqlTrackingService which can be used to track WorkFlows . Track data can be workflow, activity or user data. We can use SqlTrackingService or we can create our own custom services. Tracking also serve for auditing process.
Tracking architecture :
Tracking profiles defines events of interest..means of filtering events like which we want workflow events or activity events or user events. Tracking profile object can populated programmatically or through xml.
Tracking runtime sits between host application and Tracking Services. There is Tracking Store outside host application. Tracking Runtime requests for Tracking profiles from Tracking Services . The TrackingServices will return TrackingProfile to the TrackingRuntime. The TrackingRuntime will do the data and event filtering based on TrackingProfile and send it to the TrackingService through TrackingChannel which will be later written on the TrackingStore.

Loading and Unloading WorkFlow Instances :
WorkFlow Persistence Services : WF provides options to unload and reload workflow instances . WF ships with a pluggable service known as SqlWorkFlowPersistenceService that is designed to serialize and store WF instances in SQLServer database. When an assembly is idle for a while, which in this case occurs when the DelayActivity activity is executed, the Windows Workflow Foundation can persist your workflow to storage until it has to resume.
Workflow instances can be persisted in the following scenarios :
1. When the WF execution is completed.
2. When WF enters the idle state.
3. When we manually unload the WF instance.
We can control persistence by calling specific methods on the WorkFlowInstance object or allowing the WorkFlow to enter into idle state using Delay Activity. If the delay is executed and if the application has SqlWorkFlowPersistenceService plugged in, then the workflow runtime will automatically persist the workflow instance and recall it when the delay period expires.
WorkFlowInstance methods :
1. Load – loads the instance into memory from database.
2. TryUnLoad – does not block if it cannot be unloaded (persisted in database).
3. UnLoad – Blocks the current thread until the unload (persisted in database) is successful.
Retrieving WorkFlow tracking data :
We can use SqlTrackingQuery.GetWorkFlow(Guid instanceId) to get the WorkFlow instance tracking data.
Tracking User Data :
If we execute Activity.TrackData and set User key and User Data , this will go as User Events in dbo.UserEvent table.
Creating New Profiles : This will create a new TrackingProfile and also add Activity tracking point and Workflow tracking point. This can be done programmatically as well through XML by using TrackingProfileSerializer class. We can apply filters on tracking events.
Creating a new Custom Service : Inherit ICustomService interface and IChannelService interface and implement GetProfile and Send method.
Basic Activity Operations :
Code Conditions : The Code Condition refers to Boolean return value through ConditionalEventArgs argument.
Code Activity : Used to provide basic code execution within workflows. ExecuteCode should be set to the name of the method which should be run.
Throw Activity : Used for exception handling. When we throw expection, workflow Termination event will be executed and WorkFlow will be halted. We need to use combination of Throw and Fault Handlers.
If we do not set FaultType or Fault Property, we will get System Exception with message as ‘Fault Property Not Set”.Each FaultHandler is designed to handle only one fault i.e only one exception. Faults thrown by an activity can be only handled by parent.
By using throw and FaultHandlers, the workflow instance will get stopped . The advantage here is that we are handling the exception rather than leaving it to the WorkFlowRuntime to dispose it. If we want to continue processing even when exception occurs, we have to use try catch block inside activity code.
Compensation vs. Fault Handling
A typical scenario for compensation handling would be when an activity successfully completes, but an exception is thrown in another activity later in the workflow. Different than Fault Handling, we now want to cancel the completed work and not to undo any partial and unsuccessful work of the activity in which an exception has occurred.
The triggering of a compensation block is done by the workflow designer, and not only by the workflow runtime. This is done using the CompensateActivity
Suspend Activity :
Suspended means not currently executing but it not unloaded (persistence wont come into picture). We need to set Error string and this will be available throught the WorkFlowSuspended event handler. WorkFlow is in waiting state , waiting for some user action.
Terminate Activity :
Kills the WorkFlow instance. Can be handled using WorkFlowTerminated event.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s