Code reuse is a critical part of good software development. Why spend time and money designing, building, and testing a library if someone’s already done the heavy lifting for you? The story told way too often in software development circles is of the team that decided to “implement their own X,” where X could be a logging framework, a custom Flash graphing engine, a compression formula, and so on. The team always ends up spending way more time working on their custom creation than actually adding value to the business they are working with, and usually the project gets cancelled or goes way over budget. Don’t make the same mistake; always use an existing library whenever possible!
The Tools
For abstracting business rules into XML NxBRE Gives you the ability to pull your business rules out of your code and keep them stored in XML or Visio documents.
For adding quality logging to your application log4net Lets you create logfiles for your application with varying levels of detail. The people responsible for maintaining your application will thank you.
For implementing search functionality Lucene.Net Gives your users enhanced search functionality.
For comparing libraries LibCheck Compares two versions of an assembly to see what has changed. This can be very useful when you’re trying to diagnose why something is broken or is causing unexpected behavior.
For visually comparing assemblies Reflector.Diff Lets you visually compare the differences between assemblies.
For adding spellchecking capabilities to your application NetSpell Gives your users the ability to check their spelling while using your application.
For adding chart capabilities NPlot Lets you add charts and graphs to your application.
For sorting collections NSort Gives you the functionality to sort your collections in a number of different ways.
For adding RSS to your application RSS.NET Enables you to add RSS feeds to your site (and read from current RSS feeds) without writing a line of XML.
For adding compression to your application SharpZipLib Easily compresses files or information using any number of compression algorithms.
For writing XML documents ExcelXMLWriter Lets you easily export Excel spreadsheets from your application.
For creating PDFs iTextSharp Gives your users the ability to export PDFs from your application.
Hard-coded business rules can lead to inflexible applications that are hard to maintain. NxBRE is an open source business rules engine that helps you build more agile systems by externalizing the processing of these rules.
NxBRE started as a C# conversion of Sloan Seaman’s JxBRE and has since been vastly extended. Mainly written by David Dossot, NxBRE is available on Source-Forge, where it benefits from the functional and technical feedback of a vibrant community.
NxBRE offers two different engine flavors to better fit the skills and knowledge of developers: the Flow Engine suits the procedural-minded, while the Inference Engine is more oriented toward expert system connoisseurs. All rule files are expressed in XML, which allows for easy editing, validation, and transformation. The Inference Engine also supports rules written in a Prolog-like syntax and comes with a dedicated Stencil for Microsoft Visio 2003 that allows graphical editing of rule bases.
NxBRE at a Glance
Tool
NxBRE
Version covered
2.5.1
Home page
http://www.agilepartner.net/oss/nxbre/
Power Tools page
http://www.windevpowertools.com/tools/142
Summary
Software component for executing business rules expressed in XML. Usable in standalone or multithreaded systems.
License type
LGPL
Online resources
Documentation, online knowledge base (Wiki), forums
Supported Frameworks
.NET 1.1, 2.0
Getting Started
NxBRE is distributed for .NET 1.1 but can be recompiled on .NET 2.0. You can download the distribution from the tool’s SourceForge page (http://sourceforge.net/ projects/nxbre/). NxBRE’s distribution contains the DLL built-in debug and release modes, which you can directly reference in your projects.
NUnit 2.2 (available from http://www.nunit.org) is required for running the test suite.
NxBRE has primarily been developed with the open source IDE SharpDevelop, but it is distributed with project files for Visual Studio .NET 2003 and XML build files for NAnt.
A command-line console is available for easily testing rule bases designed for the Inference Engine. It is distributed as an independent package in the same SourceForge project.
A business rule generally consists of a condition followed by one or several actions executed if the condition is met.
The following is a classical set of business rules for computing sales discount:
Rule #1 The discount for a customer buying a product is 5.0 percent if the customer is premium and the product is regular.
Rule #2 The discount for a customer buying a product is 7.5 percent if the customer is premium and the product is luxury.
Rule #3 A customer is premium if his spending has been min 5000 Euro in the previous year.
We’ll see how these rules translate to a rule base momentarily. A rule base is a file that contains the definitions of several business rules. NxBRE uses these rule bases to control its processing.
Creating rule bases for the Flow Engine
NxBRE does not provide any facility for editing rules for the Flow Engine. Since the rules expressed in XML are similar to traditional flow-control programming, using an XML editor such as jEdit (Figure 4-1) that supports schema validation and offers contextual element insertion is generally sufficient.
Fgure 4-1. Using jEdit to create flow-control rules
The example Rule #1 shown previously can be expressed this way:
The Flow Engine contains an HTML-rendering engine that offers a convenient way to navigate through rules and read them transformed into pseudocode. Figure 4-2 shows one of NxBRE’s unit test rule files transformed in such a manner.
Figure 4-2. HTML pseudocode rendering of flow-control rules
To organize big rule bases, it is a good idea to leverage the notion of a rule set that is supported by the Flow Engine. It allows you to group several rules into a named group that gets evaluated on demand.
RuleML goes much further than simpleif/thenstatements. In fact, NxBRE’s forward-chaining Inference Engine performs pattern-matching operations and can produce combinations of matching data. See http://ruleml.org and NxBRE’s user guide for more information.
Editing rules in Visio offers several advantages, including the possibility of organizing rules in pages (Figure 4-3) or mixing rule elements with other schema elements (Figure 4-4).
Figure 4-3. Designing Inference Engine rules with Visio
HRF can be authored with any text editor. Our example Rule #1 would be written like this in HRF:
Whatever rule format is chosen, NxBRE provides a testing console as a companion package. As shown in Figure 4-5, this console allows you to easily load, run, and trace the processing of rule bases designed for the Inference Engine.
Using NxBRE in a project typically involves the following steps:
Instantiating the engine
Loading a rule base
Storing data in memory
Running the engine
Analyzing the results
Figure 4-4.Mixing rules and other schema elements
It is not possible to programmatically define rules in NxBRE.
As shown in Figure 4-6, the memory where data is loaded is called context for the Flow Engine and is called working memory for the Inference Engine. Context and working memory contain references to object instances and bits of knowledge called facts, respectively.
The following code shows a typical usage of the Flow Engine:
IFlowEngine bre = new BREImpl(); bre.Init(new XBusinessRulesFileDriver(ruleFile)) bre.RuleContext.SetObject("TestObject", tobj); bre.Process(); // check the modifications made on tobj
Figure 4-5. Testing a rule base with the Inference Engine Console
Figure 4-6. Architecture of NxBRE
And the following code shows a typical usage of the Inference Engine:
IInferenceEngine ie = new IEImpl(); ie.LoadRuleBase(new RuleML09NafDatalogAdapter( ruleFile, FileAccess.Read)); ie.Assert(new Fact("is the father of", new Individual("John Smith"), new Individual("Kyle Doe")); ie.Process(); // query the fact base for deduced facts
The Inference Engine can leverage a binder, which is a file that plays a role similar to ASP.NET code-behind files. The binder, which can be either an on-the-fly compiled C# class or a flow control rule file, is used to retrieve data from enterprise sources or business objects, to analyze complex expressions, and to perform data changes based on the engine deductions.
Using a binder contributes to a versatile implementation because it is dynamically evaluated and can therefore be altered at runtime.
The binder is also able to consume events raised by the engine when deductions are made: these events can be leveraged to implement reaction code that directly modifies business objects or enterprise data sources, instead of analyzing the memory of the engine after process time and mapping its state to the said objects and data sources.
While the Flow and Inference Engines are not thread-safe objects, NxBRE’s documentation details recommend implementation strategies for multithreaded environments such as ASP.NET or Enterprise Services.
A registry that facilitates the implementation of the Inference Engine in a multithreaded environment, with support for hot reloading of rule bases and binders, has recently been contributed as an extra package for NxBRE.
Getting Support
Support for NxBRE is available either through the online SourceForge forums or via email by writing to support@nxbre.org.
NxBRE in a Nutshell
NxBRE’s interest lies first in its simplicity, and second in the possibility of easily extending its features by delegating to custom code in the Flow Engine or by writing custom RuleBase binders in the Inference Engine.
NxBRE can be really useful for projects that have to deal with:
Complex business rules that cannot be expressed in one uniform, structured manner but require the ability to have free logical expressions
Changing business rules that force recompilation if the new rules must meet unexpected requirements
Implementing such an engine has a price, though, as data must be adapted in both ways between the application and the engine. This can impair performance and also requires adopting a different mindset for the data manipulated by the engine. Software programmers and analysts might find the learning curve too steep (and the available documentation too thin).
Management of large rule bases can be discouraging, as NxBRE does not offer the rule-management utilities its paying counterparts do. Performance has also been reported to degrade with big rule bases (more than a thousand rules), while it remains pretty insensitive to the volume of data loaded in memory.
That said, NxBRE has proven satisfactory for many implementations in the finance and health-care industries and in government. Recent releases of NxBRE have focused on improving its performance.
NxBRE lets projects whose cost constraints would not allow purchasing a commercial solution externalize business rules. It fits easily in any kind of application and starts giving results within minutes.
—David Dossot, creator of NxBRE
Please check back next week for the continuation of this article.