State Machine Work flow Discussion


Introduction

All characters in this article are fictional and any resemblance to live or dead is purely coincidental.

This is a nice talk between Mr. RC and Mr. Shiv about state machine work flow. RC starts talking about an order project and they end up in a nice discussion which gives us step by step approach of how to execute a state machine work flow.

This article was written in a straight half & hour session so please excuse for my English as it's my second language and for any spelling mistakes.so guys enjoy State machines. 

The State machine Work flow discussion

Ramprasad Chaurasiya:-  Hi Shiv how's things ?

Shivprasad Koirala :-  Doing great RC ( Ramprasad Chaurasiya ) ?

RC: - You have written more than 60 articles that's huge, looks like you are copy pasting articles from MSDN and other sources.

Shiv: - Hmmm, can we talk something better before you reveal me completely J ?.

RC: - I was reading your article on WWF. I am working currently on an order processing project and I am bit confused how the workflow aspect of the project should be approached.

Shiv: - Can you explain me the workflow part of your order project?

RC: - Ok here's the requirement for the order and also I have drawn a small sketch of how the work flow looks like:-

  • The work flow starts by user placing an order.

  • Accounts department logs in and checks if payment is made for the order. If the payment is not made then they mark the order as cancelled and it's sent to the user for payment.

  • Once the user makes the payment the order is moved to a valid order placed stage again.

  • Purchase department logs in and check if the product is in stock for the order.

  • If the product is in Stock the purchase department person enters saying the product is Instock and the order is then ready for dispatch.

  • Courier department logs in and check if the address of the order is proper. If address is not proper the order is moved to a pending stage and sent to the end user for address correction.

  • In pending stage if the user corrects the address the order is then moved back to ready for dispatch.

  • If the order is dispatched and received by the end user the delivery person marks the order as delivered.
     


 

Shiv: - Hmmm, it's an interesting work flow. This can be very easily solved by using Windows work flow foundation. The first step we need to decide is which kind of work flow we need to choose for the above.

RC: - ohhh , Are there different kind of work flows in Windows Work flow.

Shiv :- Primarily there are two kinds of work flows in WWF and depending on the nature we need to choose the work flow accordingly.

RC:- That's funny I thought a work flow is just a collection of activities which is executed depending on certain conditions. For instance below figure shows a simple work flow which has customer activities, some if condition depending on which the activities are executed. In other words what I want to say is workflow is workflow what do you mean by types of work flow.


Shiv :-  From windows work flow point of view there are two types of workflow the first is a sequential work flow and the second is a state machine work flow.

A sequential workflow has clear start and finish boundaries. Workflow controls execution in Sequential workflow. In sequential execution, one task is executed after other. Sequential workflow is more rigid in format and execution path has a determistic nature.

A State machine workflow is more dynamic in nature. Workflow has states and the state waits for events to help it move to next state. In State machine execution path is undetermestic nature.

Below figure shows visual conceptualization of fundamentals. You can see in Sequential workflow the execution path is very determent. Shiv performs the entire task sequentially and these tasks are very determent. Now have a look at the second workflow. Every state goes to other state when it receives some external events. For instance when Shiv is seeing star trek there is an event of flashing news which triggers him to see the flashing new.

RC :- In other words what we can say is that if the work flow controls the execution then its sequential and if there is some external factor which controls the work flow then it  becomes a state machine workflow.

Shiv: - Yes, that's a good summary. Looks like you have started thinking in  terms of work flows. So now let's first decide your order project is of which kind of work flow.

RC (Thinking):- Well I think it's a sequential work flow ,as the work flow has a control on the execution.

Shiv :- Ok , so let me redraw your workflow diagram , below is your changed diagram. You can see there are so many inputs from the user which changes your workflow. For instance the accounts department depending in the payment diverts the workflow, purchase department depending on stock value divert the flow and same holds true for the courier person.

RC: - I understand where you are coming from. My work flow is not in control of himself. Ok, I buy back my point my order project is of a state machine work flow.

Shiv :-  A few comments on work flow type before we move ahead. Many architects get carried with sequential work flow. If you see in your application that depending on user inputs your workflow is changing then it's a good idea to think about state machine. Ok, let me comment from more practical point of view. In actual projects it's a combination of these types rather than just one type. In other words you can have a broader state machine work flow which has lot of sequential work flow in between and vice versa.

RC :- What I also think is we should also look from the domain perspective what kind of work flow it actually looks like. Ok, this sounds good. So how can we now move ahead?

