Using the UserConnection class to create a new transaction scope

October 20, 2010 at 18:30
filed under Dynamics AX
Tagged , , ,

Hi All!

Here’s a trick I learned from a colleague:
With the class UserConnection, you can make sure a transaction isn’t rolled back even if the transaction it is in is rolled back.

Consider the following example:

static void KlForRecordNotInserted(Args _args)
{
    CustTable custTable;
    ;
   
    ttsbegin;
   
    custTable.clear();
    custTable.initValue();
    custTable.AccountNum = "000010";
    custTable.Name = "My Test Customer";
    custTable.insert();
   
    throw error("An error that causes a rollback");
    ttscommit;
}

The record will not be inserted, because an error is thrown that causes an implicit ttsabort (so the tranaction is rolled back), right?

Well, you can counter this behavior by using the UserConnection class:

static void KlForRecordInserted(Args _args)
{
    UserConnection userConnection;
    CustTable custTable;
    ;
   
    ttsbegin;
   
    userConnection = new userConnection();
   
    custTable.clear();
    custTable.initValue();
    custTable.AccountNum = "000020";
    custTable.Name = "My Test Customer";
    custTable.setConnection(userConnection); // set userconnection
    custTable.insert();
   
    throw error("An error that causes a rollback");
    ttscommit;
}

You will see that the CustTable record will be inserted in the example above.

This can be useful if you really want a record to be inserted, for example when doing logging (like in batch processes, or when debugging).
When you don’t use a UserConnection, your logging will be rolled back together with other transaction.

2 comments

RSS / trackback

  1. Santosh.R

    Good one!!!

    I learnt a new way of inserting a record without actually rolling back my transaction when a error is occured..

    Thanks a ton

  2. esat

    I used it when i need to insert error message into table over transaction process

respond