Thursday, September 29, 2022

Deserialize JSON string in D365FO using X++ code

Hi All,
Hope everyone is doing great.

Today we are here to learn one of the common requirement in every integration i.e. how to de-serialize JSON string in D365FO/AX7 using X++ code.

Below is the JSON which is showing the population count by country and our requirement is to show all this details in Infolog or insert into AX Table.

Solution :
1) Create contract class for both outer and inner node.
2) Use FormJsonSerializer::deserializeObject method.

Sample JSON : "data": [
        {
            "ID Nation": "01000US",
            "Nation": "United States",
            "ID Year": 2020,
            "Year": "2020",
            "Population": 326569308,
            "Slug Nation": "united-states"
        },
        {
            "ID Nation": "01000US",
            "Nation": "United States",
            "ID Year": 2019,
            "Year": "2019",
            "Population": 324697795,
            "Slug Nation": "united-states"
        }]

Step 1 : Create contract class 1 to hold all the values of data node. 
Note : DataMemberAttribute name should be matched with JSON key name i.e. data, ID Nation

[DataContract]
internal final class TestJSONContract
{

    String50 parmNationId, parmNation,parmYearId,parmYear,parmPopulation,parmSlugNation;

    [DataMemberAttribute('ID Nation')]
    public String50 parmNationId(String50 _parmNationId = parmNationId)
    {

        parmNationId = _parmNationId;

        return parmNationId;

    }

    [DataMemberAttribute('Nation')]

    public String50 parmNation(String50 _parmNation = parmNation)

    {

        parmNation = _parmNation;

        return parmNation;

    }

    [DataMemberAttribute('ID Year')]

    public String50 parmYearId(String50 _parmYearId = parmYearId)

    {

        parmYearId = _parmYearId;

        return parmYearId;

    }

    [DataMemberAttribute('Year')]

    public String50 parmYear(String50 _parmYear = parmYear)

    {

        parmYear = _parmYear;

        return parmYear;

    }

    [DataMemberAttribute('Population')]
    public String50 parmPopulation(String50 _parmPopulation = parmPopulation)
    {

        parmPopulation = _parmPopulation;

        return parmPopulation;
    }


    [DataMemberAttribute('Slug Nation')]
    public String50 parmSlugNation(String50 _parmSlugNation = parmSlugNation)
    {

        parmSlugNation = _parmSlugNation;

        return parmSlugNation;

    }

}

Step 2 : Create contract class for outer node.

In your case if there is more than one outer node then you need to create your class according to your JOSN. ex- if you have status and data node in your JSON but "status" is string type and "data" node contains multiple sub node then you need to create one more attribute in below class with string type and data with list type.

[DataContract]
internal final class TestJSONDataContract

{
    List parmData;
    [DataMemberAttribute('data'),DataCollectionAttribute(Types::class, classStr(TestJSONContract))]

    public List parmData(List _parmData = parmData)
    {
        parmData = _parmData;

        return parmData;
    }
}

Step 3: Create runnable class to call your API and get the result.
internal final class TestConsumeAPITest
{

    /// <summary>
    /// Class entry point. The system will call this method when a designated menu |
    /// is selected or when execution starts and this class is set as the startup class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>

    public static void main(Args _args)
    {

        System.Net.HttpWebRequest      webRequest;
        System.Net.HttpWebResponse    webresponse;
        System.Exception                        ex;
        System.IO.Stream                        responseStream;
        System.IO.StreamReader             reader;
        str                                                 output;
        ListEnumerator                            listEnumerator;

        try
        {
            new InteropPermission(InteropKind::ClrInterop).assert();

            webRequest = System.Net.WebRequest::Create("##########"); //your API URL goes here.       

            webRequest.Method = "GET";
            webRequest.ContentType = "application/json";
            webresponse = webRequest.GetResponse();
            responseStream = webresponse.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream);

            output = reader.ReadToEnd();

            TestJSONDataContract  TestJSONDataContract =                  FormJsonSerializer::deserializeObject(classNum(TestJSONDataContract),output);

            List listData = new List(Types::Class);

            listData             = TestJSONDataContract.parmData();
            listEnumerator  = listData.getEnumerator();

            while (listEnumerator.moveNext())
            {

                TestJSONContract jsonDataContract = listEnumerator.current();

                info(strFmt("Nation id %1 : %2 = %3",jsonDataCOntract.parmNationId(),              jsonDataContract.parmNation(), jsonDataContract.parmPopulation()));
            }

        }

