Navigation

Categories
Show Navigation Next Topic  »

Using Rules as Templates in Code Effects

IMPORTANT NOTE: This topic provides the core principles of rule templates and code excerpts from ASP.NET Core 2.0 Rules as Templates demo project. Please refer to that project for implementation details.

Rule templating is a great way to expand your rule authoring toolkit. Code Effects allows you to use any existing business rule as a template for other business rules.

For example, imagine the following business rule:

If Property A is not equal to ABC and Property B starts with XYZ then set Property C to 123

Now imagine that we need to have multiple rules, all having the same or similar logical structure as the rule above but with different values. The obvious solution is to use the first rule as a template for others. To do that we simply need to load the "template" rule into the Rule Editor, make changes, and save it as a new rule with new ID.

The process is very simple:

  • We need a way to tell our code whether we want to modify the existing template or create a new rule from it. There are tons of ways to do that. For instance, you could have two buttons, the Save as New Rule and Update Template. In this example we added the Save as a new rule checkbox.

    rule-templates

  • Our HomeController expects the value of that checkbox in its SaveRule action method as an indication whether we want to update the existing template or create a new rule from it. Here is a part of that method that deals with the new rule creation:

    string xml = editor.Rule.GetRuleXml();
    
    if (data.SaveAsNewRule)
    {
    	// Load the rule XML into a document object
    	XmlDocument rule = new XmlDocument();
    	rule.LoadXml(xml);
     
    	XmlNamespaceManager m =
    		new XmlNamespaceManager(rule.NameTable);
    	m.AddNamespace("x", rule.DocumentElement.NamespaceURI);
     
    	// Give this new rule a new ID
    	editor.Rule.Id = Guid.NewGuid().ToString().ToLower();
     
    	// Replace the "template" ID with the new one in rule's XML
    	rule.SelectSingleNode("/x:codeeffects/x:rule", m)
    		.Attributes["id"].Value = editor.Rule.Id;
     
    	// Save the resulting XML string as a new rule
    	xml = rule.OuterXml;
    }

Now you can create several rules based on your template:

If Property A is not equal to OPQ and Property B starts with BCD then set Property C to 999
If Property C is equal to 123 or Property A does not start with 999 then set Property B to 0 and set Property D to 1

Obviously, you can achieve the same result simply by creating these rules from scratch. But having the ability to use rules as templates for other rules makes your life a bit easier. Especially when they are combined with the reusable rules.


Post your questions on Stackoverflow and become a part of our growing community

Comments: 0