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, these rules 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 this 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 the discount to which the customer is entitled.

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

The rule is like this:

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

Modeling the rule

In this scenario, the rule would accept two 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">
  2.  
  3.   <Declaration>
  4.     <Define name="item" direction="in" />
  5.     <Define name="discount" direction="out" value="0.0f"/>
  6.   </Declaration>
  7.  
  8.   <If condition='item.Quantity >= 10'>
  9.     <Var name="discount" value="0.03f" />
  10.   </If>
  11.  
  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 with one solution:

  1. A windows form application
  2. A class library

Creating A Windows Form Application

  • Run Visual Studio as an administrator.
  • In the 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.
  • Select “.Net Framework 4.0" form the top side drop down menu.
  • Click OK to create a new solution containing a new project.

1NewProjectExecute.jpg


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

4ChangeProjectProperties.jpg


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

5ChangeOutputPath.jpg


  • 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 the “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.
  • The 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”.

8DeleteReferences.jpg


  • Select the Browse tab, then select the folder in which you have installed the Flex Rule framework. The default folder usually is “C:\Program Files (x86)\Pliant Framework\FlexRule\Framework”.
  • After finding the folder, you need to select a 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 of the required references into the project.
  • Now you need to import the XML file you have created using FlexRule designer into your project. To do so, right click on the “DiscountSample” Project, select “Add” and then “Existing Item…” or simply hit “Shift+Alt+A”.
  • In the “Add Existing Item” menu, browse to the folder in which 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 in which you have saved your Flex Rule designer project). 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 the 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 so. Just right click on the form and then select Rename.
  • Change the name from “Form1.cs” to “MainForm.cs” and hit Enter. A popup window will be shown asking you if you would 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 the “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 textboxes onto the form.
  • Right click on lable1 in your form and then select Properties.
  • Change the text in the 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. As the code uses a different name as a reference to the button (and in this case two text boxes), 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 textboxes. For 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:

22FormFinalized.jpg

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 “Browse”.
  • Find the FlexRule SDK path and then click Select Folder. (Alternatively, you can simply type the path. The 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 would 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 references. To do so, right click on the reference folder on the windows form project icon (DiscountSample) and select “Add Reference…”.
  • In the Add Reference menu click on the Projects tab and select “DiscountSample.Library” and then press OK.

Setup project license

  • In the “Solution Explorer” window, open the DiscountSample project and then open the “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 lines:
  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 in “Solution Explorer”, double click on “MainForm.cs”.

Connecting the form to rule engine

  • In the design window, double click on the “Calculate Discount” button and copy and replace the code below 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;
  14.  
  15. namespace DiscountSample
  16. {
  17.     public partial class MainForm : Form
  18.     {
  19.         public MainForm()
  20.         {
  21.             UserLicense.Initialize();
  22.             InitializeComponent();
  23.         }
  24.  
  25.         private void buttonCalculate_Click(object sender, EventArgs e)
  26.         {
  27.             // Create the line item object from the screen values
  28.             SimpleLineItem lineItem = GetLineItem();
  29.  
  30.             // Load the rule model contents as a binary array
  31.             var model = System.IO.File.ReadAllBytes("DiscountRule.Xml");
  32.  
  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);
  36.  
  37.             // calling engine and passing the line item
  38.             var result = engine.Run(lineItem);
  39.  
  40.             // Reading discount from the context
  41.             float discount = (float)result.Context.VariableContainer["discount"];
  42.  
  43.             // display discount information
  44.             MessageBox.Show(this, string.Format("Percentage: {0}%", discount * 100), "Discount calculated", MessageBoxButtons.OK, MessageBoxIcon.Information);
  45.         }
  46.  
  47.         /// <summary>
  48.         /// This method creates the required object from the values the user has entered
  49.         /// </summary>
  50.         /// <returns></returns>
  51.         private SimpleLineItem GetLineItem()
  52.         {
  53.             // getting the product name
  54.             string productName = textProduct.Text;
  55.  
  56.             // convert string to integer
  57.             int quantity = int.Parse(textQuantity.Text);
  58.  
  59.             // creating an line item
  60.             SimpleLineItem lineItem = new SimpleLineItem(productName, quantity);
  61.             return lineItem;
  62.         }
  63.     }
  64. }
  • The code is self-explanatory, but there are also 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 code below at the end of the “AssemblyInfo.cs” code.
  1. [assembly: System.Runtime.CompilerServices.SuppressIldasm]
  • Save and close the file.
  • Open “SimpleLineItem.cs” replace the code below with the code inside the file:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace DiscountSample
  6. {
  7.     public class SimpleLineItem
  8.     {
  9.         public SimpleLineItem(string productName, int quantity)
  10.         {
  11.             Quantity = quantity;
  12.             ProductName = productName;
  13.         }
  14.  
  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 - now you are done with the coding part.
  • In the “Solution Explorer window, right click on the solution Icon and select “Build Solution” or simply hit “Ctrl+Shift+B”.

23BuildSolution.jpg


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

24Output.jpg

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

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 the “F5” key or if you just want to run the program and do not need to debug it, simply press “Ctrl+F5”.

25StartDebug.jpg


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

26ReadingFirst.jpg


  • Now just hit the “Calculate Discount” button and you will see a window like the one shown below:

27ResaultFirst.jpg


  • 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%.

28ResaultSecond.jpg


  • Congratulations! 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