Oct 20, 2023

How to get the report name in RDP class

 

[ExtensionOf(classStr(AssetBalancesDP))]

final class AssetBalancesDP_AHCJH_Fin_Extension

{


    public void processReport()

    {

        SrsReportName rptName;        

        next processReport();

        AssetBalancesTmp assetBalancessTmp = this.getAssetBalancesTmp();

        AssetTable                 assetTable;      

       

        Dynamics.AX.Application.SysDocuBrandContract docubrand = this.docuBrandContract;

        rptName = docubrand.parmReportName();

        if(rptName == "MyReport_AssetBalances")

        {        

            update_recordset assetBalancessTmp

                setting                  

                    AdditionalName = assetTable.AdditionalName

                join assetTable

                    where assetTable.AssetId == assetBalancessTmp.AssetId;

        }    

    }

}

Oct 19, 2023

How to update a temp table column in D365 FO

 [ExtensionOf(classStr(AssetRollForwardDP))]

final class AssetRollForwardDP_My_Extension

{

 //  Overriding getAssetRollForwardTmp() as it is returning the temp table buffer.

 public AssetRollForwardTmp getAssetRollForwardTmp(AssetRollForwardContract _contract, Query _query)

    {

        AssetRollForwardTmp assetRollForwardTmpUpd;        

        AssetTable      assetTableBuf;         

        next  getAssetRollForwardTmp(_contract, _query);   

        assetRollForwardTmpUpd.linkPhysicalTableInstance(assetRollForwardTmp);

               

        update_recordset assetRollForwardTmpUpd

            setting 

                AssetName = assetTableBuf.AdditionalName

            join AdditionalName from assetTableBuf

            where assetRollForwardTmpUpd.assetid == assetTableBuf.AssetId;


        return assetRollForwardTmp;

    }


}

How to use From Datasource Level Record Writing Event In D365 FO

 


Public class My_LedgerJourTransAssetFrm_EventHandler

{  

     /// <summary>

    ///

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    [FormDataSourceEventHandler(formDataSourceStr(LedgerJournalTransAsset, LedgerJournalTrans_Asset), FormDataSourceEventType::Writing)]

    public static void LedgerJournalTrans_Asset_OnWriting(FormDataSource sender, FormDataSourceEventArgs e)

    {

        LedgerJournalTrans_Asset       LedgerJourTransAssetTableLoc = sender.cursor();

        LedgerJourTransAssetTableLoc.AdditionalName = AssetTable::find(LedgerJourTransAssetTableLoc.Assetid).AdditionalName;

    }


}

TABLE FIELD MODIFIED EVENT HANDLER IN D365 FO

Below is an example to trigger a function on field modified event 

1) Go to AssetTable --> Events --> onModifiedField 

2) Right click on the onModifiedField  --> Copy event handler

3) Create a new class and paste the copied eventhandler signature

4

 Class My_AssetTable_EventHandler

    /// <summary>

    /// 

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    [DataEventHandler(tableStr(AssetTable), DataEventType::ModifiedField)]

    public static void AssetTable_onModifiedField(Common sender, DataEventArgs e)

    {

       

        ModifyFieldEventArgs fieldEvent = e as DataEventArgs;

        AssetTable assetTable = sender as AssetTable;

        FieldId         fieldId = fieldEvent.parmFieldId();

        

        switch(fieldId)

        {

            case(fieldNum(AssetTable, Name)):

                if(assetTable.AdditionalName)

                {                    

                    if(Box::yesNo("Do you want to update Asset additional description with same value",DialogButton::No))

                    {

                        assetTable.AdditionalName = assetTable.Name;

                    }                    

                }

                else

                {

                    assetTable.AdditionalName = assetTable.Name;

                }

            break;

            default:

                break;

        }

    }

}

May 19, 2022

Rename .mdf and .ldf files


Try the below steps to rename the .mdf and .ldf files

1) Run the below command to get the logical file name's and physical file names of the DB.

USE AXDB

GO

SELECT file_id, name as [logical_file_name], physical_name

FROM sys.database_files

 Result : 



2) Disconnect the existing connecting and bring the DB to offline by running below scripts

USE [master];

GO

--Disconnect all existing session.

ALTER DATABASE AXDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

GO

--Change database in to OFFLINE mode.

ALTER DATABASE AXDB SET OFFLINE

3)  Refresh the DB's and check the status of AXDB should be offline

4)  Go to file locations and change the files names

5) then run the below cmd

ALTER DATABASE AXDB MODIFY FILE (Name='AXDBUAT', FILENAME='G:\MSSQL_DATA\AXDB.mdf')

GO

ALTER DATABASE AXDB MODIFY FILE (Name='AXDBUAT_log', FILENAME='H:\MSSQL_LOGS\AXDB_log.ldf')

GO

6) To bring back the DB online run below cmd

USE [master];

GO

ALTER DATABASE AXDB SET ONLINE

Go

ALTER DATABASE AXDB SET MULTI_USER

Go

7) Run the below cmd to check and confirm the status of the DB 

Select name as [AXDB],state_desc from sys.databases 



8) ReRun the below cmd to see the changed names



Apr 20, 2022

Sample excel export job (X++)

 static void CustomerDetailsExport(Args _args)

