Complete Project Walkthrough
Let us walk you through the design of a basic Trip Reservation system. The goal of this walkthrough is to build a rule set and a web client application allowing Customer to choose the Trip Package options and price them. The Web Client will be calling the RuleLab.Net BRE Web Service which will run the Customer XML input against the rules stored on the RuleLab.Net server.
The rules are implemented as a RuleLab.Net backend demo application called “Travel Reservation”. You can access it via the RuleLab.Net demo page on the main web site. Client sample application can be downloaded via the "sample client" link in the "Walkthrough Files and Links". The sample application is written in C#/.NET. It is our advice to get a hold of both the demo and the application project in order to follow along with this walkthrough. If you do not have Visual Studio.NET 2003/2005 but understand C# syntax and would like to run the client sample, you can still launch the Client Web Application and study the C# source code. Please refer to the "Walkthrough Files and Links" box.
Our Travel Package consists of a Cruise and a Hotel reservation. We will assume that the Customer has selected an available cruise and hotel via some other system. She is looking at choosing between Hotel & Cruise or Hotel Only package, the duration of the Hotel stay, an instant purchase vs. an advance reservation and the payment type preference.
Please note that the purpose of the Web Client sample is to illustrate the client side of the RuleLab.Net Web Service. It is not intended as a GUI guide and as such it utilizes the most simplistic approach to the GUI design. We'd like to focus your attention on building the required XML data document and parsing the RuleLab.Net BRE XML output.
Business Requirements
The system we'll define here could be treated as the part of a real life reservation system. It must show Customer or a Travel Agent the amount due, fees, discounts as well as provide the explanations as needed.
The requirements are as follows:
RuleLab.Net XML References
Now that we have defined the application side of the system, the next thing to do is to create the XML Data counterpart – the XML References.
At this point, if you haven’t already, please open the online Rules demo by following the link in the "walkthrough Files and Links". Once in the Rules Designer, click the “References” tab. The list of References you see resembles the application data fields. There are two types of entries here – the ones with an XML Node path and a few without. The XML path is what links the RuleLab.Net atoms with the corresponding application data fields. Entries without the path indicate runtime variables that are instantiated/utilized by Rules but not returned to the application.
The XML paths were entered via uploading the application data XML document template and copying the node paths. This functionality is invoked by clicking the “Upload Application XML File” button.
Two References are defined as “loops” – the “Customer Name” and “Booked Cruise in the Past”. They belong within the “guests” parent node which may contain up to 4 “guest” loops. For each of these References we provided a full path to their parent node – “reservation/guests”. Just like with the regular XML path, the loop path was copied with a click of an arrow button upon uploading an Application XML document.
Each XML Reference has a strong data type defined by the selection in the “Type” column. This selection is driving the Rules Designer data presentation when you are editing the rules. It is also used to validate an application XML sent to the BRE. Please note that there is no requirement to your application XML to use additional tags or attributes such as “date”. All type information is contained within the RuleLab.Net data model.
We set most of the XML References as singe-reference atoms to make them accessible at the Rule level.
Some atoms are marked as Overwritable. These can be changed by any Rule at any time without any consideration for other rules or priorities. The conflict resolution does not apply to them. Fields in this category include user messages and totals. For example, the discount message can be modified by two different rules, each of them adding text to the "messageDiscount" Atom. Click the "messageDiscount" row and the “Used Where?” button to find and browse these 2 rules. Another example – the “Total Cost”. This Atom can be changed by a number of calculation rules adjusting it with the Fee and Discount amounts. On another hand, the “Transaction is Valid” field must never be changed once a high priority rule rendered the transaction invalid and set the error message.
The 3 system fields we have entered are needed for composing Rules and Facts:
"Full Payment Due Days prior" – represents the business requirement of the full payment due date which depends on the type of a package the Customer is requesting.
"Deposit per Person" – the deposit amount is different for different type of Packages
"Discount" – this is a template for the two Facts. You can click the “Used Where?” button to locate them. Each Fact corresponds to a specific type of Discount. Note the difference between the "Discount" atom and “Fee” atoms. While both are used to instantiate Facts, the “Discount” is never returned to the Application because the application only wants the total amount of the Discount (along with the explanation messages). Fees on the other hand must each be returned to the Application.
Atoms and Facts
On the “Atoms” tab you will find 2 Atoms – "Package" and "Guest Status". Atoms on this tab were added on top of the single Reference Atoms already defined on the References tab. Click the “Used Where?” button to see how they are utilized. The Atoms where created by entering a unique alias and copying the available XML References using the arrow buttons.
Open the “Facts” tab to browse the specific data we have entered into the system. This includes the type of Packages we are offering, the available Discounts and various Fees. The Facts are utilized in the Rules for both building the Conditions (for example – "HotelAndCruise") as well as making the assignments (example – "Processing Fee Amount").
To enter a Fact into the system, we came up with a unique alias, selected an Atom to instantiate the Fact, and populated this Atom’s References with data.
A Narrative Description has been entered for the “Return Customer” Fact. It is displayed in full text in the “ReturnCustomerDiscount” Rule on the Rules browser screen. The narrative replaces the default Fact presentation syntax.
Vocabulary of Natural Terms
Click the Vocabulary tab to open the list of Vocabulary Terms that have been entered into the system. These Terms are utilized in some of the Rules (AdvanceReservation, BalancePayment) to enhance their readability.
Vocabulary Terms can be added by clicking the Add or Insert button. You can examine one of the existing Terms by selecting it and clicking the Edit button. The Term Editor that opens in response displays the Natural Term aliases and the logical expressions which implements the Term once it has been added to a Rule.
For more information please see the "Vocabulary of Natural Terms" section in the online documentation.
Rules
Having entered the XML References, Atoms, Facts, and Vocabulary you can finally implement the actual Rules. Click the “Rules” tab to browse the Rules list. You will see several sections populated with Rules in the corresponding category. While all Rules were derived from the Requirements, some are less obvious than the others. For example, the “Late Payments” section contains a rule that checks Instant reservation against the Final Pay Due Date. While there is no explicit requirement to write this rule it is implied by the definition of the Final Pay Due Date.
The Rules where entered using the Append/Insert command buttons. Clicking a rule row and the “Edit Rule” button will take you into the Editor where the rule can be altered. Please try opening a few rules including some with calculation formulas. The Editor allows clicking into every Atom, Fact or Formula which pops up the corresponding select/edit boxes. The popup offers matching choices that you can apply to the entity being edited.
Deposit
The first set of rules – under the Deposit section – calculates the deposit amount due for all guests in the party. Please refer to the Business Requirements above to see what type of deposit is required. The Deposit calculated by these Rules will only be charged if the deposit is actually due which is for the other Rules to decide.
Full Payment Days Due
These rules calculate the number of days beyond which an Advance Reservation will not be accepted. This number is applied by the “LateAdvanceReservation” rule which checks the Date of Departure against the Due Date and invalidates the transaction if the number of days left is less than the requirement.
Please open the “LateAdvanceReservation” rule from the Late Payments scetion and examine how the “number of days left” predicate is applied to “Date of Departure” atom. Also note that the error message text includes the "Full Payment Due Days Prior" system atom. It is populateed by the BRE in order to build a text message that is returned to the application for presenting in the UI.
The totals
The “TotalCalculation” is a straight forward calculation of the total price of the given package. If you haven’t looked at formulas yet, please open this rule and click the formula expression. The popup will show the expression editor along with the available Atoms and Facts that you can copy into the expression.
Since one of the requirements tells us not to require deposits on low amount purchases, we added the “DepositValidation” rule which erases the deposit amount if the criteria is met. This rule basically turns an "Advance Reservation" into the "Instant" which is enforced by the rules in the “Transaction status etc” section.
The two “Fee” rules implement the fee requirements. The “ProcessingFee” rule alters the overwritable “Total Cost” atom. The “WireTransferRule” adjusts the “Amount Due Today”. Note that the precondition will hold this rule execution until the “Amount Due Today” has been determined, therefore, this rule cannot execute until BRE’s second cycle.
Discounts
“PaymentTypeDiscount” rule calculates the discount using the “Cash Discount” Fact. It also contains the UI-type text message to explain the discount to a Customer.
The “ReturnCustomerDiscount” rule decided whether the Customer earned an additional “preferred customer” discount. It does that by examining each Guest information using the “Any” operator applied to “guest” loop data. Also of interest is the Fact narrative description utilized in this rule.
Transaction Status, Deposit Amount and Amount Due Today.
This is the core section of the ruleset. All preceding rules were the preparation for this section. For each type of the reservation, it determines the amount Customer must pay and sets the explanation/status of the transaction that should take place.
The “AdvanceReservation” rule evaluates two cases – the true advance reservation and the “converted” one (see “DepositValidation” above).
The “BalancePayment” rule ensures that the balance is indeed due. It makes an assumption that the Deposit has been paid. Since this demo carries no state, it has no way of checking if the Deposit was indeed paid. It goes without saying that this approach is only here to illustrate the rules. In a real life system, an application XML would have carried the deposit status obtained from the database.
The “InstantPuchase” rule simply copies the Total to the Amount Due Today.
Note that the “AdvanceReservation” and the “BalancePayment” rules utilize the Natural Terms from the Vocabulary.
Late Payments
This set of rules checks Customer request against time constraints. These rules have higher priority than the calculation/deposit/fee rules. They execute earlier and if they set the “Transaction is Valid” atom to “no” then the rest of the BRE rules will no longer matter. We could add the “Transaction is Valid” check to the precondition of the other rules but really their actions are harmless – as long as the GUI knows to ignore their calculation results.
Customer Data Validation
In this section there are typical user entry validation rules that ensure the supported values, number ranges and the required data. They have the highest priority in this sample.
These rules utilize XML References data type settings. For example, if an application XML contains a date string that is not a valid calendar date then the BRE will not run at all and the error will be returned to the caller.
Testing the Rules
The Rules we have created should be tested before they are deployed and utilized by the client application. Click the “Test” tab to open the test screen. In the demo version, the Test screen automatically loads the application XML sample document populated with the preset values. This XML data corresponds to the “Advance Reservation of Hotel & Cruise package” test case from the client sample application that we will review next.
You can change XML test data if you wish to experiment with the BRE. To parse data against the rules click the “Run BRE” button. The execution log will appear on the right. Your input XML will be updated by the BRE with the totals and the text messages. If you would like to try a different scenario click the “Reset” button.
Just like the other screens of the Rules Designer, the Test screen displays the clickable Atom, Fact, and Reference Rule aliases. Simply click an alias link in the Log to navigate to the definition of the corresponding entity.
Running the BRE on the default XML data via the Test screen of this demo will set the amountDueToday field. Upon clicking the “Run BRE” button, scroll all the way down to see its updated value. Now, click the “BRE Reasoning” tab. You will see a list of all atoms modified by the latest BRE pass, with the "amountDueToday" at the top. Click the “Show Reasoning” button. The resulting output explains how the system arrived to its conclusion. You will see the backtracking of all the rules that led to the final assignment you are examining.
You can find an example of utilizing the BRE Reasoning through the Web Service in the BREClient.aspx web form which is part of the sample project available for download from the product demo page.
Client application sample
If you have MS Visual Studio.Net 2003 or better, please download the client demo project and open the TravelReservation.aspx web form. Alternatively, you can browse the source code of the C# sample. The code has comments that should guide you through the application.
The sample uses a proxy class that was automatically generated by running WSDL on the BREWebService.asmx. You should be able to build the sample Project and run it on your Visual Studio.Net developer machine.
General Guidelines
To write a RuleLab.Net BRE Web Service client GUI application you have to accomplish the following:
- create an XML data template
- specify the Rules/Facts/Atoms/References files and the login
- create binding/methods for exchanging data between the UI controls and the XML data nodes
- write methods for calling the BRE Web Service and parsing the results
Application Details
There are 2 types of client applications you can build to run data against the rules engine – an online BRE client and an offline BRE client. The online BRE resides on our server and is accessed via the Web Service. The offline BRE can be installed in your local environment. This walkthrough is using the online integration method. Developers have to follow the RuleLab.Net Web Service documentation in order to build an interface with the RuleLab.Net BRE.
To build an application you’d first have to come up with a Data XML template for uploading the information to the BRE. The same XML we defined as the first step of this walkthrough is entered in the C# sample as m_xmlAppdata variable.
You have to have an account on the RuleLab.Net web site and a set of Rules/Facts/Atoms/References files either as the online files or the offline XML documents. This sample uses m_rules, m_facts, m_atoms and m_references files which have been created as part of the online Rules demo project.
To call the BRE Web Service, the developer has to code the administrator login into the client application. Please refer to the RunBREWebService method which populates the authentication header and calls the BRE. This demo sample logs in as “demo/demo”.
The “Scenarios” functionality that comes next in the source code was created for populating the user entries with data targeting the specific rules. This is done to illustrate an execution of the business rules discussed above.
CopyCustomerEntriesToXml and DisplayResults are the two methods that provide an interface between the BRE Service call and your GUI controls. They move data back and forth between the application XML nodes and the UI control values.
Conclusion
Building a RuleLab.Net application includes development of the two project categories – the backend Rules and a front end Client. The Client populates an XML document in a format recognizable by the BRE and submits it to the BRE. The BRE runs the XML data against the Rules and returns the updated data to the Client. You can manage the Rules in the Rules Designer. Client application integration requires some programming that can be accomplished in the .NET or another technology. As a result, you will create a rule based system where your business logic will be accessible and editable via the Web.
What would you like to do next?
Learn more about the RuleLab.Net online service (ASP model) or Client-hosted solution
Sign up for a free trial.
Deposit and Full Payment
Customer making an advanced reservation must pay a non-refundable deposit in the amount of:
Hotel and Cruise Package - $250 per person
Hotel Only Package - $120 per person
Full payment is due
On the Hotel and Cruise Packages – 90 days prior to the departure date
On the Hotel Only Packages – 45 days prior to the departure date
Instant purchases do not require a deposit.
If the difference between the deposit and the total amount due is less than $50 then request Customer to make an Instant purchase by paying in full.
Advance reservations past the Full Payment due date will not be accepted.
All invoices must be paid in full by the Final Pay Due date. If/when a Customer is trying to pay an outstanding balance past the Final Pay Due date, reject the transaction and inform her that the travel services have been cancelled and advise her to apply the deposit towards another trip.
If a payment is being made within 30 days of the departure then only accept a certified check, money order or a credit card.
Fees
$25 Fee will be added to all wire transfers.
$40 Processing Fee will be added to all invoices less than $600.
Discounts
If Customer is paying with cash or check and is making an Instant Purchase then offer 3% discount.
Offer 2% discount to the Return Customers who are reserving Hotel & Cruise package if at least one guest in their group has booked Hotel & Cruise package in the past.
Technical Requirements
The following information must be returned to the Client Application:
The total amount of the invoice
The deposit amount
Additional Fees
Explanation and amount of the discounts
System must allow business users to enter the transaction status and the rejection messages that will be displayed to the Customer.
All user entries must be validated at the system backend.
Implementation
Application Data XML
We start by defining an Aplication XML Data Template that is shown here along with the sample entry values. Our XML includes the following fields:
1. Data assumed to have been acquired from another system (this information would appear as readonly in a real life application GUI):
departureDate
finalPayDueDate
hotelRoomPricePerNight
cruisePricePerPerson
2. Customer entries
travelPackage – includes two fields:
hotel – yes/no
cruise – yes/no
numberOfNightsInHotel – an integer between 1 and 30
guests – a list of up to 4 “guest” nodes each defined as
guest – includes two fields:
customerName
returnTravellerCruise – yes/no
purchaseType – New Advanced Reservation, Balance Payment or Instant
paymentType - Cash, Personal Check, Certified Check, Credit Card, Wire Transfer or Money Order
3. Client supplied information
numberOfGuests – the exact number of guests in the party
4. Data expected from the RuleLab.Net BRE
transactionValid – “no” indicates invalid transaction.
messageError – an error message explaining rejection of the transaction
messageDiscount – text block listing the discounts along with explanations
messageStatus – a comment regarding Customer transaction
processingFee – the amount of the Processing Fee if applicable
wireTransferFee – fee amount if purchase was made by Wire Transfer
deposit – total amount of the deposit for the party of numberOfGuests
costBeforeDiscount – price before applying the discounts if discounts are offered
discount – the sum of all the discounts
totalCost – total invoice
amountDueToday – either the Deposit, an outstanding Balance or the full amount if Instant purchase is being made.