Executing Rules

  • Updated

This article contains the following sections:

Applying Rules

Prerequisites A valid RuleSession
Namespaces  InRule.Runtime
Classes RuleSession, Entity, RuleException
See Also

Retrieving a Rule Application, Creating a RuleSession, Creating Entities, Handling Exceptions

References InRule.Runtime.dll, InRule.Common.dll

Apply rules

 try
{
     // Apply the rules.
    session.ApplyRules();
}
catch (RuleException ex)
{
     // Handle any rule engine exceptions here.
    Console.WriteLine(ex.ToString());
}

This will execute all Auto RuleSets, calculations, constraints and classifications.


Execute explicit rulesets and rule flows

// Apply the CalculatePaymentSchedule from the mortgageEntity
mortgageEntity.ExecuteRuleSet("CaculatePaymentSchedule");

Rule flows are executed using the same method and behave in the same manner as explicit rulesets.
Any auto rules are also being applied when applying an explicit ruleset or rule flow.


Execute explicit rulesets that accept parameters

// Execute the ruleset passing in a list of parameters
mortgageEntity.ExecuteRuleSet("AddCharge", "Appraisal", 400.99);

 

Applying Rules with an Activation Model

Prerequisites A valid RuleSession and Entity
Namespaces InRule.Runtime
Classes RuleSession, Entity
References InRule.Runtime.dll, InRule.Common.dll

The following examples demonstrate how to control rule execution by Activating and Deactivating Rule Sets through a variety of techniques. The Activation should be set by calling one of the methods below, and then rules can be applied, as seen in the section above.


Activate RuleSets by Name

// Activate ruleset by name
ruleSession.ActivateRuleSets("Entity1.RuleSet1");

Deactivate RuleSets by Name

// Deactivate ruleset by name
ruleSession.DeactivateRuleSets("Entity1.RuleSet1");

Activate RuleSets by Category

// Activate ruleset by category
ruleSession.ActivateRuleSetsByCategory("Category1");

Deactivate RuleSets by Category

// Deactivate ruleset by category
ruleSession.DeactivateRuleSetsByCategory("Category1");

Activate RuleSet by Name from an Entity

// Activate ruleset by name
entity.ActivateRuleSet("RuleSet1");

Deactivate RuleSet by Name from an Entity

// Deactivate ruleset by name
entity.DeactivateRuleSet("RuleSet1");

Reset RuleSet activations

// Reset rule activations
ruleSession.ResetAllRuleSetActivations();

When calling ResetAllRuleSetActivations, the Activation status is set back to the original status at the time of authoring.

Executing Decisions

Prerequisites  A valid RuleSession
Namespaces InRule.Runtime
Classes RuleSession, RuleException
See Also Retrieving a Rule Application, Creating a RuleSession, Handling Exceptions
References InRule.Runtime.dll, InRule.Common.dll

Execute decision using DecisionInput

try
{
     // Execute the Decision
    var decision = session.CreateDecision("CalculateArea");
   decision.Execute(new DecisionInput("height", 30), new DecisionInput("width", 400));
}
catch (RuleException ex)
{
     // Handle any rule engine exceptions here.
    Console.WriteLine(ex.ToString());
}

If a Decision input is an Entity type, an Entity instance should be passed. Any Auto RuleSets, calculations, constraints, and classifications on the passed Entity will be executed.


Execute decision using JSON