{

CustTable CustTable;

SysExcelApplication application;

SysExcelWorkbooks workbooks;

SysExcelWorkbook workbook;

SysExcelWorksheets worksheets;

SysExcelWorksheet worksheet;

SysExcelCells cells;

SysExcelCell         cell;

int                          row;

DimensionAttributeValueSetStorage  dimstorage;


int         i = 0;

str         fileName    = "C:\\Users\\XXX\\Desktop\\CustDetailsWithFinDim.xlsx";

;


application = SysExcelApplication::construct();

workbooks = application.workbooks();

workbook = workbooks.add();

worksheets = workbook.worksheets();

worksheet = worksheets.itemFromNum(1);

cells = worksheet.cells();

cells.range('A:A').numberFormat('@');


cell = cells.item(1,1);

cell.value("Customer");

cell = cells.item(1,2);

cell.value("Name");

cell = cells.item(1,3);

cell.value("Warehouse");

cell = cells.item(1,4);

cell.value("CostCenter");

cell = cells.item(1,5);

cell.value("Department");

cell = cells.item(1,6);

cell.value("BusinessUnit");

cell = cells.item(1,7);

cell.value("SalesType");


row = 1;

while select CustTable

    where CustTable.AccountNum 

{

    row++;

    cell = cells.item(row, 1);

    cell.value(CustTable.AccountNum);

    cell = cells.item(row, 2);

    cell.value(CustTable.name());


    dimstorage = DimensionAttributeValueSetStorage::find(CustTable.DefaultDimension);

    for(i=1;i <= dimstorage.elements();i++)

    {

       if(DimensionAttribute::find(dimstorage.getAttributeByIndex(i)).Name == 'Warehouse')

       {

            cell = cells.item(row, 3);

            cell.value(dimstorage.getDisplayValueByIndex(i));

       }

       if(DimensionAttribute::find(dimstorage.getAttributeByIndex(i)).Name == 'CostCenter')

       {

            cell = cells.item(row, 4);

            cell.value(dimstorage.getDisplayValueByIndex(i));

       }

       if(DimensionAttribute::find(dimstorage.getAttributeByIndex(i)).Name == 'Department')

       {

            cell = cells.item(row, 5);

            cell.value(dimstorage.getDisplayValueByIndex(i));

       }

        if(DimensionAttribute::find(dimstorage.getAttributeByIndex(i)).Name == 'BusinessUnit')

       {

            cell = cells.item(row, 6);

            cell.value(dimstorage.getDisplayValueByIndex(i));

       }

        if(DimensionAttribute::find(dimstorage.getAttributeByIndex(i)).Name == 'SalesType')

       {

            cell = cells.item(row, 7);

            cell.value(dimstorage.getDisplayValueByIndex(i));

       }

    }

}

    workbook.saveAs(fileName);

    application.visible(true);

    info(strFmt('Exported %1 records',row-1));

}

Mar 29, 2022

Button Click Event Handler in D365 FO

 class InventQuarantineParmEnd_Form_EventHandler

{   

    /// <summary>

    ///

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    [FormControlEventHandler(formControlStr(InventQuarantineParmEnd, OK), FormControlEventType::Clicked)]

    public static void OK_OnClicked(FormControl sender, FormControlEventArgs e)

    {

        InventParmQuarantineOrder   InvParmQuarantineOrder;

        FormDataSource              formDataSource;


        RecId                   calendarRecId;

        FiscalCalendarPeriod    fiscalCalendarPeriod;

        TransDate               transDate;


        formDataSource = sender.formRun().dataSource(tableStr(InventParmQuarantineOrder));

        InvParmQuarantineOrder = formDataSource.cursor();



        if(InvParmQuarantineOrder.TransDate)

        {

            transDate = InvParmQuarantineOrder.TransDate;

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

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

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

            {

                throw error(strFmt("Date %1 is not open in Ledger calender. Please select date from open period", date2StrUsr(transDate, DateFlags::FormatAll)));

            }

           

        }

        if(!InvParmQuarantineOrder.TransDate)

        {

            throw error(strFmt("Please select date to proceed"));

        }

    }


}

Mar 10, 2022

Excel upload

 

static void excelUpload(Args _args)

