Search code examples
c#workflow-foundation-4

WF4 While activity condition in code


I am building a workflow in my code, and I don't know how I can add a simple (While) condition. Tried to figure out how, but no luck with it, search on the internet but no luck either.

This is a simplified version of what I am trying to do:

ActivityBuilder ab = new ActivityBuilder();
ab.Implementation = new Sequence()
{
  Variables = 
  {
     new Variable<int>("StepNo", 0)
  },

  Activities =
  {
    new While()
    {
      Condition = <the_condition>

      Body = 
      {
        //Some logic here and the StepNo is increased
      }
    }
  }   
}

The While condition should be something like "StepNo < 10". Any idea how can this be made?


Solution

  • var stepNo = new Variable<int>("stepNo", 0);
    
    var activity = new Sequence
    {
        Variables = 
        {
            stepNo
        },
    
        Activities = 
        {
            new While
            {
                Condition = new LessThan<int,int,bool>
                {
                    Left = stepNo,
                    Right = 10
                },
    
                Body = new Sequence
                {
                    Activities = 
                    {
                        new Assign<int>
                        {
                            To = stepNo,
                            Value = new Add<int, int, int>
                            {
                                Left = stepNo,
                                Right = 1
                            }
                        },
    
                        new WriteLine
                        { 
                            Text = new VisualBasicValue<string>("\"Step: \" & stepNo") 
                        }
                    }
                }
            }
        }
    };
    

    Or a version without expression activities but only with VisualBasicValue, which is also an activity:

    var stepNo = new Variable<int>("stepNo", 0);
    
    var activity = new Sequence
    {
        Variables = 
        {
            stepNo
        },
    
        Activities = 
        {
            new While
            {
                Condition = new VisualBasicValue<bool>("stepNo < 10"),
    
                Body = new Sequence
                {
                    Activities = 
                    {
                        new Assign<int>
                        {
                            To = stepNo,
                            Value = new VisualBasicValue<int>("stepNo + 1")
                        },
    
                        new WriteLine
                        { 
                            Text = new VisualBasicValue<string>("\"Step: \" & stepNo") 
                        }
                    }
                }
            }
        }
    };