try
{
     // Execute the Decision
    var decision = session.CreateDecision("CalculateArea");
   decision.Execute("{ \"height\": 30, \"width\": 400 }, EntityStateType.Json));
}
catch (RuleException ex)
{
     // Handle any rule engine exceptions here.
    Console.WriteLine(ex.ToString());
}

Executing an Independent Rule Set or Rule Flow

Prerequisites A valid RuleSession
Namespaces InRule.Runtime
Classes RuleSession, Entity
See Also Retrieving a Rule Application, Creating a RuleSession, Creating Entities

Execute an Independent Ruleset

int height = 30;
int width = 40;                     

// Create a runtime instance of the independent ruleset.
RuleSet calcAreaRuleSet = ruleSession.CreateIndependentRuleSet("CalculateArea");

// Execute the ruleset passing in the parameters
Runtime.RuleExecutionLog executionLog = calcAreaRuleSet.Execute(height, width);

 

Checking For Notifications & Validations

Prerequisites  A valid RuleSession
Namespaces InRule.Runtime
Classes Notification, Validation, RuleSession
See Also Retrieving a Rule Application, Creating a RuleSession, Creating Entities,  Applying Rules

Check for notifications

// Retrieve the notifications from the session state
foreach (Notification note in ruleSession.GetNotifications())
{
  // Handle the notification
  Console.WriteLine(note.Message);
}

 


Check for validations

// Retrieve the validations from the session state
foreach (Validation validation in ruleSession.GetValidations())
{
  // Handle the validation
  Console.WriteLine(validation.Message);
}

 

Handling Exceptions

Prerequisites  A valid RuleSession, a Try block wrapped around InRule SDK code to load state and execute rules.
Namespaces InRule.Runtime, InRule.Common.Exceptions, InRule.Repository
Classes RuleException, CompileException, CompilerError, RuntimeException
See Also Basic Example of Creating a RuleApplication in Code
References InRule.Runtime.dll, InRule.Common.dll

Below are the common exceptions to handle compile and runtime errors and the RuleException, which is the base class for all InRule exceptions. They are listed in the order in which they should be implemented.

The individual values in the AuthoringErrorCode and RuntimeErrorCode enumerations may change in future versions of InRule.

See the * class for a complete list of InRule exceptions.


Handling compiler exceptions

// Catching compile exceptions
catch (CompileException ex)
{
    foreach (CompileError err in ex.Errors)
    {
        if (err.AuthoringErrorCode == AuthoringErrorCode.SqlQueryParameterTypeIsInvalid)
        {
            // React
        }
    }
}

Handling integration exceptions

// Catching integration exceptions
catch (IntegrationException ex)
{
    if (ex.RuntimeErrorCode == RuntimeErrorCode.StateUnableToBindToMember)
    {
        // React
    }
}

 


Handling base exceptions

// Base class exception; can be used to catch all InRule exceptions
catch (RuntimeException ex)
{
    foreach (ErrorLogMessage err in ex.ErrorMessages)
    {
        if (err.RuntimeErrorCode == RuntimeErrorCode.AppSettingsSectionMissingOrMalformed)
        {
            // React
        }
  }

Runtime Settings

Prerequisites A valid RuleSession
Namespaces InRule.Runtime
Classes RuleSessionSettings, RuleSession
References InRule.Runtime.dll

These are some of the settings the rule engine uses during execution:


Overriding the current date

Gets or sets a value that will override the return value of the Today() function in the rule engine. If not set, the rule engine will use the current date.

To override the current date to January 1, 2025:

ruleSession.Settings.Now = new DateTime(2025, 1, 1);

Overriding the execution timeout

Gets or sets the maximum time for rule engine execution.

To override the default setting to 60 seconds:

ruleSession.Settings.ExecutionTimeout = new TimeSpan(0, 0, 60);

Overriding the maximum cycle count

Gets or sets the maximum cycles for rule engine execution.

To override the default setting:

ruleSession.Settings.MaxCycleCount = 200000;

Returning detailed statistics information

Gets or sets a value determining whether statistics info will be logged and returned. The default is false.

This will affect the amount of information that is displayed on the Performance Statistics report.

To override the default setting:

ruleSession.Settings.LogOptions = EngineLogOptions.SummaryStatistics;

To enable metrics logging

Set the MetricLogger property to an instance of an object that implements the IMetricLogger interface as shown below.

ruleSession.Settings.MetricLogger = new CsvMetricLogger();

For more details, refer to the CSV sample application.


Retrieving and Processing the RuleExecutionLog

Prerequisites A valid RuleSession and Entity.
Namespaces InRule.Runtime
Classes RuleSession, Entity
References InRule.Runtime.dll, InRule.Common.dll

Retrieving RuleExecutionLog from RuleSession.ApplyRules

// Apply rules and capture RuleExecutionLog
RuleExecutionLog executionLog = ruleSession.ApplyRules();

Retrieving RuleExecutionLog from Entity.ExecuteRuleSet

// Execute explicit RuleSet and capture RuleExecutionLog
RuleExecutionLog executionLog = entity.ExecuteRuleSet("CalculatePaymentSchedule");

Processing the RuleExecutionLog

The following method will take a RuleExecutionLog as a parameter and return a string with the text from all of the messages separated by line breaks.

public string GetExecutionLogText(RuleExecutionLog executionLog)
{
  // Spin through all of the messages in the RuleExecutionLog and append to a StringBuilder
  StringBuilder sb = new StringBuilder();
  foreach (LogMessage message in executionLog.AllMessages)
   {
       sb.Append(message.Description + Environment.NewLine);
   }
  // return string
  return sb.ToString();
}

See the Implementation Guide for more details.


Retrieving the Performance Statistics Report

Prerequisites A valid RuleSession
Namespaces InRule.Runtime
Classes FileSystemRuleApplicationReference, RuleSession, Entity, RuleException
See Also Basic Example Of Calling Rules Engine, Retrieve the Performance Log
References InRule.Runtime.dll, InRule.Common.dll

The following basic example demonstrates how to capture the Performance Statistics Report at run time.

// Turn on capturing of detailed statistics (if desired)
ruleSession.Settings.LogOptions = EngineLogOptions.DetailStatistics;

// Run rules
ruleSession.ApplyRules();

// Get the XML as a string for the Performance Statistics Report (includes log messages if log options configured to include them)
string reportXml = ruleSession.LastRuleExecutionLog.GetXml();

// Get the HTML as a string for the Performance Statistics Report
string reportHtml = ruleSession.LastRuleExecutionLog.GetHtml();

// write the report to the file system (could also view in a web browser control)
File.WriteAllText(@"c:\work\PerfStatsReport.html", reportHtml);


Retrieving the Performance Log

Prerequisites A valid RuleSession
Namespaces InRule.Runtime
Classes FileSystemRuleApplicationReference, RuleSession, Entity
See Also Basic Example Of Calling Rules Engine, Retrieve the Performance Statistics Report
References InRule.Runtime.dll, InRule.Common.dll

The Performance Log contains information about load, compile and execution times.  This information is also available in the InRule Event Logs.  See Event Log Details for more information.  The following example demonstrates how to capture the Performance Log information using the SDK.

    // Create the "Rectangle" entity, passing in Xml for state
    Entity rectangle = session.CreateEntity("Rectangle", inputXml);
    // Apply rules
    session.ApplyRules();
    // Get performance log information from the RuleSession
    string perfLogDetails = session.Statistics.GetRunningTotalAllReport();

Example of Performance Log

SessionId: b8ea59d5-8ec3-4c8b-947c-bb41411d8304
GetRuleApplicationDefExecTime (usually indicates a
compile): 14569.036ms (max 14569.036ms) 1
CreateRuleApplicationDefInfoExecTime: 1511.761ms (max 1511.761ms) 1
GetRuleApplicationRevisionKeyExecTime (incl. in CreateRuleApplicationDefInfo): 6.591ms 1
AggExecStatInfo.AggDirectives (incl. in Submit): 399.384ms 1
CreateSessionExecTime: 93.793ms 1
CreateEntityExecTime: 17511.331ms (max 17511.331ms) 1
LoadXmlExecTime: 93.128ms 1
SubmitExecTime: 642.903ms (max 642.903ms) 1
ProcessResponseExecTime: 22.564ms 1
ThreadId: 11
MaxCacheDepth: 5
CurrentCacheDepth: 1
CompileExecTime: 17195.075ms 1
WorkingMemCreateCnt: 1
Ruleapp 'RectangleApp': 1
CacheUpTime: 18.421sec
RunningTotalAll: 35558.794ms

Was this article helpful?

0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.