{

    //dialog

    dialog d = new dialog("Excel upload Tool");

    dialogfield dExcelFilepath,dTablename,dFieldName1,dFieldName2,dFieldName3,dFieldName4,dFieldName5,dExcelStart,dExcelEnd;

    dialogfield type1,type2,type3,type4,type5;

    DialogGroup fGroup1,fGroup2,fGroup3,fGroup4,fGroup5;


    //general variables

    filepath excelFilepath;

    tablename tableName;

    FieldName fieldName1,fieldName2,fieldName3,fieldName4,fieldName5;

    str 25   fieldtype1,fieldtype2,fieldtype3,fieldtype4,fieldtype5;

    str 100    NexcelField1,NexcelField2,NexcelField3,NexcelField4,NexcelField5;

    int     excelStart,excelEnd;

    boolean ok = true;

    #AviFiles

    SysOperationProgress    progress = new SysOperationProgress();


    //dictTable variables

    dicttable dictTable;

    dictField  dictField1,dictField2,dictField3,dictField4,dictField5;

    common common;


    //excel variables

    SysExcelApplication ldA;

    SysExcelWorkbooks   ldWbs;

    SysExcelWorkbook    ldWb;

    SysExcelWorksheets  ldWss;

    SysExcelWorksheet   ldWs;

    SysExcelCells       ldCs;

    SysExcelCell        ldCA;

    SysExcelRange       ldR;

    int                 j;

    container value( str _Value,types _type,fieldName _fieldName = '')

    {

        container conLocal [1];

        dictEnum    dictEnum;

        int         i;

        ;


        switch (_type)

        {


            case types::Integer :

            conlocal[1] = [str2int(_value)];

            break;

            case types::Real :

            conlocal[1] = [str2num(_value)];

            break;

            case types::Date :

            conlocal[1] = [str2date(_value,1)];

            break;

            case types::Int64:

            conlocal[1] = [str2int64(_value)];

            break;

            case types::UtcDateTime:

            conlocal[1] = [str2datetime(_value,1)];

            break;

            case types::Enum:

            {

                if(_fieldName != '')

                {

                    dictEnum = new DictEnum(EnumName2Id(_fieldName));

                    for(i=0;i<= dictEnum.values();i++)

                    {

                        if(dictEnum.index2Label(i) == _value)

                        {

                            conlocal[1] = [dictEnum.name2Value(_value)];

                            Break;

                        }

                    }

                }

            }

            break;

            default:

            conlocal[1] = [strfmt(_value)];

            break;


        }

        return conlocal[1];

    }

    boolean validate()

    {

        Dictionary            dictionary = new Dictionary();

        tableName         tableNameLocal;

        ;


        if(!excelFilepath)

        ok = ok && checkFailed("Please give the Excel path to import data");


        if(!tableName && ok)

        ok = ok && checkFailed("Table Name is mandatory");


        if(tablename && ok)

        {

            tableNameLocal = Dictionary.tableName(tableName2Id(tableName));

            if(!tableNameLocal)

            ok = ok && checkFailed(strfmt("Table %1 does not exist",tablename));

        }

        if(!fieldName1 && ok)

        {

            ok = ok && checkfailed("Primary Key is mandatory Proceed");

        }

        if((!FieldName2 && !fieldname3 && !FieldName4 && !Fieldname5) && ok)

        {

            ok = ok && checkFailed("Atleast one field is mandatory Proceed");

        }

        if(ok && !ExcelStart || !Excelend)

        {

            ok = ok && checkFailed("Excel start and end rows are mandatory to proceed");

        }

        if(ok && (ExcelStart > Excelend))

        {

            ok = ok && checkfailed("Excel Start row number cannot be less than Excelend row number");

        }

        if((!FieldName2 || !fieldname3 || !FieldName4 || !Fieldname5) && ok )

        {


            ok = box::yesNo("All fields are not given, you still want to proceed ?",dialogbutton::Yes,"Check validation") == dialogButton::Yes;

        }


        return ok;

    }

    ;


    dExcelFilepath = d.addField(extendedtypestr(FilePath),"Excel file path","Please select the excel");


    dTableName     = d.addField(extendedTypeStr(tablename),"Table name","Please enter tablename");


    fgroup1 = d.addGroup("Primary Key");

    dFieldName1    = d.addField(extendedtypestr(FieldName),"Primary Key","Please enter Field-1");

    type1 = d.addField(extendedtypestr(fieldType),"Primary Key","Select the field type");


    fgroup2 = d.addGroup("Field list 1");


    dFieldName2    = d.addField(extendedtypestr(FieldName),"Field-1","Please enter Field-2");


    type2 = d.addField(extendedtypestr(fieldType),"Type","Select the field type");


    fgroup3 = d.addGroup("Field list 2");

    dFieldName3    = d.addField(extendedtypestr(FieldName),"Field-2","Please enter Field-3");

    type3 = d.addField(extendedtypestr(fieldType),"Type","Select the field type");


    fgroup4 = d.addGroup("Field list 3");

    dFieldName4    = d.addField(extendedtypestr(FieldName),"Field-3","Please enter Field-4");

    type4 = d.addField(extendedtypestr(fieldType),"Type","Select the field type");


    fgroup5 = d.addGroup("Field list 4");

    dFieldName5    = d.addField(extendedtypestr(FieldName),"Field-4","Please enter Field-5");

    type5 = d.addField(extendedtypestr(fieldType),"Type","Select the field type");


    dExcelStart    = d.addField(extendedtypestr(integer),"Excel Start","Enter excel Starting row");

    dExcelEnd    = d.addField(extendedtypestr(integer),"Excel End","Enter excel ending row");

    if(d.run()== noyes::Yes)

    {

        //reading dialog

        excelFilepath = dExcelFilepath.value();

        tablename = dtablename.value();

        dictTable = new dicttable(tableName2Id(tableName));

        if(!dictTable)

           throw error(strfmt("Table %1 is not found ",tableName));


        FieldName1 = dFieldName1.value();

        if(FieldName1)

            dictField1 = new dictField(dictTable.id(),fieldname2id(dictTable.id(),FieldName1));

        if(FieldName1 && !dictField1)

            throw error(strfmt("Field %1 Not found in table %2",FieldName1,tableid2name(dictTable.id())));


        FieldName2 = dFieldName2.value();

        if(FieldName2)

            dictField2 = new dictField(dictTable.id(),fieldname2id(dictTable.id(),FieldName2));

        if(FieldName2 &&!dictField2)

            throw error(strfmt("Field %1 Not found in table %2",FieldName2,tableid2name(dictTable.id())));


        FieldName3 = dFieldName3.value();

        if(FieldName3)

            dictField3 = new dictField(dictTable.id(),fieldname2id(dictTable.id(),FieldName3));

        if(FieldName3 && !dictField3)

            throw error(strfmt("Field %1 Not found in table %2",FieldName3,tableid2name(dictTable.id())));


        FieldName4 = dFieldName4.value();

        if(FieldName4)

            dictField4 = new dictField(dictTable.id(),fieldname2id(dictTable.id(),FieldName4));

        if(FieldName4 && !dictField4)

            throw error(strfmt("Field %1 Not found in table %2",FieldName4,tableid2name(dictTable.id())));


        FieldName5 = dFieldName5.value();

        if(FieldName5)

            dictField5 = new dictField(dictTable.id(),fieldname2id(dictTable.id(),FieldName5));

        if(FieldName5 && !dictField5)

            throw error(strfmt("Field %1 Not found in table %2",FieldName5,tableid2name(dictTable.id())));


        ExcelStart = dExcelStart.value();

        ExcelEnd =    dExcelEnd.value();

        if(validate())

        {

            if(winapi::pathExists(excelFilepath))//&& winapi::fileExists(excelFilepath +'test2.Xlsx'))

            {

                // reading excel

                ldA = SysExcelApplication::construct();

                ldA.visible(false);

                ldWbs = ldA.workbooks();

                ldWbs.open(excelFilepath+'\\'+'excel.Xlsx',0,true);

                ldWb = ldWbs.item(1);

                ldWss = ldWb.worksheets();

                ldws  = ldwss.itemFromName('Sheet1');

                ldCs = ldWs.cells();

                ldR = ldCs.range('A1');


                for (j=ExcelStart;j<=ExcelEnd;j++)

                {

                    progress.setCaption("Data update is in progress...");

                    progress.setAnimation(#AviUpdate);

                    progress.setTotal(ExcelEnd);

                    progress.setText(strfmt("Record %1 is been updated", j-1));

                    progress.setCount(j-1, 1);




                    ldCA         = ldCs.item(j,1);

                    NexcelField1 =  ldCA.value().bStr();

                    ldCA         = ldCs.item(j,2);

                    NexcelField2 =  ldCA.value().bStr();

                    ldCA         = ldCs.item(j,3);

                    NexcelField3 =  ldCA.value().bStr();

                    ldCA         = ldCs.item(j,4);

                    NexcelField4 =  ldCA.value().bStr();

                    ldCA         = ldCs.item(j,5);

                    NexcelField5 =  ldCA.value().bStr();

                    common = dictTable.makeRecord();

                    ttsbegin;

                    select forupdate common where common.(fieldname2id(dicttable.id(),fieldname1)) == conpeek(value(NexcelField1,type1.value(),fieldname1),1);//str2int64(NexcelField1);//;

                    if(Common)

                    {

                        if(NexcelField2 && fieldName2)

                        {

                                common.(fieldname2id(dicttable.id(),fieldname2)) = conpeek(value(NexcelField2,type2.value(),fieldname2),1);

                         }

                        if(NexcelField3 && fieldName3)

                        {

                                common.(fieldname2id(dicttable.id(),fieldname3)) = conpeek(value(NexcelField3,type3.value(),fieldname3),1);

                        }

                        if(NexcelField4 && fieldName4)

                        {

                            common.(fieldname2id(dicttable.id(),fieldname4)) = conpeek(value(NexcelField4,type4.value(),fieldname4),1);

                        }

                        if(NexcelField5 && fieldName5)

                        {

                            common.(fieldname2id(dicttable.id(),fieldname5)) = conpeek(value(NexcelField5,type5.value(),fieldname5),1);

                        }

                        common.update();

                    }

                    ttscommit;

                    common = null;

                }

                ldWbs.close();

                info(strFmt("Task has completed,Succcessfully updated %1 records",j));

            }

            else

            {

             throw error(strfmt("Please check excel path - %1",excelFilepath));

            }

        }

    }

    else

        info("Task has cancelled");



}

Feb 24, 2022

 Query to get list of all table level indexes ....


select i.[name] as index_name,

    substring(column_names, 1, len(column_names)-1) as [columns],

    case when i.[type] = 1 then 'Clustered index'

        when i.[type] = 2 then 'Nonclustered unique index'

        when i.[type] = 3 then 'XML index'

        when i.[type] = 4 then 'Spatial index'

        when i.[type] = 5 then 'Clustered columnstore index'

        when i.[type] = 6 then 'Nonclustered columnstore index'

        when i.[type] = 7 then 'Nonclustered hash index'

        end as index_type,

    case when i.is_unique = 1 then 'Unique'

        else 'Not unique' end as [unique],

    schema_name(t.schema_id) + '.' + t.[name] as table_view, 

    case when t.[type] = 'U' then 'Table'

        when t.[type] = 'V' then 'View'

        end as [object_type]

from sys.objects t

    inner join sys.indexes i

        on t.object_id = i.object_id

    cross apply (select col.[name] + ', '

                    from sys.index_columns ic

                        inner join sys.columns col

                            on ic.object_id = col.object_id

                            and ic.column_id = col.column_id

                    where ic.object_id = t.object_id

                        and ic.index_id = i.index_id

                            order by key_ordinal

                            for xml path ('') ) D (column_names)

where t.is_ms_shipped <> 1

and index_id > 0

order by i.[name]

Feb 21, 2022

A simple job to get the user related roles information

 static void HSIN_UserAndRoles(Args _args)

{

    SecurityUserRole         securityUserRole;

    SecurityRole             securityRole;

    HSecurityRoleforUser  securityRoleforUserTmp; // My own table to store the info

    boolean                  Created;


    delete_from securityRoleforUserTmp;


    while select securityRole

        join securityUserRole

            where securityUserRole.SecurityRole == securityRole.RecId &&

                  securityUserRole.User like '*'

    {

        securityRoleforUserTmp.clear();


        securityRoleforUserTmp.User     = securityUserRole.User +" "+"("+UserInfoHelp::userName(securityUserRole.User)+")";

        securityRoleforUserTmp.Role     = securityRole.AotName;

        securityRoleforUserTmp.RoleName = securityRole.Name;


        securityRoleforUserTmp.insert();

        Created = true;

    }

    if(Created)

    {

        Info(' User roles info generated  sucessfully');

    }


}

A simple job to get roles and assigned duties

 static void HRolesAndDuties(Args _args)

{

    SecurityRole            securityRole;

    SecurityRoleTaskGrant   securityRoleTaskGrant;

    SecurityTask            securityTask;

    HSecurityDutiesperUser   hsecurityDutiesperUser; // my table to store the details

    boolean                    Created;



delete_from hsecurityDutiesperUser;


    while select  securityRole

        where securityRole.AotName like '*'

            join  securityRoleTaskGrant

            where securityRoleTaskGrant.SecurityRole == securityRole.RecId

                join securityTask

                where securityTask.RecId == securityRoleTaskGrant.SecurityTask &&

                      securityTask.Type  == SecurityTaskType::Duty

    {

       hsecurityDutiesperUser.Role   = securityRole.Name;

        hsecurityDutiesperUser.Duty   = SysLabel::labelId2String(securityTask.Name) ? SysLabel::labelId2String(securityTask.Name) : securityTask.Name;

        hsecurityDutiesperUser.Type   = securityTask.Type;

        hsecurityDutiesperUser.insert();

        Created = true;


    }

    if(Created)

    {

        Info(' Roles and duties info generated successfully');

    }

}

Jul 14, 2016

Setting Hyper-v for AX7 AX7


Prerequisites :

1.Drive size : 150GB
2.RAM: 12GB(16GB recommended
3.OS: windows 8/8.1/10(PRO) or windows server 2012/2012R2
4.Office365 account

 Step 1: Run application, that extracts remaining zips, constitute to 113GB

Step 2:
1) Enable Hyper-v .
2) Search "windows Features" enable Hyper-V.
3) For Server Click on "Add roles and Features"



