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;
doc.Load(msgStream);
//Add the facts
ArrayList facts = new ArrayList();
facts.Add(new TypedXmlDocument(messageDocType, doc));
try
{
using (Policy policy = new Policy(policyName))
{
policy.Execute(facts.ToArray());
}
}
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!
[…] Of course, another solution is to avoid use of the Call Rules shape altogether by calling the rules from a .NET component as described in my previous post on Calling the BRE from .NET Applications. […]
[…] As a point of interest (and necessity), we did not use the CallRules shape in BizTalk to execute the policy that returned our map list document. We used .NET code in a separate assembly accessed from within an expression shape. For info on how to do this, see my previous post on Calling the BRE from .NET Components. […]
[…] from .NET Applications Posted on January 17, 2011 by Ed Jones Previously, I had posted a short article on how one may go about calling the BizTalk Business Rules Engine from standard .NET code. Below, […]