Tuesday 8 November 2016

Get company address through code in AX.

static void getCompanyAddress(Args _args)
{
    CompanyInfo companyInfo;
    DirPartyPostalAddressView postalAddressView;
    ;

    companyInfo = companyInfo::find();

    select firstFast postalAddressView
        where postalAddressView.Location == companyInfo.PrimaryAddressLocation;

    info(companyInfo.Name+ "," +postalAddressView.Address);
}

Get company information in AX 2012 using X++.

static void getCompanyInfo(Args _args)
{
    CompanyInfo companyInfo;
    Description tel,fax,Email,URL;
    ;

    companyInfo = companyInfo::find();

    Email = LogisticsElectronicAddress::findRecId(companyInfo.PrimaryContactEmail).Locator;
    fax = LogisticsElectronicAddress::findRecId(companyInfo.PrimaryContactFax).Locator;
    tel = LogisticsElectronicAddress::findRecId(companyInfo.PrimaryContactPhone).Locator;
    url = LogisticsElectronicAddress::findRecId(companyInfo.PrimaryContactURL).Locator;
 
    info(strFmt("Email - %1, Fax - %2, Tel - %3, URL - %4",Email,fax,tel,URL));
}

Change date format in AX



static void dateFormat(Args _args)
{
    info(strFmt("Today date is " +date2str(today(),123,DateDay::Digits2,DateSeparator::Hyphen,
        DateMonth::Short,DateSeparator::Hyphen,DateYear::Digits4)));
}

Monday 10 October 2016

str2date function in AX.

static void str2Date(Args _arg)
{
    date d;
    ;
   
    d = str2Date("10/10/2016", 123);
   
    info(strFmt('%1', d));
    info(strFmt('%1', mkDate(dayOfMth(d), mthOfYr(d), year(d))));
}

Friday 7 October 2016

strLen Function in AX.

strLen Function

Calculates the length of the specified string.

Syntax: int strLen(str text)

Example:

print strLen("prash");
pause;

Result : 5

strKeep Function in AX.

strKeep Function

Builds a string from only the characters in the first input string that are specified to be kept by the second string.
Or
Shows only specifield value of string

Syntax: str strKeep(str _text1, str _text2)

Example:

info(strKeep("prashant","pra"));

Result : praa

strIns Function in AX.

strIns Function

Builds a string by inserting one string into another.
Syntax: str strIns(str _text1, str _text2, int _position)

Example:

info(strIns("prashant","pra",3));

Result : prpraashant

strDel Function in AX.

strDel Function

Creates a copy of a string with the specified substring removed.

Syntax:
str strDel(
    str _text,
    int _position,
    int _number)

Example:

using strDel function Note: removes 2 letters from 4th letter onwards

info(strDel("Prashant",4,2));

Result : Praant

info(strDel("Prashant",4,-3));

Result : Phant

strColSeq Function in AX.

strColSeq Function

Converts all uppercase characters to lowercase characters and also converts all special  design characters like (ÁÎ to ai) to lowercase characters

Syntax:
str strColSeq(str text)

Example:
info(strColSeq("AbçDËãBCdé"));

Result : abcdeabcde

strCmp Function in AX.

strCmp Function 

Compares two text strings.

Note: 0 if the two strings are identical, 1 if the first string sorts earlier, or -1 if the second string sorts earlier.

Syntax:
int strCmp(str text1, str text2)
The comparison performed by this method is case-sensitive.

Example:
print strCmp("prash","prash");
pause;

Result :  returns 0 if two strings are identical

print strCmp("prash","PRA");
pause;

Result :  returns 1 if first string is executed first;

print strCmp("ddd","kkk");
pause;

Result : returns 1 if the second string executed first;

print strCmp("hhh","ooo");
pause;

Result : returns -1 if the second string executed first;

strAlpha Function in AX.

strAlpha Function

Copies only the alphanumeric characters from a string.

Syntax:
str strAlpha(str _text)

Example:
info(strAlpha("prashant123$&@"));

Result : prashant123

update_recordset in AX 2012.


The X++ SQL statement update_recordset enables you to update multiple rows in a single trip to the server.


Example :-

TestTable testTableBuffer;
;

update_recordset testTableBuffer
setting field1 = field1 * 10;

insert_recordset in AX 2012.

Insert_recordset copies data from one or more tables directly into one resulting destination table on a single server trip.
Using insert_recordset is faster than using an array insert. However,
array inserts are more flexible if you want to handle the data before you insert it.

insert_recordset is a record set-based operator, which performs operations on multiple records at a time.
However, it can fall back to record-by-record operations in many situations.

Syntax :-

insert_recordset  DestinationTable  (  ListOfFields  )
select  ListOfFields1  from  SourceTable  [ where  WhereClause  ]
[ join  ListOfFields2  from  JoinedSourceTable 
[ where  JoinedWhereClause  ]]

RecordInsertList class in AX.


