Skip to main content



Developing against the RuleApplicationDef Object Model

Working with a RuleApplicationDef for Authoring​

Prerequisites​

None

Namespaces​

InRule.Repository

See Also​

Opening a RuleApplicationDef for Authoring from Catalog , Working with RuleApplicationDef in the Catalog

The RuleApplicationDef object is used to dynamically create and modify rules and schema elements in code.


Create new rule application​

RuleApplicationDef ruleAppDef = new RuleApplicationDef();

Load existing rule application from file system​

RuleApplicationDef ruleAppDef =RuleApplicationDef.Load(@"C:\RuleApps\MortgageCalculator.ruleapp");

Save a rule application to the file system​

ruleAppDef.SaveToFile(@"C:\RuleApps\MortgageCalculator.ruleapp");

Basic Example of Creating a Rule Application in Code​

Prerequisites​

None

Namespaces​

InRule.Repository, InRule.Repository.RuleElements

The RuleApplicationDef object is used to dynamically create and modify rules and schema elements in code. The example below creates the simple rectangle rule application.

// Create a new rule application named "RectangleApp"
RuleApplicationDef ruleAppDef = new RuleApplicationDef("GeneratedRectangleApp");

// Create a rectangle entity
EntityDef entityDef = new EntityDef("Rectangle");

// Add the rectangle entity the rule application's entity collection
ruleAppDef.Entities.Add(entityDef);

// Add numeric height field
entityDef.Fields.Add(new FieldDef("Height", DataType.Number));

// Set the height default value to 4
entityDef.Fields["Height"].DefaultValue = "4";

// Add numeric width field
entityDef.Fields.Add(new FieldDef("Width", DataType.Number));

// Set the width default value to 5
entityDef.Fields["Width"].DefaultValue = "5";

// Add numeric area calculation with syntax expression
entityDef.Fields.Add(new FieldDef("Area", "Height * Width", DataType.Number));

// Create a ruleset
RuleSetDef ruleSetDef = (RuleSetDef)entityDef.RuleElements.Add(new RuleSetDef("MeasurementRules"));

// Create a simple if then rule with condition expression
SimpleRuleDef ruleDef = new SimpleRuleDef("Height > 0 and Width > 0");
ruleSetDef.Rules.Add(ruleDef);

// Create a notification with tokenized message
FireNotificationActionDef notificationDef = new FireNotificationActionDef();

notificationDef.NotificationMessageText = "Generated RectangleApp: Height <%Height%> * Width <%Width%> = Area <%Area%>";

// Add the notification as an action under the if then rule
ruleDef.SubRules.Add(notificationDef);

// Save the rule application to the file system
ruleAppDef.SaveToFile(@"c:\temp\Rectangle.ruleapp");

Working With RuleSets​

Prerequisites​

A valid RuleApplicationDef and EntityDef

Namespaces​

InRule.Repository

See Also​

Dynamically Generating a Rule Application Schema

The following code samples demonstrate how to retrieve and work with RuleSets for authoring purposes.


Get a list of RuleSets from an EntityDef​

// This will return all top-level RuleSets off of an Entity
RuleSetDef[] ruleSets = entityDef.GetRuleSets();

Get a list of all RuleSets from an EntityDef​

// This will return all RuleSets off of an Entity, including RuleSets that are under Rule Folders
RuleSetDef[] ruleSets = entityDef.GetAllRuleSets();

Get a specific RuleSet by name from an EntityDef​

// This will return a single RuleSetDef
RuleSetDef ruleSetDef = entityDef.GetRuleSet("MyRuleSet");

Get a list of independent RuleSets​

// This will return a collection of independent RuleSets
RuleSetDefBaseCollection indRuleSets = ruleAppDef.RuleSets;

Get a specific independent RuleSet​

// This will return a collection of independent RuleSets 
RuleSetDef indRuleSet = ruleAppDef.GetRuleSet("MyIndRuleSet");

Enable/Disable a RuleSet​

// This will turn off the RuleSet, making it unavailable at runtime
// A disabled RuleSet cannot be turned on at runtime
ruleSetDef.IsActive = false;

Set Default Activation of a RuleSet​

// This will turn off the default activation for the RuleSet
// A RuleSet that is enabled, can be activated or deactivated at runtime via rules or the SDK
ruleSetDef.DefaultActivation = false;

Set RuleSet Run Mode​

// This will set the run mode to sequential
ruleSetDef.RunMode = RuleSetRunMode.Sequential;

Set RuleSet Fire Mode​

// This will set the fire mode to explicit
ruleSetDef.FireMode = RuleSetFireMode.Explicit;

Dynamically Generating a RuleApplication Schema​

Prerequisites​

A valid RuleApplicationDef

Namespaces​

InRule.Repository, InRule.Repository.EndPoints, InRule.Repository.ViewsAndControllers

The following examples demonstrate how to dynamically generate a rule application schema using a .NET assembly and an XSD.


Generate Rule Application Schema using an XSD​

// Create the schema def object using a name for the schema and the path to the Xsd file
XmlSchemaDef schemaDef = new XmlSchemaDef("XsdSchemaName", FilePath + "invoice.xsd");

// Embed the schema in the rule app (optional)
schemaDef.UseEmbeddedXsd = true;

// Set whether validation should run when loaded (default is true)
schemaDef.EnableXsdValidation = true;

// Add the schema def object to the rule application as an end point
ruleAppDef.EndPoints.Add(schemaDef);

// Create the schema controller which will do the import of the Xsd
XmlSchemaDefController controller = new XmlSchemaDefController(schemaDef);

// Do the import
controller.Import(FilePath + "invoice.xsd");

// Generate the rule application schema
string[] applyWarns = controller.Apply();

// Process warnings if there were any
if (applyWarns.Length > 0)
{
// handle warnings/errors
}

// Bind Fields that map to xs:enumeration restriction types to a ValueList during import
schemaDef.BindEnumerationFieldsToValueLists = true;

// Disable creation of Constraint rules for Fields that map to xs:enumeration restriction types during import
schemaDef.CreateConstraintsForEnumerationFields = false;

Generate Rule Application Schema using a .NET Assembly​

// Create Assembly and Assembly controller def objects, set isSchema to true
AssemblyDef assemblyDef = new AssemblyDef("InvoiceObject", true);
AssemblyDefController assemblyDefController = new AssemblyDefController(assemblyDef)

// Import the assembly, notes can be captured during import
string[] importNotes = assemblyDefController.Import("InvoiceObjects.dll").EntityDefsInfo.Notes;

// Get top level class by alias
AssemblyDef.ClassInfo topLevelClass = assemblyDef.ClassInfos.GetByAliasName("Invoice");

// Select all dependent entities for the top level class
assemblyDefController.CheckAllSelectedDependentEntities(topLevelClass);

// Add the assembly to the EndPoints collection (will appear as schema in irAuthor)
ruleAppDef.EndPoints.Add(assemblyDef);

// Generate the schema, notes can be captured during schema generation
string[] applyNotes = assemblyDefController.Apply();

// Bind Fields that map to Enum types to a ValueList during import
assemblyDef.BindEnumerationFieldsToValueLists = true;

// Disable creation of Constraint rules for Fields that map to Enum types during import
assemblyDef.CreateConstraintsForEnumerationFields = false;

Generate Rule Application Schema using a Database​

// Create new end point
DatabaseConnection sch =
(DatabaseConnection)ruleAppDef.EndPoints.Add(new DatabaseConnection("DbConn1", connectionString));

// Set up end point to be a schema
sch.IsSchemaDefining = true;

// Create controller that will perform the import
DatabaseConnectionController controller = new DatabaseConnectionController(sch);

// Do the import
controller.Import();

// Apply changes to the rule app, catching any errors that may have occurred
string[] errors = controller.Apply();

Modifying EndPoints​

Prerequisites​

A valid RuleApplicationDef

Namespaces​

InRule.Repository, InRule.epository.EndPoints

See Also​

Dynamically Generating a Rule Application Schema

The following code sample demonstrates how to modify the connection string of a Database Connection EndPoint.

