Monday, 20 December 2021

D 365 FO code UserID to Employee details and Vice-versa

Hi all, 

The below block of code will give you the detail of employee by is userid and Vice-Versa, 


Public HCMWorker getEmployeeDetailsByUserID(UserID    _UserId)

{

        DirPersonUser   personUser;

        HcmWorker       worker;

        if (_userId == "")

    {

        _userId == curUserId()

    }

            select firstonly * from worker

                exists join personUser

                where worker.Person == personUser.PersonParty

                &&    personUser.User == _userId;

            return worker;

        }



Public DirPersonUser   getUserDetailsByPersonnelNo(PersonnelNum    _PersonnelNo)

{

        DirPersonUser   personUser;

        HcmWorker       worker;

select * from personUser

join worker

where worker.Person == personUser.PersonParty

&&  worker.PersonnelNumber == _PersonnelNo;

Return personUser.UserID;

}


Keeping DAXing ;/

Wednesday, 27 October 2021

D 365 FO Default password for MSSQL DB one box Environment

Hi all,

Below is the default password for the Database which we are using in the One Box Dev Environment.

       

        Username "axdbadmin" 

The default password of D365FO / AX7 VM Administrator is 'pass@word1'.

The default password of D365FO / AX7 VM Database Administrator is 'AOSWebSite@123'.

Keep DAXing :)

Sunday, 17 October 2021

D 365 FO to create Sales order from X++ Code

 Hi,

the below x++ code will help you to create the Sales Order from the code behind without any form or pop up this code can be used for creating the Sales Order for the Integration forms.


class RAM_CreateSalesOrderFromCodeBehind

{

    public static void main(Args _args)

    {        

        SalesTable salesTable;

        SalesLine salesLine;

        InventTable inventTable;

        InventDim inventDim;

        CustTable custTable;

        CustAccount custAccount;

        NumberSeq numberSeq;

        SalesId salesID;

        str warehouse;

        try

        {

            ttsbegin;

            salesTable.clear();


            numberSeq = NumberSeq::newGetNum(SalesParameters::numRefSalesId());

            numberSeq.used();

salesID = numberSeq.num();

            salesTable.SalesId = salesID;

            

            salesTable.initValue();

            

            if(CustTable::find([Customer ID]))

            {

                salesTable.CustAccount = [Customer ID];

            }

            else

            {

                info(strFmt("Customer account %1 doesn't exist.", [Customer ID]));

            }


            

            salesTable.initFromCustTable();

            if(InventLocation::find([warehouse ID]).InventLocationId != "")

            {

                salesTable.InventSiteId = InventLocation::find(warehouse).InventSiteId;

                salesTable.InventLocationId = inventlocation::find(warehouse).InventLocationId;

            }

            salesTable.insert();

            try

            {

                inventTable.clear();

                inventDim.clear();

                salesLine.clear();


                select * from inventTable

                    where inventTable.itemId == [Item ID];

                    

                salesLine.clear();

                salesLine.SalesId = salesID;

                salesLine.ItemId = inventTable.ItemId;

                salesLine.itemIdChanged();


                

                salesLine.initFromInventTable(InventTable::find(salesLine.ItemId));


                if(Inventlocation::find(warehouse).InventLocationId != "")

                {

                    inventdim.InventSiteId = InventLocation::find(warehouse).InventSiteId;

                    inventdim.InventLocationId = Inventlocation::find(warehouse).InventLocationId;

                }

                salesLine.InventDimId = InventdIm::findOrCreate(inventDim).inventDimId;


                salesLine.createLine(NoYes::Yes, // Validate

                NoYes::Yes, // initFromSalesTable

                NoYes::No, // initFromInventTable

                NoYes::Yes, // calcInventQty

                NoYes::Yes, // searchMarkup

                NoYes::Yes); //


                //Set the values as per your scenario

                salesLine.SalesPrice = [Item Sales Price];

                salesLine.SalesQty = [Qty];

                salesLine.LineDisc = [Line discount];

                salesLine.LineAmount= salesLine.calcLineAmount();

                salesLine.update();

                ttscommit;

            }

            catch(Exception::Error)

            {

                ttsabort;

            }


            

            SalesFormLetter formLetterObj;

            formLetterObj = SalesFormLetter::construct(DocumentStatus::Invoice);

            formLetterObj.update(SalesTable::find(salesID));

            

            info(strFmt("Sales order created with Sales ID: %1",salesID));

        }

        catch(Exception::Error)

        {

            ttsabort;

        }

    }

}


