My software needs to have some sort of rules library. Is there anyway I can serialize a single rule?
Why a single rule? Because prior to actual rule engine execution, I'd want to be able to add some specific rules into my RuleSet, and execute that RuleSet through a windows workflow rule engine.
As per the example given here, I know I can serialize a RuleSet?
Here is a brief of how its done:
1. Creating reference to the discount property this.Discount
CodePropertyReferenceExpression discountProperty =
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression(),
"Discount");
2. Creating reference to the orderValue property
CodePropertyReferenceExpression orderValueProperty =
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression(),
"OrderValue");
3. Defining condition on orderValue object
// if this.OrderValue > 500
RuleCondition discountCondition = new RuleExpressionCondition(
new CodeBinaryOperatorExpression(
orderValueProperty,
CodeBinaryOperatorType.GreaterThan,
new CodePrimitiveExpression(500)));
4. Defining the rule action
// Create an action that sets the property Discount to 5%
RuleStatementAction setDiscountAction = new RuleStatementAction(
new CodeAssignStatement(discountProperty,
new CodePrimitiveExpression(5)));
5. Creating the RuleSet
Rule discountRule = new Rule("CalculateDiscount");
discountRule.Condition = discountCondition;
discountRule.ThenActions.Add(setDiscountAction);
ruleSet = new RuleSet("DiscountRuleSet");
ruleSet.Rules.Add(discountRule);
6. Seralizing the ruleset
RuleDefinitions ruleDefinitions = new RuleDefinitions();
ruleDefinitions.RuleSets.Add(ruleSet);
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
XmlTextWriter writer = new XmlTextWriter("MyRules.rules", System.Text.Encoding.Unicode);
serializer.Serialize(writer, ruleDefinitions);
writer.Close();
7. Executing the ruleset
RuleEngine engine = new RuleEngine(ruleSet, typeof(Shopping));
// execute the rule on a shopping object where OrderValue = 100
// expect rule action to be not fired
Shopping shoppingUnder500 = new Shopping(100);
engine.Execute(shoppingUnder500);
Console.WriteLine("shoppingUnder500 - Discount evaluated: " + shoppingUnder500.Discount);
You can get a full example at the link mentioned in the beginning. Pt 6 describes how you can persist a rule set. But I want to know if we can serialize a rule, which is nothing but a codedom condition expression & a set of statements (actions) (again represented by codedom).
Or what is a better way to store a single rule somewhere?