WF Rules: Unleashing The Rule Engine Within .NET

October 18, 2010

I have written previously about WF Rules, the rule engine that ships in .NET. As I have described, this rule engine is bundled in .NET versions 3.0 and higher, and is included in the default installation of Windows Vista and Windows 7. (If you are using .NET 4.0, you need the Extended / Full install – the WF Rules assemblies are not in the Client install.)

Getting Access To WF Rules
The average rule author who is looking to try out WF Rules will ask where to start. At they point, they may become lost in the sea of WF documentation or find that they are told to use Visual Studio, which they may not even have installed. It is indeed the case, that WF Rules is typically used as part of Windows Workflow Foundation, and the rules are typically authored within Visual Studio. However, WF Rules can also be used without Visual Studio or Workflow Foundation if one is willing to read through the documentation, download some samples and write a bit code.

A Simple Example
Inspired by a co-worker, I have put together this quick example to lower the barrier to entry a bit. This is a very bare-bones example in order to highlight the rule-specific code that is needed to utilize WF Rules without Visual Studio or Workflow Foundation. So, the code will not feature command-line arguments, a mutable file name, factoring for re-use, etc. (If you are reading this, you most likely already know how to do those things in C#.) The emphasis here is upon demonstrating the scenario with the minimum amount of code. You should be able to paste these three code snippets into three files and have a working example.

The Target Type
In order to author rules, we require a target type to write the rules against. Let’s start with a simple data class:

using System;

class Person
{
  double age;
  public double Age { 
    get
    {
      return age;
    }
    set
    {
      age = value; 
    }
  }
}

For this example, I placed this code in a file named Person.cs. You may choose to place this type within the same file as the other code below. As I said, this example is geared for simplicity.

The RuleSetDialog
Now, let’s write some short code that will instantiate the RuleSetDialog and allow us to author a rule. This code needs to do three things:

  1. Open an existing or create a new .rules file – the WorkflowMarkupSerializer is used if we load an existing RuleSet
  2. Instantiate the RuleSetDialog, while supplying the target type
  3. Save the .rules file if the rules have been updated – using the WorkflowMarkupSerializer

Here is a minimal program to do this:

using System;
using System.IO;
using System.Windows.Forms;
using System.Workflow.Activities.Rules;
using System.Workflow.Activities.Rules.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Xml;

class Program
{
  static string filename = "Test.rules";

  static void Main()
  {
    RuleSet ruleset = null;
	
    // Obtain or create ruleset
    if (File.Exists(filename))
    {
      // load file
      ruleset = Load(filename);
    }
    else
    {
      ruleset = new RuleSet();
    }

    RuleSetDialog dialog = new RuleSetDialog(typeof(Person), null, ruleset);
    DialogResult result = dialog.ShowDialog();

    if (result == DialogResult.OK)
    {
      // save the file
      Save(filename, dialog.RuleSet);
    }
  }

   static RuleSet Load(string filename)
  {
    XmlTextReader reader = new XmlTextReader(filename);
    WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
    object results = serializer.Deserialize(reader);
    RuleSet ruleset = (RuleSet)results;

    if (ruleset == null)
    {
       Console.WriteLine("The rules file " + filename + " does not appear to contain a valid ruleset.");		
    }
   return ruleset;
  }

  static void Save(string filename, RuleSet ruleset)
  {     
    XmlTextWriter writer = new XmlTextWriter(filename, null);
    WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
    serializer.Serialize(writer, ruleset);
    Console.WriteLine("Wrote rules file: " + filename);
  }
}

Authoring A Simple Rule
You will need to save each of these files before you can compile them – for example, I named them Person.cs and RuleEditor.cs.

Now we need to compile these files. You will typically find the C# compiler wherever your .NET installation is, for example:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe

Let me emphasize this – you don’t need Visual Studio for this example. If you have .NET on your machine, you should have the C# compiler already available.

If you saved the files as Person.cs and RuleEditor.cs and pass them to the compiler at the same time, you should end up with RuleEditor.exe – which we can then use to author a rule against a Person. Depending upon your environment settings, you may need to provide the following reference assemblies to the compiler at the same time: System.Workflow.Activities.dll, System.Workflow.ComponentModel.dll, and System.Workflow.Runtime.dll.

Now you should be able to execute RuleEditor.exe and author a rule such as this (click the picture to see full details):
Creating a simple rule in the rule editor dialog

Firing The Rules
Once we have our example rule authored, we need a simple program to load the ruleset and call the rule engine so we can fire the rules. (Note that the code here for loading the ruleset is the same as above.)

using System;
using System.IO;
using System.Workflow.Activities.Rules;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Xml;

class Program
{
  static string filename = "Test.rules";

  static void Main()
  {
    RuleSet ruleset = null;

    Person person = new Person();
    person.Age = 70;
		
    if (File.Exists(filename))
    {
      // load file
      ruleset = Load(filename);
    }
	
    if (ruleset != null)
    {
      RuleValidation validation = new RuleValidation(person.GetType(), null);
      RuleExecution engine = new RuleExecution(validation, person);
      ruleset.Execute(engine);
    }
  }

  static RuleSet Load(string filename)
  {
    XmlTextReader reader = new XmlTextReader(filename);
    WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
    object results = serializer.Deserialize(reader);
    RuleSet ruleset = (RuleSet)results;

    if (ruleset == null)
    {
      Console.WriteLine("The rules file " + filename + " does not appear to contain a valid ruleset.");		
    }
    return ruleset;
  }
}

This program should build much the same as the previous program. You will need to include the Person class again. In a real application, we would factor the business objects into a shared library.

Closing
I hope that this bit of code has demonstrated how readily WF Rules can be used by itself. I find it neat to see a rule engine included in a default OS installation.

Resources


Microsoft Rule Engine Survey

June 1, 2010

Are you interested in helping to shape Microsoft’s future rules products?

Microsoft is running a survey on rule engines in general, and its own rule products (WF Rules, MS BRE) in particular through the end of this week – June 4. (I would have blogged it yesterday, but was off due to holiday.)

The survey should take approximately 5 minutes to complete. If you have used the WF Rules product, you will get a few additional questions about your usage of the features. If you only use non-Microsoft rule engines, your participation is welcome as well.

Your input is appreciated.

Microsoft Rule Engine survey


Rules In WF4

March 17, 2010

My blog stats show trending topics around searches for “wf4 rule engine” and “wf rule engine” and “wf rules” among other variations. If those topics are leading people to this blog, then I might as well address the topic directly.

What Is WF?
For those who don’t know what the queries above mean – it means that people are searching for the rule engine feature (named Windows Workflow Foundation Rules Engine aka “WF Rules”) in Microsoft’s Windows Workflow Foundation (aka WF). The feature originally shipped with .NET 3.0, and I have written previously about the feature set especially as it compares to Microsoft’s other rules offering.

Changes To WF
With .NET 4.0, the Workflow Foundation is introducing a new workflow model (more details here) – so we now talk about the workflow model in .NET 3.0/3.5 as “WF3” and the new workflow model in .NET 4.0 as “WF4”. However, as mentioned at that link, all of WF3 is still available in .NET 4.0. (Note: the assemblies ship in the ‘Extended’ .NET 4.0 install and not the ‘Client’ .NET 4.0 install.)

Rules Integrated With WF4
WF4 does not include a new forward chaining rules engine that is closely integrated with the WF4 activity model (that does not preclude one being made available in the future). Again, to be very clear, the existing WF Rules features are still available in .NET 4.0 and may be used within WF4. Put another way, there is still a forward chaining rules engine in .NET – it has not gone away. A direct statement from Microsoft on the topic can be seen on the .NET Endpoint blog as follows:

“Two other major WF 4 activities that were discussed at PDC, a new state machine activity and a new forward chaining ruleset activity, will not be available with the VS2010 beta 1 release – and we will cover each of these topics in greater depth in the next month. At this point, a new forward chaining rules engine won’t be ready for the .NET 4 timeframe, and will probably see a CTP release post-VS2010 to gather feedback and to allow customers the opportunity to evaluate the direction we are considering. It’s important to note that we are working to ensure integration with the WF 3 rules engine will be possible in a number of ways, though; one example of integration back to the WF 3 rules engine is the SDK sample activity I mentioned above.”

WF3 -> WF4 Migration
There is also now some rules-specific migration guidance published here as part of some overall WF3->WF4 migration guidance. See also the WF Migration Kit CTP 1 that I posted about previously. Questions about using the WF3 rules with WF4 should most likely be addressed via the forums.

Tell Microsoft What Rules Features You Would Like To See For .NET
Finally, if you have interest in rules on the .NET platform and are willing to provide feedback to Microsoft – I encourage you to do so. In fact, it would be great if you could be as concrete as possible about your feature needs. The inclusion of a feature often depends on customer feedback. Here are some examples of feedback that you could provide to Microsoft:


  • If using the existing WF Rules feature with WF4 via the Interop activity satisfies your technical needs and why or why not.

  • If you would like to see WF Rules more fully integrated with the WF4 programming model, or not.

  • If you use or would like to use rules in applications apart from WF.

  • Specific feature feedback about WF and/or MS BRE.

  • If your needs skew more towards the runtime rule engine or BRMS tools.

Specific feature requests for the future should be provided through Connect (detailed instructions for providing feedback about WF4 through Connect).
Also, if you are interested in discussing your rules scenarios and requirements in more detail with someone from Microsoft, you can contact me via the contact form on this blog, or email me at my firstname.lastname at my employer’s domain.com.


Using A Rule Engine For Hacking

March 17, 2010

I was interested to stumble upon an issue of the hacker zine Phrack dating back to 2000 which includes a tutorial on building a vulnerability scanning system used for hacking…that includes a rule engine. The article mentions a number of things you would expect: Rete, OPS5, CLIPS, Charles Forgy, Daniel Miranker and even the monkey and bananas problem.


Microsoft’s Rule Engines

February 5, 2010

I am often asked to describe the rule engines that Microsoft ships. (The first question being: “Microsoft has rule engines?”) This question frequently comes from folks who know rules, but don’t know .NET. This post is specifically written to answer the question. Should the offerings change in the future, I will update this post as needed.

As always, this is not an official Microsoft statement. Questions about the future directions for these products should be directed to Microsoft.

As of this writing, Microsoft is currently shipping two rule engines. They are aimed at somewhat different audiences as described below.

MS BRE
The first rule engine is called the Microsoft Business Rule Engine (sometimes called “MS BRE” or “BRE”) and it has shipped as part of BizTalk Server since early 2004. BRE has shipped in BizTalk Server 2004, BizTalk Server 2006, BizTalk Server 2006 R2, BizTalk Server 2009 and I’m sure it will be included in the upcoming BizTalk Server 2009 R2.

WF Rules
The second rule engine is part of Windows Workflow Foundation in .NET, it is the Windows Workflow Foundation Rules Engine (sometimes called “Workflow Rules” or “WF Rules”). The WF rule engine originally shipped in late 2006 as part of .NET 3.0. It was also included in .NET 3.5 and .NET 4.0. If you are running Windows 7, Windows Server 2008 R2, Windows Server 2008, or Windows Vista or have installed .NET 3.0 or higher – you already have the WF rule engine on your computer. Update: I have an additional post specifically about rules in WF4.

Comparing MS BRE & WF Rules
Here are some comparisons of these engines written by other folks. Charles Young has written extensively on this topic.

A Short Summary Of Differences For Those Who Know Rules
If you asked me to summarize differences for a rules specialist, my comments would be along the following lines:

  • MS BRE is part of a BizTalk Server, which is a business-oriented server package, while WF Rules is part of the free .NET Framework which is more developer-oriented. (MS BRE may be used standalone outside of BizTalk, but is only licensed with BizTalk.) Both engines provide forward chaining execution. WF Rules also provides the option for sequential execution.
  • MS BRE rules are typically authored in the Rules Composer, while WF Rules are typically authored in Visual Studio. There are partners that provide a more BRMS-like authoring environment. MS BRE has features such as vocabularies and a respository, and is therefore closer to what Gartner defines as a BRMS.
  • MS BRE implements the Rete algorithm, while WF Rules does not. MS BRE uses eager evaluation, while WF Rules uses lazy evaluation. The performance profiles are accordingly different – WF “first hit” execution being faster, for example.
  • WF does not have assert/retract keywords or a Working Memory, while MS BRE does – so WF Rules requires all objects to be reachable from a common root object (this). (In WF Rules, support for multiple instances is achieved through forward chaining.) WF Rules supports “Else”, while MS BRE does not. MS BRE has some known restrictions around negation-as-failure. MS BRE has special handling for XML and DB fact types.

Related Technology
I would be remiss if I did not mention some Microsoft offerings that apply to related areas:

Lastly, I should also point out that the Mono Project is reimplementing Windows Workflow Foundation – including WF Rules.


October Rules Fest 2009 & 2010

February 3, 2010

Cheers to James Owen for his stewardship of the October Rules Fest for 2008 and 2009. I was only able to attend a small portion of the 2009 conference, but those portions were quite good. The sign of a healthy conference is one where attendees return as presenters and this year had a few such presentations (Andrew! David!). It was great to see everyone again, but I missed a few folks who were unable to return.

I think my previously posted comments from last year are largely still applicable:

Since James is now returning to working for a vendor, October Rules Fest will now be organized by Jason Morris. The conference is in good hands – Jason is an excellent choice. Make your wishes for ORF 2010 known now.


Have You Implemented Backward Chaining On A Microsoft Rule Engine?

January 11, 2010

Every so often I hear about a “friend of a friend” who has implemented a backward chaining project with one of the Microsoft rule engines (WF Rules, BizTalk MS BRE). However, the details usually fail to materialize. If you have worked on such a system, or know someone who has – please contact me using the contact form on this blog. I’m interested in understanding more about your project and how successfully the backward chaining implementation went.

(As always – this is mainly personal interest, and does not reflect on any future directions of my employer’s products.)


On Chaining

January 7, 2010

One of the recurring topics in the rules world is forward chaining vs. backward chaining – how they compare, when to use one or the other, and which implementations even offer back chaining. I suspect that a lot of the confusion around backward chaining is simply due to the fact that most folks haven’t implemented production-quality systems that make use of it.

One of the forward vs. backward articles is by Dietrich Kappe. In his posting, he includes a quote from Charles Forgy, including the following:

Backward chaining systems are more limited than forward chaining systems.

Dietrich points out that the article was located on the old Rulespower site and disappeared with the purchase by Fair Isaac.

I’m posting here simply to point out that the Wayback Machine has them.

Charles Forgy on Forward and Backward Chaining

I have linked directly to the latest archived version of each article segment. You can find all the RulesPower content that they have here.

For further reading on the topic, the discussions at the following links are interesting (in no particular order):


Who Said It? “any backward chaining engine must eventually…”

January 7, 2010

I found a quote that James Owen used on the JESS mailing list and I’m interested in learning where it comes from. More specifically, is it in a paper or article somewhere and I’m just overlooking it? My suspicion is that James is quoting Dr. Charles Forgy and that it isn’t published in any articles.

I’ll email James to check the source – but I wanted to highlight the quote here since it was only used on the JESS list and could use a little more exposure.

“Any forward chaining engine can be made to do backward chaining and any backward chaining engine must eventually forward chain to deliver results.”

Updated on January 13, 2010:
James has confirmed (via email) that he was paraphrasing Dr. Charles Forgy here. The comment apparently was made during OPSJ training classes.


Rules Research Archaeology

January 7, 2010

Most readers should be familiar with George Santayana‘s quote about remembering the past (also called Santayana’s Law of Repetitive Consequences).

The rise of the BRMS over the last few years has brought lots of enthusiastic new members to our little rules world. These people are eager to contribute to the field and make their own mark. It is the job of the “old guard” to make sure the newcomers are properly aware of the prior research in our field. (Having only participated in the space since 1995, I consider myself to still be a newcomer.) For example, the rise of the multi-core processor means that tons of older research in parallel rule engines is of interest and relevant. For another example, the classic work on conflict resolution strategies doesn’t appear to be online and is in a long out-of-print 30-year-old book. (And at least the prices for “Pattern-Directed Inference Systems” are somewhat affordable – as of this writing, “Human Problem Solving” starts at $190 and goes up to $800 on Amazon.) A third example is that the Wikipedia article on the Rete algorithm only has references to papers that are not online for one reason or another. (I personally haven’t even seen the “A network match routine for production systems.” working paper.)

Thus, I would like to highlight a few useful resources:

We need to work together as a group to improve the online availability of our history.