Step 3: Search "Hyper-V management"
Create Virtual switch network




Step 4:Create New virtual Machine





RAM size should be min 8GB, So better to enter 8000MB


 Provide the location of extracted (VHD file location)

Step 5: After successful creation of VM,

Search Hyper-V
Click connect and start
password:pass@word1

Step 6: Click on the below Icon to register User against 'Admin'

Step 7: Enter your Office 365 account ID and wait for confirmation dialogue
 
Step 8: Enter below link in browser in hyper-V and login with office365 account
https://usnconeboxax1aos.cloud.onebox.dynamics.com
 

 

Jan 29, 2016

The version of MS Excel is not supported - DMF Error

The version of MS Excel is not supported ............ DMF Error on validation.



By default we may not have 64-bit Microsoft Excel Driver installed on the local machine which causes this issue even though you may have 32-bit Microsoft Excel Driver in place. 

To resolve this we have to  install 64-bit Microsoft Excel Driver on 64-bit machine (OS) with 'Microsoft Access Database Engine 2010 Redistributable' (AccessDatabaseEngine_x64.msi) by using "/passive" argument.
 

DMF error " Exception from HRESULT: 0xC0048021 "

When I try to import the excel data by using DMF ..on "Preview source file" button click got the below error .

Exception from HRESULT: 0xC0048021  at Microsoft.Dynamics.AX.Framework.Tools.DMF.SSISHelper.DMFEntity.ShowPreview(Boolean isComposite)  at Microsoft.Dynamics.AX.Framework.Tools.DMF.SSISHelperService.Service.ServiceHelper.ShowPreview(DMFEntity entity)
 
To resolve this we need to modify DMFConfig file like below ...
 
Go to " C:\Program Files\Microsoft Dynamics AX\60\DataImportExportFramework"
 
Replace the values of
 
PipelineComponentInfo_Multicast
as {33D831DE-5DCF-48F0-B431-4D327B9E785D}
 
PipelineComponentInfo_ExcelSource
as  {9F5C585F-2F02-4622-B273-F75D52419D4A}
 
PipelineComponentInfo_ExcelDestination
as  {90E2E609-1207-4CB0-A8CE-CC7B8CFE2510}
 
 
 and save the file. ... :)
 
 
 
 
 

Dec 28, 2015

Financial Dimension Values from DefaultDimension

1. static void getsingleDimensionValue(Args _args)
{
    SalesTable                         salesTable = SalesTable::find("DAT-000002");
    Name                               _dimensionName = "Department";    
    DimensionAttributeValueSetStorage  dimStorage;
    str                                dimValue;
    Counter                            counter;
    ;

    dimStorage = DimensionAttributeValueSetStorage::find(salesTable.DefaultDimension);
                         
    for (Counter=1 ; Counter<= dimStorage.elements() ; Counter++)
    {
        if(DimensionAttribute::find(dimStorage.getAttributeByIndex(Counter)).Name == _dimensionName)
        {
            dimValue = dimStorage.getDisplayValueByIndex(Counter);
            info(dimValue);
        }
    }
}

2. DimensionValue getDimensionValue(RefRecID dimensionSetRecID,Name attributeName) 
{
    
    DimensionAttributeValueSet      dimAttrValueSet;
    DimensionAttributeValueSetItem  dimAttrValueSetItem;
    DimensionAttributeValue         dimAttrValue;
    DimensionAttribute              dimAttribute;
    
    dimAttrValueSet = DimensionAttributeValueSet::find(dimensionSetRecID);
    
    select dimAttrValueSetItem
        where   dimAttrValueSetItem.DimensionAttributeValueSet      == dimAttrValueSet.RecId
    join dimAttrValue    
        where   dimAttrValue.RecId                                  == dimAttrValueSetItem.DimensionAttributeValue
    join dimAttribute        
        where   dimAttribute.RecId                                  == dimAttrValue.DimensionAttribute
        &&      dimAttribute.Name                                   == attributeName;
    
    return dimAttrValue.getValue();        
}  

Create New Financial dimension with x++ in axapta

DimensionStorage dimensionStorage;
DimensionAttribute deparmentDimensionAttribute;
DimensionAttributeValue newDepartmentValue;

// Find the deparment dimension attribute
deparmentDimensionAttribute = DimensionAttribute::findByName("Department");  

// Find the new department value we want to put in the new combination.
newDepartmentValue = DimensionAttributeValue::findByDimensionAttributeAndValue(deparmentDimensionAttribute, "abc");

// Load a DimensionStorage instance with the old combination and update the first segment with new value
dimensionStorage = DimensionStorage::findById(ledgerTable.LedgerDimension);
dimensionStorage.setSegment(1,DimensionStorageSegment::constructFromValue("abc", newDepartmentValue));
ledgerJournalTrans.LedgerDimension = dimensionStorage.save();

Financial Dimension on Dialog through SysOperationFrameWork

 ===========================Contract Class================================
[
    DataContractAttribute,
    SysOperationContractProcessingAttribute(classstr(FindimUpUIBuilder), SysOperationDataContractProcessingMode::CreateUIBuilderForRootContractOnly)
]
public class CVRRentalDueDateReminderContract
{
    int numberOverdueDays;
    int overrideNumOfDays;
    str packedQuery;
    Name primaryDimensionFocus;
    // string value of range
    SerializedDimensionRange    serializedDimensionRanges;
    FreeText                    dimensionRange;
    InventDimViewContract       inventdimViewContract;

}


public Query getQuery()
{
    return new Query(SysOperationHelper::base64Decode(packedQuery));

}

[
    DataMemberAttribute(identifierStr(DimensionRange))
]
public FreeText parmDimensionRange(FreeText _dimensionRange = dimensionRange)
{
    dimensionRange = _dimensionRange;
    return dimensionRange;

}

public Map parmDimensionRangeMap(Map _dimensionRangeMap = null)
{
    XmlDocument xDoc;
    Map dimRangeMap;

    if (prmisDefault(_dimensionRangeMap))
    {
        if (serializedDimensionRanges)
        {
            xDoc = new XmlDocument();
            xDoc.loadXml(serializedDimensionRanges);

            dimRangeMap = Map::createFromXML(xDoc.root() as XmlNode);
        }
        else
        {
            dimRangeMap = new Map(Types::Int64, Types::String);
        }
    }
    else
    {
        if (_dimensionRangeMap == null)
        {
            _dimensionRangeMap = new Map(Types::Int64, Types::String);
        }
        else
        {
            this.parmSerializedDimensionRanges(_dimensionRangeMap.xml());
        }
        dimRangeMap = _dimensionRangeMap;
    }
    return dimRangeMap;
}



[DataMemberAttribute('InventDimViewContract')]
public InventDimViewContract parmInventDimViewContract(InventDimViewContract _inventDimViewContract = inventDimViewContract)
{
    inventDimViewContract = _inventDimViewContract;
    return inventDimViewContract;
}

 
[DataMemberAttribute('OverdueDays'),
SysOperationDisplayOrderAttribute('2')]
public int parmNumberOverdueDays(int _numberOverdueDays = numberOverdueDays)
{
;
    numberOverdueDays = _numberOverdueDays;
    return numberOverdueDays;
}

[DataMemberAttribute('OverrideNumOfDays'),
SysOperationDisplayOrderAttribute('1')]
public int parmOverrideNumOfDays(int _overrideNumOfDays = overrideNumOfDays)
{
    overrideNumOfDays = _overrideNumOfDays;
    return overrideNumOfDays;
}


[   DataMemberAttribute('PrimaryDimensionDimensionFocus'),
    SysOperationLabelAttribute(literalstr("@SYS329752")),
    SysOperationHelpTextAttribute(literalstr("@SYS307658")),
    SysOperationDisplayOrderAttribute('3')
]
public Name parmPrimaryDimensionFocus(Name _primaryDimensionFocus = primaryDimensionFocus)
{
    primaryDimensionFocus = _primaryDimensionFocus;
    return primaryDimensionFocus ;// ? primaryDimensionFocus : "MA+BU+DEPT" ;
}

 

