Flowcharts in Workflow 4 and the Switch activity
Note: This blog post is written using the .NET framework 4.0 Beta 2
Flowcharts are a nice addition to Windows Workflow Foundation 4. They allow for a lot of pretty complex behavior that is hard to do in a sequential workflow. In WF 3 we used to model these complex behaviors as state machine workflows. That worked but they weren't really state machines or event driven and things could get a bit tricky.
Enter the flowchart in Windows Workflow Foundation 4
One of the good things is that a flowchart is not another workflow type. No it is just another activity to drop in a workflow. So you are free to combine sequential work with a flowchart in one workflow. For example you can have a Sequence activity containing a Flowchart activity and that in turn can contain another Sequence activity which can contain another …. I guess you get the picture.
Below a Flowchart containing a mix of a FlowSwitch and a FlowDecision activity, which are only usable in a Flowchart, and some other general activities like a WriteLine and an Assign activity.
So far so good.
The one thing I don’t like is the FlowSwitch activity
The problem with the FlowSwitch is that the activity takes an expression determining the branch to execute and each branch has a case property to determine which branch is executed. Sounds like a good plan except when you start trying things. What I did was add a Random variable named rnd to the workflow so different branches would execute. To do this I added the following expression to the FlowSwitch:
Next in each of the first 3 cases I entered 1, 2 and 3 leaving the 4th as default. Sounds good right?
Well not quite!
When I ran the sample I would only get Default printed to the console. Well I guess with Random that is possible to try again. And again.
Hmm something must be wrong here.
It turns out all the cases are of type string and the expression is of type Int32. Those are never going to match! But there are no compile or runtime errors either. I am sure this is going to bite me some time in the future
Of course the FlowSwitch should just to a ToString() on the expression result, anything else would be pointless as any comparison fails. But as it doesn’t we have to do so ourselves. So I changed the Expression to:
and everything works as expected.