Wednesday 12 April 2023

UiPath Custom Rules Engine Activity Tutorial - Part 2

 

UiPath Custom Rules Engine Activity Tutorial - Part 2

In this tutorial, you create a UiPath workflow application for a fictitious online lender. It determines whether a customer is eligible for a loan according to specific criteria (rules). The criteria include the amount of the loan, the annual income of the borrower, and the duration of the loan.

To make the workflow, we will not follow the typical rule development workflow (so many if-else conditions ..) We will use the custom rules engine. By doing so, you discover the steps required to develop, deploy, and maintain a rule-based application.

Prerequisites:

·         UiPath Studio <= 2022.4.6

·         UiPath Robot <= 2022.4.6

·         Orchestrator (will use staging)

·         Data Service

·         Insights

·         Internet Access to download the package

Rules

Initially, we have the following policy (business rules) to apply for a loan ( 8 rules). Please note the priority for each one.



If you don’t want to follow along you can download the code from the last section, Source.

Procedures

1.      Create two entities that represent the business object models in data service (Borrower and Loan) as per the images below or import the attached schema file in the last section to generate the entities.:





2. Create a UiPath Studio Project (C#, Windows)



3. Import package UiPathTeam.RulesEngine.Activities

4.Import the business entities(borrower and loan) I’ll use OnlineBanking.Models as namespace.



5. From Activities Panel >> UiPathTeam.RulesEngine.Activities >> Drag Rules Activity Panel >> In Select Type Dialog Choose (OnlineBanking.Models.Loan)



6. After clicking ok in step 5, you will see the rule policy activity as in this image (Rule Policy), where you need to fill in the following:

Rule File Path: click on the ellipse icon and choose any location the dialog will create the file if it’s not exists.

Rule SetName: click on RuleSet Browser to create a group

Target Object: I created a variable of type OnlineBanking.Models.Loan to pass it to the rules engine

Result Object: same as TargetObject value



7. Click Edit Rules to start adding the rules, after adding all rules, you should get this view:

“Please note I’m using the Halt keyword in Rule 8 to end the execution if loan amount > 1M”



Your .rules file should contains the XAML representation of your code:


<RuleDefinitions xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
        <RuleDefinitions.RuleSets>
               <RuleSet Description="{p3:Null}" Name="Loan-1-0" ChainingBehavior="Full" 
xmlns:p3="http://schemas.microsoft.com/winfx/2006/xaml">
                       <RuleSet.Rules>
                               <Rule Priority="1" ReevaluationBehavior="Never" 
Description="{p3:Null}" Active="True" Name="Rule 8">
                                      <Rule.Condition>
                                              <RuleExpressionCondition Name="{p3:Null}">
                                                      <RuleExpressionCondition.Expression>
                                                             <ns0:CodeBinaryOperatorExpression Operator="GreaterThan"
 xmlns:ns0="clr-namespace:System.CodeDom;Assembly=System, Version=4.0.0.0, 
Culture=neutral, PublicKeyToken=b77a5c561934e089">
                                                                     <ns0:CodeBinaryOperatorExpression.Right>
                                                                             <ns0:CodePrimitiveExpression>
                                                                                    <ns0:CodePrimitiveExpression.Value>
                                                                                    <ns1:Int32 xmlns:ns1="clr-namespace:System;Assembly=mscorlib, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">1000000</ns1:Int32>
                                                                                    </ns0:CodePrimitiveExpression.Value>
                                                                             </ns0:CodePrimitiveExpression>
                                                                     </ns0:CodeBinaryOperatorExpression.Right> 



In workflow I used custom logs activity to measure the processing time for each loan request.
I’ll use Insights’ s dashboard as a reporting for processing time so we can compare the 
performance of the custom activity (Rules Engine) with any other way like if-else activities.

Custom Log Filed:

·         RulesEngineTransacionTimeMilliseconds

·         RulesEngineEntityId

·         RulesEngineEntityIsApproved
                                          


Testing

To test our policy I’ll do the following:

1.      Read all Loan records as sets (100 records per set) with condition IsProcessing = false

2.      Loop over each set and apply rules policy to get the result

3.      Update loan entity so we don’t read the record again.

4.      To fill data service with test data, run the GenerateTestData workflow, where it will create random data based on the DataSize argument value (there are 8 names in the workflow and the DataSize argument adjust the number of loans per name)

5.      Publish the package (Online.Banking) to your Orchestrator

6.      Grant your Robot account a read and write permission on data service

7.      Create a process to fill data; set Entry point to GenerateTestData and display name to Online.Banking.GenerateData

8.      Create a process to test the rules engine; set Entry point to Main and display name to Online.Banking.Loan

after setting the configuration you should get this view in your orchestrator



Performance:

This graph (from Insights) shows the average processing time per loan in Milliseconds using a 48,523 Records.



Source:

https://github.com/ajamaeen/UiPath-Rules-Engin-Samples

Schema file for Data Service Entities :https://github.com/ajamaeen/UiPath-Rules-Engin-Samples/blob/main/Docs/Schema.json

NuGet Package: https://github.com/ajamaeen/UiPath-Rules-Engin-Samples/releases/tag/UiPathRulesEngine

UiPath Custom Rules Engine Activity Intro - Part 1

UiPath Custom Rules Engine Activity Intro - Part 1

Intro to Rules Engine:

Almost all workflows require an enormous number of business rules. For example, car reservations made at least 20 days in advance receive a 12% discount unless the cost of the car is less than $100.

While expressing rules using the conditional flow activities (if,if-else, while …) is certainly possible, it's not always the best choice. Instead, the right approach for handling complex groups of rules can sometimes be to use a rules engine.

Encoding business rules into code using conditional activities makes the rules harder to find, read, and modify. Over the years, the software industry has invented tools for working with business rules. Called rules engines, inference engines, and logic machines. A rules engine specializes in making business rules easier to implement, process, isolate, and modify.

To make using a rules engine possible in UiPath workflows, we have created a wrapper activity on top of Windows Workflow Foundation that can be accessed through the policy activity. Using this activity, a developer can define a group of rules called a rule set. Each rule has the form IF <condition> THEN <action> ELSE <action>. 

Solution Architecture:

The image below is a high-level view of the proposed solution, more details in the upcoming sections.


Solution Architecture




Terms (Conditions, Rules, and Rule sets):

We will use three important terms in this article: Conditionsrules, and rule sets.

In a workflow, conditions are chunks of logic that return true or false.

Several workflow activities utilize conditions to guide their behavior. These activities include the While activity, If, If Else activity, and the Do While. The While activity, for instance, loops until its Condition property returns false.

Rules are conditions with a set of actions to perform. Rules use a declarative if-then-else style, where the "if" is a condition to evaluate. If the condition evaluates to true, the runtime performs the "then" actions, otherwise, the "else" actions.

Rule Set is a collection of one or more rules. As an example, we might have three rules we use to calculate the discount on the price of a car rental (shown here in pseudo-code).

if the driver’s age is greater than 55

then discount = discount + 10%

if the length of rent is greater than 5 days

then discount = discount + 10%

if the driver is married and has no accidents history

then discount = 12%

Before we can evaluate these three rules, we need to group them inside a Rule Set. We can assign each rule a priority to control the order of evaluation. workflow can revisit rules if later rules change the data used inside previous rules. We can store rules in an external XML file and feed external rules to the workflow runtime when creating a new workflow.

This graph shows in detail each term and how it’s related to each other.


Rules Set

Policy Activity

Policies are everywhere in our life. Universities define policies for student admissions, insurance companies define policies for underwriting qualifications, banks define policies for loans …
Business policy can become very complex and is full of declarative knowledge.

The custom rules engine activity (Policy Activity) provides a user interface for the user to update, create, and modify rule sets and rules. The features and execution semantics described in policy activity give us more flexibility when compared to procedural code. We can dynamically customize rules to meet the needs of a specific customer or business scenario.

UiPath policy activity is just a wrapper on top of the Microsoft workflow foundation (Rules Engine) built using UiPath template for visual studio 2019, and it uses the execute method of a RuleSet to process the rule collection.

The experience of the custom policy activity is shown in Figure 3



Figure 3 - UiPath Policy Activity


The .rules File

Rules engine uses a file with an extension of .rules to store data. it’s XAML representation of objects from the System.CodeDom namespace. The CodeDom (Code Document Object Model) namespace contains classes that construct source code in a language agnostic fashion.

At compile time, this .rules file becomes an embedded resource in workflow package.

Adding a Policy Activity

To use policy activity, follow these steps:

1.      Install package UiPathTeam.RulesEngine.Activities

2.      Drag the rules policy activity from the toolbox onto the workflow designer.

3.      In the select types dialog select the type of object you want to apply rules on

4.      Select the ellipses in the Rules File Path field to launch an open file dialog where you can either create a new rules file (.rule) or choose an existing one.

The main goal of .rule file is to have many rules policy activities referencing one rules file.

1.      RuleSet Name combobox list all available RuleSets in the selected file (step 4)

2.      In the target object enter the object which to apply the rules on

3.      In the result object enter the result object after applying the rules (you can use same target object)

4.      RuleSet Browser button launches a dialog to add versions to rule sets (Figure 4)

5.      Edit Rules button launches the Rule Set Editor for the selected rule set in RuleSet name combobox (Figure 5) In the rule set editor the Condition, Then actions, and Else actions are entered in as text and parsed into the associated object model representation; rules are built against the members on the workflow.

6.      Selecting a given rule shows its Condition, Then actions, Else actions, and a set of additional properties.

7.      Selecting OK serializes the RuleSet to the .rules file associated with the workflow



Figure 4 - RuleSet Browser



Figure 5 - Rule Set Editor

Rule Set Editor

Is the heart of the policy activity where you can add rules, enable rules, disable rules, update rule’s priority, specify chaining of the rule and set the type of reevaluation for the rule.

Rules Evaluation

Each rule in a RuleSet has a priority value with a default of 0. The rules in a RuleSet can be considered a sorted collection, ordered by the priority values. The WF Rules evaluator evaluates rules individually and executes the rule's actions based on the results of the rule's condition evaluation.

The evaluation mechanism can be conceptually described with the following procedure:

1.      Start with the list of active rules.

2.      Find the highest priority rule.

3.      Evaluate the rule and execute its Then/Else actions as appropriate.

4.      If the actions of a rule update a field/property that is used by a previous rule in the list (one with a higher priority), reevaluate that previous rule and execute its actions as appropriate. Note that only those rules with a specific dependency are reevaluated.

5.      Continue the process until all rules in the RuleSet have been evaluated.

Rules Dependencies

When an action produces a side effect that matches a dependency from a previously executed rule, the rules engine can go back and re-evaluate the previous rule. In rules engine terminology, this feature is called forward chaining.

Chaining is based on the identified dependencies among rules; more specifically, the dependencies among the actions of a rule and the conditions of other rules. These dependencies can be identified or declared in one of three ways:

·         Implicit

·         Attribute-based

·         Explicit

For detailed explanation about rules chaining consult this document https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa480193(v=msdn.10)

Implicit dependencies are identified automatically by the engine. When a RuleSet is first executed, each rule is analyzed to assess the fields/properties that it reads in its condition and writes to in its actions. This is done by walking the expression in the condition and the statements in the actions.

Attribute-based for method calls within a rule, it becomes more difficult to deterministically evaluate the reads/writes that occur. To address this problem, WF provides three attributes that can be applied to a method to indicate its actions:

·         RuleRead

·         RuleWrite

·         RuleInvoke

Attributing a method with the RuleRead attribute indicates that it reads the indicated property. Similarly, the RuleWrite attribute can be used to indicate that a method updates a given field or property.

Explicit the final mechanism for indicating field/property dependencies is through the use of the Update statement. The Update statement takes as its argument either a string that represents the path to a field or property or an expression that represents a field/property access. For example, either of the following two statements could be typed into the RuleSet editor to create an Update statement on the Name property of a Customer instance on the workflow: Update("this/customer/Name") or Update(this.customer.Name)

Forward chaining is a very powerful notion that allows atomic rules to be assembled into RuleSets without the definition of, or necessarily even the knowledge of, the dependencies among the rules.

However, in some scenarios, the rule writer may want the ability to provide more control over the chaining behavior, specifically the ability to limit the chaining that takes place. This enables the rule modeler to:

·         Limit the repetitive execution of rules, which may give incorrect results.

·         Increase performance.

·         Prevent runaway loops.

This level of control is facilitated in WF rules by these two properties:

·         A Chaining Behavior property on the RuleSet.

·         A Reevaluation Behavior property on each rule.

Both of these values can be set in the RuleSet Editor.

The Chaining Behavior property on the RuleSet has three possible values:

·         Full Chaining

·         Explicit Chaining

·         Sequential

The Full Chaining option is the default and provides the behavior described up to this point. The Explicit Chaining option turns off the implicit and attribute-based chaining and prescribes that chaining should only occur for explicit Update statements. This gives the rule writer complete control over what rules cause reevaluation. Typically, this would be used to either avoid cyclic dependencies that cause excessive (or even runaway) rule re-execution, or to boost performance by eliminating superfluous rule reevaluation not required to provide functional completeness of the RuleSet.

The final option is Sequential. This option will cause the engine to evaluate the rules in strictly linear fashion. Each rule would be evaluated once and only once and in the order of priority. Rules with a higher priority could impact rules with lower priorities, but the inverse would not be true since no chaining would occur. Therefore, this option would be used with explicit priority assignments unless no dependencies existed among the rules.

The Reevaluation Behavior on the rule has two possible values:

·         Always

·         Never

Always is the default and provides the behavior previously discussed, namely that the rule will always be reevaluated based on chaining due to the actions of other rules. Never, as the name implies, turns off this reevaluation. The rule will be evaluated once but will not be reevaluated if it has previously executed any actions. In other words, if the rule has previously been evaluated and consequently executed its Then or Else actions, it will not be reevaluated.

Halt Function

As a final control, a Halt function can be added as a rule action (simply type "Halt" into the Then or Else action boxes in the editor). This will immediately stop RuleSet execution and return control to the calling code. The usefulness of this function is not necessarily limited to chaining control scenarios, of course. A RuleSet with a specific functional goal, for example, may use a Halt function to short-circuit execution once the goal has been reached.

Kindly check part2 of this series for a sample scenario the includes all mentioned features.

https://uipath.atlassian.net/wiki/spaces/FAN/pages/edit-v2/87032353715?draftShareId=129bed9a-4b48-4f9f-a85f-54a6aee3362d

Conclusion:

A custom policy activity provides can integrate rules support into UiPath workflows.

RPA developers can easily incorporate rules at any point in their workflow and they are able to make the determination of whether to model their logic in the workflow model, rules, or code.

References

For more information kindly consult this document

https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa480193(v=msdn.10)

Complete source code:

https://github.com/ajamaeen/UiPathTeam.RulesEngine

Sample Tutorial : UiPath Custom Rules Engine Activity Tutorial -Part 2