• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Wwf
 

Wwf

on

  • 1,692 views

Windows WorkFlow Foundation Presentation

Windows WorkFlow Foundation Presentation

Statistics

Views

Total Views
1,692
Views on SlideShare
1,692
Embed Views
0

Actions

Likes
2
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

CC Attribution-NonCommercial LicenseCC Attribution-NonCommercial License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Th
  • Windows Workflow Foundation is a framework, not a language. It is cable to correctly handle persistence and compensation.
  • This slide was taken directly from the PDC slide decks from Microsoft. The key take-aways I want you to leave with today are the following: Workflows are a set of activities. Workflows run within a Host Process, which can be any application or server that you code. You can use the base activities and bases classes within the workflow framework to build your own activities that are specific to your business or domain. The components of the Windows Workflow Foundation are : The Base Activity Library - These are the out-of-the box activities and base classes to use when building your workflows and custom activities. The Runtime Engine – This is the workflow execution engine and state manager for workflows. The runtime is what is hosted within the Host Process and it controls all the workflows instantiated within that host process. The Runtime Services – The runtime is extensible by using runtime services. The services can be registered with the runtime to provide hosting flexibility and communication. For example, out of the box you can find the persistence service and tracking service which allows you to persist your workflow state to a SQL data store and track you workflow process. You can create your own services to provide more communication options between the host process and the workflows, or you can even replace a provided service if you want. For example, you could provide your own persistence service that persists the workflows to a file based store rather than a SQL Server based store. Finally, the Visual Designer – This is the developer experience for WF. This designer is integrated with Visual Studio 2005 and allows for developers to easily map out and navigate workflows. The designer can also be hosted within your own application so that you can expose it to end users so that they can modify workflows on the fly.
  • Activities are added to a workflow programmatically in a manner similar to adding XML DOM child nodes to a root node.
  • A key advantage of defining your logic with rules and declarative conditions is that they can be modified at run time by doing dynamic updates using workflow changes. In addition, rules let you separate your business logic from a workflow in order to share those rules with other workflows. Finally, defining business logic in rules allows for advanced tools, such as dependency visualization and impact analysis tools, to be built on top of the object model.
  • Host process can be a console, Win Forms, ASP.NET or Web service etc.,
  • Workflow markup is based on XAML . It enables the developers and designers to model business logic declaratively. With this declarative model, it can also possible to activate workflow by directly loading a workflow markup file into the workflow runtime engine at runtime.
  • If you use custom activities in your workflow markup code, the assembly containing your custom activity must be referenced through a type provider in your code. TypeProvider typeProvider = new TypeProvider(null); typeProvider. AddAssembly (typeof(CustomActivity).Assembly); workflowRuntime.AddService(typeProvider); In addition to code you can reference these custom assemblies from markup also: < SequentialWorkflowActivity x:Class ="XAMLWorkflow.Workflow1" x:Name ="Workflow1" xmlns:ns0 ="clr-namespace:BusinessActivities; Assembly =CustomActivityAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" "> To start workflow: WorkflowInstance instance = workflowRuntime.CreateWorkflow(workflowDefinitionReader); instance.Start();
  • Activities are the fundamental building blocks of workflows. A workflow is a set of activities that are organized hierarchically in a tree structure. An activity represents an action in a workflow. It can be a simple action such as a delay, or it can be a composite activity that consists of several child activities. Once the activity Execute method returned the Closed value of ActivityExecutionStatus. Then runtime claims this activity for disposing. If you return Closed value of this enumerator then that activity will be claimed for disposing. If returns Executing indicates to runtime that activity have extra work to do.
  • In Sequential activity the order of its actions is specified its design time. In Event-driven activity the order of its actions is determined at runtime in response to external events.
  • To call a method in the host application from the workflow you can use the CallExternalMethodActivity activity. Used with the HandleExternalEventActivity activity for input and output communications with a local service CancellationHandlerActivity: Used to contain cleanup logic for a composite activity that is canceled before all the composite activity's child activities are finished executing. CodeActivity : Enables you to add Visual Basic or C# code to your workflow. CompensatableSequenceActivity : Compensatable version of SequenceActivity. CompensatableTransactionScopeActivity : Compensatable version of TransactionScopeActivity. CompensateActivity: Enables you to call code to undo or to compensate for operations already performed by the workflow when an error occurs . CompensationHandlerActivity: Wrapper for one or more activities that perform compensation for a completed TransactionScopeActivity activity. ConditionedActivityGroup : Executes child activities based on a condition that applies to the ConditionedActivityGroup activity itself and based on conditions that apply separately to each child. DelayActivity : Enables you to build delays in your workflow based on a time-out interval. Its job is to wait for a predefined time before continuing the execution of workflow.
  • EventDrivenActivity : Wraps one or more activities that are executed when a specified event occurs. EventHandlersActivity: Provides a framework for associating events with an activity. EventHandlingScopeActivity : Executes its main child activity concurrently with an EventHandlersActivity activity. FaultHandlerActivity: Used to handle an exception of a type that you specify FaultHandlersActivity : Represents a composite activity that has an ordered list of child activities of type FaultHandlerActivity. HandleExternalEventActivity: Used together with the CallExternalMethodActivity activity for input and output communications with a local service. IfElseActivity : Tests a condition on each branch and performs activities on the first branch for which the condition equals true . It is similar to if-else statements in C#. IfElseBranchActivity : Represents a branch of an IfElseActivity activity InvokeWebServiceActivity: Enables your workflow to invoke a Web service. InvokeWorkflowActivity : Enables your workflow to invoke another workflow. ListenActivity: It is a composite activity that contains only EventDrivenActivity child activities. ParallelActivity : Lets you schedule two or more child SequenceActivity activity branches for processing at the same time. PolicyActivity : Used to represent a collection of rules. A rule consists of conditions and resulting actions ReplicatorActivity : Creates multiple instances of a single child activity.
  • SequenceActivity : Provides a simple way to link multiple activities together for sequential execution. SetStateActivity : Specifies transition to new state. StateActivity: Represents a state in a state machine workflow. StateFinalizationActivity : Used in a StateActivity activity as a container for child activities executed when leaving the StateActivity activity. StateInitializationActivity: Used in a StateActivity activity as a container for child activities executed when entering the StateActivity activity. SuspendActivity : Suspends the operation of your workflow to enable intervention in the event of some error condition that requires special attention. SynchronizationScopeActivity : Executes contained activities sequentially in a synchronized domain. TerminateActivity : Enables you to immediately end the operation of your workflow in the event of an error condition. ThrowActivity : Enables you to capture business exceptions thrown as part of the process metadata for a workflow. TransactionScopeActivity: Provides a framework for transactions and exception handling WebServiceFaultActivity: Lets you model the occurrence of a Web service fault. WebServiceInputActivity: Receives data from a Web service WebServiceOutputActivity: Responds to a Web service request made to a workflow WhileActivity: Enables your workflow to loop until a condition is met,
  • AEC stands for ActivityExecutionContext . AES stadns for ActivityExecutionStatus. Most of the activities do nothing in the Initialized state. If you want you can make any initialization setup for your activity. The solid red line represents the workflow runtime engine is responsible for transitioning an activity from the Initialized state to the Executing state, or transitioning from the Closed state to the Compensating state. The solid yellow line represents the parent activity is responsible for transitioning a child activity from the Executing state to the Closed state. If you create a custom composite activity, you must handle this yourself. The solid blue line represents the workflow runtime engine is responsible for transitioning an activity from the Executing , Canceling , or Compensating state to the Faulting state. The dashed yellow line represents the workflow runtime engine is responsible for transitioning an activity from either the Canceling state, Compensating state, or Faulting state to the Closed state. An activity can’t move from closed state to executing state . Any attempt by calling Execute() method from closed state will cause an exception. An activity may only close when all children activities are either in their Closed or Initialized states. Because this is a recursive rule, it means that the entire tree below an activity, which is attempting to close, must be Closed or Initialized for the call to succeed.
  • An activity execution context is similar to an HTTP context in that an object has a state, a set of parameters, and constructs that are unique to that given object for that given point in time. The Execute, Cancel and Close state are the only execution status changes that a parent activity can control through the AEC. All other activity states are controlled by the workflow runtime engine. An activity can only close when all spawned execution contexts (CreateExecutionContext) have been completed (CompleteExecutionContext). Violation of this behavior causes an exception to be thrown by the workflow runtime engine.
  • Metadata is related to activities in the same way that attributes are related to .NET Framework classes. Metadata is only configurable at design time and, once an activity is built, cannot be changed System.Workflow.ComponentModel.Activity.Name is a metadata because the name of an activity in a workflow's tree is part of the definition of the workflow. Instance data, on the other hand, maps to properties and fields on classes. In certain cases, you need an activity to register a property that can be used by other activities in a workflow. This kind of property is called an attached property , Attached Property is a specialized form of dependency property. You register an attached property using the RegisterAttached() method of the DependencyProperty class.
  • Custom activities can also be extended to have their own look and feel within the designer and contain their own validation code of for the smart tags (Like the code shape warned us we needed to set the execute code handler). These are done with companion classes. You create a companion class and use an attribute on the activity class to link the two.
  • WWF is flexible and extensible. The sequential workflow style is straightforward and useful for repetitive, predictable operations that are always the same. The state machine workflow style consists of a set of event-driven states. The data-driven workflow style relies on data to determine whether or not certain activities are run based on a local data state. When you start the runtime, it can then reload any workflow instances that were executing the last time the application was executed by reading these instances from the persistence store . To support this persistence store it need to support persistence service also.
  • In host application, you must create an instance of this class and pass the type specification of your workflow by using the CreateWorkflow() method.
  • Simply like .NET or C, C++ methods parameter passing is not allowed for workflows. Let us assume your workflow have properties such as Salary . Then in dictionary of name-value pairs the name should be Salary and value should be corresponding val. If the a parameter match is found then the property setter is called and the value of the parameter is passed to this setter.
  • The durability means workflows can be unloaded from memory while awaiting input and serialized into a persistent store, such as a SQL database or XML file. Whenever the input is received, the workflow runtime engine loads the workflow state information back into memory and continues execution of the workflow. With a custom activity serializer, you can decide which members are serialized and how they are serialized . This determines if those members are visible or hidden in a workflow designer.
  • WorkflowMarkupSerializer: This is the base serialization type used in the serialization infrastructure. This type provides some of the basic services for serialization that implement the serialization rules. The serializers for activities or any other custom serializers for custom activities must inherit from this class. ActivityMarkupSerializer : Inherits from the WorkflowMarkupSerializer class. This type is used to serialize all basic activities. These are activities that are not composite activities. CompositeActivityMarkupSerializer: Inherits from the ActivityMarkupSerializer class and provides the serialization for composite activities. CompositeActivityMarkupSerializer adds more methods to process child activities, which can be serialized using their own serialization providers. If you create a custom serializer, activity authors must provide a reference to the custom serializer as illustrated in the following code example. [ DesignerSerialize r(typeof(ExampleActivityMarkupSerializer), typeof(WorkflowMarkupSerializer))] public class ExampleActivity : Activity { } The first parameter specifies the serializer that should be used to serialize the instance of the class on which the attribute has been defined. The second parameter specifies the base type of the serializer. The base type of the serializer specifies the serialization scheme to use.
  • Persistence service , which stores the execution details of a workflow instance in a SQL database An example of creating custom service is : creating a persistence service that uses an XML file instead of a database for storage. Windows Workflow Foundation provides the SqlWorkflowPersistenceService that integrates well with Microsoft SQL Server 2005 Express, SQL Server 2000 or later, or SQL Server 2000 Desktop Engine (MSDE) to persist workflow information easily and efficiently.
  • By using this performance monitor tool , you can configure performance counters to record performance data and set system alerts to notify you when a specified counter's value is above or below defined threshold. < CustomWorkflowRuntimeSettings Name="Workflow1" EnablePerformanceCounters ="false"> <!-- Define common parameters and declare services required for your workflow runtime -->
  • The configuration file can be app.config or web.config according to host application.
  • Config section full description is shown below < MyWFRuntimeConfig Name="SampleApplication">
  • All Logs all messages received Off Does not log any messages Critical Logs only messages deemed as critical Error Logs critical and error messages Warning Logs critical, error and warning messages Information Logs critical, error, warning and information messages VerboseLogs Critical, error, warning, information and verbose messages

