Tuesday, 21 April 2015

AIF Calling CustCustomerService.Update using WCF from C#

Create and configure the Inbound integration port for CustCustomerService.Update

  1. Open the Inbound ports form. Click System administration > Setup > Services and Application Integration Framework > Inbound ports.
  2. Click New.
  3. Name the new integration port CRM2AXCustCustomerService.
  4. In the Adapter list in the Address group, select NetTcp.
  5. On the Service contract customizations FastTab, click Service operations.
  6. In the Select service operations form, select CustCustomerService.create,CustCustomerService.read and CustCustomerService.update in the Remaining service operations list. Click the left arrow to move the service operation to the Selected service operations list. Then, close the form.
  7. You can modify the document data policy to match the fields that you want to return in the response. If you do not specify a data policy, then all sales order schema elements are included in the response message by AIF. If you specify a data policy but do not modify the default data policy, then only the default elements are included in the sales order schema.
  8. Activate the integration port.
  9. Make note of the address that is displayed in the WSDL URI text box.
  10. Close the Inbound ports form.
Create a C# project to consume the WCF service 
  1. Open Visual Studio and create a new console application project in Visual C#. Name the project "CRM2AXMKClient".
  2. In Solution Explorer, right-click the project name and then click Add Service Reference.
The Add Service Reference dialog box opens.
  1. In the Address text box, enter the WSDL URI from the port that you created in the previous section. For example:
4.  http:// XXXXMKAOSXX:8101/DynamicsAx/Services/CRM2AXCustCustomerService
  1. Click Go. Wait for Visual Studio to find the service.
  2. Click OK to close the dialog box.
  3. Open Program.cs. In the code editor, replace the code with the following C# code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRM2AXUpdateCustCustomerService
{
    class Program
    {
        //Mallik Code to updated Customer using WCF (CustCustomerService.update()) 20/04/2015
        //  The customer service is date effective because it contains the DirPersonName, DirOrganizationName,
        //DirPartyLocation, etc. tables which have their ValidTimeStateFieldType properties set to something other than None.

        //Date effective services have properties added at the document level (the highest level in the service)
        //to indicate how you want to set the date effective entities.  
        //The properties are ValidTimeStateType, ValidAsOfDateTime, ValidFromDateTime and ValidToDateTime.
        //Either you can set those at the document level or you can set the date effective fields on each entity in the service
        //that is date effective. 

        //In the example code below, I call the read method to retrieve a customer and then I create a
        //new instance of a customer, set the date effective properties on the document according
        //to what they are on the retrieved customer and then update the CreditMax field on the customer.

        static void Main(string[] args)
        {
            string customer = "MK2";

            //ServiceReference1 is the name of ServiceReferance added to the project.
            ServiceReference1.CustomerServiceClient proxy = new ServiceReference1.CustomerServiceClient();
            var context = new ServiceReference1.CallContext() { Company = "USMF" };
            ServiceReference1.AxdCustomer foundCustomer = null;
            try
            {
                foundCustomer = proxy.read(context, readCritera(customer));
                Console.WriteLine("Read worked");
                updateCustomer(foundCustomer);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        } // end of Main


        private static ServiceReference1.EntityKey[] readCritera(string customerAccount)
        {
            ServiceReference1.AxdEntity_CustTable custTable = new ServiceReference1.AxdEntity_CustTable();
            ServiceReference1.EntityKey[] entityKeyList = new ServiceReference1.EntityKey[1];
            ServiceReference1.EntityKey key = new ServiceReference1.EntityKey();
            ServiceReference1.KeyField[] keyFields = new ServiceReference1.KeyField[1];
            ServiceReference1.KeyField keyField = new ServiceReference1.KeyField();
            keyField.Field = "AccountNum";
            keyField.Value = customerAccount;
            keyFields[0] = keyField;
            key.KeyData = keyFields;
            entityKeyList[0] = key;
            return entityKeyList;
        }

        private static void updateCustomer(ServiceReference1.AxdCustomer customer)
        {
            ServiceReference1.CustomerServiceClient proxy = new ServiceReference1.CustomerServiceClient();
            ServiceReference1.CallContext context = new ServiceReference1.CallContext();
            context.Company = "USMF";
            ServiceReference1.AxdEntity_CustTable custTable = customer.CustTable[0];

            ServiceReference1.AxdCustomer axdCustomer2 = new ServiceReference1.AxdCustomer();
            axdCustomer2.ValidTimeStateType = customer.ValidTimeStateType;
            axdCustomer2.ValidTimeStateTypeSpecified = true;
            axdCustomer2.ValidAsOfDateTime = customer.ValidAsOfDateTime;
            axdCustomer2.ValidFromDateTime = customer.ValidFromDateTime;
            axdCustomer2.ValidToDateTime = customer.ValidToDateTime;

            ServiceReference1.AxdEntity_CustTable custTableNew = new ServiceReference1.AxdEntity_CustTable();
            custTableNew._DocumentHash = custTable._DocumentHash;
            custTableNew.RecId = custTable.RecId;
            custTableNew.RecVersion = custTable.RecVersion;
            custTableNew.action = ServiceReference1.AxdEnum_AxdEntityAction.update;
            custTableNew.actionSpecified = true;
            custTableNew.CreditMax = custTable.CreditMax + 10;
            custTableNew.CreditMaxSpecified = true;
            custTableNew.CustGroup = custTable.CustGroup;
            axdCustomer2.CustTable = new ServiceReference1.AxdEntity_CustTable[1] { custTableNew };

            try
            {
                proxy.update(context, readCritera("MK2"), axdCustomer2);
                Console.Write("Worked");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed");
                Console.ReadLine();
            }
        }
    }
}

For Item /Product Refer 

https://blogs.msdn.microsoft.com/dynamicsaxscm/2011/07/06/product-item-data-management-services/



Monday, 20 April 2015

Ax 2012 AIF Calling the CustCustomerService.Create method from WCF C#

Create and configure the Inbound integration port for CustCustomerService

  1. Open the Inbound ports form. Click System administration > Setup > Services and Application Integration Framework > Inbound ports.
  2. Click New.
  3. Name the new integration port CRM2AXCustCustomerService.
  4. In the Adapter list in the Address group, select NetTcp.
  5. On the Service contract customizations FastTab, click Service operations.
  6. In the Select service operations form, select CustCustomerService.create,CustCustomerService.read and CustCustomerService.update in the Remaining service operations list. Click the left arrow to move the service operation to the Selected service operations list. Then, close the form.
  7. You can modify the document data policy to match the fields that you want to return in the response. If you do not specify a data policy, then all sales order schema elements are included in the response message by AIF. If you specify a data policy but do not modify the default data policy, then only the default elements are included in the sales order schema.
  8. Activate the integration port.
  9. Make note of the address that is displayed in the WSDL URI text box.
  10. Close the Inbound ports form.
Create a C# project to consume the WCF service 
  1. Open Visual Studio and create a new console application project in Visual C#. Name the project "CRM2AXMKClient".
  2. In Solution Explorer, right-click the project name and then click Add Service Reference.
    The Add Service Reference dialog box opens.
  3. In the Address text box, enter the WSDL URI from the port that you created in the previous section. For example:
    http:// XXXXMKAOSXX:8101/DynamicsAx/Services/CRM2AXCustCustomerService
    
  4. Click Go. Wait for Visual Studio to find the service.
  5. Click OK to close the dialog box.
  6. Open Program.cs. In the code editor, replace the code with the following C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRMCustCustomerServiceCreate
{
    class Program
    {
        ///



        /// This method is used to create a customer in Dynamics AX using AIF WCF service CustCustomerService.
        ///
        ///
        static void Main(string[] args)
        {
            try
            {
                // Try to create the customer.
                // Display the information for the customer.
                Console.WriteLine("Creating the customer : MK2" );
                WebServiceTest();
            }
            catch (Exception e)
            {
                // Display the exception message. 

                Console.WriteLine("Exception: " + e.Message);
               // c1.Abort();
            }
        }
        ///



        /// Customizaton added by Mallikarjun Gudidevuni on 20/04/2015
        ///
        static void WebServiceTest()
        {
            //ServiceReference1 is the name of ServiceReferance added to the project.
            using (ServiceReference1.CustomerServiceClient custClient = new ServiceReference1.CustomerServiceClient())
            {
                var context = new ServiceReference1.CallContext() { Company = "USMF" };
                var customers = new ServiceReference1.AxdCustomer
                {
                    CustTable = new ServiceReference1.AxdEntity_CustTable[] 
                                    { 
                                        new ServiceReference1.AxdEntity_CustTable() 
                                        { 
                                            CustGroup="10", 
                                            TaxGroup="NY", 
                                            AccountNum = "MK2",
                                            Currency = "USD",                                         
                                            DirParty = new ServiceReference1.AxdEntity_DirParty_DirPartyTable[1] 
                                            {
                                                new ServiceReference1.AxdEntity_DirParty_DirOrganization() 
                                                    { LanguageId = "en-us", Name = "Mallikarjun" }
                                            }// end of Dir
                                        }//end of ASD_CustTable()
                                    }//endof CustTable
                };//end of Customers
               
                custClient.create(
                  context,
                  customers
                  );
                custClient.Close();
            } //endof using 
        }//end of WebServiceTest
    }
}

            
               
Build the project and run
  1. Build the project. and Run.
              You can see the customer has been created in AR-->All Customers. 


Happy learning :) ...   Mallik
           
           

Wednesday, 8 October 2014

Display method filter in AX 2012