This class allows you to insert more than one record into the database at a time,
which reduces communication between the application and the database.

------------------------------------------------------------------------------------------------

void copyBOM(BOMId _FromBOM, BOMId _ToBOM)
{
    RecordInsertList BOMList;
    BOM BOM, newBOM;

    BOMList = new RecordInsertList(tableNum(BOM));

    While select BOM
             where BOM.BOMId == _FromBOM
    {
            newBOM.data(BOM);
            newBOM.BOMId = _ToBOM;
           BOMList.add(newBOM);
    }

    BOMList.insertDatabase();
}

ChangeCompany in Microsoft dynamics ax 2012.


The changeCompany statement is used to alter the database settings to another (separate) company. The syntax of the statement is:

changeCompany ( Expression ) Statement


static void changeCompany(Args _arg)
{
    VendTable vendTable;
    ;

    // Assume that you are running in company 'Test'.
    changeCompany('Test1') // Default company is now 'Test1'.
    {
        vendTable = null;
        while select vendTable
        {
            // vendTable is now selected in company 'Test1'.
        }
    }
    // Default company is again set back to 'Test'.

    changeCompany('Test2') // Default company is now 'Test2'.
    {
 
        // Clear vendTable to let the select work
        // on the new default company.
        vendTable = null;
 

        while select vendTable
        {
            // vendTable is now selected in company 'Test2'.
        }
    }
    // Default company is again 'Test'.
}

Get the Current Company in Dynamics AX

Get the Current Company in Dynamics AX.


Many times we required to get current company in our code.

To get the current company you can use curExt() frunction in AX.


static void getCurCompany(Args _arg)
{
     str company;
     ;

     company = curExt();

     Info(company);
}

Sunday 2 October 2016

Form Templates in AX 2012

There are seven different predefined form templates in ax 2012.
  • ListPage
  • DetailsFormMaster
  • DetailsFormTransaction
  • SimpleListDetails
  • SimpleList
  • TableOfContents
  • Dialog
  • DropDialog
ListPage – A list page is a form that displays a list of data related to a particular entity or business object. A list page provides provisions for displaying data and taking actions on this data. Every module has at least a couple of list pages. List pages are further classified as primary and secondary list pages. A secondary list page will only display a subset of data from the primary list page. Example, CustTableListPage, VendTableListPage, ProjProjectsListPage. Best practice is to have ListPage as a suffix in the name of the form for all list pages.
DetailsFormMaster: This template is used for forms which display data for stand-alone entities or business objects. Example includes Customers, Vendors, and Projects etc. If you look at the forms for these, i.e. CustTable, VendTable, ProjTable, their style property will be set to DetailsFormMaster.
DetailsFormTransaction: This template is used for forms which display data for entities which have child records associated with it. In other words, if the data being displayed is header-lines type in nature, use this template. Example, Sales orders, Purchase orders etc. If you look at the style property of SalesTable, VendTable, their properties will be set to DetailsFormTransaction.
SimpleListDetails – This template is used to display primary fields in a list and detailed data in a tab page. This style is useful to view all records in a form and selecting a particular record will bring up their details. Example includes HcmSkillMapping, etc.
SimpleList – This template is a very basic form which displays data in a grid. No extra or fancy detail is displayed. This style is best suited for forms where data being shown is not very detailed in nature or has limited fields. Example includes AifAction, etc.
TableOfContents – This template is the new style which should be adopted for all parameter forms in Dynamics AX 2012. Take a look at any parameters form and its style property will be set to TableOfContents. This style sets all the tabs as a hot link in the left hand side navigation pane. Clicking on the link will bring up the controls on that tab page. This style is a very neat and appealing UI design which is surely welcome. Example includes Custparameters, vendparameters, etc.
Dialog – This template is used on forms which show static data or are intended to capture some user input for further actions. These forms are mostly modal in nature and should be dismissed before any further actions can be taken.
DropDialog – This template is used for forms that are used to gather quick user inputs to perform an action. Drop dialog forms are generally attached to an action pane button. They appear to be dropping from the menu button when clicked. Example includes HcmWorkerNewWorker,  HcmPositionWorkerAssignmentDialog.
Whenever going for a new form development, always ensure that you use the template to create a new form. The template almost does 40% of your design work for you. All you have to do is add the data sources and fields and add business logic.

Thursday 22 September 2016

Create Free Text Invoice in AX using X++