        catch
        {
            ex = CLRInterop::getLastException().GetBaseException();
            error(ex.get_Message());

        }

    }

}


Step Final : Execute your runnable class to test the API and JSON format.







Monday, August 22, 2022

How to remove country specific Bank account number validation in D365FO

Hi All,

I hope everyone is doing great. Lets see how can we remove the mandatory bank account validation.

Requirement :
In my case requirement is to remove JP country region specific validation, The scenario is quite different because generally all the bank validation is necessary to pass but we want to add all those bank account which user has already added in AX 2009 and same was giving validation error in F&O.so that we have achieved this by below customization.  

Solution:  
We need to skip validation from standard code by creating new extension of Bank_JP class.










Implementation : 
Create extension for Bank_JP class to write COC of method  checkBankAccountNum() and checkBankAccount() and add below code.

[ExtensionOf(classStr(Bank_JP))]
final class Bank_JP_Test_Extension
{

    public boolean checkBankAccount(BankAccountMap _bankAccountMap)
    {
        next checkBankAccount(_bankAccountMap);
        infolog.clear(0);
        return true;

    }
    public boolean checkBankAccountNum(BankAccount _bankAccount)
    {

        next checkBankAccountNum(_bankAccount);
        infolog.clear(0);
        return true;
    }

}

Build your solution and check.

That's it.....:) 

Thursday, August 18, 2022

Create code extension of your object new feature

Hey everyone,

Exciting news! D365FO now has a cool new feature that lets you create extensions for your objects. The best part is, you don't have to worry about remembering complex syntax or messing up the naming convention in your project. It's super handy and makes working on your project a breeze! Check it out!

Check this below features-












It will create new class in your project with standard define format.


Happy Coding.... :) 


Tuesday, June 28, 2022

How to use vendor disbursement journal workflow for vendor creation

Hi D365Fo Community,
Welcome to my new blog, This is a common requirement to have workflow for Vendor Creation process but standard does not support this. so lets learn how can we utilize vendor disbursement journal workflow for vendor creation by doing small customization.

Requirement : All the new vendors should go through approval process.

Solution : 
1) Use vendor amendment workflow during vendor creation.
2) Put Vendor on Hold until it is approved.  
3) Restrict original submit to workflow functionality until user provide approval for Creation workflow.
4) Not allow to create record in proposed changes table during creation workflow.
5) Restrict to call amendment workflow in case you modify the field which is enabled in AP parameter > Vendor approval tab

Prerequisite - Need to have Vendor amendment workflow setup. Please click on vendor workflow setup.

Step by step implementation -

 Step 1 : Add new enum type of field in VendTable :
            fieldname - DemoCreationWorkflowApproved
            EDT          - NoYesId    

Step 2 : Write COC for VendTable method insert().
Description : Assign No during record creation.

[ExtensionOf(tableStr(VendTable))]
final class DemoVendTable_Extension
{
   //Assign No during record creation.
    public void insert()
    {
         if(!this.RecId)
        {
            this.DemoCreationWorkflowApproved= NoYes::No;
         }
         next insert();
    }

    // Update blocked to No once it is approved by User and set DemoCreationWorkflowApproved to Yes
     
      public static void updateWorkflowState(RecId _recId, VendTableChangeProposalWorkflowState _state)
     {
            next updateWorkflowState( _recId,  _state);
            ttsbegin;
            VendTable vendTable = VendTable::findRecId(_recId, true);
            if( _state == VendTableChangeProposalWorkflowState::Approved)
            {
                  vendTable.Blocked               =  CustVendorBlocked::No;
                  vendTable.DemoCreationWorkflowApproved= NoYes::Yes;
                  vendTable.update();
            }
            ttscommit;

      }

}

Step 3: Block the vendor for all area till it is approved.
Create new class to keep event handlers for table methods. Copy the post event handler of insert method and add below code.

class DemoVendTableEventHandler
{
    [PostHandlerFor(tableStr(VendTable), tableMethodStr(VendTable, insert))]
    public static void VendTable_Post_insert(XppPrePostArgs args)
    {
        VendTable vendTable = args.getThis() as VendTable;

        if(vendTable)
        {
            ttsbegin;
            vendTable.selectForUpdate(true);
            vendTable.Blocked = CustVendorBlocked::All;
            vendTable.update();
            ttscommit;
            vendTable.reread();

        }
    }

}

Step 4 :  Create COC for main method of class VendTableChangeProposalWorkflowSubmitManager and add below code.
This is to not allow user to use standard workflow during vendor creation.

