"Translation Exercises" Windows Workflow Foundation Program Development-Chapter 05

Source: Internet
Author: User

1.3 Developing our first workflow

Maybe you've worked with a product manager like this before: he's always around you, and doesn't say, "You haven't finished yet?" ”。 In this section, we will replace this annoying product manager with a simple Windows Workflow program. This routine doesn't show you the full functionality of the WF platform, but it gives you a glimpse into how to create and run workflows with WF.

Before we begin, we need to download and install the. NET 3.0 Framework. The installer can be found in http://netfx3.com. All versions of Visual Studio 2005 support Development on the. NET 3.0 Framework. We also need to download and install Visual Studio 2005 Extensions for Windows Workflow Foundation. This expansion pack can also be found in http://netfx3.com. However, this expansion pack does not support the Express version of Visual Studio 2005.

First, create a new workflow project with Visual Studio (File | New Project). We chose to use C # development and select the sequential Workflow console Application(sequential Workflow console application) template (see screenshot below). The project that the template generates for us consists of a reference to all the necessary WF assemblies, an empty workflow, and a Program.cs file to drive the workflow. Right-click the workflow and select the deleteoperation so that we can compile a workflow from scratch.

We can now right-click on the project file in the Solution Explorerwindow and select Add New Item ( Add Item). In the list of items that can be added, we select sequential Workflow (with code separation)(sequential workflow-code separation) and then name the new project workflow1.xoml (see screenshot below). In this xoml file is our workflow defined with a XAML tag code.

If you expand the workflow1.xoml node, we see a code-beside file (Workflow1.xoml.cs) that contains a partial class. As mentioned earlier, this partial class will generate a complete type together with the classes defined by the XAML markup code. In the following code, we have modified the classes in Workflow1.xoml.cs, adding a isfixed property and its supporting fields.

 Public Partial class workflow1:sequentialworkflowactivity{        privatebool  _isfixed;          Public BOOL isfixed        {                getreturn  _isfixed;}                 Set {_isfixed = value;}}        }

If you double-click the. xoml file, the designer window opens. At this point, ifToolboxThe window is not open yet, we can open it with the shortcut key ctrl+alt+x. We can get fromToolboxDrag one of the whileactivity, and placed between the start and end points of the workflow. whileThe activity repeats its internal subtasks until a condition has been met. and drag out aCodeactivity and put it in the while. Now, here's what our designer looks like:

Did you see that? Each activity is accompanied by a red exclamation point. This means that both activities are not validated for validation. We can stop the mouse at the exclamation point and click on the smart tag to see the validation error. If you perform the compile operation now, the validation error appears as a compilation error in the error prompt window. Let's try to fix these errors.

The Code activity requires that we assign an event handler to its Executecode event. We can do this assignment in the Properties window of the Code activity (opened with the F4 shortcut key). By double-clicking the space next to the Executecode property, the corresponding code next to the file opens, and an automatically generated event handler framework is already in place. Let's put the following code in the frame. This code asks the user if the software flaw has been fixed, and then waits for the user to press a key. If the user presses the "Y" key, the program sets the _isfixed field to true.

Private voidcodeActivity1_ExecuteCode (Objectsender, EventArgs e) {Console.WriteLine ("Is the bug fixed?"); Char Answer=Console.readkey ().        KeyChar; Answer=char.tolower (answer); if(Answer = ='y') {_isfixed=true; }        Else{Console.WriteLine (); Console.WriteLine ("Get back to work!");        Console.WriteLine (); }}

code The validation of the activity has passed, let's deal with activity. while The activity requires a valid condition (condition) attribute. There are several activities in the base Activity library that require "conditions" when they are executed, including IfElse, ConditionedActivityGroup, and replicator activities. The 9th chapter will discuss the conditions and rules in depth.

The way to set the Condition property is simple : Open the drop-down list box next to the Condition property in the Properties window, in codecondition and ruleconditionreference Two, choose one. These two options represent two different conditional presentation techniques, which are expressed in code (a method that returns a Boolean value) and the latter with a rule. Here is a selection of ruleconditionreference . A rule condition is a named expression whose evaluation result is true or false, which can be stored in a separate. Rules external file, which is easy to maintain. Now, a plus sign appears next to theCondition property, and clicking the plus sign expands the property editor.

