Table of Contents

Conditional rule execution based on context

This article will show you how to execute or not execute a server rule (validation rule, event rule) depending on the source that triggered the event.

Today, it is impossible to determine the source of a validation or event rule. However, it is possible to use an interface to share information within the same context. You can find the details of the interface on the IBusinessRuleContext documentation. You can use this mechanism, for example, to avoid executing a validation rule if the event comes from a specific server method.

Example

In this example, we have a Party entity with a Type property. We want to execute a validation rule only when the source is not the CreateInternalParty server method triggered by an action in a UI view.

The idea is therefore to indicate to the business rule context that the party type should not be checked. This key/value, that will carry this information, will be added to the CreateInternalParty server method and exploited in the CheckType validation rule.

CreateInternalParty server method :

public class CreateInternalParty : ICreateInternalParty
{
    private readonly IBusinessRuleContext _businessRuleContext;

    public CreateInternalParty(IBusinessRuleContext businessRuleContext)
    {
        _businessRuleContext = businessRuleContext;
    }

    public async Task ExecuteAsync(InternalPartyInfos[] internalPartyInfos)
    {
        // The execution of "Party.CheckType" validation rule is not triggered in this transaction
        // since it would prevent the creation of an internal party
        _businessRuleContext.TryAdd("PartyTypeCheck", false);

        ...
    }
    ...
}

CheckType validation rule :

public class CheckType : AsyncValidationRule<Party>, ICheckType
{
    private readonly IBusinessRuleContext _businessRuleContext;

    public CheckType(IBusinessRuleContext businessRuleContext)
    {
        _businessRuleContext = businessRuleContext;
    }

    public async override Task<IValidationRuleResult> ExecuteAsync()
    {
        // Depending on the context, we do not want the validation rule to be triggered
        // For example, when the party is added from CreateInternalParty server method
        if (_businessRuleContext.TryGet("PartyTypeCheck", out bool partyTypeCheck) &&
            !partyTypeCheck)
        {
            return Success();
        }

        ...
    }
}