static void CreateFreeTextInvoice(Args _args)
{
    CustInvoiceTable    custInvoiceTable;
    CustInvoiceLine     custInvoiceLine;
    CustTable           custTable;
    CustPostInvoice     custPostInvoice;
    LineNum             lineNum;
    ;

    custTable = CustTable::find('******');
    custInvoiceTable.clear();
    custInvoiceTable.initFromCustTable(custTable);
    custInvoiceTable.insert();

    custInvoiceLine.clear();
    custInvoiceLine.initValue();
    custInvoiceLine.LedgerDimension =  123456;
    custInvoiceLine.initFromCustInvoiceTable(custInvoiceTable);
    custInvoiceLine.AmountCur = 101.00;
    custInvoiceLine.Description = "Test";
    custInvoiceLine.TaxItemGroup = "";
    custInvoiceLine.ParentRecId = custInvoiceTable.RecId;

    if(!lineNum)
        lineNum = CustInvoiceLine::lastLineNum_W(custInvoiceLine.ParentRecId);

    lineNum += 1;
    custInvoiceLine.LineNum = lineNum;
    custInvoiceLine.insert();

    custPostInvoice = new CustPostInvoice(custInvoiceTable);
    custPostInvoice.run();
}

Get LedgerDimension for Vendor and Customer in AX

For Customer:-

DimensionStorage::getDynamicAccount(AccountNum, LedgerJournalACType::Cust)



For Vendor:-

DimensionStorage::getDynamicAccount(AccountNum, LedgerJournalACType::Vend)

Create output order in AX using X++.

static void createOutputOrder(Args _args)
{
    InventJournalTable journalTable;
    InventJournalTrans journalTrans;
    InventMovement inventMovement;
    WMSOrderCreate wmsOrderCreate;
    ;

    while select journalTable
        where journalTable.JournalType == InventJournalType::Transfer
           //&& journalTable.JournalId == "********"   ------------------------------------------- For Specific Journal
    {
        while select journalTrans
            where JournalTrans.JournalId == journalTable.JournalId
        {
            inventMovement = InventMovement::construct(journalTrans);

            wmsOrderCreate = WMSOrderCreate::newMovement(inventMovement, journalTrans.Qty);
            wmsOrderCreate.parmMustBeWMSOrderControlled(true);
            wmsOrderCreate.parmQty(journalTrans.Qty);
            wmsOrderCreate.parmRecalculateMaxQtyForValidation(false);
            wmsOrderCreate.parmWMSOrderType(WMSOrderType::Output);
            wmsOrderCreate.parmMaxCWQty(journalTrans.Qty);
            wmsOrderCreate.parmMaxQty(journalTrans.Qty);
            wmsOrderCreate.run();
         }
    }
}

Thursday 30 June 2016

Layers comparison in AX 4.0, AX 2009 and AX 2012





How we can find database size in AX 2012 using X++

By using following code, we can find database size in AX using code.

static void dBSize(Args _args)
{
    LoginProperty loginProperty;
    ODBCConnection odbcConnection;
    Resultset resultSet;
    Statement statement;
    SysSQLSystemInfo systemInfo;
    str sqlStatement;
    real size;
    ;
 
    systemInfo = SysSQLSystemInfo::construct();
    sqlStatement = strfmt( "SELECT size FROM sys.master_files where name = '%1'",systemInfo.getloginDatabase());
 
    loginProperty = new LoginProperty();
    loginProperty.setServer(systemInfo.getLoginServer());
    loginProperty.setDatabase(systemInfo.getloginDatabase());

    odbcConnection = new ODBCConnection(loginProperty);

    statement = odbcConnection.createStatement();
    resultSet = statement.executeQuery(sqlStatement);

    while (resultSet.next())
    {
        size = str2int(resultSet.getString(1));
        size = size*8 /1024;
        info(strfmt("%1  MB",size));
    }
}

Wednesday 29 June 2016

Create production order in AX using X++

static void CreateProductionOrder(Args _args)
{
    ProdQty         qty     = 50;
    ItemId          item    = '1234';
    ProdTable       prodtable;
    InventTable     inventTable;
    InventDim       inventDim;
    ;
    // Initialize InventTable
    inventTable = inventTable::find(item);
    // Initialize the base values
    prodtable.initValue();
    prodtable.initFromInventTable(inventTable);
    prodtable.ItemId                = inventTable.ItemId;
    prodtable.DlvDate               = today();
    prodtable.QtySched              = qty;
    prodtable.RemainInventPhysical  = qty;
    // Initialize InventDim (Obrigatory)
    inventDim.initValue();
    // Set the active BOM and Route
    prodtable.BOMId = BOMVersion::findActive(prodtable.ItemId,
                                             prodtable.BOMDate,
                                             prodtable.QtySched,
                                             inventDim).BOMId;
    prodtable.RouteId = RouteVersion::findActive(prodtable.ItemId,
                                                 prodtable.BOMDate,
                                                 prodtable.QtySched,
                                                 inventDim).RouteId;
    // Initialize BOMVersion
    prodtable.initBOMVersion();
    // Initialize RouteVersion
    prodtable.initRouteVersion();
    //Use ProdTableType class to create the production order
    prodtable.type().insert();
    // Inform Production Order Id
    setPrefix( 'Production Order');
    setPrefix( 'Production Order Number');
    info(prodtable.ProdId);
}