Keep DAXing :)

Wednesday, 6 October 2021

D 365 FO code to get the Item Price by Trade agreement (Purchase/Sales)

 Dear All,

In this post, we'll get the Item price from the Trade Agreement irrespective of Purchase or Sales Request forms.

Static method you can write in the Table or in the Extensions classes the syntax may differ if your using extension classes.

 public static Amount    findSalesItemPrice(ItemId _itemId, CustAccount _custAccount, InventDimId _inventDimId, Qty _qty)

    {

        PriceDisc                               priceDisc;

        InventTable inventTable     = InventTable::find(_itemId);

        CustTable custTable       = CustTable::find(_custAccount);

        InventDim inventDimItem   = InventDim::find(_inventDimId);

        UnitOfMeasureSymbol     unitId          = inventTable.inventTableModuleInvent().UnitId;

        Amount                   retPrice;


        priceDisc = new PriceDisc(ModuleInventPurchSales::Sales, _itemId, inventDimItem, unitId, systemDateGet(), _qty , _custAccount);


        if (priceDisc.findPrice(custTable.PriceGroup))

            retPrice = priceDisc.price();

        else if (priceDisc.findItemPrice())

            retPrice = priceDisc.price();


        return retPrice;

    }

you can Change the Customer Details to Vendor in case if your in plan to get the Item price for Puchase request forms.



Thank you

Keep Daxing:)



Tuesday, 5 October 2021

D 365 FO call the Other form by passing datasource as menu parameter

 Hi All,

in this post, we'll check how to call the Display menu Item or Form from the back end.

Step 1: Add the respective button in the existing form or new form, go to events, and copy the clicked event handler.

Sample code look alike

[FormControlEventHandler(formControlStr(SalesTable, Complete), FormControlEventType::Clicked)]

public static void Complete_OnClicked(FormControl sender, FormControlEventArgs e)

{

    // your Code       

}

now copy-paste or rewrite the below code according to your requirements.


[FormControlEventHandler(formControlStr(SalesTable, Complete), FormControlEventType::Clicked)]

public static void Complete_OnClicked(FormControl sender, FormControlEventArgs e)

{     

FormRun                             form                = sender.formRun();

        FormDataSource                      salesTable_ds        = form.dataSource(formDataSourceStr(SalesTable, SalesTable)) as FormDataSource;

   SalesTable                          salesTable = salesTable_ds.cursor();

        Args                                args;

        MenuFunction                        menuFunction;


        info(strFmt("%1",SalesStatus::None));

        if(salesTable.SalesStatus   == SalesStatus::None)

        {

            args.record(salesTable); // to send whole table as parameter

            args.caller(sender);

            menuFunction = new MenuFunction(menuItemDisplayStr(BER_CreateQuotationFromSalesOrder), MenuItemType::Display);

            menuFunction.run(args);

        }

        else

        {

            throw Error(strfmt('[LabelID]',salesTable.SalesStatus));

        }

}


Thanks

Keep Daxing :)

Monday, 4 October 2021

D 365 FO Form datasource Field Lookup in Extension Class

Hi all,

In this post, I'll explain to you how to define or add the lookup method for the Datasource field in the form by using the extension class and method.

Step 1: Go to the Field in the form for which you are willing to add the Custom lookup. Expand the Events Mouse right Click "Copy Event handled Method".

Step 2: Create a new Extension class or Paste the copied method in the new or existing extension class.

The sample code of copied method will look alike.

[FormControlEventHandler(formControlStr(SalesQuotationTable, Line_ItemId), FormControlEventType::Lookup)]
public static void Line_ItemId_OnLookup(FormControl sender, FormControlEventArgs e)
{       
}

Step 3: Copy / Type the below code  
[FormControlEventHandler(formControlStr(SalesQuotationTable, Line_ItemId), FormControlEventType::Lookup)]
public static void Line_ItemId_OnLookup(FormControl sender, FormControlEventArgs e)
{   
        Query                   query                   = new Query();
        QueryBuildDataSource    queryBuildDataSource;
        SysTableLookup          sysTableLookup;
        
        sysTableLookup = SysTableLookup::newParameters(tableNum([TableName]), sender);
        queryBuildDataSource = query.addDataSource(tableNum([TableName]));
        
        queryBuildDataSource.addRange(fieldNum([TableName], [FieldName for Filter])).value([Filter field value]);
        
        sysTableLookup.addLookupField(fieldNum([TableName], [FieldName to be selected and shown in lookup]), true);
        sysTableLookup.addLookupMethod(tableMethodStr([TableName], [FieldName to shown in Lookup]));

        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();
}

