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;
            }

Thursday, 13 June 2013

Using Temporary table in AX 2012

Find Method on Temporary Table:

// Use this pattern instead
public static TempTable find(AccountNum _accountNum, TempTable _tempTable, boolean _forUpdate = false)
{

    if (_accountNum)
    {
        _tempTable.selectForUpdate(_forUpdate);

        select firstonly _tempTable
        where _tempTable.AccountNum      == _accountNum;
    }

    return _tempTable;
}

Note: All ways use the Temporary Table variable as Global variable.

For more information :

http://www.axaptapedia.com/index.php?title=Temporary_tables

Temporary Tables in DAX 2012
In Microsoft Dynamics AX 2012 a new type of temporary table is added, ie now you have three types of Table,
Regular Tables: AOT tables used for storing data perminently in database
InMemory Tables: This type of temporary table is hosted in the client, the data will wipe out as soon as instance of the form or report (one who loaded the data in InMemory tables) is closed.
TempDB Tables: It is the new type of temporary table that is hosted in the Microsoft SQL Server database.Now the temporary tables can be joined on the database tier with regular tables. This was the joining problem we have in InMemory Tables.

Configuration Key Impact on the Tables.
In Microsoft Dynamics AX 2012, when the configuration key for a table that is listed in the AOT is disabled, the table is not dropped from SQL Server. In the earlier version of Microsoft Dynamics AX when changing the configuration key to disable a table, the table is dropped from the SQL database, deleting all data in the table.
In AX 2012 we can disable the table, but the data will not be lost, as a result Sql Server cubes or Enter application can read the data because they bypass the AOS.
Relation on the Tables.
In Microsoft Dynamics AX 2012, you should always have relations between the two tables on RecId field so the primary key for the new tables created in AX 2012 is always be Surrogate key (RecId). for Example you are creating any new table in AX 2012 so you always have the RecId field as the primary key and if you want to make relattion with any child table then you will always make the relation on RecId field and move it as a Foreign Key in child table. This is the major improvement, as the tables are now completely normalized, no redendency of data, upgrade will be easy by that to.
If you would like to know more about Surrogate key, see this link.
In order to create new Foreign key relationship (New Type added in AX 2012), Right-click on the newly created and configured Relation and choose New > New Foreign Key. You should see something similar to that

Note that the creation of a surrogate foreign key relationship automatically adds a field to the foreign key table for you!
Full Text Indexes on Tables
Microsoft Dynamics AX 2012 provides full-text functionality that enables Microsoft Dynamics AX to search business data over a large volume of text data or documents. You can create a full-text index on tables of type Main and Group.
You must configure the SQL Server full-text search functionality before you use it in the Microsoft Dynamics AX application
Same as regular SQL Server indexes, full-text indexes can be automatically updated at the same time that the data is changed in the associated tables. see related links on how to create and Use the Full text Indexes.

EP: C# Passing parametes from Modal dialog to calling page.

Parent page:

    protected void Page_Load(object sender, EventArgs e)
    {
       
        AxBaseWebPart.GetWebpart(this).ModalDialogClosed += new EventHandler(Base_ModalDialogClosed);
    }

///
    /// This method will  be used to Returning the value ModalDialogClosed.
    ///

    ///
    ///
    void Base_ModalDialogClosed(object sender, AXModalDialogClosedEventArgs e)
    {
        // Code to handle the returned value.
        string returnValue;
        returnValue = e.DialogArgs.Data;
        QtyEdit.Text = returnValue;
        try
        {
            if (returnValue != String.Empty && localRecId != String.Empty)
            {
                this.AvaOrderingListEntryDS.GetDataSet().DataSetRun.AxaptaObjectAdapter.Call("SalesLineQty", returnValue, localRecId);
            }
        }
        catch (Exception ex)
        {
            Proxy.Info objInfoLog = new Proxy.Info(this.AxSession.AxaptaAdapter);
            objInfoLog.add(Proxy.Exception.Info, "Ordering list not selected");
        }
    }

Child page:
on any button click:
protected void SaveButton_Click(object sender, EventArgs e)
    {
 AXDialogArgs args = DialogHelper.DialogArgs;
       args.Data = QtyEdit.Text;
       DialogHelper.Close(CloseDialogBehavior.Auto);
//can use the below to refresh calling page.
       //DialogHelper.Close(CloseDialogBehavior.RefreshPage);

    }

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...