1. Home
2. Modeling procedural rules

# Modeling procedural rules

Contents

◷ Reading Time: 11 minutes

### 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:

```<Procedure name="PriceSubTotal" enabled="true">

<Declaration>
<Define name="item" direction="in" />
<Define name="discount" direction="out" value="0.0f"/>
</Declaration>

<If condition='item.Quantity >= 10'>
<Var name="discount" value="0.03f" />
</If>

</Procedure>
```

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.
• In “Solution Explorer” section, right click on the project and then select Properties.
• In properties, click on the “Build” tab, look for “Output”, find “Output path”, and click on “Browse”.
• 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”.
• 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:

#### 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:
```using FlexRule.License;
```
• Go to the bottom and add these two lines of code to the end:
```[assembly: System.Runtime.CompilerServices.SuppressIldasm]
```
• 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:
```using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FlexRule.Core.Model;
using FlexRule.Core.Model.SourceConnection;
using FlexRule;
using FlexRule.Procedural;

namespace DiscountSample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}

private void buttonCalculate_Click(object sender, EventArgs e)
{
// Create the line item object from the screen values
SimpleLineItem lineItem = GetLineItem();

// Load the rule model contents as a binary array
var model = System.IO.File.ReadAllBytes("DiscountRule.Xml");

// Creating a rule engine from the loaded model
// This engine can be shared between subsequent calculation calls (requests)
var engine = RuntimeEngine.FromXml(model, Environment.CurrentDirectory);

// calling engine and passing the line item
var result = engine.Run(lineItem);

// Reading discount from the context
float discount = (float)result.Context.VariableContainer["discount"];

// display discount information
MessageBox.Show(this, string.Format("Percentage: {0}%", discount * 100), "Discount calculated", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

/// <summary>
/// This method creates the required object from the values the user has entered
/// </summary>
/// <returns></returns>
private SimpleLineItem GetLineItem()
{
// getting the product name
string productName = textProduct.Text;

// convert string to integer
int quantity = int.Parse(textQuantity.Text);

// creating an line item
SimpleLineItem lineItem = new SimpleLineItem(productName, quantity);
return lineItem;
}
}
}
```
• 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.
```[assembly: System.Runtime.CompilerServices.SuppressIldasm]
```
• Save and close the file.
• Open “SimpleLineItem.cs” replace the code below with the code inside the file:
```using System;
using System.Collections.Generic;
using System.Text;

namespace DiscountSample
{
public class SimpleLineItem
{
public SimpleLineItem(string productName, int quantity)
{
Quantity = quantity;
ProductName = productName;
}

public string ProductName { get; private set; }
public int Quantity { get; private set; }
public float Discount { get; set; }
}
}
```
• 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”.
• 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 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”.
• The program will run and the MainForm will be shown:
• Now just hit the “Calculate Discount” button and you will see a window like the one shown 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%.
• Congratulations! You have successfully created a Procedural rule using Flex Rule Designer and used it in your program.