Search This Blog

Monday, September 19, 2011

IS and AS Keywords Introduced in AX2012

In Microsoft Dynamics AX2012, the X++ language provides the as and is expression operators to control downcast assignments. Downcast assignments involve class or table inheritance.

Assignment statements that implicitly downcast can cause errors that are hard for the programmer to predict or diagnose.

 You can use the as keyword to make your downcasts explicit.
You can use the is keyword to test whether a downcast is valid at run time.
as Example
static void AsTestJob33(Args _args)
{
    
    BaseClass basec; 
    DerivedClass derivedc;

    BottomClass bottomc; ;

    derivedc = new DerivedClass();

    basec = derivedc;

    derivedc = basec as DerivedClass;

    bottomc = new BottomClass();
    bottomc = basec as DerivedClass;
}

is Example

static void IsKeywordJob46(Args _args) 
{
    DerivedClass derivedc;
    BaseClass basec;

    basec = new DerivedClass();  // An upcast.
    if (basec IS DerivedClass)
    {
        info("Test 1: (basec IS DerivedClass) is true. Good.");
        derivedc = basec AS DerivedClass;
    }

    basec = new BaseClass();
    if (!(basec IS DerivedClass))
    {
        info("Test 2: (!(basec IS DerivedClass) is true. Good."));
    }
}

AX 2012 TempDB Tables

In Microsoft Dynamics AX, one type of temporary table is a TempDB table.

We call them TempDB tables because their TableType property value is TempDB. This value comes from the TableType::TempDB enum value. The TableType property value can be set at AOT > Data Dictionary > Tables > MyTempDBTable > Properties > TableType.

Only processes that run on the server tier can instantiate TempDB tables.

Following Sample will give the little picture about how to use the TempDb Tables

Create the Class with this main method and Run the class
server public static void main(Args _args)
{
    MyTempdb MyTempdb;
    CustTable custTable;
    TableType tableTypeEnum;
    str stringWork;
    ;
   
    info("Start of main.");
    MyTempdb;.AccountNum = "4004";
    MyTempdb;.doInsert();
    MyTempdb;.AccountNum = "4005";
    MyTempdb;.doInsert();
    tableTypeEnum = MyTempdb;.getTableType();
    stringWork = "MyTempdb.TableType is: " + enum2Str(tableTypeEnum);
    info(stringWork);
    while select *
            from custTable
                JOIN MyTempdb;
            where
                MyTempdb;.AccountNum == custTable.AccountNum
    {
        stringWork = custTable.AccountNum
                + " , "
                + int2Str(custTable.MandatoryCreditLimit);
        info(stringWork);
    }
}

BP Deviation Update for AOT while Upgrading

Following job is used to update the methods with the BP Deviation documented while upgrading from one version to another version.
This job is used to update for tables,Classes,Views,FormMethods,ReportMethods.

This wont update at the datasource for forms or reports level.

static void krishh_AddBPDeviationDocumented(Args _args)
{
    TreeNode            node;

    TreeNode            childNode;
    TreeNodeIterator    nodeIt;
    FilePath            path;
    str filter,filter1;
    str BPFix='//BP Deviation Documented';
    str firstLine;
    List listSource=new List(Types::String);
    ListIterator listIterator;
    str BPFixFind='//BP Deviation Documented*';

    ;

    filter='*display*';
    filter1='*edit*';

    path        = @'\Data dictionary\tables\CustTable';
   // path        = @'\Data dictionary\views\CustTable';
    //path=@'\Classes';
    //path=@\Forms';
    path += '\\Methods';

    node        = TreeNode::findNode(path);
    nodeIt      = node.AOTiterator();

    childNode   = nodeIt.next();
    if(childNode.AOTLayer()==UtilEntryLevel::var)
    {
        while(childNode)
        {
            listSource=Global::strSplit(childNode.AOTgetSource(),'()');
            listIterator=new listIterator(listSource);
            if(listIterator.more())
            {
               if(firstLine like BPFixFind)
               {
                   info(strFmt('Table.Method:%1.%2 is already BP Deviated',childNode.AOTparent(),childNode.AOTname()));
               }
               else
                {
                  if((firstLine like filter) || (firstLine like filter1))
                    {
                        childNode.AOTsetSource(BPFix+"\n"+ childNode.AOTgetSource());
                        childNode.AOTcompile();
                        childNode.AOTsave();
                    }
                }
            }
            childNode = nodeIt.next();
        }
    }
}

Excute Query using X++

static void krishh_RunQueryFormusingCode(Args _args)
{
    QueryRun    SalesQuotationUpdate;
    SalesQuotationTable SalesQuotationTable;
    ;
    SalesQuotationUpdate = new QueryRun(QueryStr(SalesQuotationUpdate));
    if (SalesQuotationUpdate.prompt())
    {
        while (SalesQuotationUpdate.next())
        {
            if (SalesQuotationUpdate.changed(tablenum(SalesQuotationTable)))
            {
                SalesQuotationTable = SalesQuotationUpdate.get(
                    tablenum(SalesQuotationTable));
                info(SalesQuotationTable.QuotationId);
            }
        }
    }
}

Expressions in QueryRanges

static void krishh_ExpressionInQuery(Args _args)
{
    Query q = new Query(); 
    QueryRun qr;
    CustTable ct;
    QueryBuildDataSource qbr1;
    ;
    qbr1 = q.addDataSource(tablenum(CustTable));
    qbr1.name("Customer");
    qbr1.addRange(fieldNum(CustTable, AccountNum)).value(
    strFmt('((%1.%2 == "4000") || (%1.%3 == "The Bulb"))',
        qbr1.name(),
        fieldStr(CustTable, AccountNum),
        fieldStr(CustTable, Name)));
       info(qbr1.toString());
    qr = new QueryRun(q);
    while (qr.next())
    {
        if (qr.changedNo(1))
        {
            ct = qr.getNo(1);
            info(strfmt('CustomerAccountNum=%1 And Customer Name=%2',ct.AccountNum,ct.Name));
        }
    }
}

