Thursday, 17 October 2013

Code to implement paging in AX 2012

Guys below is the code to implement paging in AX 2012 
Important point worth special mention is that you have to have a proper sort by in place without which it won’t work.
And apart from doing the enablePositionPaging there is one more possibility namely enableValueBasedPaging but you need to make a value based decision which type of paging you want to do and why?

 static void ImplementPaging(Args _args)
 {
     Query query = new Query();
     QueryBuildDataSource qbds;
     QueryRun qr;
     Tableid tableId;
     Common common;
     tableid = tablename2id('VendTable');
     //Add a datasource to a query 
    qbds = query.addDataSource(tableid); 
    //Order by accountnum
    qbds.addOrderByField(fieldname2id(tableid,'AccountNum'));
    //Instantiate a Queryrun class 
   qr = new QueryRun(Query);
   qr.literals(true);
   // Enable position paging for the queryrun object
    qr.enablePositionPaging(true);
   //Add a range by providing the parameters as starting record number and number of records              qr.addPageRange(1,10);
 while (qr.next())
 {
         common = qr.getNo(1);
         info(strFmt("% 1 :",common.(Fieldname2id(tableid, 'AccountNum'))));
 }
 }

 There are other possibility as well to do paging with the help of Meta Services that have found its place in AX 2012 , but that is outside the current purview but if somebody is interested he can approach me in person.

Monday, 23 September 2013

CLR / IL Exceptions in Dynamics AX X++

CLR exceptions are due to .Net Business connector.
when AX tried to call something by reflection but the called method threw an exception.

To understand what failed, you should find what was called and what was the exception.

 1. Catch the exception (by catch (Exception::CLRError)).
 2. Get the CLR exception and look into its InnerException property.
AifUtil::getClrErrorMessage()
is usually the easiest way to do that.

 Eg:
 static void RaiseCLRException(Args _args)
 {
     ;
     //Necessary if executed on the AOS  new InteropPermission(InteropKind::ClrInterop).assert();
     try
    {
         //This will cause an exception
         System.Int32::Parse("abc");
    }
    catch(Exception::CLRError)
    {
     AifUtil::getClrErrorMessage(); 
     //Access the last CLR
      Exception info(CLRInterop::getLastException().ToString());
   }
   //Revert CAS back to normal CodeAccessPermission::revertAssert();
 }

Monday, 2 September 2013

C# how to get new value from the Gridview update event

C#: GridViewUpdateEventArgs.NewValues Property getting new value from Grid view

Eg:
Write the Selected Row updating event on the Gridview.

protected void SelectedRowUpdating_Clicked(object sender, GridViewUpdateEventArgs e)
  {
      String tempQty = String.Empty;
     // Iterate through the NewValues collection and HTML encode all
     // user-provided values before updating the data source.
     foreach (DictionaryEntry entry in e.NewValues)
    {
          e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
          tempQty = entry.Key.ToString();
          tempQty = entry.Value.ToString();
    }
   AxGridView3.EditIndex = -1; EditDeleteSelectedOrder(tempQty);
 }

Friday, 16 August 2013

EP: AX Lookup: using SetMarkedRows(IEnumerable)

// Get the roles converted into keys
IEnumerable<IAxViewRowKey> viewKeys = getViewDataKeys(e.LookupControl.LookupDataSetViewMetadata);

lookup.SetMarkedRows(viewKeys);

--------------------------------------------------------------------------------
///


    /// Get the view datakeys based on the provided Segments
    /// Written by Mallik
    private List getViewDataKeys(DataSetViewMetadata viewMetaData)
    {
        DataSetViewRow row;
        string Roles = "";
        String lSegments;
        String[] roles = Roles.Split('-');
        IAxaptaRecordAdapter axRecord;
        TableMetadata tableMetaData = MetadataCache.GetTableMetadata(TableMetadata.TableNum("smmBusRelSegmentGroup"));
        List viewDataKeys = new List();
        try
        {
            // Retrieve the current row.
            row = AvaAnnouncementsDS.GetDataSet().DataSetViews["AvaAnnouncements"].GetCurrent();
            Roles = row.GetFieldValue("Segments").ToString();
            roles = Roles.Split('-');
            // For each Segment
            foreach (string role in roles)
            {
                using (axRecord = AxSession.AxaptaAdapter.CreateAxaptaRecord("smmBusRelSegmentGroup"))
                {
                    // Try to retrieve a list of the items.
                    axRecord.ExecuteStmt("select * from %1");//where smmBusRelSegmentGroup.Segments==" + role);

                    while (axRecord.Found)
                    {
                        lSegments = axRecord.GetField("SegmentId").ToString();
                        if (lSegments.Trim() == role.Trim())
                        {
                            // Create dictionary
                            Dictionary dict = new Dictionary();
                            dict.Add("SegmentId", lSegments);
                            // Create indexes
                            List index = new List(1);
                            index.Add(tableMetaData.DefaultUniqueIndex);
                            // Get viewdatakey  Add Item to list
                            viewDataKeys.Add((IAxViewRowKey)AxViewDataKey.CreateFromDictionary(viewMetaData, dict, index.ToArray()));
                            break;
                        }//if end
                        axRecord.Next();
                    }//  while end
                }//using end
            }//for end
        }
        catch (System.Exception ex)
        {
            AxExceptionCategory exceptionCategory;

            // Determine whether the exception can be handled.
            if (AxControlExceptionHandler.TryHandleException(this, ex, out exceptionCategory) == false)
            {
                // The exception was fatal and cannot be handled. Rethrow it.
                throw;
            }
        }
        return viewDataKeys;
    }

