Modeling procedural rules

From FlexRule Wiki
Jump to: navigation, search

How to model a procedural rule

Procedural rules are used to represent behaviors of the type "IF condition THEN action". For example, such rule can answer the question: “Should this customer get a discount?” by executing rules of the form “IF some-condition THEN give customer a discount”. As a result, the model should consist of two parts: a sensory precondition (or “IF” statement) and an action (or “then”). If a situation precondition matches the current state of the world, then the action is said to be triggered. To demonstrate it better, we are going to use a very simple case in which a customer gets a specific amount of discount if he buys a certain number of goods. As you can see, the rule has only two parameters and one condition.

Main rule body

In this rule we are going to implement a customer discount business rule. This procedural rule decides if the customer gets any discount and how much discount customer is entitled to.

This discount rule is based on the numbers of quantity of an item customer is going to purchase (for example).

The rule is like this:

Customer is entitled to 3 percent discount if he purchase more (or equal) than 10 items of the product

Modeling the rule

In this scenario the rule would accepts 2 parameters:

  • An input parameter: Numbers of quantity to be purchased
  • An output parameter: The amount of discount

Create the rule

You can use the rule designer to Create a new rule project using this article and model the following rule

  1. <Procedure name="PriceSubTotal" enabled="true">
  3.   <Declaration>
  4.     <Define name="item" direction="in" />
  5.     <Define name="discount" direction="out" value="0.0f"/>
  6.   </Declaration>
  8.   <If condition='item.Quantity >= 10'>
  9.     <Var name="discount" value="0.03f" />
  10.   </If>
  12. </Procedure>

Loading and executing a rule

To load and execute a rule you will need to create a project in visual studio. Before you do, make sure FlexRule SDK is installed and the machine key is obtained from the PliantFramework website.

In this Example, we need to create two separate projects within one solution:

  1. A windows form application
  2. A class library

Creating A Windows Form Application

  • Run Visual Studio as administrator.
  • In main window choose “File” → “New” → “Project” or simply press “Ctrl+Shift+N” to open the new project window.
  • In the installed template section on the left hand side, click on “Visual C#” and then choose “Windows Forms Application”.
  • Enter the “Name”, “Location”, and “Solution Name” for the project.
  • Then select “.Net Framework 4.0" form the top side drop down menu.
  • Click OK to create a new solution containing a new project.


  • In “Solution Explorer” section, right click on the project and then select properties.


  • In properties, click on “Build” tab, look for “Output”, find “Output path”, click on “Brows”.


  • Find the FlexRule SDK path and then click select folder. (Alternatively, you can simply type the path. FlexRule default installation folder is usually at “C:\Program Files (x86)\Pliant Framework\FlexRule\Framework\”)
  • In “Solution explorer window expand “Properties” and delete “Resources.resx” and “Setting.setting”. You are not going to use them so it is better to keep everything clean.
  • Next step is to make your references right. So open the references folder, and delete all references except “System”, “System.Data”, “System.Drawing”, System.Windows.Forms”, and “System.Xml”.


  • Select Browse tab select the folder you have installed Flex Rule framework in it. The default folder usually is “C:\Program Files (x86)\Pliant Framework\FlexRule\Framework”.
  • After finding the folder, you need to select couple of references one by one:
  1. FlexRule.Core.Element
  2. FlexRule.Core.Library
  3. FlexRule.Engine
  • Select each by clicking on them and then hitting OK.
  • Repeat the last step three more times to import all the required references into the project.
  • Now you need to import the XML file you have created using FlexRule designer into your project as well. To do so, right click on the “DiscountSample” Project, select “Add” and then “Existing Item…” or simply hit “Shift+Alt+A”.
  • In “Add Existing Item” menu, browse to the folder you have saved the XML file (if you have used FlexRule Designer to create the XML file, then it can be found in the Folder that you have saved your Flex Rule designer project in). Do not forget to change the view option to all files in order to be able to see the file. After selecting the file, hit Add button to XML being added to your project.
  • The next step is to change the Form name in the solution explorer window. This step is not absolutely necessary but just to keep it consistent it is better to do it. Just right click on the form and then select rename.
  • Change the name from “Form1.cs” to “MainForm.cs” and hit the Enter. A popup window will be shown asking you if you like to rename all references in the project to code element “Form1”? Hit Yes and continue.
  • Now it is time to edit our windows form. In “Solution Explorer” window, double click on MainForm.cs to open the design window.
  • From the Toolbox drag and drop two Labels, one Button and two textbox into the form.
  • right click on the lable1 in your form and then select Properties.
  • Change the text in properties window to “Product:”.
  • Do the same to the Lable2 but this time change it to “Quantity:”
  • Repeat the same procedure for “button1” but here other than the text you will need to change the name as well. Simply because the code uses a different name as reference to the button (and in this case two text boxes). So change the button text to “Calculate Discount”. Then scroll down to design and change the (Name) from “button1” to “buttonCalculate”.
  • Do the same for the two textbox. For the textbox1 the text should be changed to “Milk Bottle” (as we use milk bottle as an example) and then the (Name) should change to “textProduct”. For textbox2, change the text to “5” and change the (Name) to “textQuantity”.
  • In the end your form should look something like this:


Creating a Class library

  • On the “Solution Explorer” window, right click on the solution icon; select Add and then new Project.
  • Click on “Visual C#” in “Recent Templates” and this time select Class Library.
  • Enter the name “DiscountSample.Library” for the project and press OK.
  • In Solution Explorer right click on the “DiscountSample.Library” project folder and select properties.
  • In properties, click on “Build” tab, look for “Output” find “Output path”, click on “Brows”.
  • Find the FlexRule SDK path and then click select folder. (Alternatively, you can simply type the path. FlexRule default installation folder is usually at “C:\Program Files (x86)\Pliant Framework\FlexRule\Framework\”)
  • Now we need to change the class name in our class library. By default, it is named Class1.cs. Just to make it more understandable, right click on the Class1.cs, select rename and change its name to SimpleLineItem.cs.
  • Again a popup window will be shown asking you if you like to rename all references in the project to code element “Class1”? Hit Yes and continue.
  • Add the “DiscountSample.Library” (the class library that you have just created) as one of your reference. To do so, right click on the reference folder on windows form project icon (DiscountSample) and select “Add Reference…”.
  • in Add Reference menu click on Projects tab and select “DiscountSample.Library” and then press OK.

Setup project license

  • In “Solution Explorer” window, open the DiscountSample project and then open “Properties” folder. Inside the folder you will find a file named: “AssemblyInfo.cs”
  • Open the file by double clicking on it and add this line to the top right after the three first line.
  1. using FlexRule.License;
  • Go to the bottom and add these two lines of code to the end:
  1. [assembly: System.Runtime.CompilerServices.SuppressIldasm]
  2. [assembly: LicenseProviderAttribute(typeof(FileBasedLicenseProvider))]
  • Save and close the file and now again in “Solution Explorer” double click on “MainForm.cs”.

Connecting the form to rule engine

  • In the design window, double click on “Calculate Discount” button and copy and replace the below code with the existing.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using FlexRule.Core.Model;
  9. using FlexRule.Core.Model.LoadAdapters;
  10. using FlexRule.Core.Model.SourceConnection;
  11. using FlexRule;
  12. using FlexRule.Procedural;
  13. using FlexRule.License;
  15. namespace DiscountSample
  16. {
  17.     public partial class MainForm : Form
  18.     {
  19.         public MainForm()
  20.         {
  21.             UserLicense.Initialize();
  22.             InitializeComponent();
  23.         }
  25.         private void buttonCalculate_Click(object sender, EventArgs e)
  26.         {
  27.             // Create the line item object from the screen values
  28.             SimpleLineItem lineItem = GetLineItem();
  30.             // Load the rule model contents as a binary array
  31.             var model = System.IO.File.ReadAllBytes("DiscountRule.Xml");
  33.             // Creating a rule engine from the loaded model
  34.             // This engine can be shared between subsequent calculation calls (requests)
  35.             var engine = RuntimeEngine.FromXml(model, Environment.CurrentDirectory);
  37.             // calling engine and passing the line item
  38.             var result = engine.Run(lineItem);
  40.             // Reading discount from the context
  41.             float discount = (float)result.Context.VariableContainer["discount"];
  43.             // display discount information
  44.             MessageBox.Show(this, string.Format("Percentage: {0}%", discount * 100), "Discount calculated", MessageBoxButtons.OK, MessageBoxIcon.Information);
  45.         }
  47.         /// <summary>
  48.         /// This method creates the required object from the values user has entered
  49.         /// </summary>
  50.         /// <returns></returns>
  51.         private SimpleLineItem GetLineItem()
  52.         {
  53.             // getting the product name
  54.             string productName = textProduct.Text;
  56.             // convert string to integer
  57.             int quantity = int.Parse(textQuantity.Text);
  59.             // creating an line item
  60.             SimpleLineItem lineItem = new SimpleLineItem(productName, quantity);
  61.             return lineItem;
  62.         }
  63.     }
  64. }
  • The code is self-explanatory, but if you find it hard to understand, there are comments that can help you to understand it better.
  • Save and close the MainForm window.
  • Again in solution explorer, open the “DiscountSample.Library” navigate to “Properties” and then open “AssmblyIfo.cs.
  • Type the below code in the end of the “AssemblyInfo.cs” code.
  1. [assembly: System.Runtime.CompilerServices.SuppressIldasm]
  • Save and close the file.
  • Open “SimpleLineItem.cs” replace below code with the code inside the file:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  5. namespace DiscountSample
  6. {
  7.     public class SimpleLineItem
  8.     {
  9.         public SimpleLineItem(string productName, int quantity)
  10.         {
  11.             Quantity = quantity;
  12.             ProductName = productName;
  13.         }
  15.         public string ProductName { get; private set; }
  16.         public int Quantity { get; private set; }
  17.         public float Discount { get; set; }
  18.     }
  19. }
  • Save and close the file and you are done with the coding part.
  • In the “Solution Explorer window, right click on solution Icon and select “Build Solution” or simply hit “Ctrl+Shift+B”.


  • If everything is done properly, you should see the output window reporting that the build has been successful without any error.


  • If you get any error, just go through the tutorial step by step and check if everything is done right.

Reading the rule results

  • To read the result, you need to first run the program. So from the menu, select “Debug” and select “Start Debugging. You can perform the same operation by hitting “F5” key or If you just want to run the program and do not need to debug it, simply by pressing “Ctrl+F5”.


  • The program will run and the MainForm will be shown:


  • Now just hit the “Calculate Discount” button and you have to see a window like below:


  • Because the quantity is below 10 and rule indicates that the discount is only applicable if the quantity is equal or higher than 10, the discount percentage shown will be 0%.
  • Change the Quantity to a number greater than 10 and this time the calculated discount will be 3%.


  • Congratulation…! You have successfully created a Procedural rule using Flex Rule Designer and used it in your program.

Download the Working Sample

Download solution and source code