WF from entry to entry (Chapter 1): status-based workflow

Source: Internet
Author: User

Previous Article: [translation] WF from entry to mastery (Chapter 1): build custom activities

After learning this chapter, you will learn about:
1. understand the concept of a state machine and how it is simulated into workflow processing.
2. Create a status-based workflow
3. Use the initial and terminal status Conditions
4. Use code to switch the status

In Chapter 4 "Introduction to activities and workflow types", I have explained the types of workflows you can create using WF, where I mentioned status-based workflows. The status-based workflow model is considered to beFinite Automaton(Finite state machine). A State-based workflow is very popular when a workflow needs to interact with external events. When an event is triggered and processed by the workflow, the workflow can switch the status as required.
WF provides a rich development experience for creating State-based workflows. Many of the things you have seen so far in this book apply to State-based workflows. For example, when a status is switched over, if you want to, you can execute several sequential activities for condition determination (using rules or code ), or use an iterative activity structure to cyclically access some data points. The only real difference is how activities are queued for execution. In an ordered or parallel workflow, they are queued in the order of appearance. However, in a status-based workflow, the activity switches to the status to queue. Events usually drive these switching processes, but this rule is not universal. Let's look at the concepts of state machines and combine these concepts with the WF activities you can use to build your workflow.

State Machine Concept

The purpose of a state machine is to build discrete points in your business flow and switch over events for control. For example, power your washing machine on, close the door, and press the start button. When you press the start button, a state machine is initialized, which cleans your clothes to be washed by running various cleaning cycles until all these cycles are completed.
The state machine has a known starting point and a known ending point. The intermediate state should be controlled by triggering the expected event, but the machine is always in a specific State. Sometimes events throw the state machine into an invalid state. This situation is no different from maintaining unprocessed exceptions in your application, the whole process is either a sudden stop or a complete crash. In either case, switching to an invalid state requires close monitoring, at least in digital electronic systems.
In general, Chapter 1 covers the basic concepts related to state machines. You can take a quick look at the "status activity" section. Let's go from how to design activities to how to use activities in state-based workflows.

Usage Status Activity

Maybe you will not be surprised, in your state-based workflowStateActivity builds a state. It is a combination activity, but it is limited to accepting only a specific type of activity as its sub-activity. They are:EventDrivenActivity,StateInitializationActivity,StateFinalizationActivities and otherStateActivity.EventDrivenActivities wait (Listen) events that will lead to switching to another State, and when the status is switched in and out,StateInitializationAndStateFinalizationIs to ensure that the corresponding processing activities can be executed separately. You can drag the secondStateActivity to an existingStateIt may seem a bit odd in the activity, but its intention is to provide the ability to embed sub-state machines in the parent state machine.
There is also a limit on the number of valid activities that your status can accommodate. Only oneStateInitializationAndStateFinalizationYou can only have one of them, but each of them cannot have more than one. They are not required.
But it does not mean that you cannot have only one or more sub-accounts.EventDrivenAndStateActivity. In fact, multipleEventDrivenActivity, because each event may switch to a different status. For example, a "disapprove" event may switch to the final state (end state), while an "approve (approve)" Event) "event may switch to a predefined status and require more approval. AsStateActivity. If you want to create an embedded state-based workflow, more than one workflow is allowed. Only one status-based workflow (switchover) is built into a simple ordered workflow. Therefore, you should directly use an ordered workflow in that case. UseStateYou only need to drag an instance of an activity from the toolbox to the Workflow view designer. The only necessary condition is that the workflow itself must be a state-based workflow rather than a sequential workflow. Then, determine what kind of sub-activities your status activities should accommodate and drag them as needed. Remember that you can only insert four types of activities.

Use SetState Activity

