How To Override The Persist Method Properly

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.

Why Acumatica Can T Restore Snapshot Bigger Then 2gb

Why Acumatica can't restore snapshot bigger then 2Gb?

Hello everybody,

today I want to share with you my guess regarding why Acumatica can't restore snapshot bigger then 2 Gb. As far as I see at database level, all files are going into table UploadFileRevision. If to look into structure of this table, you'll find that it has column data, which looks like this: 

 

if to google a bit, you'll find that maximum size which Varbinary(MAX) can accomodate is 2 Gb. 

That's why if you snapshot is bigger then 2 Gb, look for other way of restoring of your snapshot

Summary

As of now it is my guess on why snapshot can't be restored. I'll update everybody how to deal with this, once I'll find solution, which satisfies me completely.

Gross Income And Net Income

 

Hello everybody,

today I want to leave a note on gross income and net income from two standpoints: business and employee.

Gross income = Total sales - Cost of goods sold

Net Income = Total sales - Cost of goods sold - Selling expenses. 

Because Gross income = Total sales - Cost of goods sold quite often Net income is recorded in this form:

Net Income = Gross income - Selling expenses

 

If some business had 1 000 000 $ sales and cost of goods sold is 600 000 $ and selling expenses are 250 000 then

Gross income = 1 000 000 - 600 000 = 400 000

Net Income = 400 000 - 250 000 = 150 000

But if you are an employee, then for you differnet definitions are applied.

Gross income = all salary without any deductions

Net income = what left for employee.

If a person has salary 1000, and 300 of deductions of taxes then his net income is 700 ( his selling expenses considered to be equal zero )

 

How To Implement Pxstringlistattribute In Acumatica

 

Hello,

today I want to leave a post about code quality regarding of PXStringListAttribute. If to look in older versions of Acumatica manuals ( for example T200 manual ) you can see something like this:

public class Something : IBqlTable
{
 
    [PXStringList(
        new string[]
        {
            ShipmentTypes.CollectorNew,
            ShipmentTypes.CollectorSent,
            ShipmentTypes.CollectorResponded,
            ShipmentTypes.CollectorExpired
        },
        new string[]
        {
            "New",
            "Sent",
            "Responded",
            "Expired"
        })]
    [PXString]
    public virtual string Field { getset; }
}

Recommended syntax as of now looks like this:

public class Something : IBqlTable
{
 
    [SurveyResponseStatus.List]
    [PXString]
    public virtual string Field { getset; }
}
 
 
public static class SurveyResponseStatus
{
    public class ListAttribute : PXStringListAttribute
    {
        public ListAttribute() : base(
            new string[] { CollectorNew, CollectorSent, CollectorResponded, CollectorExpired },
            new string[] { Messages.CollectorNew, Messages.CollectorSent, Messages.CollectorResponded, Messages.CollectorExpired })
        { }
    }
 
    public const string CollectorNew = "N";
    public const string CollectorSent = "S";
    public const string CollectorResponded = "R";
    public const string CollectorExpired = "E";
 
    public class CollectorNewStatus : PX.Data.BQL.BqlString.Constant<CollectorNewStatus> { public CollectorNewStatus() : base(CollectorNew) { } }
    public class CollectorSentStatus : PX.Data.BQL.BqlString.Constant<CollectorSentStatus> { public CollectorSentStatus() : base(CollectorSent) { } }
    public class CollectorRespondedStatus : PX.Data.BQL.BqlString.Constant<CollectorRespondedStatus> { public CollectorRespondedStatus() : base(CollectorResponded) { } }
    public class CollectorExpiredStatus : PX.Data.BQL.BqlString.Constant<CollectorExpiredStatus> { public CollectorExpiredStatus() : base(CollectorExpired) { } }
}

and also class Messages looks somehow like this:

[PXLocalizable(Prefix)]
public static class Messages
{

    #region Survey Response Status
 
    public const string CollectorNew = "New";
    public const string CollectorSent = "Sent";
    public const string CollectorResponded = "Responded";
    public const string CollectorExpired = "Expired";

also new code from initial standpoint looks as much bigger amount of lines, but from standpoint of reusability, it's much better. It's easier to decorate any String column, which is much easier to use. Also in your code, you can make comparisons against compiled constant instead of hard coding string values.

Summary

Take your time to kind of memorize, or bookmark new way of using syntax, which will be easier to re-use and maitan.

 

How To Deal With Could Not Load File Or Assembly In Acumatica

 

Hello everybody,

today I want to share one workaround, which I sometime use as temporary measure for migration projects. Imagine, that you've added reference to your bin folder of one of your old customizations. Then you build it, and you've got this error message:

Server Error in '/xxx' Application.


Could not load file or assembly 'xxxx' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

 

This error happens because you have in your customization C# part references to some older dll's which are not compatible with current version of Acumatica. So ideal solution would be to re-add to your current class library proper dll.

Another TEMPORARY measure would be add something like this to your Post-build event command line:

command similar to this:

xcopy /Y /I "d:\SourceCode\build20r1core\KNMCCore\obj\Debug\KNMCCore.*" "c:\Program Files\Acumatica ERP\Matrix\Bin\"

Summary

xcopy says to visual studio please make copy

/Y - don't ask for confirmation

/I - copy multiple items

and then goes two string parameters - source with it's mask, and destination.

Pandemic Of Covid 19 No Pandemic Of Selfishness

 

If you don't like long read, then read next sentence. Essence of the article: If everybody in the world would lock himself at home for 2 weeks, or at let's say for one month, COVID-19 will die. But because of everybody says "I have the most important reason to go outside, or I will die" we see unstopping spread of COVID-19. And pandemic is fed by such people. Again, if you don't like long read, then skip rest of the article.

Congratulations to those who have enough courage to continue reading. Think about it. Quarantine during 2 weeks definitely shows if you have COVID-19 or not. It takes at maximum one month to get medical treatment from COVID-19 if you are sick with something like diabetes, chronic obstructive pulmonary disease, some stage of cancer, or some other medical factors which increases your chances to die. But that not always the case. My wife knows the guy, which was 30 years old, regularly visited gym, and he died. Again, if everybody would lock himself for one month, then COVID-19 would die. But each and every day I'm seeing yelling of people which say: we are going to die from hunger! Our factories will be closed! Our businesses will be closed! From rejecting COVID-19 completely to something like: those people will die anyway, COVID-19 was invented artificially, COVID-19 was created in laboratory to kill older generation. Afterwards those people make posts in social media of themselves going outside without mask, leaking toilet cover, making anti-COVID-19 party.

From childhood a lot of parents teach their children: selfishness is bad. Unfortunately not all of parents teach it. A lot of parents teach their children: you are the only important person in the universe. Which leads to creation of only-me people. And those people spread COVID-19 more and more. Why? Because they have more important reason to go outside, then life of somebody else.

It is reflected not only in COVID-19. Pretty much other diseases have the same picture. Think about AIDS. Why it is spreading? If to exclude blood transfusion, it spreads because there are those, who have important reason to transmit it further. Those people don't think or don't want to think about life of others after infecting. They have important reasons to spread AIDS further. Similar story happens with tuberculosis. This disease also spreads in pretty much similar way, just mortality rate is not as fast. And again, why it spreads? Germs is just one chain of transportation. Other chain of transportation are people, which have important reason to stop taking pills, and have important reason to go outside!

Egoism is shown on all the levels of human society. Consider the story of China with first doctor which reported about dangerous COVID-19. He was fined for the first time. But why that happened? Because somebody selfishly thought: we have very important reasons not to close the city. Consider Great Britain and this statement: "many more people will lose loved ones to coronavirus". Is it not egoism? What were the reasons of making initial decisions? Pretty much the same, as initially thought China officials: how are we going to lock such and such city? Or what about USA? Pretty much the same reasoning. How I'm going to lock such and such city/state? What is behind such and such statement? Egoism. Think about Spain, France, Italy, Russia, and so on. I can continue this list on and on, but you'll see this pattern again and again: some egoists looks for excuses to go outside, other egoists think for reasons to permit them to go outside and third egoists think how to earn on it. As outcome everybody loosing.

Spend now, to avoid meltdown later. Everyone looks for those, who will spend for him instead of spending themselves. In the end everybody loose. Selfish and non selfish. What kind of person/country/government/politician you are?

P.S. I want to add, that not everyone behaves selfishly, there are a lot of self sacrificing people in fighting with coronavirus. But number of egoists is so big, that we see spread of coronavirus, AIDS, tuberculosis and much more other diseases. If humankind will not find a way of dealing with egoism...

 

How To Add User Defined Fields To Any Entity In Acumatica

 

Hello everybody,

today I want to describe how at code level you can add User defined fields in Acumatica to any entity. Sequence will be this:

