Calling the BRE from .NET Applications

For an improved version of the code below, click here

One common misconception regarding the Business Rules Engine is that you need BizTalk to use it. Actually, you can call the Rules Engine from any .NET code. Below is some sample code that takes in a message and runs it against a specified policy.

Our incoming message in this example is an XLANGMessage as one would find while working with BizTalk, but it needn’t be. Note that before calling the rules engine, we had to go through some machinations to convert the message into an XmlDocument. If you start off with an XmlDocument in the first place you can remove the conversion code and the reference to the System.IO and the Microsoft.XLANGs.BaseTypes namespaces.

using System.Xml;
using System.IO;
using System.Collections;
using Microsoft.XLANGs.BaseTypes;
using Microsoft.RuleEngine;

public static XmlNode CallRules(string policyName,
    XLANGMessage msg, string messageDocType)
    //Convert to XmlDocuments
    Stream msgStream = (Stream)msg[0].RetrieveAs(typeof(Stream));
    XmlDocument doc = new XmlDocument();
    doc.PreserveWhitespace = false;

    //Add the facts
    ArrayList facts = new ArrayList();
    facts.Add(new TypedXmlDocument(messageDocType, doc));

        using (Policy policy = new Policy(policyName))
    catch (Exception ex)
        throw ex;

    //retrieve the return document from the output array
    return ((TypedXmlDocument)facts[0]).Document;

The code here is geared toward working with Xml. However, rules may also be executed against .NET components–you just have to make sure that you initialize them and send them to the BRE as facts by adding them to the “fact array”. After executing the policy, whatever changes the rules engine made to the “fact” would be present when retrieved from the array.

Please feel free to reply or email with your comments, questions, or advice!

About Ed Jones

Ed is a .NET and Integration architect for Avanade in the Twin Cities. Contact Ed

What do you think?

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: