-->

Friday 28 November 2008

How to use NGinn rules engine

1. Required libraries

To use NGinn.RippleBoo engine in your application you need to add references to the following libraries:

  • NGinn.RippleBoo

  • Rhino.DSL.dll

  • Boo.Lang.dll

  • Boo.Lang.Compiler.dll

  • NLog.dll



2. Invoking RippleBoo

The code below shows how to configure rule repository and how to execute some rules.

using System;
using System.Collections.Generic;
using NGinn.RippleBoo;

class TestMe
{
private RuleRepository _repos;

public TestMe()
{
_repos = new RuleRepository();
_repos.BaseDirectory = "c:\\rules";
_repos.ImportNamespaces.Add("System");
}

public void RunSomeRules()
{
Dictionary<string, object> variables = new Dictionary<string,object>();
variables["Email"] = "my@email.com";
variables["Timestamp"] = DateTime.Now;

Dictionary<string, object> context = new Dictionary<string,object>();
context["Output"] = Console.Output;

_repos.EvaluateRules("some_rules.boo", variables, context);
}
}


RuleRepository class stores common configuration properties for your rules and allows you to call rules stored as '*.boo' files in base directory. It compiles the rule scripts and caches them so subsequent evaluations are fast. If rule script changes, it will be automatically recompiled. You should create rule repository once and hold it as long as needed.

Rule evaluation is done in 'RunSomeRules' method. To execute rules you call RuleRepository.EvaluateRules, passing the rule file name and two dictionaries.
First one contains variables that can be referenced from rules through 'Variables' object. The second one contains 'context' object, they can be referenced from rules throug 'Context' object.

Example rule:
ruleset "SomeRules":
rule "R1":
when Variables.Email.EndsWith("mydomain.com")
action:
Context.Output.WriteLine("Email from my domain")



This rule references the 'Email' variable and the 'Output' context object. Please note that in rules you don't have to quote the variable names - it's because of Boo language's IQuackFu magic interface.
RuleRepository.EvaluateRules method is thread safe.

No comments: