Accessing Dynamics 365 Directly from Rule Helper
In the default Rule Execution setup, all relationships between Entity types must be established before these entities can be used by the rule app. This behavior is intuitive, but it is not ideal for all business problems. The InRule Integration framework provides a 'Rule Helper' assembly that can be used directly in a rule app and allows rules to load, compare, and assign data that is not related in Dynamics before rules are executed. The Integrating the Rule Helper Component section of this appendix provides more information for setting up a Rule App to use the Rule Helper.
When to use the Query from Rules Approach
The query from rules approach adds value for the following business problems:
- The rules need to reference "lookup" information that may be in a list or set of Entities that are not specifically related to the current Entity hierarchy
- The purpose of rules is to create new relationships between Entity instances that already exist in Dynamics
- The rules need to compare many combinations of unrelated Dynamics Entities and produce results about best possible matches or scores
- A custom filter is required when loading data for 1:N or N:N relationships
- The rules need to delete an entity from Dynamics instead of only removing the relationship
Deleting an entity with relationships configured to cascade delete will also delete those related entities. Carefully review your entity schema and relationships before using the delete functionality in the Rule Helper
Working with Disconnected Fields when Loading and Saving Data
One of the most important integration concepts when loading Dynamics data from rules is the notion of "Disconnected" Fields and Fields that have "Auto Load" and "Auto Save" disabled.
irX allows the rule author to explicitly control the "Auto Load" and "Auto Save" behaviors of Fields that are connected to Dynamics.
The example below shows a Collection named CandidateProducts. Since the Collection is not marked with a blue triangle, it is not considered to be attached to Dynamics.
Although Entity Fields and Collections may be "Disconnected" from Dynamics, the types contained by the Collections can be set to types that were imported from Dynamics.
If a Field is added to the schema using irAuthor, then it will be disconnected from Dynamics. If a Field has been imported from Dynamics using irX, then it can be disconnected from Dynamics by clicking the Disconnect Item button in the irX ribbon.

Two additional settings appear in the irX ribbon that offer additional control over automatic loading and saving behaviors for Fields that remain connected to Dynamics. In the example below, both buttons are "lit up", which denotes that the settings are enabled. By default, automatic loading and saving is enabled for all Fields that are connected to Dynamics.

Integrating the Rule Helper Component
InRule provides a sample rule application (DynamicsRules) that is already configured for RuleHelper usage. You can simply edit this rule app, or, if you wish to integrate RuleHelper into an existing rule app, you can copy both the UDF Library "RuleHelper" and End Point "CrmHelper" from the DynamicsRules rule to another rule application.
If you wish to manually create the UDF Library and End Point in irAuthor, follow the steps below.
-
Create a new rule app using the irX add-in for irAuthor.
-
Create a new ".NET Assembly Function Library" end point and bind the end point to the InRule.Crm.RuleHelper.dll assembly. Select the DynamicsDriver class and then select the methods that should be callable from rules. Edit the name of the end point to "CrmLib" or similar. Select the methods from the DynamicsDriver that are needed for the Rule Application. You do not need to select all the methods. Only import the methods that will actually get used by rules. Additional methods can always be imported later by revisiting the endpoint screen and reloading the assembly.

-
Add a User Defined Function library and set the name to "CrmHelpers" or similar. This library will contain functions that the rules will call to query Dynamics.
-
Add a User Defined Function to the new library. The example below shows a UDF that will be used to execute the QueryCollection method on the DynamicsDriver. Fill out the UDF with script that will call a method on the DynamicsDriver.
The methods on the DynamicsDriver are designed to be reused for more than one Entity type, Field, or set of Fields. The name of the Target Field or Collection should be supplied as a string. When querying a Collection of results, an optional "where" clause can be provided that will be forwarded to calls against the CRM SDK. In addition, an "order by" clause can be provided to return sorted results.
This integration pattern relies on the "Context" object that is available from irScript. The Context object returns information based on the context under which a given UDF is executed. For example, when executing an Entity Rule Set, the Context.Entity returns a reference to the Entity against which the current Rule Set is executing. The Context and its child properties are passed to the DynamicsDriver so it has enough information to form calls to Dynamics 365 and map responses back to the InRule Rule Session.
When using Context with a Decision, Context.Entity cannot be used by Decisions. Instead, the UDF will need to pass the entity in as a parameter.
The Context.FunctionLibraries property can be used to create calls to the .NET assembly library methods, such as the methods imported in Step 5 above. The following script example demonstrates how to use the Context object in irScript to form a call to a static .NET method:
Context.FunctionLibraries.DynamicsDriver.QueryCollection(Context, Context.Entity, collectionName, filter, orderBy, connectionString);
The "connectionString" argument is optional due to the fact that the overloading of the methods on the DynamicsDriver is not passed in the by the rule engine or irX. It will then be looked up from either the .NET config file based on the given environment. As a rule of thumb, it is generally not recommended to override the connection string in this manner as it can perpetuate difficult debugging scenarios and inadvertent dependencies.
Below is a sample connection string that needs to be defined in the irAuthor.exe.config XML for native irVerify to call the RuleHelper. For information on Dynamics connection string formatting, refer to https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/xrm-tooling/use-connection-strings-xrm-tooling-connect.
<connectionStrings>
<add name="DynamicsCRM"
connectionString="AuthType=OAuth;Username=jsmith@contoso.onmicrosoft.com;
Password=passcode;Url=https://contoso.crm.dynamics.com;AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;
RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;LoginPrompt=Auto "/>
</connectionStrings>
-
Rules can now be authored to execute methods on the DynamicsDriver. These methods can be used to load Collections, single Entities, or single Fields from Dynamics based on conditional logic within rules.