http://dynamicsaxsolutionsworld.blogspot.no/2011/09/how-to-add-search-find-filter.html

This is for my reference and got it from above site.

How to add Search/ Find /Filter functionality to Display method in dynamics AX
Dynamics AX, can retrieve output values by using table field and display method. As we know, usually standard dynamics AX filter functionality is working only for table field. But sometimes we have to do filter functionality for display method too. Below I’m going to explain how to add a filter functionality for Display method.

1.      Here I have added display method (disCustName) to display customer name on the “IND_BusRelation” form. In this form main data source is “smmBusRelTable”.

2.      Change “AutoDeclaration” property from No to Yes of the “disCustName” data field.
3.      Override “context()” method of the “disCustName” data field and add following code.
  
public void context()
{
    int             selectedMenu;
    formrun         fr;
    Args            ag;
    Name            strtext;
    querybuilddataSource qb1;
    queryrun    qr;
    query       q;
    PopupMenu menu = new PopupMenu(element.hWnd());
    int a = menu.insertItem('Filter By Field');
    int b = menu.insertItem('Filter By Selection');
    int c = menu.insertItem('Remove Filter');
    ;

    selectedMenu = menu.draw();
    switch (selectedMenu)
    {
    case -1: //Filter by field
            break;
    case a:
            ag = new args('SysformSearch');
            fr = new formrun(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   = smmBusRelTable_ds.query();
                qb1 = q.dataSourceTable(tablenum(smmBusRelTable));
                qb1 = qb1.addDataSource(TableNum(CustTable));
                qb1.addLink(FieldNum(smmBusRelTable,CustAccount),FieldNum(CustTable,AccountNum));
                qb1.addRange(FieldNum(CustTable,Name)).value(strtext);
                smmBusRelTable_ds.query(Q);
                smmBusRelTable_ds.executeQuery();
            }
            break;

    case b:   // Filter By Selection
            q   = smmBusRelTable_ds.query();
            qb1 = q.dataSourceTable(tablenum(smmBusRelTable));
            qb1 = qb1.addDataSource(TableNum(CustTable));
            qb1.addLink(FieldNum(smmBusRelTable,CustAccount),FieldNum(CustTable,AccountNum));
            qb1.addRange(FieldNum(CustTable,Name)).value(disCustName.valueStr());
            smmBusRelTable_ds.query(Q);
            smmBusRelTable_ds.executeQuery();
            break;
    case c :   // Remove Filter
            q   = new Query();
            qb1 = q.addDataSource(tablenum(smmBusRelTable));
            qb1.clearLinks();
            qb1.clearRanges();
            smmBusRelTable_ds.query(Q);
            smmBusRelTable_ds.removeFilter();
            break;

    Default:
            break;
    }

}

4.       Run the form and do right Click on Customer Name field.


 

Wednesday, 1 October 2014

Debug user control (Visual Studio) in EP

IN Enterprise Portal.


Debugging in the ASP.NET Development Server Environment

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


To debug a User Control in the ASP.NET Development Server environment, you must create a Dynamics AX Webpart Page that will run the User Control. For more information, see How to: Test User Controls in Visual Studio.
To debug in the ASP.NET Development Server environment

1. Start Visual Studio.

2. Open the EP Web Application project that contains the User Control that you want to debug.

3. View the code for the User Control. Do this by right-clicking the User Control in Solution Explorer, and then clicking View Code.

4. Add breakpoints to the appropriate locations in the code.

5. In the Debug menu, click Start Debugging.

6. In the web browser window that is displayed, click the file name for the Dynamics AX Webpart page (.aspx) that contains the User Control that you want to debug. Visual Studio should stop execution at the designated breakpoints.



Debugging in Enterprise Portal

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


To debug a User Control that is running in Enterprise Portal, you must enable debugging for the Enterprise Portal web site, and then configure your EP Web Application project for debugging.
To enable debugging for the Enterprise Portal web site

1. On the system that is running Enterprise Portal, locate the web.config file for the Enterprise Portal site. Typically, this found in C:\inetpub\wwwroot\wss\VirtualDirectories\80\. If you are running Enterprise Portal on a port other than 80, the web.config file will be found in a folder with that number.

2. Use a text editor such as Notepad to edit the web.config file.

3. Search for the node that is named compilation. Set the debug attribute for this node to true.



Copy



ImportantImportant

We do not recommend that you enable debugging in production environments for Enterprise Portal.


4. Save the changes to the web.config file.

To debug in Enterprise Portal

1. Start Visual Studio. If User Account Control (UAC) is active, be sure you start Visual Studio with administrative privileges.

2. Start Enterprise Portal.

3. Open the EP Web Application project that you want to use for debugging.

4. In the Debug menu in Visual Studio, choose Options and Settings. Expand the Debugging group and select General. Be sure that Require source files to exactly match the original version is not marked. Click OK.