Thursday, 25 July 2013

EP: Multi Select & Loop DataSet (Looping Data set in C#)





When you set the AllowMarking property to true, the user can mark multiple rows in the grid. You may want to know which rows the user has marked. The following example shows how to use the GetMarkedRowsSet method for the data source view to retrieve the set of marked rows. In this example, the name of each marked row is added to a list box.

This example uses the .NET Business Connector to access data. It requires access to the following namespaces:

C#

using Microsoft.Dynamics.AX.Framework.Portal.Data;

using Microsoft.Dynamics.Framework.BusinessConnector.Session;

using Microsoft.Dynamics.Framework.BusinessConnector.Adapter;

 

The following code for a button retrieves the list of marked rows.

C#

protected void Button1_Click(object sender, EventArgs e)

{

    // Create a container.

    IAxaptaContainerAdapter recordIds = this.AxSession.AxaptaAdapter.CreateAxaptaContainer();

 

    // Get the marked rows.

    IReadOnlySet rows = this.AxDataSource1.GetDataSourceView("FCMRooms").DataSetView.GetMarkedRowsSet();

 

    // Create an enumerator to examine each marked row.

    IEnumerator enumRows = rows.GetEnumerator();

 

    DataSetViewRow row;

    string description;

 

    // Clear the list box.

    ListBox1.Items.Clear();

 

    while (enumRows.MoveNext())

    {

        // Get the current row.

        row = (DataSetViewRow)enumRows.Current;

 

        // Retrieve the name of the room.

        description = row.GetFieldValue("RoomName").ToString();

 

        // Add the item to the list box.

        ListBox1.Items.Add(description);

    }

}

 

Friday, 19 July 2013

EP: Code to Modify the standard Title bar in EP


//set the titlebar to show the record context
 ITitleProvider titleProvider = AxBaseWebPart.GetWebpart(this) as ITitleProvider;
        try
        {
            row = this.GetCurrentRow;
            if (row != null)
            {
                titleProvider.ShowContext = false;
                //set the title----
                SalesId = row.GetFieldValue("SalesId").ToString();
                ItemId = row.GetFieldValue("ItemId").ToString();
                titleProvider.Caption = String.Format(Labels.GetLabel("@AVA1712") + ": " + SalesId + ", " + ItemId);
}
        catch (System.Exception ex)
        {
            AxExceptionCategory exceptionCategory;
            // Determine whether the exception can be handled.
            if (AxControlExceptionHandler.TryHandleException(this, ex, out exceptionCategory) == false)
            {
                // The exception was fatal and cannot be handled. Rethrow it.
                throw;
            }
        }

Wednesday, 3 July 2013

Accessing (AXBound) Bound Field Properties

///

    /// Code to get Field from Grid. Mallik
    ///

    ///
    ///
    ///
    static AxBoundField GetField(DataControlFieldCollection fields, string name)
    {
        foreach (DataControlField field in fields)
        {
            // Is this the field being searched for?
            AxBoundField boundField = field as AxBoundField;
            if (boundField != null && String.Compare(boundField.DataField, name, true) == 0)
            {
                return boundField;
            }
        }
        // Nothing found, so return null.
        return null;
    }

--------------------------------------------------------------------------------------------------------------------------
The following example uses the method created above to set the ReadOnly property for the SalesQty bound field in the AxGridView1  grid object for an AxForm.
-------------------------------------------------------------------------------------------------------------------------
AxBoundField RelatedSalesQty;
        AxBoundField RelatedSalesUnit;
        try
        {
            row = this.GetCurrentRow;
            authorizationStatus = row.GetFieldValue("AvaAuthorizationStatus").ToString();
            if (authorizationStatus == "0")//Labels.GetLabel("@AVA114"))
            {
                AxGridView1.AllowEdit = true;
                AxGridView1.AllowDelete = true;
                AxGridView1.AutoGenerateEditButton = true;
               
                RelatedSalesQty = GetField(AxGridView1.Columns, "SalesQty");
                RelatedSalesQty.ReadOnly = false;
                RelatedSalesUnit = GetField(AxGridView1.Columns, "SalesUnit");
                RelatedSalesUnit.ReadOnly = false;
                //AxGridView1.Columns.Contains("SalesQty")
                ret = true;
            }

How to Get Trade Agreement Line Discount Percentage by Item and Date in D365FO Using X++

  In Microsoft Dynamics 365 Finance and Operations (D365FO), trade agreements are used to manage prices and discounts for customers, vendor...