26 November 2021

Try catch exception example in D365FO

 class TestClass

{

    public static void main(Args args)

    {

        PurchTable purchTable;

        

        System.Exception ex;

        

            //Counter cnt = 1;

            while select purchTable

            {

                try

                {

                    //doing updation on  the purchatable.

                }


                catch(ex)

                {

                    System.String messageEx = ex.Message;

                    warning(strFmt("There is an error%1",messageEx));                    

                }

            }

        

       

    }


}

21 November 2021

ED365FO event handler to get current database record

   public static void TRGvalidateHours(FormControl sender, int controlName)

    {

        FormRealControl  control = sender as FormRealControl;

        FormRun     formRun = sender.formRun();

        FormStringControl projIdControl = formRun.design().controlName(formControlStr(TSTimesheetEntry,ProjId));

        

        FormDataSource TSTimeSheetLineWeek_ds  = formRun.dataSource(formDataSourceStr(TSTimesheetEntry,TSTimesheetLineWeek)) as FormDataSource;

        TSTimesheetLineWeek timesheetLineWeek = TSTimeSheetLineWeek_ds.cursor();

        TSTimesheetTable    timeSheetTable = TSTimesheetTable::find(timesheetLineWeek.TimesheetNbr);

        ProjTable           projTable = ProjTable::find(projIdControl.text());

}

14 November 2021

Exception handling in D365 FO - Capture the exception

System.Exception        ex;

 try

{

    // total logic

 }

            catch(ex)

            {

                System.String messageEx = ex.Message;

                info(strFmt("Exception: %1",messageEx));

            }

            catch (Exception::CLRError)

            {

                ex = CLRInterop::getLastException().GetBaseException();

                error(ex.get_Message());

            }

25 October 2021

D365FO disposable context class example

Scenario: Payment journal Customer receipt data is not getting.

Below is the route cause: the temp table record is getting cleared.

To fix issue implemented the disposable context concept.

New class :

class CITPaymProposalReportContext implements System.IDisposable
{
    static CITPaymProposalReportContext instance;
    public CustVendPaymProposalTmp vendPaymProposalTemp;

    public void new()
    {
        if (instance)
        {
            throw Error ("Nesting of CITPaymProposalReportContext is not supported.");
        }
        instance = this;
    }

    public void dispose()
    {
        instance = null;
    }

    static public CITPaymProposalReportContext current()
    {
        return instance;
    }

}


Before clearing the record to get it and keep it in global variable using context class so need to create extension for the "CustVendPaymProposalTmp" table insert() method.

[ExtensionOf(TableStr(CustVendPaymProposalTmp))]
final class CITCustVendPaymProposalTmp_TBL_Extension
{
    public void insert()
    {
        using (CITPaymProposalReportContext context = new CITPaymProposalReportContext())
        {
            next insert();
            context.vendPaymProposalTemp = this;
        }

    }

}

Create another extension- Post COC - "PaymentProposalReport" insert payment method and get the record and assign to variable.

[ExtensionOf(classStr(PaymProposalReport))]
final class CITPaymProposalReportClass_Extension
{

  protected void insertPayment(CustVendPaymProposalTmp _custVendPaymProposalTmp)
    {
        
        LedgerJournalTrans ledgerJournalTrans;
        CustVendPDCRegister custVendPDCRegister;
        
        next insertPayment(_custVendPaymProposalTmp);

        CITPaymProposalReportContext context = CITPaymProposalReportContext::current();
        if (context && context.vendPaymProposalTemp)
        {
            _custVendPaymProposalTmp = context.vendPaymProposalTemp;
        }
        
        select ledgerJournalTrans
                        where ledgerJournalTrans.RecId == _custVendPaymProposalTmp.WLKLedgerJournalTransRecId;
        
        if(ledgerJournalTrans)
        {
            _custVendPaymProposalTmp.WLKAmountInTxt = Global::numeralsToTxt(abs(_custVendPaymProposalTmp.PaymentAmountMST));
            _custVendPaymProposalTmp.WLKTxt = ledgerJournalTrans.Txt;
            _custVendPaymProposalTmp.WLKUserId = ledgerJournalTrans.ledgerJournalTable().createdBy;

            select custVendPDCRegister
                        where custVendPDCRegister.LedgerJournalTrans == ledgerJournalTrans.RecId;

            _custVendPaymProposalTmp.PaymReference = ledgerJournalTrans.BankCentralBankPurposeText;
            _custVendPaymProposalTmp.WLKCheckNumber = ledgerJournalTrans.DocumentNum;
            _custVendPaymProposalTmp.BankAccountTableName = ledgerJournalTrans.offsetAccountName();
            _custVendPaymProposalTmp.WLKMaturityDate = ledgerJournalTrans.DocumentDate;
            _custVendPaymProposalTmp.ttsbegin();
            _custVendPaymProposalTmp.selectForUpdate(true);
            _custVendPaymProposalTmp.update();
            _custVendPaymProposalTmp.ttscommit();
            PaymProposalReport::insertCustSettlementTmp(_custVendPaymProposalTmp);
        }
    }
}

