How you can protect your code from commits happening in event subscriber code

Hello, today I want to share a micro post, which is based on CommitBehavior which is one of the Method Attributes available in Business Central.

Overview

Thanks to the Decoration of the CommitBehavior function, we can define if we want to avoid at all costs, that a Commit can be made within said method. If this is applied on an IntegrationEvent, then any Subscription Event that tries to add a Commit would be ignored or thrown in error depending on how it was configured.

Basic concepts

CommitBehavior:

Specifies the behavior of a commit call inside the method scope.

Syntax

[CommitBehavior(Behavior: CommitBehavior)]

Arguments

Behavior
 Type: CommitBehavior
Specifies if a commit must be ignored or throw an error. The options are: Ignored or Error.

Taken from https://learn.microsoft.com

Examples

Extension Sample

Two codeunits have been created as an example of how the CommitBehavior works, one with the error parameter and the other with ignore.

Codeunits

MyPublishingThrowError

In this we use the parameter Error. Generating the following explicit message each time a commit is attempted in the event call:

Commit is prohibited in the current scope. The operation cannot continue. Contact your system administrator.

Code:

MyPublishingIgnoreError

The following codeunit uses the CommitBehavior decor with the ignore parameter, which means that it would silently ignore any commit attempted in the method invocation.

This way, the commit is ignored but the user won’t notice it.

Code:

Note: Both previously presented codeunits have the Validate method, totally optional, which is used as a decision element to execute in the main method if a commit should be made or not.

MySuscribing

The following codeunit is the method that subscribes to both codeunits.

Code:

Tests

Video 1

In the following video, a button calls the codeunit that throws the error if a commit is executed, and another button silently ignores the commit.

In this first video, the Validate function was configured to return true, which after the events were executed, would create a commit in the main method.

Video 2

Similar to the first video, except that the Validate function was configured to return false, which after the events were executed, would throw an error in the main method.

Conclusion

This was a short post on how to use the CommitBehavior decoration and its usefulness to block or protect commits that could happen in event subscriber code.

For more information visit the official documentation: https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/attributes/devenv-commitbehavior-attribute

All the code used in the videos and this post can be found at the following github link.

This is all, I hope it has been useful.

Leave a Reply

Your email address will not be published. Required fields are marked *