When the Condition property is expanded , the Properties window allows us to conditionname(the condition name) and Expression (expression) to set. Click the ellipsis (...) next to Condition . button, selectCondition(Selection Criteria) dialog box will pop up.

Click New Condition ... (New condition ...) ) button pops up the following rule Conditioneditor (rule Condition editor).

We intend to have the while activity loop execution until the flaw is fixed, so the rule we enter is!this. Isfixed (the IntelliSense feature that comes with the editor lets us steal a little bit lazy), then click the OKbutton. When you return to the Select Condition dialog box, you can see that the editor has named our condition Condition1. Please select Condition1 and click OK. The settings for the while activity conditionname and Expression have been completed, and validation has been passed.

Now open the Program.cs file, where the main method is the entry point of the console program. We need to host the WF runtime and let it execute our workflow. All the template code we need is already available in the Workflow engineering template. Take a look at the following code:

classprogram{Static voidMain (string[] args) {WorkflowRuntime WorkflowRuntime=NewWorkflowRuntime (); Workflowruntime.workflowcompleted+=NewEventhandler<workflowcompletedeventargs>(workflowruntime_workflowcompleted); Workflowruntime.workflowterminated+=NewEventhandler<workflowterminatedeventargs>(workflowruntime_workflowterminated);                WorkflowInstance instance; Instance= Workflowruntime.createworkflow (typeof(Workflow1)); Instance.                Start ();        WaitHandle.WaitOne (); }        Static voidWorkflowruntime_workflowterminated (Objectsender, WorkflowTerminatedEventArgs e)                {Console.WriteLine (e.exception.message);        Waithandle.set (); }        Static voidWorkflowruntime_workflowcompleted (Objectsender, Workflowcompletedeventargs e)        {Waithandle.set (); }        StaticAutoResetEvent WaitHandle =NewAutoResetEvent (false);}

The first step is to generate a WorkflowRuntime instance. The code already has two event handlers specified for the runtime, so if the workflow terminates (because of an exception) or ends, we will be notified accordingly. The CreateWorkflow method is then called to generate an instance of the defect repair workflow, and the invocation parameter is our workflow type. Because the workflow engine executes the workflow asynchronously, we must block the main thread with a AutoResetEvent object and wait for the workflow to end (otherwise, the console program may exit before the workflow starts executing). The AutoResetEvent object blocks a thread until the object enters the signal state, and we happen to call the set method of the AutoResetEvent object in the two previously mentioned event handler to set it to signal state.

Now we can build this workflow solution and then run its executable file on the command line.

1.4 Summary

Software developers have been using workflows to model and implement business processes from the very beginning. During this time, we already know that the workflow may run long and often needs to get input from the user. Meeting these challenges by creating a robust workflow is a daunting task. An ideal example of workflow creation is to split the definition of a workflow from the execution engine of the workflow.

Once the definition of the workflow is separated from the execution engine, we can build the domain-specific language by building the workflow component. If a business person understands a domain-specific language, he can also understand a workflow by ignoring the details of exception handling and state tracking.

Windows Workflow brings a workflow execution engine and a series of workflow development tools to the Microsoft platform. The execution instructions for the WF engine are activities, and we can use graphical designers, XAML, code, or a combination of them to orchestrate the activity. WF also provides the services required by some workflow engines, including persistent services, threading services, and transactional services. So we can say: The prospect of working with WF for workflow development is bright.

Chapter Links:

"Translation exercises" development of Windows Workflow Foundation program

"Translation exercises" development of Windows Workflow Foundation Program-Preface


"Translation Exercises" Windows Workflow Foundation Program Development-Chapter 01

"Translation Exercises" Windows Workflow Foundation Program Development-Chapter 02

"Translation Exercises" Windows Workflow Foundation Program Development-Chapter 03

"Translation Exercises" Windows Workflow Foundation Program Development-Chapter 04

"Translation Exercises" Windows Workflow Foundation Program Development-Chapter 05

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.