Wwf Wwf Presentation Transcript

  • Windows Workflow Foundation Ch. Vishwa Mohan Freelance Software Consultant & Corporate Trainer
  • Table of Contents
    • Introduction to Workflow Foundation
    • Workflow Activities
    • Workflows & Workflow Runtime
    • Building Sequential Workflows
    • Communication with the Host
    • Custom Activities
    • State Machine Workflows
    • Using Transactions
    • Web Services and Workflows
    • WCF Services and Workflows
    • Policies and Rule Sets
    • Updating Workflows Dynamically
    • Windows Workflow Foundation Services
    • Embedding the Workflow Designer
  • Introduction to Workflow Foundation
  • WWF Overview
    • Windows Workflow Foundation (WWF) is the programming model, engine, and tools for quickly building workflow-enabled applications on Windows.
      • Workflow provides a model where you can define and execute processes using a set of building blocks called activities .
    • Some of the scenarios of Windows Workflow Foundation includes:
      • Enabling work-flow within the line of business applications.
      • User-interface page flows.
      • Document-centric workflow.
      • Human workflows.
      • Composite workflows for Service-oriented applications.
      • Business rule-driven workflows.
      • Workflow for systems management.
    • WWF provides a consistent and familiar development experience.
      • The WWF API provides fully support for VB.NET and C#.
      • A specialized workflow compiler and debugger to debug within workflow.
      • A graphical workflow designer.
      • Facility to develop your workflow completely in code or in markup.
    • Windows Workflow Foundation is a framework , not a language . It is cable to correctly handle persistence and compensation .
  • Workflow Overview
    • A workflow is a set of elemental units called activities that are stored as a model that describes real-world processes.
      • Workflows provides a way of describing the order of execution and dependent relationships between pieces of short-or long running work.
      • Here activities might be executed by people or by system functions.
    • Every running workflow instance is created and maintained by an in-process runtime engine referred to as the Workflow Runtime Engine .
      • There can be several workflow runtime engines within an application domain .
      • Also each instance of the runtime engine can support multiple workflow instances running concurrently. ( Here workflow runtime deals scheduling these instances ).
    • When a workflow model is compiled, it can be executed inside any windows process includes: ( Because a workflow hosted in a process ).
      • Console application.
      • Windows Forms based applications.
      • Windows Services.
      • ASP.NET Web Sites
      • ASP.NET Web Services.
    • A workflow can easily communicate with its host application.
  • Host Process Windows Workflow Foundation Runtime Engine A Workflow An Activity Runtime Services Base Activity Library Custom Activity Library Visual Designer WWF Architecture
    • Key Concepts:
      • Workflows are set of activities .
      • Workflows run within a HostProcess .
      • Developers can build their own custom activity libraries .
    • Components:
      • Base Activity Library : Out-of-box activities and base for custom activities.
      • Runtime Engine : Workflow execution and State management
      • Runtime Services : Hosting flexibility and communication.
      • Visual Designer : Graphical and code based construction.
  • What is an Activity ?
    • Activities are the elemental unit of a workflow.
      • An activity can perform a single action ( Eg: Writing a value to DB or sending an email ) or it can be a composite activity and consists of set of activities.
    • Activities have two types of behavior:
      • Runtime : It specifies the actions upon execution.
      • Design Time : It controls the appearance of the activity and its interaction while being displayed within the designer.
    • Activities are executed according to given flow path . When all the activities are finished running, the working flow instance is completed its execution.
    • WWF framework consists a library of in-built activities also provides the mechanism for you to create your own activities; so it enables extensibility & reusability between workflows. Some of the framework in-built activities are:
      • CallExternalMethodActivity
      • IfElseActivity,
      • IfElseBranchActivity
      • CodeActivity
      • FaultHandlersActivity, etc…,
  • Workflow Rules & Conditions
    • WWF can implement business logic as either rule or conditions . Conditions are used by one of the following activities to control activity execution.
      • IfElseBranchActivity
      • ConditionedActivityGroup
      • WhileActivity
      • ReplicatorActivity
    • Here conditions are expressed as declarative or defined in code .
      • Declarative conditions are created as code DOM statements in the “ .rules” file.
      • Code-based conditions reference a method in the workflow’s code file that returns its result through Result property.
    • Rules , like conditions , are expressed as code DOM statements, and are collected in the rules XML file.
      • Here Rules include a condition statement and collection of actions which are performed based on the Result of the conditions.
      • Rules are collected into rule sets , which support both simple sequential execution of rules , and sophisticated forward-chaining of rules .
    • Rule sets are executed by the PolicyActivity activity.
  • Fault Handling
    • Exceptions that occur in activities are handled asynchronously by workflow runtime engine in a process called fault handling .
      • Exceptions are scheduled in a queue to be handled later. If the exception type matches the one that is handled by a particular FaultHandlerActivity activity, that activity will handle the exception.
      • All the unhandled exceptions is bubbled up through parent activities until it ultimately causes the termination of workflow instance.
  • Building Host to Run Workflows
    • The WWF runtime engine is responsible for creating and maintaining running workflow instances.
      • The runtime engine will be executed inside a host process .
      • The default mechanism for initializing WWF is to use the WorkflowRuntime class.
      • WorkflowRuntime wfRuntime = new WorkflowRuntime( );
      • Once runtime instance is created you can subscribe for events those are raised by runtime engine also can configure any services used by runtime engine.
      • wfRuntime. WorkflowCompleted += OnWorkflowCompleted;
      • wfRuntime. WorkflowTerminated += OnWorkflowTerminated;
      • //Now add the services used by runtime.
      • wfRuntime. AddService (new SqlTrackingService(conn)):
      • Finally, create and start workflow instance.
      • WorkflowInstance instance = wfRuntime. CreateWorkflow (typeof(MyWorkflow));
      • instance. Start() ;
      • To remove the service from runtime you can use RemoveSerice() method. Make sure runtime service is stopped ( i.e., not executing ). runtime. RemoveService (SqlTrackingService);
  • Creating Workflow By Code
    • To create a Workflow programmatically as follows:
      • Create a console application in Visual Studio.
      • Add the following libraries to references of your project.
        • System.Workflow.Activities
        • System.Workflow.ComponentModel
        • System.Workflow.Runtime
      • Add a class file to your project and name the file as HelloWorld.cs . Now name the class name as HelloWorld and derived it from SequentialWorkflowActivity .
      • class HelloWorld : SequentialWorkflowActivity { }
      • In this class, declare a private variable of type CodeActivity .
      • private CodeActivity helloWorldActivity;
      • Now define a public constructor in this class and initialize CodeActivity instance in this constructor also associate code handler and add it to workflow.
      • this.helloWorldActivity = new System.Workflow.Activities. CodeActivity ();
      • this.helloWorldActivity. Name = "HelloWorldActivity";
      • this.helloWorldActivity. ExecuteCode += new EventHandler(this. My HelloWorld);
      • Finally implement the MyHelloWorld event handler in your class:
      • private void My HelloWorld(object sender, EventArgs e) { }
    • The complete code inside your workflow class Constructor is :
    • this. CanModifyActivities = true ;
    • this. Name = "MyHelloWorldWorkflow";
    • this.helloWorldActivity = new System.Workflow.Activities. CodeActivity ();
    • this.helloWorldActivity. Name = "HelloWorldActivity";
    • this.helloWorldActivity. ExecuteCode += ne w EventHandler(this.HelloWorld);
    • this.Activities. Add (this. helloWorldActivity );
    • this. CanModifyActivities = false ;
  • Creating Workflow By Code
    • The next step in creating and executing workflow is load your workflow by workflow runtime and execute it.
      • In your project Program.cs file, within the main function create instance of WorkflowRuntime and create workflow instance as follow:
      • using ( WorkflowRuntime workflowRuntime = new WorkflowRuntime () ) {
      • AutoResetEvent waitHandle = new AutoResetEvent ( false );
      • workflowRuntime. WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { waitHandle.Set(); };
      • WorkflowInstance instance = workflowRuntime. CreateWorkflow (typeof(HelloWorldApp.HelloWorld));
      • instance. Start ();
      • waitHandle.WaitOne();
      • }
  • Creating Workflow By Markup
    • In addition to programmatically developing workflow, WWF also allows declarative way to create workflows by using XAML .
      • These markup files can be compiled into a workflow type and loaded directly into the workflow runtime engine at runtime.
      • In addition they can also be compiled into a workflow type with code-behind files.
      • You can also use rules & rule conditions in markup.
    • With the help of this markup language, in addition to creating workflows, you can also persist workflows by using WorkflowPersistanceService .
      • When programmatic workflows are serialized with the WorkflowMarkupSerializer , they become workflow markup.
  • Creating Workflow By Markup
    • The basic structure of the workflow markup contains the root node , followed by the child activities in that workflow as nested sub elements.
      • Here root node represents the type of workflow (Eg: Sequential, State Machine).
      • Each element in the workflow is represented as nodes of either composite activities or the workflow itself.
      • Each element in a workflow markup file corresponds to a workflow component.
      • XAML also provides the ability to insert procedural code within a workflow markup using the x:Code directive element. ( Code must be in CDATA section).
    • If you use custom activities in your workflow markup code, then you need to reference the custom activity assembly in markup code as follows:
    • < SequentialWorkflowActivity x: Class =&quot;XAMLWorkflow.Workflow1&quot; x: Name =&quot;Workflow1&quot;
    • xmlns:ns0=&quot;Assembly=CustomActivityAssembly”>
    • <ns0: CustomActivity x: Name =&quot;CustomActivity1&quot;/>
    • </ SequentialWorkflowActivity >
    • To start workflow instance from markup file create XmlReader object contain markup file and pass it to CreateWorkflow() method of WorkflowRuntime . Finally call Start() method on WorkflowInstance object.
    • The IfElseActivity is represented in markup by the <IfElseActivity> element.
    • Example of code in markup file:
    • < CodeActivity x:Name=&quot;codeActivity1“ ExecuteCode=“MyMethod&quot;>
    • <x:Code><![ CDATA [
    • void MyMethod(object sender, EventArgs e) { }
    • ]]></x:Code>
    • </ CodeActivity >
  • Workflow Activities
  • Introduction to Activities
    • Everything in a workflow is an activity . In WWF the activity is just a class that ultimately derived from the Activity class.
      • Activity class defines a number of overridable methods (Eg: Cancel , Dispose, HandleFault, Execute ) and the most important of these methods is the Execute() .
      • override ActivityExecutionStatus Execute ( ActivityExecutionContext context ) {
      • return ActivityExecutionStatus.Closed ;
      • }
      • When the runtime schedules the activity for execution, the Execute() method is ultimately called. ( Here you can write your custom code ).
      • The Execute() method return type is ActivityExeuctionStatus ( AES ). This enumeration values represents the status of activity instance within workflow instance. The possible values of ActivityExecutionStatus enumeration are:
        • Initializing
        • Executing
        • Canceling
        • Closed
        • Compensating
        • Faulting
    • These values used by runtime to determine whether the activity has completed successfully, is still processing or one of the other possible states.
  • Activities Types
    • There are two main types of Activities:
      • Simple Activities : Activities those are derived from Activity class can be thought of as callable functions ( i.e., Execute , Cancel, etc.,) from the workflow.
      • Composite Activities : Activities that are derived from CompositeActivity class. These activities are container for other activities. These activities design time behavior is considerable different from Simple activities. ( Eg: ParallelActivity, IfElseActivity, ListenActivity ).
    • Like workflow, an activity can be sequential or it can be event-driven .
  • Predefined Activities
    • The WWF framework provides several predefined activities. These activities provides functionality for control flow, conditions, event handling, state management and communication with application and services.
      • All these activities are defined in System.Workflow.Activities namespace.
      • The naming conversions for activities is to append Activity to activity name.
    • The below is a list of WWF defined in built activities listed alphabetical order:
      • CallExternalMethodActivity
      • CancellationHandlerActivity
      • CodeActivity
      • CompensatableSequenceActivity
      • CompensatableTransactionScopeActivity
      • CompensateActivity
      • CompensationHandlerActivity
      • ConditionedActivityGroup
      • DelayActivity
  • Predefined Activities
    • The below is a list of WWF defined in built activities listed alphabetical order:
      • EventDrivenActivity
      • EventHandlersActivity
      • EventHandlingScopeActivity
      • FaultHandlerActivity
      • FaultHandlersActivity
      • HandleExternalEventActivity
      • IfElseActivity,
      • IfElseBrachActivity
      • InvokeWebServiceActivity
      • InvokeWorkflowActivity
      • ListenActivity
      • ParallelActivity
      • PolicyActivity
      • ReplicatorActivity
  • Predefined Activities
    • The below is a list of WWF defined in built activities listed alphabetical order:
      • SequenceActivity
      • SetStateActivity
      • StateActivity
      • StateFinalizationActivity
      • StateInitializationActivity
      • SuspendActivity
      • SynchronizationScopeActivity
      • TerminateActivity
      • ThrowActivity
      • TransactionScopeActivity
      • WebServiceFaultActivity
      • WebServiceInputActivity
      • WebServiceOutputActivity
      • WhileActivity
  • Activity Execution Model
    • An activity may go through six different states it its lifetime:
    • An activity goes to initialized state when the Workflow runtime calls the activities Initialize() method. AEC created here.
    • Next runtime calls the Exeucte() method of activity. Here your activity enters into Executing state. Primary functionality performed here at this stage. It can return any one of the values of AES enumerator.
    • An activity is put into the Canceling state by a parent activity explicitly, or because an exception in executing activity.
    • The Closed state is the last and final state of an activity .
    • From Closed states if your business logic demands it can goes to Compensating sate and return back to Closed state.
    • If an exception is thrown during executing, compensating and canceling state then transmit to Faulting state.
    • An activity can’t move from Closed state to Executing state.
    • An activity may only close when all children activities are either in their Closed or Initialized states.
  • Activity Execution Context
    • Every activity has an activity execution context that represents the execution environment of the activity.
      • An ActivityExecutionContext (AEC) is the execution environment that is created for an activity when the host application calls the Start() method.
      • The ActivityExecutionContext (AEC) provides a composite activity with the ability to execute ( ExecuteActivity() ) or Cancel ( CancelActivity() ) a child activity. It can also close itself through the CloseActivity() method. Remaining all other activity states are controlled by the workflow runtime.
      • The AEC has a property called ExecutionContextManager that enables it to generate new AECs. These AECs are generated every time a parent activity, such as a WhileActivity , ReplicatorActivity , or ConditionedActivityGroup activity, runs its child activities more than once.
      • Certain composite activities, such as ReplicatorActivity , WhileActivity activities, create multiple instances of their child activities during execution, and each child activity has its own execution context that it runs in.
      • Every activity also transitions through various states during its lifetime. Some transitions are controlled by the workflow runtime engine , while others can be user controlled.
  • Activity Properties
    • There are two types of activity properties:
      • Meta Properties: These properties are immutable at runtime, so the properties must be set to a literal value at design time. (Eg: Name property of Activity).
      • Instance Properties: These properties can be set at design time, or the property can be bound to instance data. ( Eg: Error string on a SuspendActivity ).
        • If the property is bound to instance data, in which case the actual value is not determined until runtime.
        • These properties can also be modified directly during workflow execution.
    • The dependency properties provide a centralized repository of a workflow's state. It is basically a hash table.
    • An attached property is one the property is defined in one class/activity but used on another activity or class. These properties are specialized form of dependency properties .
      • Here you need to register the property. To register an attached property you can use RegisterAttached() method of the DependencyProperty class.
  • Activity Companion Classes
    • Activity also have companion classes:
    • The additional features are added to activities via attributes .
      • [ ToolboxItem (typeof(ActivityToolboxItem))]
      • [ Designer (typeof(MyDesigner))]
      • p ublic partial class MyActivity : Activity {
      • }
    Activity Designer Validator CodeGenerator Serializer
  • Workflows & Workflow Runtime
  • Workflows
    • You can write workflows directly in code , in markup or combination of both .
      • WWF enables model-driven workflow development , providing natural design visibility and hiding system-level concerns such as transactions , state management , and concurrency control .
    • The two primary facets of programming workflows:
      • Designing workflows and their activities.
      • Using workflows in your application.
    • A Workflow is simply a list of activities .
      • Each workflow instance is uniquely identified by its InstanceId property. This is a GUID and that can be assigned by the runtime.
      • The class responsible for executing workflow is the WorkflowRuntime class.
      • You can access your specific workflow from the runtime by using the GetWorkFlow( guid ) method of the WorkflowRuntime Class.
    • There are two types of Workflows available in WF.
      • Sequential Workflows
      • State Machine Workflows
      • Data-driven Workflows
    • Workflow itself is just another type of activity.
  • Workflow Runtime
    • A Workflow doesn’t exists on its own. A workflow is always executed within the context of workflow runtime .
      • This runtime support is available by instantiating the WorkflowRuntime class.
      • The workflow runtime contains methods to construct instances of workflows.
      • There are six various CreateWorkflow() methods used to construct the workflow instances, These methods returns the workflow instance object.
        • In addition runtime also contains methods for reloading a workflow instance and enumerating all running instances.
      • To start running your workflow, you need to call Start() method from the returned WorkflowInstance object. Because sequential workflow doesn’t rely on an external event to run, it begins immediately.
      • The workflow runtime also supports number of events that are raised while workflows are executing. The events are:
        • WorkflowCreated : Raised when new workflow instance is constructed.
        • WorkflowIdled : Raised when a workflow is awaiting input.
        • WorkflowCompleted: This event is raised when the workflow has finished.
  • Events Raised by WWF Runtime
    • The following table lists the events that can be raised by the Workflow runtime engine that pertain to the workflow runtime engine itself are:
      • ServicesExceptionNotHandled
      • Started
      • Stopped
    • The following events are the workflow instance events that can be raised by the workflow runtime engine .
      • WorkflowAborted
      • WorkflowCompleted
      • WorkflowCreated
      • WorkflowIdled
      • WorkflowLoaded
      • WorkflowPersisted
      • WorkflowResumed
      • WorkflowStarted
      • WorkflowSuspended
      • WorkflowTerminated
      • WorkflowUnloaded
  • Passing Parameters to Workflow
    • Passing parameters to workflow is some what different.
      • To pass parameters by storing them in a dictionary of name-value pairs and when you construct workflow you pass through this dictionary.
      • Dictionary <string, object> parms = new Dictionary <string, object>();
      • params . Add (“OrderID”, 12345);
      • WorkflowInstance myWorkflow = wfRuntime. CreateWorkflow (typeof( MyWorkflow ), parms );
      • In name-value pair, the name should match to any one of the public property of workflow. When the name doesn’t correspond to any one of public property on the workflow, then an exception will be thrown.
    • Once parameters passed to workflow you need to link these parameters to activities . The process of linking is called binding .
      • A bindable property is displayed in the property grid within Visual Studio. By double-clicking on the bind icon on this property grid display a dialog box allows you to select an appropriate property to link to this property.
  • Returning Result from Workflow
    • When a workflow finishes its execution, the workflow runtime raises the WorkflowCompleted event.
      • For this completed event handler the contextual information about the workflow is passed. It contains the data from that workflow.
      • private void MyWorkflowCompleted(object sender, EventArgs e) {
      • WorkflowCompletedEventArgs we = e as WorkflowCompletedEventArgs;
      • KeyValuePair <string, object> parms = we. OutputParameters ;
      • //By iterating params you will get the multiple return values from workflow.
      • }
  • Characteristics of Workflow
    • In workflows, Tracking is the ability to specify and capture information about workflow instances and store that information as the instances execute.
      • WWF provides the SqlTrackingService , it stores the collected tracking information in SQL database.
      • In addition you can also write your own tracking service also.
      • When a new workflow is created, the tracking service requests a tracking channel to be associated with that workflow.
      • All tracking information from the workflow is then sent to this tracking channel.
      • The tracking service can track three types of events:
        • Workflow Instance Events,
        • Activity events
        • User Events.
      • In addition you can also configure type and amount of information that your service wants to receive for a particular workflow instance or type of workflow by providing a tracking profile .
  • Characteristics of Workflow
    • Activities can be a compensatable activity.
      • Compensation is the act of undoing any actions that were performed by a successfully completed compensatable activity because of an exception in a workflow.
    • WWF framework simplifies the process of creating stateful, long-running , persistent workflow applications.
      • The workflow runtime engine manages workflow execution and enables workflows to remain active for long periods of time and survive application restarts. This durability is the key tenet of WWF.
    • Workflows, activities, and rules can be serialized and deserialized .
      • The serialization enables the workflow in workflow markup files, and view their properties, fields , and events in a workflow designer.
      • WWF provides default serialization capabilities for standard activities, or you can create your own serializer for custom activities.
    • WWF enables you to dynamically update your workflow instance and declarative rules during runtime. Before activities are scheduled for execution, you can change expected behavior, flow control and so on.
  • Serialization in Workflow
    • The WWF framework provides a serialization support that is used to serialize and deserialize workflows.
      • WWF provides default serialization capabilities for standard activities, or you can create your own serializer for custom activities.
      • By default, a workflow is serialized to workflow markup .
      • Workflow markup is the serialized form of object hierarchies.
      • With DesignerSerializer attribute; specify custom serializer to custom activity.
    • WWF infrastructure provides the following classes to support serialization
      • WorkflowMarkupSerializer
      • ActivityMarkupSerializer
      • CompositeActivityMarkupSerializer
      • The serializers for activities or any other custom serializers for custom activities must inherit from WorkflowMarkupSerializer class.
      • ActivityMarkupSerializer class inherits from WorkflowMarkupSerializer . This serializer is used to serialize all basic activities ( i.e., not composite activities ).
      • CompositeActivityMarkupSerializer derived from ActivityMarkupSerializer class provides serialization for composite activities.
  • Services in Workflow
    • The workflow runtime engine uses many services when a workflow instance runs. Some of the services the runtime engine uses are:
      • Persistence Service
      • Scheduling Service
      • Transaction Service
      • Tracking Service
      • These service components are pluggable, which allows applications to provide these services in ways that are unique to their execution environment.
      • In addition, Workflow provided services you can also create custom services to extend the workflow foundation platform by deriving from base service classes .
    • Host processes can communicate with workflows by exchanging the data through custom local communication services .
      • Local communication services implement user-defined interfaces that defines methods & events that will be passed between the workflow and the host process
      • Host processes can also interact with a specific activity in a specific workflow instance by using a unique ID that is passed between the host process and the workflow as an event argument. This is known as correlation .
  • Workflow Performance Monitoring
    • You can monitor workflow performance by using Performance ( Perfmon.exe ) on Windows XP or Vista.
      • By using this performance monitor tool , you can configure performance counters to record performance data and set system alerts to notify you when a specified counter's value is above or below defined threshold.
      • WWF provides a set of performance counters with the WWF performance object that you can use to track the performance of the workflow runtime as it executes workflow instances. Some of the performance counters are:
        • Workflows Completed
        • Workflows Created
        • Workflows Created/sec
        • Workflows Executing
        • Workflows In Memory
      • WWF performance counters are enabled by default. You can disable them by either setting the EnablePerformanceCounters attribute to false in a workflow configuration file, or changing it programmatically in the WorkflowRuntimeSection class property EnablePerformanceCounters .
    <?xml version=&quot;1.0&quot;?> <configuration> <configSections> <section name=&quot; CustomWorkflowRuntimeSettings &quot; type=“xxx&quot; /> </configSections> < CustomWorkflowRuntimeSettings Name=&quot;Workflow1&quot; EnablePerformanceCounters =&quot;false&quot;> <!-- Define common parameters & declare services --> </CustomWorkflowRuntimeSettings> </configuration>
  • Workflow Configuration Files
    • WWF host application can use configuration files to control the behavior of a WorkflowRuntime object.
      • Within the configuration file crate a configuration section as shown below:
      • <configuration>
      • < configSections >
      • < section name =“ MyWFRuntimeConfig &quot; type =&quot;System.Workflow.Runtime.Configuration.WorkflowRuntimeSection, System.Workflow.Runtime, Version=3.0.00000.0, Culture=neutral, PublicKeyToken 31bf3856ad364e35&quot; />
      • </ configSections >
      • </configuration>
      • Your configuration file can contain multiple configuration sections only one section is used during instantiation of WorkflowRuntime.
      • In this configuration, we are defining the services , when you create an instance of a WorkflowRuntime object these services are added to runtime. ( Next slide )
        • In addition to this configuration file we will add services programmatically also.
  • Workflow Configuration Files
    • Once the configuration section has declared now add the configuration information section to your configuration file as shown below:
      • < MyWFRuntimeConfig Name=&quot;SampleApplication&quot;>
      • < CommonParameters >
      • <add type =&quot;ConnectionString&quot; type =“SQL Connstring values&quot; />
      • </ CommonParameters >
      • < Services >
      • <add type =&quot;DefaultWorkflowSchedulerService&quot; maxQueuedWorkItems =&quot;20&quot;/>
      • <add type =&quot;SharedConnectionWorkflowTransactionService” />
      • <add type =&quot;SqlWorkflowPersistenceService” UnloadOnIdle =&quot;false&quot;/>
      • </ Services >
      • </ MyWFRuntimeConfig >
      • The CommonParameters element defines any parameters that are used globally across multiple services.
    • In your host application, while creating runtime object pass name of the configuration section as a parameter to the WorkflowRuntime constructor.
    • WorkflowRuntime runtime = new WorkflowRuntime(&quot; MyWFRuntimeConfig &quot;);
  • Enable Workflow Logging
    • Using the configuration file, you can output WWF logging information:
    • < system.diagnostics >
    • <switches>
    • <add name=&quot;System.Workflow LogToFile&quot; value=“All&quot; />
    • <add name=&quot;System.Workflow.Runtime&quot; value=&quot;All&quot; />
    • <add name=&quot;System.Workflow.Runtime.Hosting&quot; value=&quot;All&quot; />
    • <add name=&quot;System.Workflow.Runtime.Tracking&quot; value=&quot;All&quot; />
    • <add name=&quot;System.Workflow.Activities&quot; value=&quot;All&quot; />
    • <add name=&quot;System.Workflow.Activities.Rules&quot; value=&quot;All&quot; />
    • </switches>
    • </ system.diagnostics >
      • The first add node enables logging to a file. The file is created in your host application directory using the name WorkflowTrace.log .
      • The other option is to enable logging to a TraceListener by setting the name parameter equal to &quot; System.Workflow LogToTraceListener &quot;.
  • Thank You !