02 July 2021

D365 postman Error: Maximum response size reached

 

My requests take longer time to receive response


ResponseSize.png

In the latest version v7.3.5, the response time is longer and status code displays earlier than the response, as it relatively takes a longer time to load large responses on the application. We also have a limit of 50mb response that can be safely viewed. By default, we do not load response larger than 50mb. But if it extends, 100 MB is maximum buffer we currently have, so you can still change the response size up to 100 by navigating to Settings > General Tab > Max response size in MB.

MaxResponseSize.png

If your response exceeds 100+ MB, it is probably not going to succeed. But as a workaround, you can try the "Send and Download" option when running the request which should help you.

D365FO Odata - d365 postman please verify that the user is valid and set up correctly

 {

    "Message""Please verify that the user is valid and set up correctly."
}

Sol:

System Administration > Setup > Azure Active Directory Applications

Click the +New button to add a new registration.  

Grab the Application ID from the registration in the Azure Portal and insert it into the Client ID field.

Fill out the rest of the fields as necessary.

28 June 2021

How to get the control name in D365FO

 PurchId purchId = purchCreateOrder.design().controlName(formControlStr(PurchCreateOrder,PurchTable_PurchId)).valueStr());

27 June 2021

X++ code to get contact person Vendor/Customer which is specified in the Purchasing demographics AX 2012 / D365 FO

Table relations:

contactPerson.CONTACTPERSONID == VendTable.contactPersonId

DirPartyTable.RecId  == ContactPerson.Party

Below is the single line logic to get it.

 ContactPerson::find(VendTable::find("US-104").ContactPersonId).personName()




17 May 2021

How to override lookup form control methods using extensions / events in d365FO

 How to stop standard lookup and override the new lookup method.

FormControlCancelableSuperEventArgs formControlCancelSuper = e as FormControlCancelableSuperEventArgs;

        SysTableLookup sysTableLookup = SysTableLookup::newParameters(tableNum(ProjCategory), sender);

      

        sysTableLookup.parmQuery(query);

        sysTableLookup.performFormLookup();

        formControlCancelSuper.CancelSuperCall();

11 May 2021

X++ code to check Fiscal calendar period in AX 2012 and D365FO

X++ code to check Fiscal calendar period in AX 2012 and D365FO 

used to get the period status (Open, On hold and Closed)

  public static boolean checkFiscalCalendarPeriod(TransDate _transDate)

    {

        RecId calendarRecId;

        FiscalCalendarPeriod fiscalCalendarPeriod;


        calendarRecId = Ledger::fiscalCalendar(CompanyInfo::find().RecId);


        fiscalCalendarPeriod = FiscalCalendarPeriod::findPeriodByCalendarDate(calendarRecId, _transDate, FiscalPeriodType::Operating);


        if (_transDate)

        {

            if (!fiscalCalendarPeriod)

            {

                return checkFailed(strFmt("@SYS17614",date2StrUsr(_transDate, DateFlags::FormatAll)));

            }


            if (fiscalCalendarPeriod.currentLedgerPeriodStatus() != FiscalPeriodStatus::Open)

            {

                return checkFailed(strFmt("@SYS17615", date2StrUsr(_transDate, DateFlags::FormatAll)));

            }

        }


        return true;

    }

24 April 2021

How to get dataSource in DataSource Fileld COC in D365FO

 [ExtensionOf(formdatafieldstr(EntAssetRequestTableCreate, RequestTable, Object))]

final class TRGEntAssetRequestTableCreateFDF_RT_Object_Extension

{

    public void modified()

    {

        FormDataObject dataObject = any2Object(this) as FormDataObject;

        next modified();

        FormDataSource fds = dataObject.dataSource().formRun().dataSource(formDataSourceStr(EntAssetRequestTableCreate, TRGEntAssetRequestObjectTableView));

        fds.executeQuery();

    }

}

22 April 2021

Events get current record in D365FO

 Formrun formRun                          = sender.formRun();

        FormDataSource datasource                = formRun.dataSource(formDataSourceStr(CustInvoiceTemplate,CustInvoiceTemplate));

        CustInvoiceTemplate custInvoiceTemplate       = datasource.cursor();

21 April 2021

Enable / Disable the dialog field using UIBuilder in Service class / SysOperation fremework

 class TRGIntCalcBorrowingCostUIBuilder extends SysOperationAutomaticUIBuilder

{

    private TRGIntCalcBorrowingCostContract intCalcBorrowCostContract;

    private DialogField dialogPeriodCode;



    /// <summary>

    /// Auguments the UI behavior.

    /// </summary>

    public void postBuild()

    {

        intCalcBorrowCostContract = this.dataContractObject();

        super();

        dialogPeriodCode = this.bindInfo().getDialogField(this.dataContractObject(), methodStr(TRGIntCalcBorrowingCostContract, parmPeriod));

        dialogPeriodCode.enabled(false);

    }


}

09 April 2021

