Tuesday, August 14, 2018

Creating a Custom Inbound AIF Service in Microsoft Dynamics AX 2012



Overview

Application Integration Framework (AIF) services are used to communicate with external systems or applications. Microsoft Dynamics AX 2012 has the following types of services:
  1. Document services
  2. Custom services
  3. System services
An AIF service can be Inbound or Outbound. An Inbound service is used when you want to send data to an external system and Outbound services are used when you want to retrieve data. This tutorial will guide you in creating Custom Inbound AIF services in Microsoft Dynamics AX 2012. Custom services are used when:
  1. The complexity of the entities is relatively low.
  2. When you want to have full control of the service contract.
  3. When data contracts needs to be shared with different entities.

Pre-requisites

  1. Microsoft Dynamics AX 2012
  2. AIF services must be installed and configured on IIS

Important Concepts

  1. Service operation

    Service operations are class methods that expose any business logic in a service. To define a service operation, add the SysEntryPointAttribute attribute at the top of a method. Any existing method can be converted to a service operation by adding this attribute at the beginning of the method.
    &absp;
    Note:
    The service operation name cannot include Create, Find, Update or Delete. These names are reserved to be used by AIF Document services. AX will make an exception when they are called from a client.
  2. SysEntryPointAttribute

    SysEntryPointAttribute defines the authorization checks that will be performed when a method is called from the server. This attribute must be set on all the service operations. If the value is “true”, it means that authorization checks will be performed for all the tables accessed in the method and if set to “false”, no authorization checks will be performed.
  3. AifCollectionTypeAttribute

    AifCollectionTypeAttribute is used when you want to use a collection as a return type or in a parameter of a service operation. This attribute defines the type of data a collection contains.

Scenario

As part of this tutorial the service will return the list of customer names in Dynamics AX.

Steps

  1. First we will create a new class which will contain Service operations.

  2. Open AOT. Go to Classes and create a new class. Let’s name it CustomerServiceDemo.

  3. Set the RunOn property of the class to Server. This will make sure the class always executes on the server.
  4.  
     
  5. Add a new method and name it as getCustomerNameList. This method will query customers’ names and return a Type list string. Write the following code in the method:
  6. [SysEntryPointAttribute(true),
    AifCollectionTypeAttribute('return', Types::String)]
    //return denotes the parameter type and String specifies the type of data the collection will hold
    public List getCustomerNameList()
    {      
        CustTable       custTable;    
        List list = new List(Types::String);    
        
        //select all customers
        while select * from custTable        
        {
            //add customer name in the list
            list.addEnd(custTable.name());
        }
        
        return list;
    }
  7. The SysEntryPointAttribute tells AX that this method is a service operation method.

  8. Now we will create a new service and add the above created service operation to it.

  9. Go to Services, right click and select New Service.

  10. Name it as CustomerServiceDemo.

  11. Open the properties of the newly created service and select the CustomerServiceDemo class in the Class field.

  12. Now expand the CustomerServiceDemo service node and add a new Operation by right clicking on Operations and selecting Add Operation.

  13. All service operations present in the class will be listed. Select the getCustomerNameList service operation by checking the Add field in the grid and press OK.

  14. The next step is to create a service group and deploy the service to the Inbound Port.

  15. Go to Service Groups, right click and select New Service group.

  16. Name it as CustomerServiceDemoGroup.

  17. Set the AutoDeploy to Yes (Service will start automatically when AOS is started) and set the Description as Customer name service.

  18. Right click the newly created service group and select New Service Node Reference.

  19. In the newly created service node, set the Service property to CustomerServiceDemo. The Name property will automatically default to the Service name.

  20. Now right click the service group and select Deploy Service Group.

  21. A success message will appear if the service group is successfully deployed.

  22. To verify it, go to System administration à Setup à Services and Application Integration Framework à Inbound ports.

  23. The Service group name CustomerServiceDemoGroup will appear here as Port name with a green check mark. This shows that service group is deployed and active. If a red ‘x’ is appearing, select Activate from the action pane to activate the port.

  24. The WSDL URI is the URL of the service which can be used by external systems to access the service.

  25. To test whether the service is running properly, open the Visual Studio Command Prompt by going to All Programs à Microsoft Visual Studio 2010 à Visual Studio Tools à Visual Studio Command Prompt.

  26. Write wcftestclient and press enter. WCF Test Client will open.

  27. Now, go to File àAdd Service.

  28. In the Add Service dialog box, paste the WSDL URI of the port and press OK.

  29. The WCF Test Client will open the service with the list of operations available.

  30. Double click the getCustomerNameList. It will open the operation details in the right hand side pane.

  31. Click the Invoke button. The result of the service will appear in the Response pane.

  32. Pat yourself on the back. You are finished!

Virtual Company & Table Collections in Dynamics Ax