The example above includes a call to the default business language templates for a method on the DynamicsDriver. The InRule vocabulary features can be used to modify these templates to be more user-friendly for business users.
The Target Collection in the sample rule is called "FamilyMembers". This is a Field that either does not exist in Dynamics (only for use in rules), or has been imported and then "disconnected" from Dynamics using the "Disconnect Field" button, or has "Auto Load" disabled.
Please see the following sections for more details on the creating the "filter" clauses similar to the one used this example.
Filtering Queries using the Where Clause Builder
When loading data from Dynamics during rule execution, it is critical that the rule author is able to author logic to specify which Entity data to load. Using the RuleHelper, this is accomplished by allowing the rule author to pass in a "filter" or "where" clause into the calls against the DynamicsDriver class.
During execution of the DynamicsDriver, the filter clause is parsed into an Abstract Syntax Tree (AST) and then translated into a LINQ expression tree, so it can be consumed using the CRM SDK. The filter clause is based on the InRule function syntax format.
The InRule function syntax format is used for the following reasons:
- The syntax rule format is consistent with the rule authoring experience used throughout irAuthor
- This format can make good use of the InRule AST parser that is included as part of irSDK
The diagram below depicts the logical flow of steps used by the DynamicsDriver and WhereClause builder classes to query data from rules.

The diagram and notes below contain some additional information about forming the filter clause in a rule:

- All the Field names that are used are the Dynamics friendly names that are used in the Rule Application. These names are mapped back to the Dynamics Field names in the parser.
- String literals should be wrapped in single quotes, date literals should be wrapped in pound signs.
- Simple operators are supported to compare values, such as =, !=, >, < (ex. Age > 21, Name != 'Ralph').
- Multiple conditions can be chained together using 'and' and 'or' keywords.
- The expression tree builder will attempt to call a given .NET framework function if it appears in the expression.
- The .NET call must be expressed as a function, with the first argument being the name of the Field to operate on. The remainder of the arguments will be passed through in order to the .NET function call when it is formed.
- Examples: StartsWith(FirstName, 'A') EndsWith(LastName, 'ez') Contains(LastName, 'Smith')
- Any non-static methods on the .NET String class are candidates to be called as functions using the parser syntax above. However, InRule has only tested the StartsWith, EndsWith, and Contains methods on the String class.
- The following keywords and operators are supported by the InRule AST parser and expression tree translation code: =, <>, !=, +, -, *, /, or, and, xor, >, >=, <, <=, ^, %
The filter expression also supports querying against related entities, simply by appending the related entity name in front of the relevant query field. Querying against related entities requires that all entities queried in the relationship chain be imported into irAuthor. The queried fields on each of the queried entities do not necessarily need to be imported, but if they are not, the entire Dynamics schema field name must be used, rather than their irAuthor aliases.

In this example, we are populating a collection by querying the Contact entity, which is the "parent" entity here. We are then applying a filter statement to return only contacts with related Cases that have Descriptions starting with "A." Cases in this example is the "child" entity. Notice how the hierarchy of the related entity down to field is denoted. If you wanted to drill down another layer to a "grandchild" entity (in this example, an entity related to Case), it would be accomplished by simply continuing the chain from entity to field. Below is an example of a "grandchild" case:

This example would return Accounts that have related Contacts with Cases with Descriptions starting with "A." The filter expression can support querying in this manner up to 15 "layers" deep, including the initially queried entity. Put another way, you can have up to 15 different related entities in a single filter expression.
The filter expression supports querying against multiple properties from different related entities. In the below example, we are querying for Contacts with Cases that have Descriptions starting with "A" and also have Leads with Names starting with "A."

Ordering Query Results with the OrderByClauseBuilder
The DynamicsDriver class also supports the ability to control the order of the results returned from Dynamics by passing in an optional "order by" clause. The order by clause can accept only a single Field name, which should be the name of the Field in the Rule Application. The results are always sorted in ascending order, unless the Field name is followed by the "desc" syntax. Please see the examples below:
To sort ascending, pass the Field name to use in the sort:
To sort descending, pass the Field name to use in the sort followed by the "desc" keyword:
The "order by" clauses generally contain much simpler expressions than "where" clauses. However, InRule syntax rules format is used for the order by clause to be consistent with the where clause approach.
The parsing and translation of the order by clause is handled in the Rule Helper contained in the
Methods Available in the Rule Helper
The following table lists the public, static methods that are available in the DynamicsDriver
| Method Name | Description |
|---|---|
LoadMappedChildCollection | Populates a child Entity Collection based on an existing 1:N relationship in Dynamics. The Collection is populated based on existing parent-child relationship data in Dynamics. |
LoadMappedChildEntity | Populates a child Entity Field based on an existing 1:1 relationship in Dynamics. The Field is populated based on existing parent-child relationship data in Dynamics. |
QueryCollection | Populates an Entity Collection with a set of a given Entity type. An optional filter clause (where clause) can be used to define selection criteria for the Entity set. The Collection does not need to correspond to a 1:N relationship in Dynamics. |
QueryEntity | Populates an Entity Field or variable based on a query to Dynamics. An optional filter clause (where clause) can be used to define selection criteria for the Entity. The Field does not need to correspond to a 1:1 relationship in Dynamics. If more than one Entity is returned from the query to Dynamics, then the first Entity in the set is used. |
QueryField | Populates a primitive Field or variable based on a query to Dynamics. An optional filter clause (where clause) can be used to define selection criteria for the Entity. If more than one Entity is returned from the query to Dynamics, then the Field value from the first Entity in the matching set is used. |
QueryNtoNCollection | Loads entities across an N:N Collection that has been defined in Dynamics. The relationship name and parent and child ID Fields must be provided. |
LoadMappedNtoNCollection | Similar to QueryNtoNCollection, except that the relationship must be imported into the Rule Application. |
DeleteEntity | Deletes an entity referenced by a lookup field. Unlike other rule helper methods, the deletion will not be performed immediately, but will be marked for deletion and then processed with other changes returned to Dynamics from the execution service |
DeleteEntityFromCollection | Similar to DeleteEntity, but takes a reference to a collection and index instead of a lookup field. |
GetUserLocalTimeFromUtc | Converts a Dynamics UTC time value into the local time for a given user. This method makes use of the LocalTimeFromUtcTimeRequest that is part of the CRM SDK. |
Additional Flags Available to Control Loading and Caching Behaviors in the Rule Helper
During a given query operation, there may be advanced use cases that require specific control over loading or reloading data from Dynamics 365. The optional overloads of the QueryEntity and QueryCollection methods expose a set of optional Boolean flags that help control caching and depth of loading behaviors. The table below list these parameters:
| Parameter Name | Description |
|---|---|
loadChildren | Denotes if the execution service should recurse the Entity graph and load all children. If false, no children are loaded below the Collection Members that are loaded. The default value is true. |
useCaching | Denotes if previously loaded Dynamics Entities should be reused from the InRule entity cache, or if new entity instances should be created. If false, the original entity data will be requested from Dynamics, and a copy of the Entity is created. The Instance ID is not set to the GUID of the Dynamics Entity, which will also prevent changes to this entity from being written back to Dynamics. This functionality can, for example, be used to load the original values for an entity persisted in Dynamics when rules are run on update and compare the original and updated values. The default value is true. |
overwriteIfLoaded | Denotes if a previously loaded Dynamics Entity should be repopulated with the latest values in Dynamics. This behavior will overwrite Field values stored in the cache. The default value is false. |
cacheInAppDomain | Denotes if the result of the query should be saved in the persistent AppDomain cache. The difference between this parameter and the 'useCaching' parameter above is that enabling this parameter will save the query result in a cache that will persist across multiple different rule executions, where the above parameter only enables caching within the scope of a single rule execution. For more information, refer to Configuring the AppDomain Cache |
The default values should always be used for the cache settings unless there is a specific use case that requires different behaviors.