Try Post with full rollback

With the introduction of “Post Preview” in NAV2016, Microsoft has made it possible to post and check what the result would be.
To make the preview possible Microsoft has disabled all COMMIT’s in the posting routines when you “Post Preview”.
Sometimes you need to make an interface like scanning for example where you need to post something in standard NAV.

The flow would be like this.

  • First you clear the document quantities like “Qty. To receive”.
  • Then you fill the quantities of the scanner into the document.
  • And then you try to post the document.

No rocket science but the main struggle you will have is error handling.
When you send the post instruction from the scanner to NAV and NAV gives you an error, you need to show it.
That is no problem. You can easily catch the return and present it on the scanner.
After you fix the problem and try to post the document again you will see that your quantities are sometimes doubled. The previous posting information isn’t cleared.

Now instead of undoing the quantities and checking what is posted and what not, I figured out something else.
Something intuitive.

And guess what, I abused the “Post Preview” mechanism.

The concept will look like this:

  • First I post the purchase receipt with “Post Preview”
  • Then I check if there was an error and present it if there was
  • And if there is no error I will post the purchase receipt again with “No Post Preview”

This looks like a piece of cake I thought, but I eat the whole cake while making this concept work.
The biggest issue was avoiding COMMIT and of course runtime errors.
So to make it work I need to use “TryFunction” and “ASSERTERROR”.

First I need to put my preview post code into a “Try Function”.

Then I can call this function and catch the error like this.

Every “Post Preview” will end up with an error. That is default NAV.

But when you check codeunit 81, Microsoft has made a function called “GetPreviewModeErrMessage” which gives you the error of a “Post Preview”.
So when the returned error is not the “Post Preview Error” everything is posted with success.

Now I can move to the final step and this is real posting.
After some testing I found that my previous values where still filled in.
I need to clear everything and now “ASSERTERROR ERROR(”)” comes into action.
It will rollback every table modifications and continue with the next code.

So my final code will look like this.

Maybe it can be useful for you. So enjoy.

Leave a Reply

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