[ExtensionOf(classStr(VendTableChangeProposalWorkflowSubmitManager))]
final class DemoVendTableChangeProposalWorkflowSubmitManager_Extension
{
    public static void main(Args _args)
    {
        if (!_args.record() || !_args.caller())
        {
            throw error(Error::wrongUseOfFunction(funcName()));
        }

        VendTable  vendTable = _args.record();
        if(vendTable.DemoCreationWorkflowApproved== NoYes::No)
        {
            throw error("Creation workflow not yet approved.");
        }
        next main(_args);
    }
}

}

Step 5 : Create COC for init() method of form VendChangeProposal
We will not allow to open proposed changes form on modification of any standard field which is enabled for amendment workflow, and delete the record if exists for vendor if not approved and workflow state is Not Submitted.

[ExtensionOf(formstr(VendChangeProposal))]
final class DemoVendChangeProposalForm_Extension
{
    public void init()
    {
        VendTableChangeProposal vendProposal;
         next init();
        if(!callerRecord.DemoCreationWorkflowApproved)
        {
            if(callerRecord.Workflowstate == VendTableChangeProposalWorkflowState::NotSubmitted)
            {
                delete_from vendProposal
                where vendProposal.VendTable == callerRecord.RecId;
            }
            this.close(); // code the close the open form
        }        

    }

}

Step 6 : Create new class to call amendment workflow and add below code.

class DemoCallVendorDisbursementWFHelper
{
    public static void main(Args _args)
    {

        FormDataSource ds =  _args.caller().datasource();
        VendTable                      vendTable = ds.cursor();

        if(vendTable)
        {
            DemoCallVendorDisbursementWFHelper ::submitToVendWorkflow(vendTable);
            ds.research(true);
            ds.refresh();
        }
    }

    public static void submitToVendWorkflow(VendTable _vendTable)
    {

        WorkflowCorrelationId      workflowCorrelationId;
        if(_vendTable.DemoCreationWorkflowApproved)
        {
            throw error("Vendor creation workflow is already approved.");
        }

        Notes note = strFmt("%1 Vendor changes",_vendTable.AccountNum);
        workflowCorrelationId =      Workflow::activateFromWorkflowType(WorkflowTypestr(VendTableChangeProposalWorkflow),     _vendTable.RecId,note , NoYes::No);        

        _vendTable.selectForUpdate(true);
        _vendTable.WorkflowState = VendTableChangeProposalWorkflowState::Submitted;
        _vendTable.update();
        _vendTable.reread();       
        VendTableChangeProposal vendTableChangeProposal =                       VendTableChangeProposal::findByVendRecId(_vendTable.RecId);

        if(!vendTableChangeProposal)
        {
            //Need to have one record created with vendor recId or else it will throw the error during approval.
            vendTableChangeProposal.Name        = _vendTable.name();

            vendTableChangeProposal.VendTable   = _vendTable.RecId;
            vendTableChangeProposal.insert();
        }       
    }
}

Step 7 : Create new menu item button on form and set below property
Menu item type - Action
object = DemoCallVendorDisbursementWFHelper



Note - By above button we can only submit the workflow rest other workflow operation can be handled by standard workflow button i.e. Approve, delegate, workflow history.

That's it!!!, Please implement this and let me know if you face any issues.
Please add comment and like if you like this blog.

Next Blog - How to add custom field in Vendor amendment workflow. 

Wednesday, June 22, 2022

How to add sender email address for Payment remittance (Advice) in D365FO

How to Add Sender Email Address for Payment Remittance (Advice) in D365FO

How to Add Sender Email Address for Payment Remittance (Advice) in D365FO

Hi All,

Thank you for visiting this blog. This blog is all about how to set the from email address for Print Management functionality.

As we all know, there is no option in standard to configure the sender email address for the Payment advice report or any other report which is printing through Print Management, except if we configure it by electronic reporting. So let's see how we can achieve this by doing a very small customization.

Please visit my previous blog for how to set email subject from print management.

If you look into the standard class SrsReportRunMailer, there is a method buildFromEmailAddress(). This method is picking the email address of the current user ID and using it as the from email address. This we want to change to the custom parameter, i.e., Test@gmail.com.

PS - I am writing COC of emailReport() method of class SrsReportRunMailer because buildFromEmailAddress() method is declared as private so we cannot create COC or event handler of it.

Please follow the below steps to complete this customization.

Step 1: Create a New Parameter

Create a new parameter in the accounts payable parameter form to store the from email address.