Hope this post will help you to add the Customlookup in Datasource field.


Thanks,

Keep Daxing :)

Sunday, 5 September 2021

D 365 FO New Report or new Design of Existing Report in Print Management

 The simple way to add a new report or new design of an existing report in Print management 



Step-1 Create new class RAM_PurchPurchaseOrderReport


Step-2 Find class PrintMgmtDocType in Application Explore and open in designer 


Step-3 find the delegate in PrintMgmtDocType class Delegate name is  getDefaultReportFormatDelegate



Step-4 Subscribe to the event of the above-highlighted event in the newly created class


Step-5 Now add your report design in the RAM_EventHandlerResult_PrintManagement


[SubscribesTo(classStr(PrintMgmtDocType), delegateStr(PrintMgmtDocType, getDefaultReportFormatDelegate))]
    public static void PrintMgmtDocType_getDefaultReportFormatDelegate(PrintMgmtDocumentType _docType, EventHandlerResult _result)
    {
        if(PrintMgmtDocumentType::PurchPurchaseOrderConfirmation ==_docType)
        {
            _result.result(ssrsReportStr(RAM_PurchPuchaseOrder,Report));

        }

      
    }


Step-6 Perform build and sync and verify on D365FO


Keep Daxing :)


Tuesday, 31 August 2021

Dynamics 365 FO deploy SSRS reports through Windows PowerShell

 In this blog, by using the below script we'll deploy SSRS reports in Microsoft Dynamics 365 Finance and Operations using Windows PowerShell  


Open Windows PowerShell in administrator mode and run the below script.

cd C:\AOSService\PackagesLocalDirectory\Plugins\AxReportVmRoleStartupTask\

 

.\DeployAllReportsToSsrs.ps1

For online Cloud-hosted Dev VM, we will run below script

cd [AOS Direcotory]:\AosService\PackagesLocalDirectory\Plugins\AxReportVmRoleStartupTask\

 

.\DeployAllReportsToSSRS.ps1 -PackageInstallLocation "[AOS Direcotory]:\AosService\PackagesLocalDirectory"

While executing the command you’ll see the below window.



After successfully deploying all the reports you'll see the result and status of each report deployment on the same window



Keep Daxing :)

Sunday, 29 August 2021

D 365 FO Form Data source field Lookup

The below code will help you to create a lookup method for the Form Level Datasource field.

1) go to Form Open the Datasource where you want to add the Lookup select the Field to expand the property under method go to Override method and then select lookup method.

2) After selecting that it will create a method and you can copy-paste the below code inside the method.

3) Change the Tabke and condition according to your requirements. (Here for the demo I'm using Customer details CustTable).


public void lookup(FormControl _formControl, str _filterStr)

            {

                Query                   query = new Query();

                QueryBuildDataSource    queryBuildDataSource;

                SysTableLookup          sysTableLookup;


                sysTableLookup = SysTableLookup::newParameters(tableNum(EcoResProduct), _formControl);

                queryBuildDataSource = query.addDataSource(tableNum(EcoResProduct));

                                     queryBuildDataSource.addRange(ProductType).value(enum2Str(EcoResProductType::Service));


                sysTableLookup.addLookupField(fieldNum(EcoResProduct, Displayproductnumber));

                sysTableLookup.addLookupField(fieldNum(EcoResProduct, SearchName));

                sysTableLookup.addLookupField(fieldNum(EcoResProduct, ItemClassification));


                sysTableLookup.parmQuery(query);

                sysTableLookup.performFormLookup();

            }







Thanks

Keep Daxing :)

Tuesday, 24 August 2021

D 365 FO Dialog Confirmation Box

Below is the line code that will help you to ask the confirmation from the user before executing the actual logic.


            if (box::yesNo('[Confirmarion message]', dialogButton::Yes, "Confirm changes") == dialogButton::Yes)

            {

                info(strFmt("Yes"));

//Your Logic if your select the Confirmaiton message Yes

            }



Thank you

Keep Daxing :)

Tuesday, 10 August 2021

D 365 FO / Ax 2012 /2009 X++ code to find the Logged in Worker details

Hi all,