Shiv :- So let's first try to visualize what are the important elements in state machine work flow. There three important things in state machine work flow initial state , action and the final state.  You can see from the figure a simple example of state machine. So you have a initial state, a action happens and it moves to the some other state. For instance a bulb is first in a on state and then switch off and it moves to a off state.

RC :- Ok , I am trying to get a feel of state machines.

Shiv :-  So let's first visualize the whole order work flow from these three aspects. So below is a table which shows the whole work flow from the above three perspective.

First state

Action / Event

Next state

Order placed

InStockEvent

Order Approved

Order placed

NotPaidEvent

Order cancelled

Order cancelled

PaymentMadeEvent

Order placed

Order Approved

AddressNotProperEvent

Order Pending

Order pending

AddressCorrectedEvent

Order Approved

Order Approved

DispatchedEvent

Order Delivered

RC :- Ok , that a good visualization. So what I understand is we have in all 4 different states and some 6 to 7 events. I think our state machine diagram will look something as below.

Shiv :-  nice you are catching up on state machines. Ok now that we are clear about our states and about our events. It's time to make the complete work flow using WWF.

RC :- That sounds sense. I really do not like theory there should be some practical implementation.

Shiv :- We will be using VS 2008 enterprise and .Net 3.5

RC :- Why not express edition ?.

Shiv :- Well WWF does not come with express edition.

RC :- Ok noted.

Shiv :- So before we move ahead and talk about practical. There's a one more point we need to cover. In a typical work flow project we have two important things one is the work flow and the second is the client which can be windows or web application which consumes that work flow. In state machine work flow we need to define a interface with all action. This interface is the only thing which the work flow knows. So any client who wants to invoke the work flow should make calls using this interface.

RC :- Ok , got it so this interface is the gateway to make calls to the work flow.

Shiv :- Yes you said right. So below is our interface, so that the first step we need to do create the interface. So we below figure shows that we have created a "IOrder.cs" interface. The important point to note is we have referenced "System.Workflow.Activities" and attributed the interface with "ExternalDataExchange". We have then define all our events for the states in this interface.



RC :- That's a pretty simple step.

Shiv: - Ok now do add new project and select "State machine work flow library"


Shiv :- Once you create the work flow project you will be popped up with a work flow designer as shown below. Now every state in a work flow had events so go the work flow tool box and drag and drop the event driven component on the state activity.

RC: - Hang on shiv, correct me if I am wrong. As per our discussion logically every state should have events by which the state changes its action and it should also have which next state it should move after the event.

Shiv :-  You are absolutely right. So double click on the state and drag two things one is handle external event which defines which event it should listen to and second is the set state which says which is the next state it should move on.

RC :- Ok great. So how should we define the events and next state for the state.

Shiv :- If you remember we had defined a interface. It's time to start using it. So go to the properties of the handle event and select the interface type and the event for the same. The below figure shows the state is order placed and we need to handle the instock event.

Shiv :- Now to specify the  next state. So goto the property of the set state component and specify target state name.

Shiv :- So create states , create event we need to handle in the states and the next state. You will see you end up in to something like as shown below.

RC :- The visuals look great and appealing.

Shiv :- Yeah! The most important part for WWF is to get a feel of the  work flow development..

RC :- Ok , this sounds good. What next.

Shiv :- One of the most important points we have forgotten is we need to make our concrete class which will be called by the client. So let's implement the interface Iorder.  You can see the below class clsOrder which implements IOrder. We have just displayed simple console messages. Remember this concrete class will called by client and all the below methods of the class will be invoked by the client. This class internally calls the interface which in turn invoked the work flow engine.

    public class clsOrder : IOrder
    {
        #region IOrder Members
        public event EventHandler<ExternalDataEventArgs> NotPaid;
        public event EventHandler<ExternalDataEventArgs> InStock;
        public event EventHandler<ExternalDataEventArgs> PaymentMade;
        public event EventHandler<ExternalDataEventArgs> Dispatch;
        public event EventHandler<ExternalDataEventArgs> AddressNotProper;
        public event EventHandler<ExternalDataEventArgs> AddressCorrected;
        public event EventHandler<ExternalDataEventArgs> ProductStocked;
        #endregion
        public void CallNotPaid(ExternalDataEventArgs args)
        {
            NotPaid(null, args);
            Console.WriteLine("This order is not paid");
        }
        public void CallInStock(ExternalDataEventArgs args)
        {
            InStock(null, args);
            Console.WriteLine("Product is InStock");
        }
        public void CallPaymentMade(ExternalDataEventArgs args)
        {
            PaymentMade(null, args);
            Console.WriteLine("Payment is made for this Order");
        }
        public void CallDispatch(ExternalDataEventArgs args)
        {
            Dispatch(null, args);
            Console.WriteLine("Dispatch the Order");
        }
        public void CallAddressNotProper(ExternalDataEventArgs args)
        {
            AddressNotProper(null, args);
            Console.WriteLine("Adress is not Proper");
        }

        public void CallAddressCorrected(ExternalDataEventArgs args)
        {
            AddressCorrected(null, args);
            Console.WriteLine("Adress is corrected");
        }

        public void CallProductStocked(ExternalDataEventArgs args)
        {
            ProductStocked(null, args);
            Console.WriteLine("Product is stocked");
        }
    }

