Loading ...

How To Override The Persist Method Properly

Hello everybody,

today I want to write a few words on how to override persist method of Acumatica properly. When I say properly I mean not save just some fragment of data, but use transaction like approach.

In other words how to achieve all or noghint during persisting.

Quite often I see template like this:

public void Method1()
{
    //normal flow
}
 
string message = "Forbidden to do anything at 18 hour";
public void Method2()
{
    if (DateTime.Now.Hour == 18)
    {
        throw new PXException(message);
    }
}
 
public void RollBackMethod1AndMethod2()
{
 
}
 
 
[PXOverride]
public void Persist(Action del)
{
    try
    {
        del();
        Method1();
        Method2();
    }
    catch (Exception ex)
    {
        if(ex.Message == message)
        {
            RollBackMethod1AndMethod2();
        }
    }

Take a note how it works. Initially it will persist some base data to db, and then executes Method1 and Method2 which throws exception. As usually it is logically to conclude that if Method1 or Method2 generated some or another exception, that it would be good not to persist data into Acumatica. How to achieve this? You can use for this purpose PXTransactionScope. 

Take a look on this sample:

public void Method1()
{
    //normal flow
}
 
string message = "Forbidden to do anything at 18 hour";
public void Method2()
{
    if (DateTime.Now.Hour == 18)
    {
        throw new PXException(message);
    }
}
 
public void RollBackMethod1AndMethod2()
{
 
}
 
 
[PXOverride]
public void Persist(Action del)
{
    using (var ts = new PXTransactionScope())
    {
        del();
        Method1();
        Method2();
    }

As you probably can guess, PXTransactionScope will make sure that either all data remained persisted, or nothing.

Summary

In case if you need to have all or nothing during persistance to database, then feel free to use PXTransactionScope, it will help you to get all or nothing during persitance to database, and also it will help you to avoid adding complicated logic of tracking what was persisted, what wasn't persisted, and how to clean up the data.