We have open project from last post Refactoring Workflows as we seen on it, WF4
consists of a designer that edits .xaml
files and a runtime that invokes activities. When we author
a workflow, we are creating a new kind of activity and because activities are just
classes that inherit from System.Activities.Activity
or one of its subclasses, we can declare workflows using C#, VB or XAML. In
this post, we will implement our “greeting” business process by creating
an activity in C# or VB.
We will create an activity in code and write the text to the console using Console.WriteLine.
We will create an activity in code and write the text to the console using Console.WriteLine.
- Right-click the HelloWorkflow project, point to Add and click Class. Type SayHelloInCode in the Name box.
- Add
the following namespace directives to the file.C#using System.Activities;Visual BasicImports System.Activities
- CodeActivity is an abstract class. That means that when we inherit from it, we must override the Execute
method. This is the place where we will do the work of our activity. Replace
the default implementation of the class with the following code.C#public class SayHelloInCode : CodeActivity{protected override void Execute(CodeActivityContext context){Console.WriteLine("Hello Workflow 4 in code");}}(Code Snippet - Introduction to WF Lab - SayHelloInCode Class VB)Visual BasicPublic Class SayHelloInCodeInherits CodeActivityProtected Overrides Sub Execute(ByVal context As CodeActivityContext)Console.WriteLine("Hello Workflow 4 in code")End SubEnd Class
- Change
Program.cs (C#) or Module1.vb (Visual Basic) to use the new SayHelloInCode class. To do this,
locate the WorkflowInvoker.Invoke method code, and replace it with the
following code:C#static void Main(string[] args){WorkflowInvoker.Invoke(new SayHelloInCode());}Visual BasicShared Sub Main(ByVal args() As String)WorkflowInvoker.Invoke(New SayHelloInCode())End Sub
- Press
CTRL+F5 to run the workflow without debugging. The application should
run in a console window and print the message “Hello Workflow 4 in code".The completed HelloWorkflow application
Note: Why would I create a code activity?
Writing
business logic in code is nothing new. Why would we go to the effort to write
it in a special class that inherits from CodeActivity? The reason is that by
doing so now our business logic can be composed into other larger business
processes that use the workflow runtime. As we will see later in the next posts it
will also benefit from a model for threading and data management that provides
for highly scalable and long running business applications.
No comments:
Post a Comment