Execute Windows Workflow Rules without Workflow
Embedding business rules is very powerful and useful. If you are using Windows Workflow Foundation you can model you business process and use a PolicyActivity. But If you don't want to model your business process with a workflow, but still want to execute rules in it?
The Windows Workflow Foundation Rules Engine has the API for it. I'll take this post to explore it a little bit and give some examples.
You can run a RuleSet against any object…
Typically you would execute your RuleSets against you workflow, to change the workflow state according to some properties. But, you can also execute rules againt any other .net object.
Create a RuleSet
The RuleSet Editor Dialog is exposed as part of the API, so you can use it to create RuleSets as part of your program:
// Create a RuleSet that waorks with Orders (just another .net Object)
RuleSetDialog ruleSetDialog = new RuleSetDialog(typeof(Order), null, null);
// Show the RuleSet Editor
ruleSetDialog.ShowDialog();
// Get the RuleSet after editing
RuleSet ruleSet = ruleSetDialog.RuleSet;
Serialize and Deserialize rules
Windows Workflow Foundation uses the WorkflowMarkupSerializer to Serialize and Deserialize rules.
// Serialize to a .rules file
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
XmlWriter rulesWriter = XmlWriter.Create(fileName);
serializer.Serialize(rulesWriter, ruleSet);
rulesWriter.Close();
// Deserialize from a .rules file.
XmlTextReader rulesReader = new XmlTextReader(fileName);
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
ruleSet = (RuleSet)serializer.Deserialize(rulesReader);
rulesReader.Close();
Execute RuleSet againt an object
Execute your RuleSet after editing, serializing and deserialising it, but first validate that the rules can be executed against the input object.
// Execute the rules and print the entity's properties
Order myOrder = new Order(...);
RuleValidation validation = new RuleValidation(typeof(Order), null);
RuleExecution execution = new RuleExecution(validation, myOrder);
ruleSet.Execute(execution);
Download a sample project that demonstrates creation, editing, serialization and execution of RuleSet against a custom object.
Enjoy!