Below is the line of code that will help you to get the Logged in employee details is he mapped with User in the Userinfo Form.



                 HcmWorker hcmWorker;

                hcmWorker = hcmWorker::find(DirPersonUser::findUserWorkerReference(curUserId()));

                info(strFmt("Current Worker name is : %1 ",hcmWorker.name()));




Thank you

Keep Daxing :)

Monday, 2 August 2021

D 365 FO X++ Code to duplicate the selected Line from Sales Order

Below is a block of code that we can use for copying the existing sales line or selected SalesLine details on the same SalesOrder or another SalesOrder. Basically is it the same as CopyLine functionality in Sales Order.


                      salesLineUpdate.clear();

                    salesLineUpdate.initFromSalesTable([FromSalesTable]);

                    salesLineUpdate.initFromSalesLine([FromSalesLineTable]);

                   ttsbegin;

                    salesLineUpdate.createLine(NoYes::Yes, // Validate

                    NoYes::Yes, // initFromSalesTable

                    NoYes::Yes, // initFromInventTable

                    NoYes::Yes, // calcInventQty

                    NoYes::Yes, // searchMarkup

                    NoYes::Yes);

                    ttscommit;



thank you 

Keep Daxing :)

Thursday, 29 July 2021

D 365 FO Get object of Caller Form in Extension Class

 [ExtensionOf(formStr(PurchCreateFromSalesOrder))]

final class DXN_PurchCreateFromSalesOrder_extension 

{

   

    [PostHandlerFor(formStr(PurchCreateFromSalesOrder), formMethodStr(PurchCreateFromSalesOrder, init))]

    public static void PurchCreateFromSalesOrder_Post_init(XppPrePostArgs args)

    {

        FormRun             formRun    = args.getThis();

        str                 callerFormName;


        callerFormName = formRun.args().caller().name();

        info(strfmt("%1",callerFormName));

    }

}



Thank you,

Keep Daxing :)

Tuesday, 13 July 2021

D 365 FO Form field level query lookup

Go to the field for which you want to add the query-based lookup, select the field under field, select the lookup method, paste the below code, and change wherever required.


For me, I'm Adding the Customer details lookup for the field

public void lookup()

        {

            Query                   query = new Query();

            QueryBuildDataSource    queryBuildDataSource;

            SysTableLookup          sysTableLookup;

            super();


            sysTableLookup = SysTableLookup::newParameters(tableNum(CustTable), this);

            queryBuildDataSource = query.addDataSource(tableNum(CustTable));


            sysTableLookup.addLookupField(fieldNum(CustTable, AccountNum));

            sysTableLookup.addLookupField(fieldNum(CustTable, Party));

            sysTableLookup.addLookupField(fieldNum(CustTable, RecId));


            sysTableLookup.parmQuery(query);

            sysTableLookup.performFormLookup();

        }



Thank you

Keep Daxing :)

D 365 FO OnActivated(xFormRun eventhandler) extension method to hide the control.

 [FormEventHandler(formStr([FormName]), FormEventType::Activated)]

    public static void LWSOrderTable_OnActivated(xFormRun sender, FormEventArgs e)

    {

        FormDataSource          [DataSourceName]_ds    = sender.dataSource(formDataSourceStr([FormName], [DatasourceTableName]));

        FormTabControl          [ControlTabName]   = sender.design().controlName(formControlStr([FormName], [FormControlName]));

        if([Condition] == NoYes::Yes)

        {

            [ControlTabName].visible(true);

        }

        else

        {

            [ControlTabName].visible(false);

        }

    }

Sunday, 27 June 2021

D 365 FO Enable or disable & Mandatory or Non Mandatory based on Checkbox field using Extension Class

  [FormControlEventHandler(formControlStr(EcoResProductParameters, [FieldName]), FormControlEventType::Modified)]

    public static void [FieldName]_OnModified(FormControl sender, FormControlEventArgs e)

    {

        FormCheckBoxControl allowVehicleCreation = sender.formRun().design().controlName(formControlStr(EcoResProductParameters,[FieldName]));

        FormStringControl allowVehicleCreationGroup = sender.formRun().design().controlName(formControlStr(EcoResProductParameters,[FieldForWhichValidationRequired]));


        if(allowVehicleCreation.value() == NoYes::Yes)

        {

            allowVehicleCreationGroup.mandatory(true);

            allowVehicleCreationGroup.enabled(true);

        }

        else

        {

            allowVehicleCreationGroup.mandatory(false);

            allowVehicleCreationGroup.enabled(false);

        }

    }