// Get endpoint from loaded RuleApplicationDef object
EndPointDef endPointDef = ruleAppDef.EndPoints["DatabaseConnection1"];

// Cast into a DatabaseConnection object
DatabaseConnection dbConn = (DatabaseConnection)endPointDef;

// Update the connection string
dbConn.ConnectionString = newConnectionString;

Authoring a UDF in Code​

Prerequisites​

None

Namespaces​

InRule.Repository, InRule.Repository.RuleElements

The sample code snippet below illustrates authoring a UDF and using an ExecuteMethodActionDef to execute the UDF.

// Create a ruleapplication
RuleApplicationDef ruleAppDef = new RuleApplicationDef();
EntityDef entity1 = ruleAppDef.Entities.Add(new EntityDef("Entity1"));
entity1.Fields.Add(new FieldDef("InputText"));
entity1.Fields.Add(new FieldDef("Pattern"));

// Add a UDF library
UdfLibraryDef udfLibrary = new UdfLibraryDef("StringFunctionsLibrary");

// Define UDF to match a string for a given pattern
UdfDef udf = new UdfDef("IsPatternMatch");

// Input arguments
UdfArgumentDef arg1 = new UdfArgumentDe("InputText");
arg1.ArgumentTypeInfo.DataType = DataType.String;
udf.FunctionArguments.Add(arg1);
UdfArgumentDef arg2 = new UdfArgumentDef("Pattern");
arg2.ArgumentTypeInfo.DataType = DataType.String;
udf.FunctionArguments.Add(arg2);

// Return type
udf.ReturnTypeInfo.DataType = DataType.Boolean;

// Function declaration
CalcDef func = new CalcDef();
func.FormulaText = "return InputText.Contains(Pattern);";
udf.FunctionBody = func;

// Add UDF to the library
udfLibrary.UserDefinedFunctions.Add(udf);
ruleAppDef.UdfLibraries.Add(udfLibrary);

// Add an execute method action to execute UDF
RuleSetDef rs1 = new RuleSetDef("r1");
ExecuteMethodActionDef execUdf = new ExecuteMethodActionDef();
execUdf.AliasName = "StringFunctionsLibrary";
execUdf.MethodName = "IsPatternMatch";
ExecuteMethodActionParamDef p1 = new ExecuteMethodActionParamDef("abcdeedef", "InputText");
execUdf.ParameterValues.Add(p1);
ExecuteMethodActionParamDef p2 = new ExecuteMethodActionParamDef("deed", "Pattern");
execUdf.ParameterValues.Add(p2);

rs1.Rules.Add(execUdf);
entity1.RuleElements.Add(rs1);

Inline Table and Value Lists​

Namespaces​

InRule.Repository, InRule.Repository.RuleElements,

There are changes to the techniques used to access inline tables; in InRule SDK 4.5 and later, these are accessed through the RuleAppDef see below:

RuleApplicationDef ruleAppDef = RuleApplicationDef.Load(@"c:\temp\test.ruleapp");

// Loop through all the data elements
foreach (var dataDef in ruleAppDef.DataElements)
{
// try to cast the dataDef into a tableDef - if this fails
// then we will ignore the dataDef since we will only process tables
TableDef tableDef = dataDef as TableDef;
if (tableDef != null)
{
// Check its an inline table - will not process linked tables
if (tableDef.TableSettings.TableSourceType == TableSourceType.Inline)
{
// get the name
string tableName = tableDef.Name;

// Get the data - this adds all the cols in the table
List<string> columnNames = new List<string>();
foreach (var col in tableDef.TableSettings.InlineDataTable.Columns)
{
columnNames.Add(col.ToString());
}

// Iterate the rows in the table and rows to XML
foreach (System.Data.DataRow dr in tableDef.TableSettings.InlineDataTable.Rows)
{
// only access the fields in the collection of names- you could
// filter using this.
foreach (string colName in columnNames)
{
// get the data for each column name
string rowItemData = "";
rowItemData = string.Format("Name:{0} Value:{1}", colName, dr[colName].ToString());
}
}
}
}