Transactions and the SP_TransactionNotification

Hi everyone,

Thought I’d share with you something that I experienced recently.

SAP Business One makes available a stored procedure that according to the documentation can be used to perform some “checks” and, in the case of failure, stop the process.

Take the following code:

// SP_TransactionNotification

if @object_type = 13
begin
set @error = -123
set @error_message = N'Test error message'
end

-- Select the return values
select @error, @error_message

// addon code

var invoice = (Documents) company.GetBusinessObject(BoObjectTypes.oInvoices);
var items = invoice.Lines;

invoice.CardCode = @"C23900";
items.ItemCode = @"A00001";

int result = invoice.Add();
if (result != 0)
{
    string message = company.GetLastErrorDescription();
    DisplayErrorMessage(message);
}
else
{
    DisplaySuccessMessage("Operation completed successfully");
}

This code will always fail on:
int result = invoice.Add();

This happens because the stored procedure is preventing the action from succeeding.

When you combine the same code with a transaction:

// transaction code

try
{
    company.StartTransaction();

    var invoice = (Documents)company.GetBusinessObject(BoObjectTypes.oInvoices);
    var items = invoice.Lines;

    invoice.CardCode = @"C23900";
    items.ItemCode = @"A00001";

    int result = invoice.Add();
    if (result != 0)
    {
        if (company.InTransaction)
        {
            company.EndTransaction(BoWfTransOpt.wf_RollBack);
        }

        string message = company.GetLastErrorDescription();
        DisplayErrorMessage(message);
    }
    else
    {
        company.EndTransaction(BoWfTransOpt.wf_Commit);
        DisplaySuccessMessage("Operation completed successfully");
    }
}
catch (Exception e)
{
    Console.WriteLine(e);
    throw;
}

The above code only fails on the:
company.EndTransaction(BoWfTransOpt.wf_Commit);

This is an important difference. Depending on the flow of your code it can lead to some head-scratching bugs.

When using transactions don’t rely on the return result of the Add/Update methods, since these will succeed until the transaction is committed.

Hope this helps.

Cheers.

Leave a Reply

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