Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report this article.
Typical Enterprise application include the next elements: one front end, such as Web interface, a back end database access layer, such as SQL Server and business logic services in between. While it is now common practice to use frameworks and components, commercial or not, for the front end and back end layers, there is no standard way of structuring dynamic business logic. This article tries to give a survey for replace the IF…THEN hard code statement, with a framework that gave us the same benefits of configurability, readability, and reuse that we already exist in other areas, using the Smart Rules Tools.
Smart Rules Tools is a Business Rules Management System, created by Kontac. which facilitate the separation of business rules from application code, allowing dramatic reduction in maintenance and enhancement costs for software applications. Use of Smart Rules will allow organizations to substantially reduce their development resource requirements while shortening development latency to near zero. Thus, the agility of Smart Rules will allow organizations to become more competitive in their markets while enjoying the bonus of cost reduced development
Typical business rules can be represented as simple if-then statement:
If a driver’s age is younger than 18, then decline to rent.
Traditionally, business rules are embedded in application code, and might appear in a VB.NET application as follows:
'Simple business rule
Public Function CheckUnderAgeRule() As Boolean
Dim DeclineRent As Boolean = False
If Me.Age < 18 Then
DeclineRent = True
End If
Return DeclineRent
End Function
We've all come across similar (or even more complex) business logic. While this has been the standard way of implementing business logic in traditional programming languages, there are many problems with it:
How are we going to solve this problem? One solution, in .NET, is write the code in text file and attach the code, in runtime, using Reflection. Other solution that is gaining traction is to use a rule engine. Rule engines are frameworks for organizing business logic that allow the developer to concentrate on things that are known to be true, rather than the low-level mechanics of making decisions.
Kontac, allows a business analyst to change business policies expressed as rules quickly with little or no assistance from a programmer. Applications using Smart Rules, called rule enabled applications, can quickly adapt to new regulations, improvements in internal company processes, and changes in relationships with customers and suppliers.
To get started, download the Smart Rules and create a new VB.NET project in Visual Studio .NET and make sure to add reference to SmartRules.Engine.dll and add you CareRental.exe to GAC.
Alternatively, the code for this article includes a completed Dictionary file – if you don't want to build the business dictionary for yourself, feel free to import the completed alias (CarRentalAliases.xml, on zip file) via the Smart Rules Deployment Wizard. There is more information about using this tool later in this paper.
Before working with Smart Rules you need to define a data model. A data model contains business data definitions for facts or data objects used in rules, including: .NET class fact types, XML fact types, and DataTable or Data Row types (Database fact types).
We need three .NET components facts, incorporate .NET components into your rules as facts is an important feature that significantly increases the rules' flexibility, Rather than just working on static data, this feature allows your rules to interact with instances of your components – reading and writing properties, calling methods – to provide a programmable and dynamic element to your business rules.
PayType component
Public Enum PayType
Cash
Credit_Card
Check_Card
End Enum
This component helps us restrict if Customer pay type is by Credit Card, Check Card or Cash. Some rules apply for each pay type.
Customer Component
Public Class Customer
Private _Name As String
Private _Age As Integer
Private _LicenseNo As String
Private _PaymentType As PayType
Private _PreAccidents As Boolean
Private _AbleToDrive As Boolean
'Properties Get for each field.
End Class
This class is the business object representing a Customer, who wants rental a car. This component provides basic information like the Pay Type for initial deposit or Age accidents, the rental company can configure the minimal age for rent a car.
RentalInfo Component
Public Class RentalInfo
Private _Reason As String
Private _PickupDate As Date
Private _ReturnDate As Date
Private _CustomerName As String
Private _CarId As Integer
Private _RentalAmount As Decimal
Private _DepositAmount As Decimal
Private _ExtraCharge As Decimal
'Get/Set properties
'…………….
Public Property Reason() As String
Get
Return Me._Reason
End Get
Set(ByVal Value As String)
Me._Reason = Value
End Set
End Property
Public Function DaysOfRent() As Integer
Dim Ts As TimeSpan = Me._ReturnDate.Subtract(Me._PickupDate)
Return Ts.Days
End Function
The final piece of our facts is this third .NET component. This simple component represents the Rental info functionality that our rules need to call on; in this example the logic is some very simple local code. The class has two key members used for Smart Rules Studio:
Because we are going to use a database for the source of vehicles, we need build the basic car table information using the next script:
CREATE TABLE [Vehicle] ( [VehicleId] [int] IDENTITY (1, 1) NOT NULL, [RateDaily] [money] NOT NULL, [VehicleType] [varchar] (50) NOT NULL, [VehicleStatus] [int] NOT NULL, [MinDays] [int] NOT NULL ) ON [PRIMARY] GO INSERT INTO [Vehicle]([RateDaily], [VehicleType], [VehicleStatus], [MinDays]) VALUES (45, ‘Truck’, 1, 4) INSERT INTO [Vehicle]([RateDaily], [VehicleType], [VehicleStatus], [MinDays]) VALUES (35, ‘VAN’, 1, 2)
The car Rental business rules development will be done in the Smart Rules Studio. The car rental sample, customer specifies driver information and the business rules determine if a rental company service representative should decline to rent a vehicle due to driver age restrictions, and calculate net charges payable by a customer, including deposit, total rent by days, and extra charges. Now you create one rule, the Under Age rule.
Starting Smart Rules Studio
You access to Smart Rules Studio from Smart Rules menu, Smart Rules save the data in any compatible SQL Server database, include MSDE 2000.
Click here to enlarge
The Smart Rules Studio Interface
Names of the methods and classes used in Smart Rules can often be pretty complex, like its:
Customer.get_Age() is less than 18 OR CarRentalDB.Vehicle.VehicleType is equal to 2
To facilitate work with complex class names or methods names, Smart Rules allows business analysts to create rules using familiar names with a feature called business dictionary. If you use dictionary their rules will be look like below:
In English:
Customer Age is less than Min age for rent a car or The vehicle Type is equal to Truck
In Spanish:
La Edad del Cliente less than Edad minima para rentar or El Tipo de Vehiculo is equal to Camioneta
You can develop rules without building a business dictionay, but you decrease the readability of your code, if you don't use dictionaries. As stated earlier, a dictionary maps your .NET classes, and database information to user-friendly text.
Alternatively, the code for this article includes a completed dictionarie files – if you don't want to build the dictionary for yourself, feel free to import the completed dictionaries and rule sets via the Smart Rules Deployment Wizard. There is more information about using this tool later in this paper.
Putting the Dictionary Together
The Business Dictionary Pane
To actually build our Dictionary we'll be using the Smart Rules Studio. The user interface to do this is very straightforward. Here are the basic steps:
Specifying the Business Dictionary for Class Fact Definitions
To specify the business Dictionary for Class Fact definitions, the VB.NET GetAge property, do the following:
We need to repeat steps 1 to 4 for the following .NET component members RentalInfo.get_Reason() method, Alias name "Get declined reason".
The same way you can create Dictionary for Databases, using the Add New Data Row Alias submenu from Add New Database alias, and for the age limit constant 18 using the Add Literal Alias submenu from Add Constant Alias menu.
Finally, we need to save and lock our new alias. Right-click on your alias and select Save. Then right-click it again and select Lock.
The Smart Rules Knowledge base is the top-level container and the starting point for working with Smart Rules Studio.
The Knowledge base Pane
To create a Rule Set, do the following:
Creating a Rule for the Car Rental Sample
After creating a RuleSet you can create rules within the RuleSet. In this section, you create the UnderAge rule. The UnderAge rule tests the following:
If the driver's age is younger than 18, then decline to rent.
The following actions are associated with the UnderAge rule:
Rule Sets are groups of rules, rules creation works differently from Dictionaries . Dictionaries use a dialog windows, Rules creation employs drag and drop and right click extensively, To define the UnderAge rule:
Adding Actions for the Under Age Rule
Actions are associated with pattern matches. When a rule’s "If" portion matches, the Rules Engine activates the "Then" portion and prepares to run the rule’s action. In this section, you add two actions for the UnderAge rule. The first action set the reason value to "Declined rental". The second action Assert the RentalInfo for continue processing the rules with the updated values.
To add the actions that set the reason to declined and assert the RentalInfo to memory for a match of the UnderAge rule, do the following:
Finally, we need to save and deploy our new RuleSet. Right-click on your version and select Save. Then right-click it again and select Deploy.
In order to use the business rule engine, you must add a reference to it and instruct it which RuleSet to execute.
When executing a RuleSet, you can specify a particular version, or provide no version ensuring that you use the latest deployed version every time.
Dim customerFact As Customer
Dim rentalInfoFact As RentalInfo
Dim vehicleFact As TypedDataRow
'Constructors....blah blah blah...
'Get lasted deployed Rule for CarRental versions
Dim engine As RuleEngine = GetRuleEngineWithKnowledgeBase("CarRental")
'Declare the short term fact for assert objects to engine
Dim shortTermFacts(3) As Object
shortTermFacts(0) = customerFact
shortTermFacts(1) = rentalInfoFact
shortTermFacts(2) = vehicleFact
shortTermFacts(3) = New Customer.PayType 'We need add the Paytype enum fact too
' Asserting is the act of loading facts (.NET objects, XML Documents, etc.) into the memory of the executing RuleSets.
engine.Assert(shortTermFacts)
'Execute the Rule
engine.Execute()
Show the standard code to call and executing rules. for load the DataRow from database, the application needs to assert prepopulated DataTable or DataRow objects. For load a .NET class, is different, the class must be signed and loaded in the GAC.
Test with different values and review the output, also you can modify the rules for test another scenarios.
When you work with the Smart Rules Studio, you're loading and saving rule sets and dictionaries from a specified SQL Server database. You might be wondering how you move those rules and Dictionary from that machine to a new location. The answer, as you might have guessed, is the Rules Engine Deployment Wizard.
The code supplied with this paper contains both a Dictionaries and a Rule Sets. To make use of these files you'll need to first add the exe CarRental.exe into your GAC. Import the Dictionary file (CarRentalAliases.xml) followed by the RuleSet file (CarRentalKnowledge.xml). Finally, you need to deploy the RuleSet.
This article demonstrated a problem that most programmers have had to face: how to put some order on the complexity of business logic. We demonstrated a simple application using Smart Rules Engine as a solution and introduced the notion of rule-based programming, including how these rules are resolved at runtime.