Friday, September 16, 2011

AX2012 QueryFilter Class

The following X++ code example uses the QueryFilter class to filter the result set from an outer join.

The QrySalesAndLines query joins the parent and child tables on an equality test between parent's primary key field and child's foreign key field. The following job adds another join filter criteria which tests whether the Quantity field equals 66.

static void krishh_QueryFilter(Args _args)
{
    Query query2;
    QueryBuildDataSource qbDataSource3;
    QueryRun queryRun4;
    // Ax2012 class
    QueryFilter qFilter7;
    SalesOrder recSalesOrder;
    SalesOrderLine recSalesOrderLine;
    struct struct5;
    struct5 = new struct
        ("int SalesOrderID;"
        + "date DateAdded;"
        + "str SalesOrderLineID;"
        + "int Quantity"
        );
    query2 = new Query("QrySalesAndLines");
    qbDataSource3 = query2.dataSourceName("SalesOrderLine_1");
    qFilter7 = query2.addQueryFilter(qbDataSource3, "Quantity");
    qFilter7.value("66");
    queryRun4 = new QueryRun(query2);
    while (queryRun4.next())
    {
        recSalesOrder = queryRun4.getNo(1);
        recSalesOrderLine = queryRun4.getNo(2);
        struct5.value("SalesOrderID", recSalesOrder.SalesOrderID);
        struct5.value("DateAdded", recSalesOrder.DateAdded);
        struct5.value("SalesOrderLineID", recSalesOrderLine.SalesOrderLineID);
        struct5.value("Quantity", recSalesOrderLine.Quantity);
        info(struct5.toString());
    }
}

Execute External DB Query using X++


static void krishh_ExecuteExternalDBQuery()
{
    LoginProperty loginProperty;
    OdbcConnection odbcConnection;
    Statement statement;
    ResultSet resultSet;
    str sql, criteria;
    SqlStatementExecutePermission perm;
    ;
    // Set the information on the ODBC.
    loginProperty = new LoginProperty();
    loginProperty.setDSN("dsnName");
    loginProperty.setDatabase("databaseName");
    //Create a connection to external database.
    odbcConnection = new OdbcConnection(loginProperty);
    if (odbcConnection)
    {
        sql = "SELECT * FROM MYTABLE WHERE FIELD = "
            + criteria
            + " ORDER BY FIELD1, FIELD2 ASC ;";
        //Assert permission for executing the sql string.
        perm = new SqlStatementExecutePermission(sql);
        perm.assert();
        //Prepare the sql statement.
        statement = odbcConnection.createStatement();
        resultSet = statement.executeQuery(sql);
        //Cause the sql statement to run,
        //then loop through each row in the result.
        while (resultSet.next())
        {
            //It is not possible to get field 3 and then 1.
            //Always get fields in numerical order, such as 1 then 2 the 3 etc.
            print resultSet.getString(1);
            print resultSet.getString(3);
        }
        //Close the connection.
        resultSet.close();
        statement.close();
    }
    else
    {
        error("Failed to log on to the database through ODBC.");
    }
}

ADD Query to AOT using X++

Sample X++ code used to Add the Query to AOT.
static void Krishh_addQueryToAOTUsingX++(Args _args)
{
    TreeNode                treeNode;
    Query                   query;
    QueryBuildDataSource    qbds;
    QueryBuildRange         qbr;
    str                     queryName = "MyQuery";
    #AOT
    ;
    treeNode = TreeNode::findNode(#QueriesPath);
    query = treeNode.AOTfindChild(queryName);
    if (!query)
    {
        treeNode.AOTadd(queryName);
        query = treeNode.AOTfindChild(queryName);
        qbds  = query.addDataSource(tablenum(Address));
        qbr   = qbds.addRange(fieldnum(Address,Name));
        query.AOTcompile(1);
        query.AOTsave();
    }
}

Tuesday, September 13, 2011

AX2012 Compiler Window Changes Explained

Following diagaram explains the Compiler window changes.

Ax2012 Meta Model

What is new in the meta model for AX 2012? Quite a lot – here is a short summary:
  • SSRS Report is added, it will replace Reporting Library and Report.
    Create an SSRS Report for any reporting needs.
  • Parts are introduced: Info Part, Form Part, Cue and Cue Group.
    These all provides additional information that can be hosted on a form. An Info Part provides a simple grid, a Form Part can host a form inside a form, a Cue provides visual KPIs.
  • Service and Service Group Provides capabilities for exposing X++ classes as .NET services – wsdl style.
  • New security concepts: Role, Duty, Privilege, Security Policy, Code Permission and Process Cycle. These are all part of the new role based security framework. Notice the meta model contains Role – allowing the developer to specify predefined roles.
  • Security key is deprecated
  • Visual Studio Project is added
    You can now have VS projects (like C# and VB) in the meta model – yes, they support layer based customization and rapid deployment like all other meta model concepts.
  • …. and much more
 The diagram below shows the most common relationships between concepts. Each arrow should be read as “using”. For example:
  • Menu uses Menu Item. A menu has a collection menu items.
  • Menu Item uses Form. A menu item references a form. This form is launched when the user clicks the menu item.
  • Form uses Table. A form uses a table as a data source.
  • Table uses Extended Data Type. The fields on a table is defined using extended data types. 
Provided the below diagram, and pinned it to a wall in my office. It serves me as a reference when I navigate the new areas of AX 2012. I hope it can do the same for you.