RC :- Oh ok. So this class will be consumed by the client right.

Shiv :- Yes that absolutely right. So we need to create the work flow instance using the work flow runtime and start the instance. We also need to add the order class clsorder object as a service.

WorkflowInstance objWorkFlowInstance;
WorkflowRuntime objWorkFlowRuntime = new WorkflowRuntime();
clsOrder objOrder = new clsOrder();
ExternalDataExchangeService objService = new ExternalDataExchangeService();
Guid InstanceId = Guid.NewGuid();
objWorkFlowRuntime.AddService(objService);
objService.AddService(objOrder);
objWorkFlowInstance = objWorkFlowRuntime.CreateWorkflow(typeof(OrderWorkFlow.WorkflowOrder), null, InstanceId);
objWorkFlowInstance.Start();

RC
:- Ok , so how will the complete client code look like.

Shiv :- So below is the code snippet which shows how our client code looks like. What I have done is I am taking inputs and invoking the work flow methods accordingly.

         WorkflowInstance objWorkFlowInstance;
            WorkflowRuntime objWorkFlowRuntime = new WorkflowRuntime();
            clsOrder objOrder = new clsOrder();
            ExternalDataExchangeService objService = new ExternalDataExchangeService();
            Guid InstanceId = Guid.NewGuid();
            objWorkFlowRuntime.AddService(objService);
            objService.AddService(objOrder);
            objWorkFlowInstance = objWorkFlowRuntime.CreateWorkflow(typeof(OrderWorkFlow.WorkflowOrder), null, InstanceId);
            objWorkFlowInstance.Start();
            Console.WriteLine("Work flow started");
            ExternalDataEventArgs objDataEventArgs = new ExternalDataEventArgs(InstanceId);
            objDataEventArgs.WaitForIdle = true;
            Console.WriteLine("1 - This order is not paid");
            Console.WriteLine("2 - Product is InStock");
            Console.WriteLine("3 - Payment is made for this Order");
            Console.WriteLine("4 - Dispatch the Order");
            Console.WriteLine("5 - Adress is not Proper");
            Console.WriteLine("6 - Adress is corrected");
            Console.WriteLine("7 - Product is stocked");
            Console.WriteLine("Enter Appropriate inputs ");
            int intValueEntered = 0;
            while (intValueEntered < 7)
            {
                intValueEntered = Convert.ToInt16(Console.ReadLine().ToString());
                if (intValueEntered == 1)
                {
                    objOrder.CallNotPaid(objDataEventArgs);
                }
                else if (intValueEntered == 2)
                {
                    objOrder.CallInStock(objDataEventArgs);
                }
                else if (intValueEntered == 3)
                {
                    objOrder.CallPaymentMade(objDataEventArgs);
                }
                else if (intValueEntered == 4)
                {
                    objOrder.CallDispatch(objDataEventArgs);
                }
                else if (intValueEntered == 5)
                {
                    objOrder.CallAddressNotProper(objDataEventArgs);
                }
                else if (intValueEntered == 6)
                {
                    objOrder.CallAddressCorrected(objDataEventArgs);
                }
                else if (intValueEntered == 7)
                {
                    objOrder.CallProductStocked(objDataEventArgs);
                }
            }


RC
:- Ok let me run it. Great I can see the order is first placed , then when I entered 2 the product moved in stock and when I did dispatch it moved in a delivered state.


Shiv :- The most important part in work flow is the work flow logic is now in your work flow project and your business component are self contained and they are doing their own activity.

RC :- Great man, From where can I download the Source code? Tonight at home I would like to see the same.

Source Code


Shiv
:- You can find the Source code at the top of this article.

In case you are still not clear with work flow basic you can go and read Windows Workflow Foundation (WWF).

Up Next
    Ebook Download
    View all
    Learn
    View all