WF from entry to entry (Chapter 3): workflow instances

Source: Internet
Author: User

Previous Article: WF from entry to mastery (chapter 2): workflow Runtime

After learning this chapter, you will learn about:
1. initialize a workflow instance in either of the following ways:
2. determine the status of your running workflow instance
3. Stop a workflow instance
4. determine the reason for your workflow being idle or terminated

A workflow instance consists of one or more activities. (We will start to introduce various activities in chapter 7: "Basic Activity Operations.") "primary activity" or "root activity" is called "workflow definition ". "Workflow definition" usually acts as a container for other activities to work.
Note: "workflow definition" is what you want workflow to execute, while a workflow instance is a "workflow definition" being executed ". There is a significant difference between them. One is being executed, and the other is not.
Where does a workflow instance come from? Of course, they should be created by you. If you have difficulties in completing this task and the automatically created workflow meets your application requirements, it can also be completed by the software, but at least you need to write the workflow task or the task that will be executed for you during the workflow operation. Microsoft provides workflow running, and you have to create the rest. After all, this is your application.
WF can help you with the creation of these areas. WF will not only execute the workflow instances you have created, but also help you create them. WF integrates a wide range of graphic interface designers, which can help you integrate workflow into your ASP. NET Web Forms, Windows Forms, or WPF applications in the same way. You can scroll the mouse in the toolbox, select one from many activity items, drag it to the design interface, and release it. If this activity item has configurable properties, you can use the attribute panel in Visual Studio to configure it to conform to your intent. We have used the workflow designer briefly in Chapter 1. Here we will use it again. After all, almost all work related to WF is to create workflow tasks, the use of the workflow visualization designer is a huge component of the development process.

The workflow instance is similar to any other software. They start to run until they are terminated. These may be that all records in the database have been processed, all files to be compressed have been compressed, or the documents sent by workflow to each approver have been approved (agreed or disagree ), or the process has been completed. It has only one normal start position, but one or more normal locations that may stop.
The instance can also maintain errors and exceptions. You can handle these exceptions or not. In some cases, you may not want to handle exceptions and leave them for later processing.
Sometimes, a workflow processing process can be executed for a long time. For example, a processing process sends an order for a part and waits for the order to be received. The model and number of parts must be confirmed before workflow ends, which may take days, weeks, or even months. Therefore, does a workflow instance need to remain active in the memory for several days, weeks, or months? What if the server crashes or the power is down? Is your workflow instance, data, and application status lost?
Workflow instances and activities that constitute instances are an important part of the workflow process. WF provides powerful support for creating and executing workflow instances. Let's take a look at the WorkflowInstance object.

Introduction to WorkflowInstance objects
WorkflowInstance is a WF object that provides you with an independent workflow task context (Environment ). You can use this object to find out how things will be performed in your processing tasks. Just as we have methods and attributes to control the workflow runtime, we also have methods and attributes to interact with our workflow instances. Table 3-1 lists most WorkflowInstance attributes. Table 3-2 lists frequently used methods. We will also see some additional attributes and methods in chapter 5, "workflow tracking ".
Table 3-1 attributes of WorkflowInstance

Attribute Function
InstanceId Obtain the unique identifier (Guid) of the workflow instance)
WorkflowRuntime Obtain the WorkflowRuntime of this workflow instance.

Table 3-2 WorkflowInstance

Method Function
ApplyWorkflowChanges Apply for changes to the workflow instance through the WorkflowChanges object. This allows you to modify a workflow during execution (adding, removing, or changing activities). When a dynamic change is implemented, the workflow instance is paused.
GetWorkflowDefinition Search for the root activity of this workflow instance.
Resume Resume the execution of the previously paused workflow instance. If the workflow instance is not paused, do not do anything. If the workflow instance is paused, The WorkflowResumed event is triggered after the workflow instance is restored.
Start Start the execution of a workflow instance and call ExecuteActivity on the Root Activity of the workflow instance. If a Start exception occurs, it calls Terminate to Terminate the workflow instance and append the exception information as the cause of termination.
Suspend Pause the workflow instance synchronously. If the workflow instance is already in the paused status, do not do anything. If the workflow instance is running, the instance will be paused when the workflow is running, and SuspendOrTerminateInfoProperty (reasons) will be set and Suspend will be triggered.
Terminate Terminate this workflow instance synchronously. When the host needs to terminate a workflow instance, the instance is terminated and the final state of the instance is persisted. Then WorkflowInstance sets SuspendOrTerminateInfoProperty (indicating the reason) and enters Terminate. Finally, it triggers the WorkflowTerminated event and transmits the cause of termination to the Message attribute in WorkflowTerminateException and includes it in the parameter of the WorkflowTerminatedEventArgs event. In addition, if an exception occurs during persistence, the exception will be uploaded to the WorkflowTerminatedEventArgs event parameter during workflow runtime.

