Saturday, January 8, 2011

Calling the BRE from .NET Applications

Ref:http://talentedmonkeys.wordpress.com/2010/08/23/calling-the-bre-from-net-applications/

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.

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;
}

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.

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.


No comments:

Post a Comment