14-1 looks familiar if you recall the example of a state machine that I introduced in chapter 4. Indeed, it is a (simplified) vending machine status chart. I think it would be interesting to make such a status chart into a real state-based WF workflow and use a user interface to drive it. Considering my lack of art cells, this user interface is formed into a simple vending machine that does not contain alcoholic drinks ("soda.
 
Figure 14-1 status chart of the beverage machine
Considering that there is no user interaction, the interface of the beverage vending machine application is 14-2. The price of a bottle of beverage is $1.25. When you make a coin, all the beverage image buttons on the left are inactive. However, when you have invested enough, these beverage buttons can be used and you can make a choice. This simplified model does not handle such issues as refunds and changes, but you can modify the application as needed.
Note: For simplicity, I have not made this sample application internationalized. It simulates vending machines that only accept American currency. However, remember that the focus here is the workflow, not the currency unit used.

Figure 14-2 user interface when the beverage dispenser is in the initial state
However, you cannot really place a coin in a Windows Forms Application, So I provide three buttons (5 cents, 10 cents, and 25 cents ). Sorry, only these coins are available. When you click a coin button for the first time, a new status-based workflow instance is started, as shown in figure 14-1. Figure 14-3 shows how the beverage machine has invested several coins. A status-based workflow tracks the coins received at any time and returns the total amount to the application, which displays the coins on a simulated LCD Diode display.

Figure 14-3 drinking machine user interface with coins
When enough coins are invested, the workflow notifies the application that users can choose to drink now, as shown in Figure 14-4. The application makes the beverage buttons on the left of the user interface available (enable ).

Figure 14-4 beverage dispenser user interface for beverage selection
When you click a drink button on the left, that is, the blackening button shown in-4, a label is displayed and "Soda!" is displayed !", This is a way for me to simulate a bottle of the selected beverage from the machine. To Reset the entire process, click "Reset. This does not affect the workflow but resets the buttons on the user interface. Figure 14-2 shows the user interface in this case. You can start all the processing processes again.

Figure 14-5 user interface of the beverage dispenser after a bottle of beverage is selected
You have created a large number of application code. If you read thisSodaMachineSample Code, you will find that I useCallExternalMethodActivity (see "workflow data transfer" in Chapter 8th) andHandleExternalEventActivity (See Chapter 1 "event activity "). There are a lot of tools to interact with your workflow and your application. The rest of the work is to create the workflow itself. The following describes the specific practices.

  Create a status-based workflow
1.SodaMachineThe application provides you with two versions: The full version and the incomplete version. You need to download the source code of this chapter and openSodaMachineFolder.
2. WhenSodaMachineAfter the solution is enabled in Visual Studio, select "generate solution" from the "generate" menu of Visual Studio ". The project in the solution contains various dependencies. Compile the solution to generate the Assembly that can be referenced by the associated project.
3. In the Solution Explorer window of Visual Studio, findSodaFlowProjectWorkflow1.csFile. Then open the workflow in the Workflow view designer to prepare for editing.
  Note: I have created this basic workflow project because you have read the CallExternalMethod and HandleExternalEvent related technologies in Chapter 8th and Chapter 10th. Repeat the necessary steps to create these regular activities is not necessary, but if you create a workflow project from the beginning, you need to do this.

4. The workflow is now uniqueStateActivity composition. Select thisStateActivity1Activity, rename it as"StartState".
5. When a workflow is created, Visual Studio automatically adds an originalStateActivity. But it also uses this activity as the start activity. After you rename the activity in the previous step, the workflow will lose the activity. To reset this activity as the starting activity, you must clickStateOther than the activity to activate the attributes of the entire workflow. In the Property panel, you will seeInitialStateNameAttributeStateActivity1ChangeStartState. Note: You can enter this value directly to this attribute or select from the drop-down list box.StartState.

6. Now we needStateDrag the activity to the Workflow view designer interface. Like what you remember, whenSetStateYou can easily specify the target status during work. DragStateActivity to the designer interface and place itStartStateNext to the activity. Change its nameWaitCoinsState.

7. Drag anotherStateActivity to the Workflow view designer interface, change its nameWaitSelectionState.

8. Drag the last State activity to the Workflow view designer interface and change its nameEndState.

9. Just as you want to re-specify the start status, you also need to tell the WF end status. Click anyStateThe workflow view designer interface outside the activity to activate the attributes of the workflow. SpecifyCompletedStateNameThe property isEndState. Visual Studio then clearsEndStateAnd change the icon in the upper left corner. As before, you can enterEndStateYou can also select it from the drop-down list box.

10. Now let's add some details. SlaveStartStateStart by draggingStateInitializationActivity and put it inStartState.

11. Double-click the one you just addedStateInitialization1Activity, which will go to the ordered Workflow Editor.

12. DragCodeActivity to thisStateInitializationActivity. Specify itsExecuteCodeMethod:ResetTotal. Then Visual Studio will add the correspondingResetTotalAnd switch to the code editing view. At this time, we do not want to add the code. We should go back to the Workflow view designer.

13. DragSetStateActivity to the designer interface, put it in the one you just addedCodeUnder the activity.

14. SpecifySetStateOfTargetStateNameThe property isWaitCoinsState.

15. Return to the status editor view of the Workflow view designer and clickWorkflow1The hyperlink button in the upper left corner.

The status editor displaysStartStateDirectionWaitCoinsState.

16.StartStateNow it is complete. Next we will goWaitCoinsState. First dragEventDrivenActivity to the designer interface and place itWaitCoinsState. In the attribute panel of Visual StudioNameModify attributeCoinInserted.

17. Double-clickCoinInserted EventDrivenActivities make the sequence Workflow Editor appear.

18. DragCoinInsertedCustom activity to thisEventDrivenThe surface of the activity. Note: If you have not compiled the entire solutionCoinInsertedEvents are not displayed in the toolbox. If you missed step 1, you may have to removeEventDrivenActivity for successful compilation.

19. SelectExternalEventHandler CoinInserted1Activity, clickCoinValueProperties to activate the Browse (...) button, and then click the Browse button. This opens the "bind 'coinvalue' to activity attributes" dialog box. Click the "bind to new member" tab and enterLastCoinDropped. In this case, you should select "create Attribute". If not, select it so that you can create a new dependency attribute. Click "OK ".

20. Now we need to make a judgment: Have users just invested enough money to make those beverage buttons available? Therefore, dragIfElseActivity to the Workflow view designer interface, put itCoinInserted EventDrivenIn the activity, its location isCoinInserted1.

21. SelectIfElseActivity1To display its properties in the property panel. For itsConditonAttribute and select "code condition ". Then expandConditionAnd thenConditionSubattribute InputTestTotal. After adding a new method in Visual Studio and switching to the code editing view for you, return to the Workflow view designer.

22.TestTotalTotal amount that you finally put into the beverage machine. (We will complete the workflow design in the Workflow view designer before adding the code, because some of the attributes we need have not yet been created .) If we invest enough money, we need to switchWaitSelectionState. Therefore, dragSetStateTo thisIfElseActivity (IfElseBranchActivity1) On the left branch, specify itsTargetStateNameIsWaitSelectionState.

23. SupposeTestTotalThe workflow determines that there is not enough amount to buy a beverage. The workflow needs to convey the total amount of money currently invested in the beverage dispenser. Therefore, dragUpdateTotalAnd put it inIfElseThe right branch of the activity.UpdateTotalIs a customCallExternalMethodActivity.

24.UpdateTotalRequires a total value to be communicated, so select itsTotalProperties and click the Browse (...) button to open a new binding dialog box. When the BIND dialog box opens, select the "bind to new member" tab and enterTotalConfirm that the "create Attribute" option is selected. Click "OK ".

25. Click the Hyper Text style in the upper left corner.Workflow1Return to the status designer view. DragStateFinalizationGo to the Workflow view designer interface and place itWaitCoinsState.

26. Double-clickStateFinalizationActivity1Activity reactivate the sequence designer view.

27. DragReadyToDispenseAnd put it inStateFinalizationActivity1.ReadyToDispenseIt is also a customCallExternalMethodActivity.

28. What you just addedReadyToDispense1The activity returns the final total value to the main application. To do this, it needs to accessTotalAttribute. LookReadyToDispense1ClickFinalTotalProperties, and then clickFinalTotalIn the browser (...) button. Click the Browse button to open the binding dialog box, but this time it is "binding to existing members ". Select from ListTotalClick "OK ".

29. Click the hypertext StyleWorkflow1Return to the status designer view. SelectEventDrivenActivity and put it on the designer InterfaceWaitSelectionStateActivity. Name itItemSelected.

30. Double-clickItemSelected EventDrivenThe activity goes to the sequence designer view.

31. Drag a customExternalEventHandlerActivitiesItemSelected, Put it inItemSelected EventDrivenActivity.

32. The main application triggersItemSelectedEvent. When this event occurs, we need to switchEndState. To do this, we need to addSetStateActivity. Therefore, dragSetStateAnd put it inItemSelected EventDrivenActiveItemSelected1. Specify itsTargetStateNameIsEndState.

33. Click the hypertext style button.Workflow1Return to the status designer view.

34. From the perspective of the Workflow view designer, this workflow is complete, but we need to write some code. In the solution manager of Visual Studio, selectWorkflow1.csFile, and then open the file in code editing mode to prepare for editing.
35. ViewWorkflow1.csSource file, findResetTotalMethod. Insert the following codeResetTotalMethod:

 // Start with no total.
Total = 0.0m;

36. Finally, findTestTotalMethod. Add the following code for this method:

 // Add the last coin dropped to the total and check
// to see if the total exceeds 1.25.
Total += LastCoinDropped;
e.Result = Total >= 1.25m;

37. Compile the entire solution. Fix any possible compilation errors.
Now you can press F5 or Ctrl + F5 to run the application. Click a coin button. Is the total amount displayed on the LCD updated? Can you choose a drink when you invest enough money?
  Note: If the application crashes due to InvalidOperationException, it is most likely that the reference is not completely updated after the solution is compiled for the first time. You can simply recompile the entire application (Repeat Step 1) and run the application again. It should be able to run cleanly.

Source code: contains the exercise project and complete code in this chapter.

Next article: WF from entry to mastery (Chapter 1): workflow and transactions

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.