I got asked recently if it was possible to use the Workflow Rules engine to remove items from a collection.

It turns out that it's actually quite easy to do, as long as you understand how the rules engine works, and how to iterate over collections.  So before I show you how to remove items from a collection, let's run through how you can use a rule set to iterate through a collection.

Oh, before we go any further, this blog post is based on the "RulesWithCollectionSample" that you can get from the netfx3 site.

So if you haven't already done so, go to the site, download the sample and make sure everything compiles and runs properly. P.S. make sure you have the ExternalRuleSetToolkit sample from the site as well since the RulesWithCollections.rules file that comes with the sample need to be imported into the database using the ExternalRuleSetToolkit.

What you should see when you run the sample is a screen that looks like the following:


When you click on the "Calculate on Object Collection" the workflow rules engine is invoked, calculates the sum of the individual items in the collection and displays the result next to the button.

The question is how?

Understanding Rule Chaining

The key to this sample is an understanding of how the rules engine works.  The rules engine is a forward chaining rules engine, which in simple terms means that if a rule relies on a property in it's evaluation and a subsequent rule changes the value of that property then the rule will be reevaluated as well as any subsequent rules in the chain.

What this means is that if we have 2 rules defined as follows:

1) if Customer.Priority = 2 then CallCentre.StaffType="Manager" else CallCentre.StaffType="Normal"

2) if Customer.Name = "Special Customer" then Customer.Priority=2

And if the customer in question is a "Special Customer" with a priority of 0 then what will happen is the following:

i) The Condition clause for Rule 1 will get evaluated.  Because Customer.Priority is part of the condition (ie the rule depends on that value) then the Customer.Priority property will be tracked by the rules engine.  Conversely, the CallCentre.StaffType is not part of the rule condition and is therefore not tracked by the rules engine.

ii) Because the customer has a priority of 0 the CallCentre,StaffType is assigned to "Normal".

iii) Rule 2 is evaluated and since the Customer.Name matches the condition the Customer.Priority value is changed to 2.

iv) Here's where the magic happens.  The rules engine detects that the Customer.Priority value has changed and that Rule 1 (which is higher in the rule chain) depended on that value in it's evaluation.  The rules engine stops processing any further rules, goes back to Rule 1 and re-executes it, resulting in the CallCentre.StaffType value being changed to "Manager".

And before you ask, yes - it's entirely possible to set up an infinite loop in your rules when chaining is being used.

For this reason and because you don't always want the chaining to happen it is possible to change the default chaining behavior of a rule set.

Iterating Collections

OK, now to the sample code.

As shown above the sample has a list of numbers in the list box.  When you click on the "Calculate On Object Collection" button an Order object is created that contains a collection of OrderItem objects.  Each OrderItem in the collection has a price based on the corresponding list entry.

The workflow rules engine is then invoked on the Order object using the OrderRuleSet which in turn iterates over the elements in the collection and calculate the sum of the OrderItems giving a total order value.

Now, unless you were particularly into self-harm this is not something you would normally do via the rules engine but it does show you the principle involved in collection iteration.

Let's have a look at the ruleset.  You should see that there are 4 rules all at different priority levels.  The first rule to be executed is the one with the highest priority (larger numbers are higher priorities) - the Initialize rule.

The Initialize rule merely obtains the enumerator for the OrderItems collection and assigns it to the Order.enumerator property.

Rule: Initialize

Condition: 1 == 1

Then: this.enumerator = this.OrderItems.GetEnumerator()

Else: ---

What's with that 1 == 1 business?  Well, all it does is force the Condition to evaluate to tru.  My personal preference if you want to use something to always evaluate to true is to use "true".  Using 1 == 1 just feels wierd.

The next rule, IteratorOverItems, performs a MoveNext using the iterator we obtained in the inialise shed.  MoveNext will return true until it reaches the end of the collection.

Rule: IteratorOverItems

Condition: this.enumerator.MoveNext()

Then: this.CurrentItem = (RulesWithCollectionSample.OrderItem)this.enumerator.Current
System.Console.WriteLine("Assignedenumerator" + this.OrderItems[0].Price)

Else: System.Console.WriteLine("we are all done")

If MoveNext didn't fall off the end of the collection, we take the current item from the iterator and assign it to the Order.CurrentItem property.  We could reference the value from enumerator.Current in later stages, but by placing the value in a specific property we make it easier for the rules engine to know when the value changes.

The next rule is the IndividualItem rule

Rule: IndividualItem

Condition: this.CurrentItem != null

Then: this.Total = this.Total + this.CurrentItem.Price * this.CurrentItem.Quantity
System.Console.WriteLine("Running Total: " + this.Total.ToString())