[DataMemberAttribute,
AifQueryTypeAttribute('_packedQuery', querystr(CustTable))]
public str parmQuery(str _packedQuery = packedQuery)
{
;
    packedQuery = _packedQuery;
    return packedQuery;
}
 

[
    DataMemberAttribute(identifierStr(SerializedDimensionRanges))
]
public SerializedDimensionRange parmSerializedDimensionRanges(SerializedDimensionRange _serializedDimensionRanges = serializedDimensionRanges)
{
    serializedDimensionRanges = _serializedDimensionRanges;
    return serializedDimensionRanges;
}


public void setQuery(Query _query)
{
    packedQuery = SysOperationHelper::base64Encode(_query.pack());
}

===========================Service Class==================================

public class CVRRentalDueDateReminderService extends SysOperationServiceController
{
}


[SysEntryPointAttribute(true)]
public void checkDueDates(CVRRentalDueDateReminderContract _dueDateReminderContract)
{
    QueryRun      queryRun;
    CustTable     custTable;
    Map           dimensionRangeMap;
    MapEnumerator rangeMapEnumerator;
    RecId         dimAttrRecId;
    str           dimensionCriteria;



    dimensionRangeMap = _dueDateReminderContract.parmDimensionRangeMap();

     rangeMapEnumerator = dimensionRangeMap.getEnumerator();

     while (rangeMapEnumerator.moveNext())
    {
         dimAttrRecId = rangeMapEnumerator.currentKey();
        dimensionCriteria = rangeMapEnumerator.currentValue();
        info(dimensionCriteria);

    }
    // Get the query from the data contract
    queryRun = new QueryRun(_dueDateReminderContract.getQuery());

    while (queryRun.next())
    {
        custTable = queryRun.get(tableNum(CustTable));
        info(custTable.AccountNum + "Name = " + custTable.name());

    }
}




public CVRRentalDueDateReminderContract getCVRRentalDueDateReminderContract()
{
    return this.getDataContractObject('_CVRRentalDueDateReminderContract') as CVRRentalDueDateReminderContract;
}

public static CVRRentalDueDateReminderService construct()
{
    return new CVRRentalDueDateReminderService();
}

public static void main(Args _args)
{
    identifierName                         className, methodName;
    SysOperationExecutionMode              mode;
    CVRRentalDueDateReminderContract  contract;
    CVRRentalDueDateReminderService  reminderService ;//= CVRRentalDueDateReminderService::construct();

    [className, methodName, mode] = SysOperationServiceController::parseServiceInfo(_args);
    reminderService                    = new CVRRentalDueDateReminderService(className, methodName, mode);

    reminderService.parmDialogCaption("Vivek Testing for fin Dimension");
    contract = reminderService.getDataContractObject('CVRRentalDueDateReminderContract');
    reminderService.startOperation();
}

=========================UI Builder Class=================================


public class FindimUpUIBuilder extends SrsReportDataContractUIBuilder
{

    CVRRentalDueDateReminderContract  contract;

    DialogField dialogFieldPrimaryFocus;
    DialogGroup dialogDimensionsGroup;
    DialogField dialogFieldDetailLevel;
    Map     dimControlsMap;
    Map dimControlMap;
    Map dimRangeMap;
}

public void build()
{
     DialogField                 dimField;
    str                         thisVal;
    str                         thisLabel;
    DimensionAttributeSetItem   dimensionAttributeSetItem;
    DimensionAttribute          dimensionAttribute;
    DimensionEnumeration        dimAttrSetForLedger;
    super();
    contract = this.dataContractObject() as CVRRentalDueDateReminderContract;

    dialogDimensionsGroup = this.dialog().addGroup("@GLS101565");
    dialogDimensionsGroup.hideIfEmpty(false);

    dialogDimensionsGroup = this.dialog().addGroup("@GLS101565");
    dialogDimensionsGroup.hideIfEmpty(false);

        // Control map maps dimension attributes to physical controls
        dimControlMap = new Map(Types::Int64, Types::Class);

        // DimRangeMap map dimension attributes to ranges
       // dimRangeMap = contract.parmDimensionRangeMap();
        dimAttrSetForLedger = DimensionCache::getDimensionAttributeSetForLedger();

        while select DimensionAttribute from dimensionAttributeSetItem where dimensionAttributeSetItem.DimensionAttributeSet == dimAttrSetForLedger
            join * from dimensionAttribute where dimensionAttribute.RecId == dimensionAttributeSetItem.DimensionAttribute
        {
               //  thisVal = DimensionAttribute::find(dimensionAttributeSetItem.DimensionAttribute).Name;

                thisVal = '';

            thisLabel = dimensionAttribute.localizedName();

            dimField = this.dialog().addFieldValue(extendedTypeStr(String255), thisVal, thisLabel);
            dimField.registerOverrideMethod(methodstr(FormStringControl, lookup), methodstr(LedgerTrialBalanceUIBuilder, lookupDimensionAttribute), this);

            dimControlMap.insert(dimensionAttributeSetItem.DimensionAttribute, dimField);
        }
        //IfFin dim show based on dimension set you should pass set name in below parm
         this.updateForFocus(contract.parmPrimaryDimensionFocus());
}
///
/// Implements a custom lookup for dimension attribute.
///
///
/// The FormStringControl for which the lookup fields must be associated.
///
///
/// It uses the DimensionAttribute table for lookup.
///
private void lookupDimensionAttribute(FormStringControl _dimensionValue)
{
    Args                    e;
    FormRun                 lookupFormRun;
    DimensionAttribute      dimAttr;
    Object                  object;

    if (_dimensionValue != null)
    {
        // Construct arguments for the custom lookup
        e = new Args();
        e.name(formStr(DimensionDefaultingLookup));
        e.lookupValue(_dimensionValue.text());
        e.caller(_dimensionValue);

        // Find the dimension attribute associated with the string control which called this method
        dimAttr = DimensionAttribute::findByLocalizedName(_dimensionValue.label());
        e.lookupField(dimAttr.ValueAttribute);
        e.record(dimAttr);

        // Run the custom lookup and init the lookup form
        lookupFormRun = classfactory.formRunClass(e);
        lookupFormRun.init();

        // Specify this is the callback on the lookup form by casting the
        // form to an object and late binding the setResultCallback method
        if (SysFormRun::hasMethod(lookupFormRun, identifierStr(setResultCallback)))
        {
            object = lookupFormRun;
            object.setResultCallback(this);
        }

        _dimensionValue.performFormLookup(lookupFormRun);
    }
}