More methods related to WorkflowInstance are not listed yet. In chapter 6 "loading and detaching an instance", we will see more details about the persistent workflow when it comes to the database.

Start a workflow instance
Before starting a workflow instance, we must have a workflow task for WF to execute. In chapter 1, we created a workflow-based project through Visual Studio, which automatically contains a workflow task, and we modified it for U. s. and the postal code of Canada. If the program is used, we can return to the project to copy the source code and use the pcodeflow.exe assembly. Then we can directly use the created workflow. Actually, you can do this.
However, we should try to learn how to write workflow applications. Let's simulate a long-running task by using an ordered workflow with latency. We will execute some code before the delay to bring up an information dialog box. After the delay, an information dialog box will pop up again to indicate that our work has ended. Through the course of this book, our examples will be more and more detailed and rich, but now we are still in the entry stage, we will also keep our examples and focus more on concepts rather than improving our skills.
Note: Remember, the sequential workflow executes the activity one by one. This processing method can be compared with the state machine workflow. The state machine workflow executes the activity based on the state change. If you are confused about this, don't worry. We will enter this topic in the next chapter.

Add an ordered workflow project in WorkflowHost Solution
1. Start Visual Studio 2008 and load the solution named "WorkflowHost" created in the previous chapter to prepare for editing.
2. Add a new workflow project to the solution.
3. Select the sequence workflow library for the Project template.
4. The project name is LongRunningWorkflow.
Now open the view designer of workflow to prepare for creating our workflow task. In the larger picture in the view designer, we will add three activities to this new workflow task: Two Code activities and one Delay activity. The Delay activity will be placed in the middle of two Code activities, so that we can bring up an information dialog box before and after the Delay operation. At first, we will specify an appropriate latency value, but later we will modify the workflow task so that the workflow task can receive a specific latency value during initialization.

To create this simulation, You need to execute an ordered workflow for a long time. 
1. Activate the workflow view designer and move the mouse to the toolbox.
2. Select the Code activity from the toolbox and drag the component to the surface of the workflow designer.

3. Release the mouse and place the Code Activity component in the workflow.
4. Just like in chapter 1, we will add some Code to the Code activity to execute the worflow task when it passes through this activity. Click the Code activity here to make sure that the property Panel of the activity is activated.
5. Activate the ExecuteCode property drop-down box in the property panel, which allows you to name the event to be triggered and this event is triggered when the Code is executed in the Code activity.
6. Enter "PreDelayMessage ". In this way, an event is added to the worflow code. Later, we will modify this code to display an information dialog box. However, we continue to work on the view designer of workflow because we need to add two other activities.

7. Select the Delay activity from the toolbox and add it to the Code activity.

Note: ordered activities are executed in sequence just like what we do now. The sequence is determined by the activity position in the workflow view designer. The activity at the top of the workflow designer window is executed first. The execution sequence of other activities is determined by the direction (arrow) at the bottom of the view designer window. In the next chapter, we will review this process.
8. We need to create a latency value for our Delay activities. Therefore, we need to change the attribute of TimeoutDuration in the Visual Studio attribute panel. Change the last two "00" to "10", which means that the Delay activity will wait 10 seconds for workflow to proceed with the next step.
9. Now we need to add the second Code activity to display the second information dialog box. To this end, repeat steps 2 and 6 to add a new Code activity, but set the ExecuteCode attribute to "PostDelayMessage" to name the event. The final result of workflow displayed in the workflow view designer is as follows:

We still have two tasks left unfinished. In the end, we need to introduce our workflow assembly into our main application to execute it. But first, we must add the necessary code to display the two information dialog boxes. We have created two events in our workflow code: PreDelayMessage and PostDelayMessage. We will add the event processing code for them, which is actually the code in the pop-up information dialog box.

Add code for events before and after latency 
1. Click the Workflow1.cs file in the LongRunningWorkflow project to view its code.
2. Add a reference to "System. Windows. Forms" and declare the following namespace in the Workflow1.cs file:
Using System. Windows. Forms;
3. Locate the newly inserted PreDelayMessage method and insert the following code into the method:
MessageBox. Show ("the code before the latency is being executed. ");
4. Similar to the previous step, locate the newly inserted PostDelayMessage method and insert the following code into the method:
MessageBox. Show ("the Code after the delay is being executed. ");
If you compile this solution at this time, there will be no errors, but the WorkflowHost application will still be suspended as in the previous chapter. Why? Although we have created a workflow assembly that we can use, we did not request the main application to execute it. The WorkflowCompleted event is never triggered, so the automatic reset event will not release the main thread of the application.
To execute our workflow task, we need to reference our newly created workflow assembly and add code so that the WorkflowRuntime object can kick off the work of the workflow task. Let's start now.

Host a custom workflow assembly and start a workflow instance without Parameters
1. Add a reference to LongRunningWorkflow in the WorkflowHost of the project.
2. If we compile this application now, WorkflowHost will fail to compile. Why? The reason is that when we created the WorkflowHost project in the previous chapter, we only added the required references to support compiling in the current environment. But now, we have added a "System. Workflow. Runtime" reference. At the same time, a ready-made workflow assembly is introduced to our host application. Therefore, we need to add more reference related to workflow for the WorkflowHost project. The references we need to add include "System. Workflow. Activities" and "System. Workflow. ComponentModel ".

3. Open the Program. cs file and locate the following code in the Main method:
Console. WriteLine ("wait for workflow to complete. ");
4. Add the following code below the above Code:

WorkflowInstance instance = workflowRuntime. CreateWorkflow (typeof (LongRunningWorkflow. Workflow1 ));
Instance. Start ();

5. Compile and execute the WorkflowHost application.
The execution result is as follows:
Let's go back to the following key code: WorkflowInstance instance = workflowRuntime. CreateWorkflow (typeof (LongRunningWorkflow. Workflow1 ));
Instance. Start ();

Here, we use the CreateWorkflow method of the WorkflowRuntime object to create a workflow instance that we want to execute. When we get a returned WorkflowInstance object, we call its Start method to initialize workflow. Note that this workflow instance can be executed without pre-input parameters. What if I could input a variable latency value in advance? We will discuss this topic in the next section.

Start a workflow instance with Parameters 
The Workflow instance started with input parameters maps the received parameters with related public attributes. That is to say, to pass in a variable latency value, we only need to create a public attribute named "Delay" on our workflow instance and provide a latency value when creating this instance. If you are familiar with XML serialization and "XmlSerializer" in. NET, the process of creating a workflow instance is similar to the process of deserializing an XML stream into A. NET object. In fact, this is almost the same.
The parameter Values expected to be passed into the workflow instance are usually stored in the Values of a Dictionary Object. the keywords of the Dictionary Object use the string type, and the corresponding Values use simple Object objects. The typical code is as follows:
Dictionary Parms = new Dictionary ();
Then you can use the Add method of the Dictionary object to Add parameters. The keyword must be a string, which indicates the name of the public attribute exposed by the root activity of workflow. In addition, the corresponding value type must be consistent with the activity property type. For example, we pass in an integer-type latency value and a property named Delay is exposed in our workflow instance to correspond to it, add a parameter to the Dictionary Code as follows:
Parms. Add ("Delay", 10); // Delay: 10 seconds.
Let's write some code again. We do some minor changes, but this will get a lot of functionality. We use the console command line to receive an integer we entered as the latency value. So that our program will not run forever, we will limit this value to between 0 and 120, meaning the delay range is from 0 s to two minutes. We will also add the Delay attribute to workflow. Let's make the first correction to our workflow component.
Add an INPUT attribute for workflow
1. Open the Workflow1.cs file to prepare for editing.
2. Add the following code after the constructor of Workflow1:

Private Int32 _ delay = 10;

Public Int32 Delay
{
Get {return _ delay ;}
Set
{
If (value <0 | value> 120)
Value = 10;
If (ExecutionStatus = ActivityExecutionStatus. Initialized)
{
_ Delay = value;
DelayActivity1.TimeoutDuration = new TimeSpan (0, 0, _ delay );
}
}
}

We checked the passed integer value. If it is out of the range, we will specify a default value. We checked whether workflow is in the forthcoming execution status (not in the executed status ). This prevents someone from modifying the latency value in our workflow operation. We also need to make a few modifications to the Main method. We need to enter a parameter in the command line as the delay value. If it is not an integer value, we exit. Otherwise, we will accept it. If it exceeds the range (0 to 120 seconds), we will impose necessary constraints on it (default value: 10 seconds ). The steps for modifying Main are as follows:
Start a workflow instance with Parameters
1. Open the Progrom. cs file to prepare for editing.
2. Locate the following code:

WorkflowRuntime. WorkflowIdled + = new EventHandler <WorkflowEventArgs> (workflowRuntime_WorkflowIdled );
WorkflowRuntime. WorkflowCompleted + = new EventHandler <WorkflowCompletedEventArgs> (workflowRuntime_WorkflowCompleted );
WorkflowRuntime. WorkflowTerminated + = new EventHandler <WorkflowTerminatedEventArgs> (workflowRuntime_WorkflowTerminated );

3. Add the following code after the above Code:

Int32 delay = 0;
String val = args. Length> 0? Args [0]: "10 ";
If (! Int32.TryParse (val, out delay ))
{
Console. WriteLine ("You must enter an integer value! ");
Return;
}

Dictionary <string, object> parms = new Dictionary <string, object> ();

4. Find the following code:

WorkflowInstance instance = workflowRuntime. CreateWorkflow (typeof (LongRunningWorkflow. Workflow1 ));

5. Change the above Code:

WorkflowInstance instance = workflowRuntime. CreateWorkflow (typeof (LongRunningWorkflow. Workflow1), parms );

Compile and run the program as in the first chapter. by inputting the delay time of different values, you can see the latency effect of the two pop-up information dialog boxes.

Determine the status of the Workflow instance 
Interestingly, if you look at the methods and attributes of the workflow runtime object and the workflow instance object, you cannot find the status-related attributes. How do you know if a workflow is being executed? If there is one, what is it in that state? Idle? Is the execution in progress? How are we sure?
I will skip a short step forward, and most of the logic is placed on the confirmation of the workflow status. The workflow definition of a given workflow instance provides you with the execution status of workflow. A base Activity exposes the ExecutionStatus attribute, which is a member of the ActivityExecutionStatus enumeration. The enumerated values and meanings of ActivityExecutionStatus are listed in Table 3-3.
Table 3-3 ActivityExecutionStatus enumerated values

Attribute Function
Canceling The activity is being canceled.
Closed The activity has been disabled.
Compensating The activity is compensated.
Executing The activity is currently running.
Faulting The activity has generated and maintains an exception.
Initialized The activity has been initialized but has not yet run.

All enumerated values in Table 3-3 involve an active object, but you must remember that workflow definition is an activity. This means that if we query the workflow definition status, we can effectively determine the status of the entire instance. The following process demonstrates how to add the corresponding code to query workflow definitely.

Determine the execution status of the workflow instance
1. Open the Program. cs file of the WorkflowHost project to prepare for editing.
2. Locate the Main method and locate the following code:
Instance. Start ();
3. To let us see the status of the workflow instance, we can directly query the workflow definition status and output the result to the console. Insert the following code under the code located in the previous step:
Console. WriteLine ("workflow is in the status of {0. ",
Instance. GetWorkflowDefiniton (). ExecutionStatus. ToString ());

Terminate a Workflow instance
If you need to do so, you can easily Terminate a workflow instance by executing the Terminate method of the workflow instance object. If you add WorkflowTerminated event processing to your application, you can get the cause of termination from the Message attribute of Exception. You will find that the Exception is encapsulated in WorkflowTerminatedEventArgs and passed into the WorkflowTerminated event handler. These codes are included in WorkflowHost. We also need to add a line of code to end the workflow instance.
Terminate a workflow instance
1. Open the Program. cs file and find the code we just added:
Console. WriteLine ("workflow is in the status of {0. ",
Instance. GetWorkflowDefinition (). ExecutionStatus. ToString ();
2. Add the following code under the above Code:
Instance. Terminate ("User canceled ");
If you compile and run the WorkflowHost program and provide a latency value of 25 seconds for it, you will not see any information dialog box. The output result of the console is as follows:

Dehydration and Rehydration 
Before we leave the topic of the workflow instance, I want to talk about the concepts of "dehydrating" and "rehydrating" instances. If you have a long-running workflow task or a large number of tasks, you can uninstall the task and store the required execution environment information to an SQL Server database, this requires a service running on WF.
In chapter 6, we will discuss the storage issue in detail. I mentioned it here because, for one thing, the target is a workflow instance. On the other hand, we should listen to these terms. I don't want you to go deep into this book, but you still don't understand their basic meaning.
When you "dehydrate" an instance, you are removing it from the execution status and storing it for future recovery. A typical practice is to use the WF persistence service, but you can also write your own services for the same task. When your application detects that the workflow instance needs to be restarted, you will "rehydrate" the instance and it will return the current execution status. There are many reasons for doing so. All these books will be briefly described later.

Download source code: WorkflowHost

Next article: [translation] WF from entry to mastery (chapter 4): Introduction to activities and workflow types

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.