Integrating Dynamics AX with Mobile apps using ASP.NET Web API

Introduction What if your customer asks you to integrate Dynamics AX with your Mobile application? In that case you need to be smart. If you have worked with WCF, you would be having an idea that when you host WCF you get a WSDL link which you can use to add a service reference. 

Dynamics AX has AIF (Application Integration Framework) which is used to integrate Microsoft Dynamics AX with external software systems.

MSDN says:

"Application Integration Framework (AIF) provides an extensible framework that supports multiple asynchronous transports, as well as synchronous transport using Web services, to reliably exchange documents in XML format with trading partners or other systems.

An exchange starts with a document, that is, a document class defined using Microsoft Dynamics AX business logic. The document is serialized into XML and header information is added to create a message, which may then be transferred into or out of your Microsoft Dynamics AX system (called the local endpoint within AIF)."

Now issue here is that you need to integrate different table of Microsoft Dynamics and need to Get and Post data to them. Two options here:

  1. create a WCF and host that to communicate with my Mobile Application that may be Android , iOS or Windows Phone & Store
  2. create ASP.NET web API and communicate with my Mobile Application.

Preferred to use ASP.NET web API on WCF, here are some of the reasons

WCF ASP.NET Web API
Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them. HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them. Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security. Uses basic protocol and formats such as HTTP, WebSockets, SSL, JQuery, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns. HTTP is request/response but additional patterns can be supported through SignalRand WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas. There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET framework. Ships with .NET framework but is open-source and is also available out-of-band as independent download.

Once we are done with developing our ASP.NET Web API we are going to host that using IIS Server and use public IP to let our mobile application communicate with our Microsoft Dynamics AX through Web API. Being mobile guy I don't have much idea of  Dynamics AX. It took me few hours to understand Dynamics AX and in this tutorial I would start from scratch as if you never interacted with Dynamics AX previously. So, lets start,

Lets start with a simple table, I would first create a simple table having not more than three attributes, 

  1. 1) ID
  2. 2) First Name
  3. 3) Last Name

and name the table as STUDENT.

We need to Create a Unique Index field as well because if we are targeting READ and FIND method of Document Service. In AOT under Query Node with Name AxdStudentInfo, create a new DataSource and add StudentInfoTable. Right click on field and set Dynamic Property to Yes

Now right click on “StudentInfoTable” Node and set its Update properties to true, so Update methods will created against this query object

Now in Development environment from top menu click on AIF frame and then select on Create Document Service and click on it. For this result in running a Wizard

Select following options from Wizard, select the query which we create above mentioned drop down.

  • Name the Document Name
  • Press Next button, from thenext button check all the checkbox as per following screen shot.
  • Press on Next Button
  • Press on Generate button.
  • Press On Finished button.

There is possibility of errors in generated code, You can find complete code generated with wizard in private project in Dynamics Ax.

Right click on AxdStudentInfo and compile again. You have delete two methods cacheObject and cacheRecordRecord in AxStudentInfoTable and compile the whole project.

Now right click on StudentInfoService and set namespace http://schemas.Student.com/ServiceContracts

Now create a right on Service group Node and create a new service group.

Drag and drop service node under Student InfoService group. So Student Service will be available for in side service group.

Now generate Inc CIL or right click on StudentInfoServicegroup and click deploy

After successful deployment you may find following info box

Now open a new work space and go at System Administration module and open in bound port under Application integration framework And Open Application Inbound framework

Copy WSDL URL and now our real work starts

Create New ASP.NET project and select Web Api from template.

Create New Controller and Create a Post Method for that.

Now we need to consume our WSDL Link, for that we need to first of all add a Service Reference in solution explorer. Enter your WSDL link complete he Wizard.

After you have added service reference you need to consume that service reference and sync that with POST method of your Web API.

POST method

public void Post([FromBody]Person value)
 {
 ServiceReference2AxdStudentQuery _TableQuery = new ServiceReference2AxdStudentQuery();
 ServiceReference2AxdEntity_StudentsTable_1 _StudentTable = new ServiceReference2AxdEntity_StudentsTable_1();
 _StudentTable.Name = value.Name;
 _StudentTable.ID = value.ID;
 _TableQuery.StudentsTable_1 = new ServiceReference2AxdEntity_StudentsTable_1[1] { _StudentTable };
 ServiceReference2StudentQueryServiceClient _Client = new ServiceReference2StudentQueryServiceClient();


 ServiceReference2CallContext _callContext = new ServiceReference2CallContext();
 _callContext.Company = "USMF";

 ServiceReference2EntityKey[] entityKeys = _Client.create(_callContext, _TableQuery);
 
 }

Now what you need to do is to start that Web Api in Google Chrome as it renders JSON more easily.we are using JSON as format of data so I need to add two lines to change that form XML to JSON. Add these lines in WebApiConfig.cs file

WebApiConfig.cs

 var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
 config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
 

To test it you just need to post to the URL of your Web API using any of the tool. I personally use Fiddler. When you would open Table in Table Explores you would notice that your POST have added data respectively to Dynamics Student Table. We are done with your Integration, Now next part here is to integrate that with  mobile.

All the work I have done here is in a server environment. To use that Web API I need to host that using IIS Server. Here a blog that you can follow. http://www.asp.net/web-api/overview/hosting-aspnet-web-api

Once you have hosted your Web API, you would be having a URL that you may use to hit that.

You can consume that API on any of the platform that supports JSON. e.g. Windows , Android, iOS or any platform including JAVA.

Let's try look at procedure to consume that in Universal Windows Platform Application.

Whenever you are parsing JSON you need to request data using Client. Well it's same for parsing Json.net way or native way.

Request data using Client:

First you need initialize client to request JSON data,

 var client = new HttpClient();

Then for obvious reasons you need to put request URL for JSON data,

request URL for JSON data:

HttpResponseMessage response = await client.GetAsync(new Uri("http://YourserviceURL"));

It's time to get JsonString so that we can parse that,

JsonString

var jsonString = await response.Content.ReadAsStringAsync();

Now here things become a bit tricky, my json is consisted to simple JSONArray, your JSON may appear a bit different from what my json looks like. Here is a way to know how your json looks like. Just navigate to http://json2csharp.com , put the url of JSON and it would return you with respective C# class of your JSON, You may use that to cast you JSON object.

As this JSON is a simple array so I just need to cast that to JSONArray and get out objects from that. I have saved my JSON respective C# class as  "RootObject"

JSON Root OBject

 JsonArray root = JsonValue.Parse(jsonString).GetArray();
 for (uint i = 0; i < root.Count; i++)
 {
 //Parse that accordingly
 });

here obs_mydata is the ObservableCollection where we are adding channels, whereas RootObject is my JSON respective C# class. Now you just need to bind your Observable Collection with UI. We would strongly suggest you to follow MVVM pattern and get full out of BLEND for VS.

To get respective C# class of your JSON you can use online tool like: http://json2csharp.com/

Credits

 Some of documentation of MSDN has been used as part of blog.