Thank you

Keep Daxing :)

D 365 FO Command / Script to make the Development Env to Maintenance Mode

//Run the Command in Powershell

Maintenance On

C:\AOSService\PackagesLocalDirectory\bin\Microsoft.Dynamics.AX.Deployment.Setup.exe --metadatadir C:\AOSService\PackagesLocalDirectory --bindir C:\AOSService\PackagesLocalDirectory\bin --sqlserver . --sqldatabase axdb --sqluser [AXDBAdminUsername] --sqlpwd [Password] --setupmode maintenancemode --isinmaintenancemode true


Maintenance off

C:\AOSService\PackagesLocalDirectory\bin\Microsoft.Dynamics.AX.Deployment.Setup.exe --metadatadir C:\AosService\PackagesLocalDirectory --bindir J:\AosService\PackagesLocalDirectory\Bin --sqlserver . --sqldatabase axdb --sqluser [AXDBAdminUsername] --sqlpwd [Password] --setupmode maintenancemode --isinmaintenancemode false



//Run the Query on MSSQL Query browser

select Value from sqlsystemvariables a where a.PARM = 'configurationmode'

update sqlsystemvariables set VALUE = 1 where PARM = 'configurationmode'



The best result you'll get it after restarting IIS services (iisreset) cmd



Thank you,

Keep Daxing :)

Wednesday, 23 June 2021

D 365 FO to refresh caller FormDataSource from a Extension Class

 class UpdatePurchLine_Extension

{

static void main(Args args)

{

PurchLine purchLine;

FormDataSource purchLine_DS;

purchLine_DS = args.record().dataSource();

;


purchLine = args.record();


//Set of Code

purchLine_DS.executeQuery();

purchLine_DS.refresh();

}


}


Thank you,

Keep Daxing :)

Tuesday, 22 June 2021

D 365 FO Enable or disable field based on condition using Extension Class

 [FormDataSourceEventHandler(formDataSourceStr(PurchTable, PurchLine), FormDataSourceEventType::Activated)]

    public static void PurchLine_OnActivated(FormDataSource sender, FormDataSourceEventArgs e)

    {

        //Declaration of the Form Datasource

        FormDataSource              fds             = sender.formRun().dataSource(formDataSourceStr(PurchTable,PurchLine));

        PurchLine                   purchLine       = fds.cursor();

        FormRun                     fr              = sender.formRun();

        PurchParameters             purchParameters = PurchParameters::find();

        boolean                     allowEdit = true;

        //Form Tab page declaration for allowing to customize

        FormTabPageControl          ftpc = fr.design(0).controlName("TabLineFixedAsset");

        

        allowEdit = purchParameters.BER_AllowEditPOLineAfterReceipt;

        //condition

        if(PurchLine.PurchStatus == PurchStatus::Received)

        {

            //controls where the enable set true or false based on the condition execution

            fds.object(fieldNum(PurchLine ,PurchQty)).allowEdit(allowEdit);

            fds.object(fieldNum(PurchLine ,PurchPrice)).allowEdit(allowEdit);

            fds.object(fieldNum(PurchLine ,LineAmount)).allowEdit(allowEdit);

            fds.object(fieldNum(PurchLine ,DiscAmount)).allowEdit(allowEdit);

            fds.object(fieldNum(PurchLine ,DiscPercent)).allowEdit(allowEdit);

           //Fixed asset tab enable false if the Ststus is received.

            ftpc.allowEdit(false);

        }

    }


Thank you,

Keep Daxing :)

Thursday, 10 June 2021

D365 FO Refresh Called from after function call

 Hi All,

The below code will help you to refresh the call from after the data operations, for me I'm refreshing the PurchTable form after duplicating line from exiting lines.


 protected static  void updateCaller(PurchTable  _purchTable)

    {

        PurchTable  purchTable = _purchTable;//purchTable::find(PurchLine::findRecId(_args.record().RecId));

        Object callerPurchTableDataSource = FormDataUtil::getFormDataSource(purchTable);


        if (callerPurchTableDataSource)

        {

            callerPurchTableDataSource.reread();

            callerPurchTableDataSource.refresh();


            if (formDataSourceHasMethod(callerPurchTableDataSource, identifierStr(reReadLines)))

            {

                callerPurchTableDataSource.reReadLines();

            }

        }

    }


Thank you,

Keep Daxing :)