PowerShell Rules Engine: How-To Technical Details
Posted by Igor Moochnick on 02/15/2008
In my recent article, Marrying Workflows into PowerShell (Part 1 of 2), PowerShell Rules Engine, I’ve shown an example of how to use a Rule Set editor, shipped with Workflows Foundation, in your own application and how to evaluate rules against managed objects. Actually, PowerShell was used as a specific example of how to use this technology.
I haven’t invented anything new and this information is readily available from different public sources, but, I think, it’ll be better if I’ll explain how it works for the readers of this blog.
There are 3 simple steps to get this technology to work for you:
- Create and edit rule sets via the Rule Set Dialog and serialize the rules into an XML
- Load (deserialize) the Rule Set from an XML file
- Evaluate/apply the rules against your own objects
The step #1 is implemented in the ShowDialog function:
Note line #3 – if you’ll provide a valid instance of a Rule Set – the editor will allow you to edit it, if you don’t have a Rule Set, provide a new instance in the editor will fill it in with your new rules. In the line #15 the newly edited Rule Set is written (serialized) to an XML file with WorkflowMarkupSerializer.
The step #2 is implemented in the LoadRules function:
Note that this function is doing a reverse Rule Set deserialization with the WorkflowMarkupSerializer and returning a Rule Set instance (if everything wen right).
The last, and the most important step #3, is executed in the Run-Rules CmdLet. It evaluates the rules against each and every PSObject in the command pipeline.
First the rule set is validated against the target type (lines #2-3), the same type used while creating the rule set in the first time (line #4 in ShowRulesDialog). Then the rules are applied to the managed object (lines #17-18). The rules can modify the object which can change the flow of the logic. In line #20 the code checks if the StopProcesing flag was set or cleared which forces the object to be written back to the command pipe or omitted.
Hope this post was educational and showed how easy it is to use the Rule Set editor in your applications.