This article describes how Dynamics Ax Virtual Company and Table Collection work. We will also discuss how to move data from normal company to virtual company when you introduce virtual company in existing Ax implementation.

Virtual Company:

Dynamics Ax stores data as per company in tables. But there might be occasions when you want to share data across companies, like country, state, zip codes data. This sharing of data is achieved by creating a virtual company and storing data in this virtual company. Normal companies are then configured to read/write data from this virtual company. The only purpose of virtual company is to share data across companies, you cannot log into this virtual company.

Before seeing how to do virtual company setup, I would like you to show another trick that can be used to share data across Ax. There is a property on Ax tables called "SaveDataPerCompany", you can use this property to save data globally in Ax. To share data set this property to "No".


Note: This data is shared by all the companies in Ax. This option will delete DataAreaId field and default (DataAreaId, RecId) index from the table. If you want more control on shared data, like which companies can share and which can not then use virtual company. 

Virtual Company setup:

Step 1: Create Table Collection

Decide which tables you want to share and create a table collection for these functionally related tables. For example; if you want to share Global Address Book across companies then you can utilize the existing table collection "DirPartyCollection".

To create a table collection, go to AOT\Data Dictionary\Table Collections and on right click select "New Table Collection", then just drag your required tables in this collection.

Step 2: Create Virtual Company, configure/attach normal companies and table collection

Create a virtual company that will hold the shared data for normal companies.
Note: Before doing the below steps, make sure you are the Ax administrator and the only user online.
  1. Go to Administration -- Setup -- Virtual company accounts, and create a virtual company.
  2. Decide which companies needs to share data and attach those normal companies with this virtual company.
  3. Attach the table collection with this virtual company.

Your Ax client will re-start and you are done with setting up the virtual company account.

Now, when you have virtual company in place, all new data will be saved in this virtual company. Only companies attached to the virtual company can use this shared data. All other companies which are not attached will work normally, these companies will continue to read/write data as per company bases.

How to move existing data to virtual company?
When you setup a new virtual company, Ax does not move data automatically from normal company to virtual company. This is done by system administrator manually.

There are many ways to do this data move, but I will discuss only two approaches here.

Ax Import / Export:
This is standard Ax approach.

  1. Manually export existing normal company data from Ax.
  2. Remove duplicate records from this exported data set. 
  3. Delete exported data from normal companies.
  4. Import the exported data back in Ax, while logged into one of the participating companies. 
  5. Create records deleted in point 2 again in Ax using your logic. How you want to handle duplicate? For example, if you have customer 'Rah' in more than one normal company, what you want to do with this?
Direct SQL:
Use this approach if you have good knowledge about SQL queries and Ax table structures/relationships. Below are few points that will help you understand what to do and how to do.

  • All Ax tables store data as per company unless otherwise specified. For this, Ax uses a special field called DataAreaId. In case of virtual company, it does not matter from which normal company you log-in, it is always the virtual company id which is stored in DataAreaId field of shared tables. 
  • Ax also assigns a unique 64bit number to each record in table. For this, Ax uses a special field called RecId. This RecId is unique in the table and is generated by Ax when you insert a new record in Ax. It is not related to DataAreaId / Company.
  • For unique records between all participating normal companies, update the DataAreaId to the virtual company id.
  • For duplicate records, create them again in Ax using some Ax job or Ax import/export technique.

Send the item master to a 3PL in AX 2012 AIF



So this post didn’t end up exactly the way I thought it would when I started it. Earlier this week we were talking about setting up integration with a 3PL, and we need to send that company a copy of the item master from one of our Dynamics AX companies. I remembered doing this a year or so ago for another company which was integrating Dynamics AX with a manufacturing shop floor production control system. My memory was that we’d used a standard Dynamics AX function with no customisation – but my memory was playing tricks, we’d done three minor enhancements to the standard process, which I’ll mention as we walk through the setup and process.
There’s a standard function that can send your items as an XML message, and the first thing that we need to do is to deploy that service as a Service group. Open the AOT and create a new Service group:

Then drag the Service InventItemService into that group, giving:

And then Right-click > Deploy the service group – that can take a while. Then close the AOT.
Now we need an outbound port. Systems administration > Setup > Services and Application Integration Framework > Outbound ports:

For this port I’m using a folder (and the File system adapter) and, as you can see above, I’ve created a folder I can write these outbound messages to. Next click on Service operations and select the InventItemService.find service operation:

Close the Select service operations window and tick the ‘Customise documents’ checkbox and click on the Data policies button, and a form opens which allows you to select which fields are going to be exported:

However, there are a few fairly glaring omissions from this service: the item name (which of course is held on the Product master); and Barcodes; and Product dimensions (config, size, colour, style, if you’re’ using those). There are separate AIF services for Barcodes and Products, but the best action here is to customise this service to add in any ‘missing’ fields which you require. In case you’re counting, that’s the second customisation.
There aren’t a lot of other setup options:

I’ve added logging but probably that’s not necessary. OK. Activate the outbound port:

Next navigate to your items, Product information management > Common > Released products, and click on the ‘General’ action tab, and click on the ‘Send …’ button.
Incidentally, if you haven’t done the setup above, when you click the send button you’ll see an error message like this:

But if everything is setup correctly you’ll get:

The first time you open this form you’ll have to select your Outbound port name (which of course defines the folder you’re writing to). Then you have to setup the filter query to select the items which will be exported, and oddly this form doesn’t remember the filter query you previously used; nor does it default to the item selected when you click the Send button, and it doesn’t have a Batch tab to setup this function up as a recurring batch job. That’s the third customisation that’s required. Set your filter and click the OK button:

The system writes a trigger record into the AIF queue. Systems administration > Inquires > Services and Application Integration Framework > Queue manager:

AIF messages are processed by an AIF batch job, and this consists of four batch tasks. As I’ve said before there’s a good example of the batch job you need in the demo data. Systems administration > Inquires > Batch jobs > Batch jobs:

(If you setup your own job remember to setup the processing conditions so that the tasks process one after another in this sequence).
So we wait for the job to run, and hey presto a file appears in our outbound folder:

It’s an XML file with a unique date/time stamp file name. In this case the message looks like this:

If you don’t have a taste for the customisations required to export additional fields and convert this function to a recurring batch job check out this post: A simple outbound interface for Dynamics AX 2012.

Monday, August 6, 2018

RunBase Framework in Microsoft Dynamics AX 2012


Overview

RunBase framework provides a common software platform for data manipulation in Microsoft Dynamics AX. It provides a standardized pathway to create batch jobs and periodic processes.
RunBase framework can be used to run a process periodically or to manipulate some data over a period of time.
Using RunBase framework has the following advantages:
  1. All future updates are integrated automatically
  2. Common layout of dialog
  3. Remembering the user selections from the last run
  4. Easy to implement
To implement RunBase framework, extend a class with RunBaseBatch.

Pre-requisites

  1. Microsoft Dynamics AX 2012
  2. Batch server must be configured

Important Methods

  1. Run

    Run is the central method of the RunBase framework and is where all business logic is written. All data manipulation statements are placed in this method.
  2. Description

    Description is a static method that returns a descriptive name of a batch job. This name is then shown as a caption on the batch job dialog to identify the specific job in batch queue.
  3. Main

    Main is a static method which provides the entry point for a batch job. This method calls the prompt method, which calls the RunBase dialog, and run method which processes the batch job.

Scenario

As part of this tutorial, the RunBase class will mark all customers on-hold who have exceeded their credit limit.

Steps

  1. First create a new class. Open AOT àClasses
  2. Right click on Classes, select New Class, and create a new RunBaseDemo class

  3. Open the class declaration by right clicking on the RunBaseDemo class and selecting View Code

  4. Write the following code:
  5. class RunBaseDemo extendsRunBaseBatch
    {

    }
     

  6. Add a new method and name it as description. Write the following code in the method:
    client server static ClassDescription description()
    {
        return “Mark customers on-hold”;
    }

  7. Add a new method and name it as main. Write the following code in the method:
    static void main(Args _args)
    {
        RunBaseDemo objClass = new RunBaseDemo();

        //prompt for runbase framework dialog
        if (objClass.prompt())
        {
           //run the process
           objClass.run();
        }
    }

  8. Override the run method and write the following code:
    public void run()
    {
        CustTable custTable;

        //start transaction
        ttsbegin;

        try
        {
            //select all customers
            while select forUpdate * from custTable
            {

                //if credit limit is reached, placed on-hold
                if(custTable.CreditMax && custTable.balanceMST() > custTable.CreditMax)
                {
                    custTable.Blocked = CustVendorBlocked::Invoice;
                    custTable.update();
                }
            }

            //end transaction
            ttsCommit;
        }
        catch
        {
            //throw error of failure
            error(“Process failed”);
        }
    }


  9. Run the job by right clicking on the RunBaseDemo class and select Open. Alternatively, the job can also be called from a menu item

  10. The RunBase framework dialog will open

  11. There are two ways to run the batch job, only once and periodically
    1. If once, click OK. Use this option if you want to run the job just this time
    2. If periodically, schedule the batch job. Use this option if you want to run the job periodically. Follow the following steps to schedule the batch job
      • Check the Batch processing box
      • Select the respective batch group from the Batch group drop down
      • Click on the Recurrence button

      • In the Recurrence dialog, set an appropriate schedule and click OK

      • Click OK to schedule. It will now run the job according to the inputted schedule

      • Batch job history can be viewed from System administration à Inquiries à Batch jobs à Batch job history