Step 2: Create a New Class

Create a new class to write COC of emailReport() method. The class name should end with _Extension. Example: TestSrsReportRunBuilder_Extension


[ExtensionOf(classStr(SrsReportRunMailer))]
public final class TestSrsReportRunBuilder_Extension
{

}
    

Step 3: Add the Below Code


public boolean emailReport(SrsReportEMailDataContract emailContract, System.Byte[] reportBytes, str fileName)
{
    str tofindStr = 'Payment advice'; // this string should be present in email subject which can be defined in Print Management parameter.
    str emailSubject = emailContract.parmSubject();

    if (strScan(emailSubject, tofindStr, 1, strLen(emailSubject))) 
    {
        fromAddress = VendParameters::find().TestFromEmailAddressPaymentAdvice;
        mailer = this.parmSysMailer();
        if (!fromAddress || !SysEmailDistributor::validateEmail(fromAddress))
        {
            error(strfmt("@SYS134596", "@SYS4083"));
        }
    }

    // Next call
    boolean ret = next emailReport(emailContract, reportBytes, fileName);
    return ret;
}
    

Expected result :

Example Image

Thursday, June 9, 2022

Throw exception from Catch block - New feature after PU 31 in D365FO

Hi All,
Lets understand this new feature to throw the exception from catch block .

Now we can use throw from catch block. This way throw will work like re-throw and send cached exception to the outer catch block. Lets understand it by sample code.

X++ Code.
try
{
    throw Exception::error;
}
catch
{
    // locally handle exception
    // then rethrow for caller
    throw;
}


Thank you.

Wednesday, June 8, 2022

Difference between Insert and RecordInsertList in D365FO

Hi All,
let's learn how RecordInsertList makes difference in your system performance.

As we all know insert() method and RecordInsertList both are used to insert the record into database. but here we will discuss when we should use insert and when we should use RecordInsertList. 

insert() method will insert only one record at a time. This is required to use when there is any dependent action i.e. if you want to store RecordId of header table into line table also if there is some code which is written in insert method and we want to call it then we need to use insert method.

RecordInsertlist will insert multiple records in database by one DB trip. This is faster than insert method.

X++ Code For insert() method

Create runnable class and add below code into it, make sure you have sample table created (TestInsertRecordTable with 2 fields RecordNumber and Description)

internal final class TestRecordListInsertJob1
{
    public static void main(Args _args)
    {

        int                 i;
        int                 timerStart, timerEnd;
        str                 timeConsumed;       
        TestInsertRecordTable  testInsertRecordTable;
        timerStart     = timeNow();
        
        ttsbegin;

        for (i = 1; i<10000; i++)
        {
            testInsertRecordTable.RecordNumber = i;
            testInsertRecordTable.Description = 'TestDescription';
            testInsertRecordTable.insert();
        }

        ttscommit;

        timerEnd = timeNow();

        timeConsumed = timeConsumed(timerStart, timerEnd);

        info(strFmt("Insert method result: Added %1 rows in %2 seconds", i, timeConsumed));

    }
}


Result of insert method took 45 seconds to insert 10000 records.







X++ code  for RecordInsertList
Create runnable class and add below code into it.

internal final class TestRecordInsertJob2
{
    public static void main(Args _args)
    { 
            int                     i,timerStart, timerEnd,row;
            str                     timeConsumed;
            TestInsertRecordTable   testInsertRecordTable,newTestInsertRecordTable;
            RecordInsertList        testInsertRecordTableList;

            testInsertRecordTableList =  new RecordInsertList(tableNum(TestInsertRecordTable));
            timerStart = timeNow();
            row = 1;

            ttsbegin;
            for (i = 10001; i<20000; i++)
            {
                newTestInsertRecordTable.RecordNumber = i;
                newTestInsertRecordTable.Description = 'TestDescriptionRecordInsertList';
                testInsertRecordTableList.add(newTestInsertRecordTable);

                row++;
            }
            testInsertRecordTableList.insertDatabase();
            ttscommit;

            timerEnd = timeNow();

            timeConsumed = timeConsumed(timerStart, timerEnd);

            info(strFmt("RecordInsertList result : Added %1 rows in %2 seconds", row, timeConsumed));

        }

}

Result of RecordInsertList took 2 seconds to insert 10000.




RecordInsertList is far faster than insert() so always prefer it in your logic.

Update Values During Data Entity Import in D365FO

Update Values During Data Entity Import in D365FO Updating Field Values During Data Entity Import in Dynamics 365 Finance ...