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: Conditions, rules,
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.
A 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