///
/// Override this method in order to register the dialog field methods to capture events.
///
public void postRun()
{
    DialogField dialogFieldSecondaryFocus;
    Dialog dialogLocal = this.dialog();

    super();

    // This method should be called in order to handle events on dialogs.
   // dialogLocal.dialogForm().formRun().controlMethodOverload(false);

    // dimension sets
   // dialogFieldPrimaryFocus = this.bindInfo().getDialogField(this.dataContractObject(), methodstr(LedgerTrialBalanceContract, parmPrimaryDimensionFocus));
   // dialogFieldPrimaryFocus.registerOverrideMethod(methodstr(FormStringControl, lookup), methodstr(LedgerTrialBalanceUIBuilder, dimensionSetLookup), this);
   // dialogFieldPrimaryFocus.registerOverrideMethod(methodstr(FormStringControl, modified), methodstr(LedgerTrialBalanceUIBuilder, dimensionSetModified), this);
}

public void setDimensionAttributeValue(DimensionAttribute _dimensionAttribute, RecId _dimAttrValueRecId, str _value)
{
    // Force a save of the set(s) as the user may leave the tab at any point and no event will be raised to force a savedimControlMap
}
 
///
/// Updates the dialog fields for the dimension hierarchy.
///
///
/// The dimension hierarchy name.
///
public void updateForFocus(Name _dimensionHierarchyName = '')
{
    RecId                   dimHierarchyRecId;
    MapEnumerator           controlMapEnumerator;
    DimensionHierarchyLevel dimHierarchyLevel;
    boolean                 setHasDimension;
    DialogField             dimField;
    RecId                   dimAttrRecId;
    boolean                 anyDimensionsVisible;

     dimHierarchyRecId = DimensionHierarchy::findByTypeAndName(DimensionHierarchyType::Focus, _dimensionHierarchyName).RecId;

        // Clear out existing dialog fields
        controlMapEnumerator = dimControlMap.getEnumerator();
        while (controlMapEnumerator.moveNext())
        {
            dimAttrRecId = controlMapEnumerator.currentKey();
            dimField = controlMapEnumerator.currentValue();

            setHasDimension = false;

            if (dimHierarchyRecId)
            {
                    select firstOnly RecId from dimHierarchyLevel where
                        dimHierarchyLevel.DimensionHierarchy == dimHierarchyRecId &&
                        dimHierarchyLevel.DimensionAttribute == dimAttrRecId;

                setHasDimension = (dimHierarchyLevel.RecId != 0);
            }
            else
            {
                 select firstOnly RecId from dimHierarchyLevel where
                        dimHierarchyLevel.DimensionAttribute == dimAttrRecId;

                setHasDimension = (dimHierarchyLevel.RecId != 0);
            }

            dimField.visible(setHasDimension);
            anyDimensionsVisible = anyDimensionsVisible || setHasDimension;
        }

        dialogDimensionsGroup.visible(anyDimensionsVisible);

}

 

 

Dec 10, 2015

Cross reference update Job for AX objects

static void XRefUpdateBatch(Args _args)
{
    ;
    xRefUpdate::truncateXrefTables();
    xRefUpdateIL::updateAllXref(true, false, true);
    info("Cross reference update batch job created.");
}

Dec 9, 2015

Toggling administrative privileges in AX 2012 R3 through code

static void ToggleAdminMode(Args _args)
{
    ;   
    SecurityUtil::sysAdminMode(!SecurityUtil::sysAdminMode());
    info(strFmt('Admin mode: %1', SecurityUtil::sysAdminMode()));
}

Note :- Once you restart the AX client, your privileges will be restored to normal.

Dec 7, 2015

Generate Xml file for XDS class in AX


static void GenerateXSDSchema_AxdCustTable(Args _args)
{

AxdCustTable    AxdCustTable;
XML             xml;
XMLDocument     xmlDocument;

;
AxdCustTable = AxdBase::newClassId(classnum(AxdCustTable));
xml          = AxdCustTable.getSchema();
xmlDocument  = XMLDocument::newXML(xml);
 
//TODO Select file to write XML output to
xmlDocument.save("D:\\XSDSchema_AxdCustTable.xml");

}