5. Add the User Control to the EP Web Application project.

6. If the User Control uses any proxies to access X++ code, add the needed proxy projects to the solution in Visual Studio. To add a proxy project, click the Project menu, choose Add EP Proxy Project. Select the proxy project and click OK. The EPApplicationProxies project is the most frequently used proxy project.

7. Attach the Visual Studio debugger to the process for Enterprise Portal. In the Debug menu, click Attach to Process.

8. Click Select to specify the type of code you want to attach to. Mark Managed (v2.0, v1.1, v1.0), and then click OK.

9. Mark the Show processes from all users and Show processes in all sessions to be sure that all processes are being displayed.

10. In the Available Processes list, select the w3wp.exe process that is being used for Enterprise Portal. If there are multiple processes with that name, the values in the Type and User Name columns may help you determine which is the process being used for Enterprise Portal. If you cannot determine which process is being used, select all of the w3wp.exe processes.

11. Click Attach to attach the Visual Studio debugger to the selected processes.

12. View the code for the User Control. Do this by right-clicking the User Control in Solution Explorer, and then clicking View Code.

13. Add breakpoints to the appropriate locations in the code.

14. In Enterprise Portal, navigate to the page that contains the User Control that you want to debug. When the breakpoints you set are encountered, the Visual Studio debugger should stop execution at the designated breakpoints.
 

EP: C# Code to capture mouse click event on AXGridView / Code to get the cell index on AXGidView

EP: C# Code to capture mouse click event on AXGridView / Code to get the cell index on AXGidView


-----we need to write the code in page render method-----

protected override void Render(HtmlTextWriter writer)
    {
        // Ensure that the control is nested in a server form.
        if (Page != null)
        {
            Page.VerifyRenderingInServerForm(this);
        }
        #region Code for mouse click event
        
         //Add the extras to each row.
        foreach (GridViewRow row in AxGridView2.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                // Show hand like the mouseover of buttons. (Not very functional, but very cute.)
                //row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
               
                // Each Cell will need its own PostBack link, with the necessary information in it.
                foreach (TableCell cell in row.Cells)
                {
                    if (row.Cells.GetCellIndex(cell) >= 8) // click to apply only for cell index > 8
                    {
                        // Although we already know this should be the case,
                        // make safe code. Makes copying for reuse a lot easier.
                        if (cell is DataControlFieldCell)
                        {
                            // Put the link on the cell.
                            cell.Attributes["onclick"] =
                                Page.ClientScript.GetPostBackClientHyperlink(AxGridView2,
                                String.Format("CellSelect${0},{1}", row.RowIndex, row.Cells.GetCellIndex(cell)));
                            // Register for event validation: This will keep ASP from giving nasty errors from
                            // getting events from controls that shouldn't be sending any.
                            //Page.ClientScript.RegisterForEventValidation(AxGridView2.UniqueID,
                            //    String.Format("CellSelect${0},{1}", row.RowIndex, row.Cells.GetCellIndex(cell)));    
                        }
                    }
                }
            }
        }
        #endregion Code for mouse click event
        base.Render(writer);
    }

-----Now Add the RowCommand method for the AXGridview-----

///
    ///
    ///

    string selectedCellDate;
    ///
    /// To get selected cell index
    ///

    ///
    ///
    protected void AxGridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {       
        #region
        this.DisplayMatrix();
        // Don't interfere with other commands.
        // We may not have any now, but this is another safe-code strategy.
        if (e.CommandName == "CellSelect")
        {
            // Unpack the arguments.
            String[] arguments = ((String)e.CommandArgument).Split(new char[] { ',' });
            // More safe coding: Don't assume there are at least 2 arguments.
            // (And ignore when there are more.)
            if (arguments.Length >= 2)
            {
                // And even more safe coding: Don't assume the arguments are proper int values.
                int rowIndex = -1, cellIndex = -1;
                int.TryParse(arguments[0], out rowIndex);
                int.TryParse(arguments[1], out cellIndex);
                // Use the rowIndex to select the Row, like Select would do.
                // ...with safety: Don't assume GridView2 even has the row.
                if (rowIndex > -1 && rowIndex < AxGridView2.Rows.Count)
                {
                    AxGridView2.SelectedIndex = rowIndex;
                }
                if (cellIndex >= 8)
                {
                    selectedCellDate = this.ConvertToDateTime(txtFromDate.Text).AddDays(cellIndex - 8).ToString();
                    this.GetRelatedOrders(chkboxProductCategory.Checked, selectedCellDate);
                }
            }
           
        }       
        #endregion       
       
    }
    #endregion
 

How to Disable “Advanced Filter or Sort” and Enforce Custom Filters on Any D365FO Form

 In Dynamics 365 Finance and Operations, users can apply filters through the “Advanced filter or sort” feature found under the Options tab...