Running RuleSets Programmatically
In addition to running RuleSets using the PolicyActivity activity, you can run and evaluate rules within a RuleSet programmatically. For example, assume that you want to execute a RuleSet against an activity (a workflow or any other activity type) from within the activity code. The following code demonstrates how this is done:
RuleValidation validation = new RuleValidation(typeof(customActivity),
null);
// "this" in the call below refers to the activity instance.
RuleExecution execution = new RuleExecution(validation, this);
customRuleSet.Execute(execution);
Generally, when you use rules within a workflow, you would also pass the ActivityExecutionContext when constructing the RuleExecution instance. The primary advantage of providing the context is that you can send rule execution information to the host’s tracking provider.
You can also execute RuleSet objects using the RuleEngine object directly. The following code shows how this is done.
RuleValidation validation = new RuleValidation(typeof(customActivity),
null);
// "this" in the following call refers to the activity instance.
RuleEngine engine = new RuleEngine(customRuleSet, validation);
engine.Execute(this);
Note that if you just want to validate a rule set against a given type (for example, does it contain all the members referenced in the rules) you can express this as the following:
bool result = myRuleSet.Validate(validation);
The result of the Validate method call is true if the RuleSet is valid. The RuleValidation instance has an Errors property with the validation errors.
Note
You can also use RuleSets outside a workflow. The RuleSet could be written against any .NET Framework type.
See Also
Reference
RuleSet
Validate
RuleValidation
RuleExecution
ActivityExecutionContext
PolicyActivity