Else: System.Console.WriteLine("current item is null")

So, we check if the Current OrderItem the iterator gave us still references a real, live, breathing object and if it does we add the OrderItem total cost onto the Order object's Total.

So, that's it.  3 simple rules and we're done.

Well not quite.  If we ran this rule set now, we would only ever get the total using the first OrderItem in the collection.

We need some way to cause the enumerator.MoveNext() method to get reevaluated so we can get the next OrderItem from the collection, but the only way a rule gets re-evaluated is when the objects used in the Condition change.  We don't want to change the iterator itself, we just want to call MoveNext() again.

Explicit Chaining

This is where the final rule kicks in.

Rule: FInished

Condition: this.CurrentItem == this.CurrentItem

Then: System.Console.WriteLine("Finished True")

Else: System.Console.WriteLine("Finished False")

First up we check this.CurrentItem against itself.  It should always return True, so the Then action in the rule will get evaluated.

In here you'll notice the use of the Update method.

The Update method is part of the rules engine and tells the engine that a property (or properties) has been changed and any rules that depend on that property should be re-evaluated.  You don't actually have to change the value of the property itself, you're just telling the rules engine to act as if the value changed.

The IteratorOverItems rule uses the this.enumerator property in it's condition.  Updating the enumerator will cause the rule to be reevaluated, causing MoveNext() to be called, which in turn updates the CurrentItem property, causing the IndividualItem property to be reevaluated and thus incrementing the Order.Total property to give us our total.

After seeing this there's a few questions you might ask:

What's up with that weird slash notation in the Update statement? Think of it like a path to a property.  In this case there is only one property, but the Update statement allows you to mark multiple properties as updated using wildcards. e.g Update("this/*").  If you want to use dot notation that's fine as well.  Just use Update(this.enumerator) - no quotes.

Why does the Condition use this.CurrentItem and not just use True?  Simple.  Once a rule is evaluated it is marked as done.  It will only ever get reevaluated if the properties in it's condition clause are updated.  The value "True" is a constant so the rule would never get re-evaluated.  By using this.CurrentItem, every time the current item changes this rule gets evaluated again.


So, now we have a pattern to how to iterate collections:

1. Get the enumerator

2. Use MoveNext and get the Current element of the collection

3. Do something with that current item (ie your business rules, etc).  Make sure the Current Item is used in the Condition so the the rule is reevaluated for each item

4. Call Update() on the enumerator to force re-evaluation of the IteratorOverItems rule and ensure that this rule uses CurrentItem in the condition.


Deleting Items In A Collection

Phew! Now that we know how to iterate over a collection how about we try and delete something from it.  Let's try removing every OrderItem with a price greater than 20?

It's pretty much the same as iterating the collection, but the thing to watch for is that when you delete an element from a collection you invalidate the enumerator and have to get a fresh one.  We'll need some way to force the enumerator to get refreshed.

Rule: Initialise (priority 2)

Condition: this.ID == this.ID

Then: this.enumerator = this.OrderItems.GetEnumerator()
System.Console.WriteLine("Got the enumerator")

Else: System.Console.WriteLine("Didnt get the enumerator")

Note the difference here.  The condition is no longer 1 == 1 (or True).  Why, because we're going to Update() the ID property after we delete an element to force the rule to re-evaluate, in turn refreshing our enumerator.

Rule: Iterate (priority 1)

Condition: this.enumerator.MoveNext()

Then: this.CurrentItem = (RulesWithCollectionSample.OrderItem)this.enumerator.Current
System.Console.WriteLine("Got an item")

Else: System.Console.WriteLine("No more items")

This is the same as the previous Iterate rule.  Nothing different at all

Rule: IndividualItem (Priority 0)

Condition: this.CurrentItem != null && this.CurrentItem.Price > 20

Then: System.Console.WriteLine("Got an item over 20")
System.Console.WriteLine("About to remove an item")

Else: System.Console.WriteLine("Got an item under 20")

Ok, here's where the action is.  In the Condition we check the CurrentItem for null and then check it's price.  If the item is null or the price is under 21 then we'll execute the Else actions.

The Else action just calls Update() on the enumerator - just like in the collection iteration ruleset above.

But what happens when the price is over 20?

First we remove the item from the collection using the normal .NET Remove method.

We then mark the ID field of the Order object as updated using the Update() statement.  This causes the Initialise rule to get reevaluated, which results in restarting our collection processing all over again.

If we were to just Update() the enumerator using Update(this.enumerator) instead, we would get a run time error when MoveNext() is called since the collection has been changed.  Forcing the Initialise rule to get reprocessed ensures that we get a fresh enumerator for the collection and avoids the run time errors.