Martijn's blog - E-Commerce, EAI, BizTalk and .NET

2005/10/05

Testing remote Business Rules (BRE)

When using remote Business Rules, you might encounter a situation where you might want to test a policy, stored in a remote SQL Server. I had some security issues, just a tip, here's how I resolved it:

using Microsoft.RuleEngine;

// 0 = LOGON32_PROVIDER_DEFAULT
// 2 = LOGON32_LOGON_INTERACTIVE
IntPtr token = IntPtr.Zero;
   
const string domain = "MYDOMAIN";
const string password = "MYPASSWORD";
const string username = "MYUSERNAME";
const string server = "MYSERVER";

if(LogonUser(username, domain, password, 2, 0, out token) != 0)
{
 WindowsIdentity identity = new WindowsIdentity(token);
 WindowsImpersonationContext context = identity.Impersonate();

 try
 {
  SqlRuleStore ruleStore = new SqlRuleStore(
   string.Format("Integrated Security=SSPI;Database=BizTalkRuleEngineDb;Server={0}", Server));

  RuleSetInfo currentRuleSetInfo = null;

  // retrieve information about the latest published RuleSet from the RuleStore
  RuleSetInfoCollection ruleSets = RuleStore.GetRuleSets(Policy, RuleStore.Filter.LatestPublished);
     
  if(ruleSets.Count > 0)
  {
   // select the retrieved RuleSetInfo object
   currentRuleSetInfo = ruleSets[0];

   // retrieve the latest published RuleSet from the RuleStore
   RuleSet currentRuleSet = RuleStore.GetRuleSet(currentRuleSetInfo);
    
   // create a PolicyTester to test the RuleSet
   PolicyTester tester = new PolicyTester(currentRuleSet);

   tester.Execute(facts, this);
  }
 }
 catch(Exception e)
 {
  System.Diagnostics.WriteLine(e.ToString());
 }
 finally
 {
  context.Undo();
  CloseHandle(token);
 }
}

Ofcourse, as I typed this at heart, some things (like the actual facts being put into the execute action of the PolicyTester) might not compile / work when plainly copied into Visual Studio. Make sure to reference Microsoft.RuleEngine.dll from your project. Also note that this is an example and could be enhanced greatly. ;-)

2 Comments:

  • Hi there MartijnĀ“s,
    Great resource of information.

    I tryed your code:
    RuleSetInfoCollection ruleSets = ruleStore.GetRuleSets("rule name", RuleStore.Filter.LatestPublished);

    The only problem here is that this gets both published AND deployed versions of vocabulary and I can not see any obvious way to just get the deployed version. Any hints?

    Please reply to martijn@angeloh.com
    as well!

    Regards
    Evangelos

    By Anonymous Anonymous, at 11:27 AM  

  • Vocabularies cannot be deployed. If you mean Policies, the code should give you the latest one, no others.

    By Blogger Martijn Hoogendoorn, at 11:41 AM  

Post a Comment

<< Home