Beginning wf4-Chapter 2 workflow based on background code

Source: Internet
Author: User

In the previous chapter, we successfully implemented a simple workflow example through the workflow engine designer. Next we will use the background code to implement the same process.

 

Console Program

Create a console Program

 

Add reference to "launch M. activties"(Note: This library must be referenced during workflow development)

At the same time, modify the namespace in program. CS as follows:

using System;using System.Activities;using System.Activities.Statements;using System.Activities.Expressions;

Add the following code to the main () function:

WorkflowInvoker.Invoke(CreateWorkflow());Console.WriteLine("Press ENTER to exit");Console.ReadLine();

At this point, you will find that the code in the first chapter is already similar, but the createworkflow function replaces the original New workflow1. The difference is that the workflow1 function is automatically generated by the workflow designer engine, while the createworkflow function needs to be created manually.

 

Design Workflow

In the previous chapter, when we use the workflow designer to design, we can simply think that "workflow" is actually a collection of many embedded "classes" and Period "attributes.

Next, we will use the background code to implement a simple instance. Add the createworkflow function implementation to the program. CS file. The Code is as follows:

static Activity CreateWorkflow(){    Variable<int> numberBells = new Variable<int>()    {        Name = "numberBells",        Default = DateTime.Now.Hour    };    Variable<int> counter = new Variable<int>()    {        Name = "counter",        Default = 1    };    return new Sequence()    {    };}

In this function, we first define two "int" type workflow variables based on "variable <t>", called "numberbells" and "counter" respectively ", they will be used in subsequent activities.(As described in the first ticket)

The createworkflow function eventually requires that an instance of the activity type be returned and executed in workflowinvoker. In fact, it is not difficult to find through the code that createworkflow actually generates a sequance object, because the sequance is inherited from the activity.(Note: For the description of polymorphism, you can refer to the object-oriented content)

 

Level 1

So far, we have defined an empty activity of the basic sequance type, and we will enrich it. The first layer of code is as follows:

return new Sequence(){    DisplayName = "Main Sequence",    Variables = {numberBells, counter },    Activities = {        new WriteLine()        {            DisplayName = "Hello",            Text = "Hello, World!"        },        new If()        {            DisplayName = "Adjust for PM"            // Code to be added here in Level 2        },                            new While()        {            DisplayName = "Sound Bells"            // Code to be added here in Level 2        },        new WriteLine()        {            DisplayName = "Display Time",            Text = "The time is: " + DateTime.Now.ToString()        },        new If()        {            DisplayName = "Greeting"            // Code to be added here in Level 2        }    }};

In the code, you first set "displayname" and the variables associated with the activity, and initialize a series of activities. The statistics are as follows:

Activity Name
Writeline Hello
If Adjust for PM
While Sound bells
Writeline Display time
If Greeting

The content of the "writeline" activity has been set, and other major activities will be provided in "Layer 2.

 

Layer 2

To implement the first "if" activity, enter the following code:

DisplayName = "Adjust for PM",                        // Code to be added here in Level 2Condition = ExpressionServices.Convert<bool>    (env => numberBells.Get(env) > 12),Then = new Assign<int>(){    DisplayName = "Adjust Bells"// Code to be added here in Level 3}

In the code, we set the "condition" and "then" attributes (there is no requirement for the "else" branch ). However, the implementation of the "Assign" activity will be described in the next layer.

 

Expression

The convert <t> static function of expressionservices can be used to create a temporary variable of the "inargument <t>" type, which is exactly required by the "condition" attribute. At the same time, because these classes and methods are based on generics, they can be applied to all types. In this example, we will need to generate a "bool" type applied to the "condition" attribute.

All expressions in the WF environment are based on lambda expressions. (Omitted in the original article about the lambda expression syntax details), the expression here is evaluated for the "condition" at runtime.

Because a workflow is state-independent, it does not store data of task elements. This requires defining some variables through the "variable" type to store some common data, and may obtain the real value of this type through its get () method. Of course, this must depend on the context of the activity. Activitycontext. In practical applications, many "variable" will be used to differentiate each other in a specific workflow instance. In this case, it will be used to determine whether the value is greater than 12.

 

Enter the following code in the "while" activity:

 

 DisplayName = "Sound Bells",// Code to be added here in Level 2 Condition = ExpressionServices.Convert<bool>    (env => counter.Get(env) <= numberBells.Get(env)), Body = new Sequence() {     DisplayName = "Sound Bell"// Code to be added here in Level 3 }

In fact, the "condition" attribute of the "while" activity depends on a judgment value, it is also a "bool" variable of the "inargument <t>" type created through "expressionservice. Here, we will use "count <= numberbells" to determine. In this case, you will find that both variables can obtain real values through the get () method.

 

For the second "if" activity, we name it "greeting" and enter the following code:

DisplayName = "Greeting",// Code to be added here in Level 2 Condition = ExpressionServices.Convert<bool>      (env => DateTime.Now.Hour >= 18), Then = new WriteLine() { Text = "Good Evening" }, Else = new WriteLine() { Text = "Good Day" }

In the code, the input parameter "env" in "condition" is not actually used, but it is still defined in the Code and assigned the value of the current time to it, used to determine whether the value has passed six o'clock P.M. In the "then" and "else" attributes, a "writeline" activity is created to output "Good evening" and "good day" respectively ".

 

Layer 3

In the first "if" activity (the activity called "adjust for PM"), we created an empty "Assign" activity in its "then" attribute. To improve it, enter the following code:

 DisplayName = "Adjust Bells",// Code to be added here in Level 3 To = new OutArgument<int>(numberBells), Value = new InArgument<int>(env => numberBells.Get(env) - 12)

 

AssignActivity

The "Assign" type supports generics. Here we want to operate on an integer value, so it can be defined as "Assign <int> ". The "to" attribute in this activity is an "outargument" type, which is constructed by a variable originally defined, the "value" attribute uses an "inargument" type. The operation result of this activity will be used in the "condition" attribute of the subsequent "if" and "while" activities, so it must be completed in advance.

 

Sequence

In the while activity, what we provide for the body is an empty sequence ". It defines a series of activities that will be continuously executed in the loop body. The Code is as follows:

 

 DisplayName = "Sound Bells",// Code to be added here in Level 2 Condition = ExpressionServices.Convert<bool>     (env => counter.Get(env) <= numberBells.Get(env)), Body = new Sequence() {     DisplayName = "Sound Bell",     // Code to be added here in Level 3     Activities =     {         new WriteLine()         {             Text = new InArgument<string>(env => counter.Get(env).ToString())         },         new Assign<int>()         {             DisplayName = "Increment Counter",             To = new OutArgument<int>(counter),             Value = new InArgument<int>(env => counter.Get(env) + 1)         },         new Delay()         {             Duration = TimeSpan.FromSeconds(1)         }     } }

The code above adds three activities for "sequcence:

A "writeline" activity used to display the "counter" value.

An "Assign" activity used to add the "counter" value.

A "delay" activity for latency.

 

In this example, the "writeline" activity does not output unified text every time, but displays the value of an expression. Because its "text" attribute requires a "string" type, we define an "inargument <string>" type to provide support. Now we can use these lambda expressions to get the current value of the variable through get (), and convert "int" to "string" through "tostring ".

Of course, in the "delay" activity, we use the "fromseconds" static method of the "timespan" type to achieve the latency effect.

 

Run the program (F5)

 

Source code:Chapter02

 

For all documents and code indexes related to this series, see:

Beginning WF: Windows workflow in. Net 4.0 Reading Notes

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.