Wednesday, 9 December 2015

To Export a model using command prompt:

1. Open command prompt as run as administrator
2. change the directory to management utilities 
for ex: if the managementUtilities are present in E:\Program Files\Microsoft Dynamics AX\60\ManagementUtilities
3. change directory to E drive using cd E:
4. once the directory is changed enter the command E:> E:\Program Files\Microsoft Dynamics AX\60\ManagementUtilities
5. E:\Program Files\Microsoft Dynamics AX\60\ManagementUtilities> axutil export /model:DES /file:BPCheck (where DES is the existing model and BPCheck is the filename we need to export) 
Finally the model will be exported to E:\Program Files\Microsoft Dynamics AX\60\ManagementUtilities.

Friday, 4 December 2015

To Find the phone number of the customer:


    LogisticsElectronicAddress LogisticsElectronicAddress;
    DirPartyLocation DirPartyLocation;
    int contactPhoneCounter = 0;

    while select Locator from LogisticsElectronicAddress exists join DirPartyLocation
    where
    DirPartyLocation.Party == _custInvoiceJour.custTable_InvoiceAccount().Party
    &&
    DirPartyLocation.location == LogisticsElectronicAddress.location
    && LogisticsElectronicAddress.type == LogisticsElectronicAddressMethodType::Phone
    {
        contactPhoneCounter++;
        if (contactPhoneCounter==1)
        {
                cachedCompanyContactPhone1 = LogisticsElectronicAddress.Locator;
        }
        else if (contactPhoneCounter==2)
        {
            cachedCompanyContactPhone2 = LogisticsElectronicAddress.Locator;
        }
        else
        {
            break;
        }
    }

Thursday, 26 November 2015

Code to find Dimension Name:


public name hsGetDepartmentName(DimensionDefault  _dimensionDefault)
        {
             str                                 name;
              DimensionAttributeValueSetItem      valueSetItem; 
              DimensionAttribute                  dimAttribute; 
              DimensionAttributeValue             dimAttributeValue; 
            //Getting the Department name for the record.
              select DimensionAttributeValueSet from valueSetItem 
                    where valueSetItem.DimensionAttributeValueSet == _dimensionDefault 
                            join RecId from dimAttributeValue 
                                where valueSetItem.DimensionAttributeValue == dimAttributeValue.RecId 
                                    join RecId from dimAttribute 
                                        where dimAttributeValue.DimensionAttribute == dimAttribute.RecId 
                                              && dimAttribute.Name == enum2str(sysdimension::Department);
        
             name = DimensionAttributeValue::find(dimAttributeValue.RecId).getName();
        
            return name;
        }

To import demo data in AX 2012 R3:

1.       Install Test data transfer tool
2.       Open command prompt as administrator and then  cd\ C:\Program Files (x86)\Microsoft Dynamics AX 2012 Test Data Transfer Tool (Beta)
3.       Then type dp.exe import C:\Program Files (x86)\Microsoft Dynamics AX 2012 Test Data Transfer Tool (Beta) servername\axinstance name

Job for generating parm methods:


static void CreateAxBCParmMethod(Args _args)
{
    axGenerateAxBCClass axGenerateAxBCClass;

    axGenerateAxBCClass = AxGenerateAxBCClass::newTableId(tablenum(PurchReqLine));//tablenum can be the table                                                                                   //for which we want to generate                                                                                 //parm methods
    axGenerateAxBCClass.run();

}

Filter by field in ax 2012:

To have filter by filed option in ax 2012, we need to override context method at the control level in the design as shown below.

public void context()
{
    int             selectedMenu;
    formrun         fr;
    Args            ag;
    Name            strtext;
    querybuilddataSource qb1, qb2, qb3;
    classFactory    cf;
    query       q;
    #define.SysFormSearch('SysFormSearch')
    #define.FindEdit('FindEdit')
    PopupMenu menu = new PopupMenu(element.hWnd());
    int a = menu.insertItem("@DES212");
    int c = menu.insertItem("@DES213");
    ;

    selectedMenu = menu.draw();
    switch (selectedMenu)
    {
    case -1: //Filter by field
            break;
    case a:
            ag = new args(#SysFormSearch);
            cf = new classFactory();
            fr = cf.formRunClass(ag);
            fr.run();
            fr.wait();
//Reading User entered value for filter process
            strtext = fr.design().controlName(#FindEdit).valueStr();
            if(strtext)
            {
//Creating a query for filter
                q   = custVendExternalItem_ds.query();
                qb1 = q.dataSourceTable(tablenum(custVendExternalItem));
                qb1 = qb1.addDataSource(TableNum(InventTable));
                qb1.addLink(FieldNum(custVendExternalItem,ItemId),FieldNum(InventTable,ItemId));
                qb2 = qb1.addDataSource(tableNum(EcoResProduct));
                qb2.relations(true);
                qb3 = qb2.addDataSource(tableNum(EcoResProductTranslation));
                qb3.relations(true);
                qb3.addRange(FieldNum(EcoResProductTranslation,Name)).value(strtext);
                custVendExternalItem_ds.query(Q);
                custVendExternalItem_ds.executeQuery();
            }
            break;

    case c :   // Remove Filter
            q = new Query();
            qb1 = q.addDataSource(tableNum(custVendExternalItem));
            qb1.addRange(fieldNum(custVendExternalItem, ModuleType)).value(strfmt("%1,%2",enum2str(ModuleInventPurchSalesVendCustGroup::Vend),
                enum2str(ModuleInventPurchSalesVendCustGroup::VendGroup)));
            custVendExternalItem_ds.query(Q);
            custVendExternalItem_ds.executeQuery();

            break;

    Default:
            break;
    }

}

Refreshing form part through listpage form and normal form


Problem description: Form parts in Dynamics AX usually make use of linked data sources to activate changes. However there may the case that your form part does not have a direct datasource link to the parent form or simply needs to activate code to populate the info displayed. In this case one needs a mechanism to call code on the form part when the record on the parent form is changed.
Solution: To resolve the issue one needs to create method call-backs between the two forms. Two approaches need to be followed based on whether the form part has been added to a list page or to a normal form.
Standard forms
  1. Create your form and form parts.
  2. Add your form part to your main form
  3. On your main form create a reference to your form part in the class declaration e.g. Object _part;
  4. Create a method on your main form e.g. “registerForChange(Object _part); with the following code:public void registerForChange(Object _part){
        part = _part;
    }
    This method will allow your form part to provide a reference of itself to the main form.
  5. On your form part’s init method. Call this method register call the above method passing itself as a reference. Note: you will need to perform step #4 on all forms that will use this form part.
    public void init()
    {
        Object caller;    caller= args.caller();    if(caller)    {
            caller.registerForChange(this)    }
    }
  6. On your form part create an doRefresh method, your main form will call this method whenever a form part refresh is needed. This method can have an parameter that your would like the main form to pass through. In this example we will pass the active record from the main form  E.G.publicvoid doRefresh(Common _record){
    //Do custom form part refresh.
    }
  7. Finally, on your main form, call the the method in #6 at the appropriate time. In this example calling “part.doRefresh(myTable);” in the myTable datasource’s active method works well. You could also do your call from a button on the main form or on any other trigger.
ListPage variation
If you are planning on using the form part as part of a list page. You need to make the following adjustments.
  1. Create a reference to your part in the list page’s ListPageInteractionClass’ ClassDeclaration e.g. Object part;
  2. For step #4 add the “registerForChange” to your list page’s ListPageInteractionClass
  3. For step #5 detect whether your part is being called from a ListPage or a normal form: E.G.
    public void init()
    {
        Object caller;    SysSetupFormRun formRun;
    super();
        caller= this.args().caller();    if(caller)    {
    formRun = caller;
    if (formRun.pageInteraction())
    {
    caller = formRun.pageInteraction();
    caller
    .registerForChange(this);        } else
    {
    caller.registerForChange(this);
    }
    }
    }
  4. On the relevant method in your list page interaction class call the part’s doRefresh method. For this example use the selectionChanged method
    public void selectionChanged()
    {
    ListPage listPage = this.listPage();
    if (listPage.activeRecord(“MyTable”))
    {
    part.doRefresh(listPage.activeRecord(“MyTable”));
    }
    }

To connect to External database below is the sample code:


public static void renameCustAccountsinRetailDB(CustAccount _oldName = "",
                                                CustAccount _newName = "" )
{
    #OCCRetryCount
    LoginProperty                 loginProperty;
    OdbcConnection                odbcConnection;
    Statement                     statement;
    ResultSet                     resultSet;
    str                           sql;
    SqlStatementExecutePermission perm;
    Map           mapRetailTables  =  new Map(Types::String,Types::String);
    MapEnumerator enumerator;

    mapRetailTables.insert('POSTRANSACTION','CUSTACCOUNT');
    mapRetailTables.insert('RETAILPUBRETAILCHANNELTABLE','DEFAULTCUSTACCOUNT');
    mapRetailTables.insert('RETAILCOUPONISSUERTABLE','CUSTACCOUNT');
    mapRetailTables.insert('RETAILCHANNELTABLE','DEFAULTCUSTACCOUNT');
    mapRetailTables.insert('RETAILPUBRETAILSTORETABLE','USEDEFAULTCUSTACCOUNT');
    mapRetailTables.insert('RETAILTRANSACTIONLOYALTYREWARDPOINTTRANS','CUSTACCOUNT');
    mapRetailTables.insert('RETAILTRANSACTIONTABLE','CUSTACCOUNT');
    mapRetailTables.insert('RETAILSTORETABLE','USEDEFAULTCUSTACCOUNT');
    mapRetailTables.insert('RETAILTRANSACTIONSALESTRANS','CUSTACCOUNT');
    mapRetailTables.insert('RETAILCUSTAFFILIATION','CUSTACCOUNTNUM');

    //ODBC Conection
    //Set information on the ODBC
    loginProperty = new LoginProperty();
    loginProperty.setDSN("RetailDSN");
    loginProperty.setDatabase("SICCSTOREDB2");
    try
    {
        //Create connection to external DB
        odbcConnection = new OdbcConnection(loginProperty);

        if (odbcConnection)
        {

            while (enumerator.moveNext())
            {
                sql = "update "+ enumerator.currentKey() +" set "+ enumerator.currentValue()+" ="+ _newName+" where "+enumerator.currentValue()+" ="+ _oldName;

                //assert permission for sql string
                perm = new SqlStatementExecutePermission(sql);

                perm.assert();

                //Prepare statement
                statement = odbcConnection.createStatement();
                resultSet = statement.executeQuery(sql);
            }
            resultSet.close();
            statement.close();
        }
        else
        {
            error("Failed to log on to the database");
        }
    }
    catch
    {
        throw error(" Please try again");
    }
}

To Compile AX 2012 R3 through command prompt:


axbuild.exe xppcompileall /aos=01 /altbin="E:\Program Files (x86)\Microsoft Dynamics AX\60\Client\Bin" /workers=6

Wednesday, 24 June 2015

Generate file name with current date and time(CSV or Textfile)
Below code will be useful


dateTime = strfmt("%1 %2",date2str(systemdateget(),321,2,0,2,0,4,dateflags::none),time2str(timenow(),Timeseparator::Colon,timeformat::hour24));
Date getting one day less in HCMEmploymentEmployee table because of the timezone.
Following syntax will resolve this issue.

probationDate = DateTimeUtil::date(DateTimeUtil::applyTimeZoneoffset (hcmEmploymentEmployee.ProbationEndDate, DateTimeUtil::getUserPreferredTimeZone()));