Looping selected records in the form in D365FO and X++ code to loop form selected records.


When the class main method initiated there can pass the args.record to below method and can loop records.

Reference: Class: PurchReqCancel

private void runLoopCancelWin(Common _common)
    {
        FormDataSource fds            = FormDataUtil::getFormDataSource(_common);
        Common         common;

        for (common = fds.getFirst(1) ? fds.getFirst(1) : fds.cursor(); common; common = fds.getNext())
        {
            this.doCancel(common);
        }
    }








02 March 2021

Dynamics 365 FO Extension for Form Datasource field and to get the current record

 [ExtensionOf(formdatafieldstr(EntAssetRequestTableCreate, RequestTable, Object))]

final class TRGEntAssetRequestTableCreateFDF_RT_Object_Extension

{  

    public void modified()

    {

        FormDataObject dataObject = any2Object(this) as FormDataObject;

        next modified();        

        FormDataSource fds = dataObject.dataSource().formRun().dataSource(formDataSourceStr(EntAssetRequestTableCreate, TRGEntAssetRequestObjectTableView));

        fds.executeQuery();

    }

Dynamics AX 365 FO – How to register jumpref method on form control / get the jumpref link in the form control

Create an event for OnPostRun for form events

[FormEventHandler(formStr(EntAssetWorkOrderTableCreate), FormEventType::PostRun)]

    public static void EntAssetWorkOrderTableCreate_OnPostRun(xFormRun sender, FormEventArgs e)

    {

        FormStringControl formCtrl = sender.design().controlName(formControlStr(EntAssetWorkOrderTableCreate, TRGEntAssetRequestObjectTableView_RequestId));

        formCtrl.registerOverrideMethod(methodStr(FormStringControl, jumpRef), methodStr(EntAssetRequestTableCreateForm_Extension, jumpRefRequestId), sender);

    }

Create extension class for the form methods and add jumprefMethod in it:

[ ExtensionOf(formstr(EntAssetWorkOrderTableCreate)) ]

final class TRGEntAssetWorkOrderTableCreateForm_Extension

{    

    public void TRGJumpRefRequestId(FormControl _formControl)

    {

        MenuFunction                        menuFunction;

        EntAssetRequestTable                entAssetRequestTable;

        TRGEntAssetRequestObjectTableView   entAssetRequestObjectTableView;

        Args                                args = new Args();

        FormDataSource                      fds = _formControl.formRun().dataSource(formDataSourceStr(EntAssetWorkOrderTableCreate, TRGEntAssetRequestObjectTableView));

        entAssetRequestObjectTableView      = fds.cursor();

        if (_formControl)

        {

            entAssetRequestTable = EntAssetRequestTable::find(entAssetRequestObjectTableView.RequestId);

        }

        args.record(entAssetRequestTable);

        args.lookupRecord(entAssetRequestTable);

        menuFunction = new MenuFunction(menuitemDisplayStr(EntAssetRequestTable), MenuItemType::Display);

        menuFunction.run(args);

    }

}

01 March 2021

How to fix BP warning in Dynamics 365 FO

 Need to add the SuppressBPWarning for methods if not using any Parameters:

Example:

[FormDataSourceEventHandler(formDataSourceStr(EntAssetRequestTableCreate, TRGEntAssetRequestObjectTableView), FormDataSourceEventType::QueryExecuting),

        SuppressBPWarning('BPParameterNotUsed', 'The parameter is not required in this context')]

    public static void TRGEntAssetRequestObjectTableView_OnQueryExecuted(FormDataSource sender, FormDataSourceEventArgs e)

    {


=====

[FormDataSourceEventHandler(formDataSourceStr(AccountingDistribution, AccountingDistribution), FormDataSourceEventType::Activated),

        SuppressBPWarning('BPParameterNotUsed', 'Parameter required by the event interface')]

27 February 2021

Capturing infolog error messages in AX 2012 X++ code to capture the error infolog

InfologData             infoLogData;

SysInfologEnumerator    sysInfologEnumerator;

 sysInfologEnumerator = SysInfologEnumerator::newData(infolog.infologData());

 while (sysInfologEnumerator.moveNext() )

 {

        switch (sysInfologEnumerator.currentException())

        {         

            case Exception::Warning:

                 info(strFmt("Message is %1", sysInfologEnumerator.currentMessage()));

            break;

        }

}

=============

 catch (Exception::CLRError)

                {

                    ex = ClrInterop::getLastException();

                    if (ex != null)

                    {

                        ex = ex.get_InnerException();

                        if (ex != null)

                        {

                            error(ex.ToString());

                        }

                    }

                }

25 February 2021

D365FO COC methods and usage

How to get Form data source field method COC current record:

FormDataObject dataObject = any2Object(this) as FormDataObject;

FormDataSource dataSource = dataObject.DataSource();

CustGroup custGroup = dataSource.cursor();


Ledger Voucher creation Framework and x++ code to create ledger voucher

 Please click her for MS reference file Below is the out of the box example reference and code. SalesInvoiceJournalPostSubBill_Extension->...