  1. In PXDataSource add attribute EnableAttributes. It may look like this:
<px:PXDataSource EnableAttributes="true" ID="ds" 

2. For target entity create table with same name, but with suffix KvExt. Query for creation of such a table may look like this:

CREATE TABLE [[TargetTable]KvExt](
	[CompanyID] [int] NOT NULL,
	[RecordID] [uniqueidentifier] NOT NULL,
	[FieldName] [varchar](50) NOT NULL,
	[ValueNumeric] [decimal](28, 8) NULL,
	[ValueDate] [datetime] NULL,
	[ValueString] [nvarchar](256) NULL,
	[ValueText] [nvarchar](max) NULL,
 CONSTRAINT [[TargetTable]KvExt_PK] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[RecordID] ASC,
	[FieldName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
 
ALTER TABLE [[TargetTable]KvExt] ADD  DEFAULT ((0)) FOR [CompanyID]
GO

just replace [TargetTable] with necessary DAC class. For example I wanted to create User defined fields for entity CovidQuizKvExt:

CREATE TABLE [CovidQuizKvExt](
	[CompanyID] [int] NOT NULL,
	[RecordID] [uniqueidentifier] NOT NULL,
	[FieldName] [varchar](50) NOT NULL,
	[ValueNumeric] [decimal](28, 8) NULL,
	[ValueDate] [datetime] NULL,
	[ValueString] [nvarchar](256) NULL,
	[ValueText] [nvarchar](max) NULL,
 CONSTRAINT [CovidQuizKvExt_PK] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[RecordID] ASC,
	[FieldName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
 
ALTER TABLE [dbo].[CovidQuizKvExt] ADD  DEFAULT ((0)) FOR [CompanyID]
GO

As outcome I've got on my page something like this:

Summary

As you can see, it's very easy from development standpoint to add user defined fields to any Acumatica form

How To Unit Test Soorderentry Extension In Acumatica

 

Hello everybody,

today I want to show to unit test, and I mean really unit test SOOrderEntry graph extnesion in Acumatica with XUnit.

In order to achieve it, you'll need following steps:

  1. Create .Net Class library
  2. Reference xUnit
  3. Create public class that inherits from TestBase class
  4. Add override ResisterServices 
  5. Create something like PrepareGraph with usage of TestBase.Setup class
  6. Write your mehtods.

I will not describe how steps 1 - 4 may look, as it is pretty obvious, but step 5 and 6 at C# level may look like this:

public class SOOrderEntrySDExtTests : TestBase
{
    protected IPXCurrencyService CurrencyService;
    protected IFinPeriodRepository FinPeriodService;
 
    public SOOrderEntryExtTests()
    {
        FinPeriodService = new PX.Objects.Unit.FinPeriodServiceMock();
        CurrencyService = new PX.Objects.Unit.CurrencyServiceMock();
    }
 
    protected override void RegisterServices(ContainerBuilder builder)
    {
        base.RegisterServices(builder);
        builder
            .Register<Func<PXGraphIFinPeriodRepository>>(context
                =>
            {
                return (graph)
                    =>
                {
                    return FinPeriodService;
                };
            });
        builder
            .Register<Func<PXGraphIPXCurrencyService>>(context
                =>
            {
                return (graph)
                    =>
                {
                    return CurrencyService;
                };
            });
    }
 
    private SOOrderEntry PrepareGraph()
    {
        Setup<SOOrderEntry>(
           new SOSetup
           {
               DefaultOrderType = "SC",
               TransferOrderType = "TR",
               ShipmentNumberingID = "SOSHIPMENT",
               ProrateDiscounts = true,
               FreeItemShipping = "S",
               FreightAllocation = "A",
               CreditCheckError = false,
               MinGrossProfitValidation = "W"
           });
        
        
        var graph = PXGraph.CreateInstance<SOOrderEntry>();
        graph.CurrentDocument.Insert(
            new SOOrder()
            {
                OrderType = "SC",
                OrderDesc = "some test desc"
            }
            );
        var graphExtension = graph.GetExtension<SOOrderEntryExt>();
        
 
        return graph;
    }
 
    [Fact]
    public void CheckInsertion()
    {
        var graph = PrepareGraph();
        graph.CurrentDocument.Current.Approved = true;
        graph.CurrentDocument.Update(graph.CurrentDocument.Current);
 
        Assert.Equal(graph.CurrentDocument.Current.CuryID, "USD");
 
    }
}

Few more comments regarding code. 

  1. As of now, in order to give to SOOrderEntry setup classes, you'll need to go from one exception message to another. Not very convenient, but the only available way
  2. RegisterServices was copy/pasted from Github post of Dmitriy Naumov
  3. You may need to take a look on graphExtnesion
  4. Regarding extension fields I suggest to set up them in the cache

Summary

Acumatica team put big amount of efforts in order to add stability to their products. Also they put a lot of efforts for giving line for adding stability to Acumatica by other ISV. It will be a crime not to benefit from it. Crime against customers!

 

 

 

How To Catch All Mysql Queries Generated By Acumatica

Hello everybody,

finally I found out how to catch all queries to MySQL server, generated by Acumatica. Well, in context of My SQL as usually people work more with MYOB, but under the hood MYOB is Acumatica.

Typical schema of Acumatica <-> MySQL connection looks like this:

In order to get generated MySQL queries, you may need some proxy service, which will intercept queries. You can use MySQL proxy, but instead of MySQL proxy I suggest to use Neor Profile SQL as it has much more convenient UI:

 

In order to achieve such catching of all My SQL queries, you'll need following steps:

  1. Install Neor Profile SQL.
  2. In your Acumatica web.config make following change:
  <connectionStrings>
    <remove name="ProjectX_MySql" />
    <remove name="ProjectX" />
    <add name="ProjectX" providerName="System.Data.SqlClient" connectionString="Server=localhost;Port=4040;Database=PXProjecti

pay especial attention to this part: Port=4040

3. Next goes configuration of Neor Profile SQL. Create connection to MySQL server in a way similar to what you see on screenshot:

4. You are all set. Now Acumatica will send SQL queries to Neor Profile SQL, while Neor Profile SQL will re-translate them to My SQL:

Summary

If you need to catch generated My SQL queries, you can go with My SQL query proxy and logging all files to file. Or with help of Neor Profile SQL you may get nice tool for tracking all generated queries. 

And also with such steps you can track everything that MYOB generated!

How To Point Mysql To Another Port Then 3306

 

Hello everybody,

today I want to describe how to point to non standard port in My SQL for Acumatica.

Below goes fragment from my Web.config

    <remove name="ProjectX" />
    <add name="ProjectX" providerName="System.Data.SqlClient" connectionString="Server=localhost;Port=4040;Database=PXProjectionMySql2;Uid

you can use this knowledge for having multiple MySQL instances on the same machine and for catching generated SQL queries.