You are on page 1of 493

Table of Contents Introduction 0-1

Welcome ........................................................................................................ .... 0-1 Microsoft Dynamics Courseware Contents ........................................................ 0-2 Documentation Conventions .............................................................................. 0-3 Student Objectives ............................................................................................. 0-4

Chapter 1: Introduction to Services and Application I ntegration Framework

1-1

Objectives........................................................................................................ ... 1-1 Introduction...................................................................................................... ... 1-1 Concepts ......................................................................................................... ... 1-2 Integrations...................................................................................................... ... 1-9 Summary ........................................................................................................ .. 1-14 Test Your Knowledge ....................................................................................... 1-15 Quick Interaction: Lessons Learned ................................................................. 1-16 Solutions.......................................................................................................... . 1-17

Chapter 2: Architecture

2-1

Objectives........................................................................................................ ... 2-1 Introduction...................................................................................................... ... 2-1 High Level Features and Concepts .................................................................... 2-2 Topology.......................................................................................................... ... 2-7 Usability ......................................................................................................... ..... 2-9 Support for Data Model Changes ..................................................................... 2-14 Summary ........................................................................................................ .. 2-15 Test Your Knowledge ....................................................................................... 2-16 Quick Interaction: Lessons Learned ................................................................. 2-17 Solutions.......................................................................................................... . 2-18

Chapter 3: Installation and Upgrade

3-1

Objectives........................................................................................................ ... 3-1 Introduction...................................................................................................... ... 3-1 Installation ....................................................................................................... ... 3-2 Lab 3.1 - Configure Services to Use IIS ........................................................... 3-16 Lab 3.2 - Install MSMQ..................................................................................... 3-19 Upgrade........................................................................................................... . 3-22 Summary ........................................................................................................ .. 3-29 Test Your Knowledge ....................................................................................... 3-30 Quick Interaction: Lessons Learned ................................................................. 3-31 Solutions.......................................................................................................... . 3-32

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Application Integration Framework and Services in Microsoft Dynamics AX 2012 Chapter 4: Administration 4-1

Objectives........................................................................................................ ... 4-1 Introduction...................................................................................................... ... 4-1 Set Up Batch ...................................................................................................... 4-2 Lab 4.1 - Set Up Batch ....................................................................................... 4-6 Integration Ports ................................................................................................. 4-9 Adapters ......................................................................................................... .. 4-15 Summary ........................................................................................................ .. 4-24 Test Your Knowledge ....................................................................................... 4-25 Quick Interaction: Lessons Learned ................................................................. 4-27 Solutions.......................................................................................................... . 4-28

Chapter 5: Development Concepts

5-1

Objectives........................................................................................................ ... 5-1 Introduction...................................................................................................... ... 5-1 Service Types..................................................................................................... 5-2 Document Services ............................................................................................ 5-7 Lab 5.1 - Add Validation and Defaulting to a Web Service............................... 5-24 Lab 5.2 - AIF Document Service Wizard .......................................................... 5-25 Custom Services .............................................................................................. 5-27 System Services............................................................................................... 5-27 How AIF Exchanges Data ................................................................................ 5-31 Customizing the AIF Pipeline ........................................................................... 5-41 Business Operations Framework ..................................................................... 5-52 Lab 5.3 - Business Operations Framework ...................................................... 5-56 Security .......................................................................................................... .. 5-58 Summary ........................................................................................................

.. 5-64 Test Your Knowledge ....................................................................................... 5-65 Quick Interaction: Lessons Learned ................................................................. 5-68 Solutions.......................................................................................................... . 5-69

Chapter 6: Working With Services

6-1

Objectives........................................................................................................ ... 6-1 Introduction...................................................................................................... ... 6-1 Call an External Service ..................................................................................... 6-2 Create and Call a Custom Service by Using a Basic Port.................................. 6-6 Lab 6.1 - Create and Call a Custom Service by Using a Basic Port................. 6-10 Call a Document Service by Using NetTcp ...................................................... 6-13 Lab 6.2 - Call a Document Service by Using NetTcp ....................................... 6-17 Call a Document Service with the File Adapter ................................................ 6-20 Lab 6.3 - Call a Document Service with the File Adapter ................................. 6-26 Create a Synchronous Document Exchange between BizTalk and AIF .......... 6-30 Exchange Documents by Using the MSMQ Adapter........................................ 6-36 Call the Metadata Service ................................................................................ 6-42

ii

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Table of Contents
Lab 6.4 - Call the User Session Service........................................................... 6-46 Create and Deploy Outbound Exchange.......................................................... 6-48 Lab 6.5 - Create and Deploy an Outbound Exchange...................................... 6-60 Summary ........................................................................................................ .. 6-67 Test Your Knowledge ....................................................................................... 6-68 Quick Interaction: Lessons Learned ................................................................. 6-69 Solutions.......................................................................................................... . 6-70

Chapter 7: Troubleshooting and Logging

7-1

Objectives........................................................................................................ ... 7-1 Introduction...................................................................................................... ... 7-1 Monitoring Services and AIF .............................................................................. 7-3 Troubleshooting............................................................................................... . 7-10 Lab 7.1 - Debugging Services .......................................................................... 7-16 Summary ........................................................................................................ .. 7-19 Test Your Knowledge ....................................................................................... 7-20 Quick Interaction: Lessons Learned ................................................................. 7-21 Solutions.......................................................................................................... . 7-22

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

iii

Application Integration Framework and Services in Microsoft Dynamics AX 2012

iv

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework

CHAPTER 1: INTRODUCTION TO SERVICES AND APPLICATION INTEGRATION FRAMEWORK


Objectives
The objectives are: List the high-level features of Services and Application Integration Framework (AIF).

Introduction

Discuss integration planning and options.

Microsoft Dynamics AX 2012 provides many services that can be used by the Microsoft Dynamics AX components and with third-party applications. Services are programmable artifacts in Microsoft Dynamics AX 2012. There are many out-of-the-box document services that are shipped with Microsoft Dynamics AX 2012, which can be used as it is, or customized to fit requirements. Additionally, new document services can be created, and any static method call can be exposed as a service. All customizable application and framework X++ services in Microsoft Dynamics AX 2012 are compiled to Microsoft Intermediate Language (MSIL). These services can be grouped together and deployed to ports, which is a new concept introduced in Microsoft Dynamics AX 2012. A port represents a Windows Communication Foundation (WCF) service endpoint. By default, a port is hosted on the Application Object Server (AOS). Microsoft Dynamics AX 2012 also ships with three non-customizable system services: the Metadata service, the Query service, and the User session service. With these services, clients can interact with and retrieve system information, thus enabling the development of more powerful applications, data queries through Office add-ins, and inquiries into system structure.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

1-1

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Services and the Application Integration Framework
In Microsoft Dynamics AX 2012, services provide a first-class programming model for integration and enable the Microsoft Dynamics AX application to expose its functionality by means of Windows Communication Foundation-based services. Application Integration Framework (AIF), built on top of services, supports the processing of incoming and outgoing messages, such as message transforms and value look ups. Together, services and AIF provide the programming model, tools, and infrastructure support for message-based integration of application functionality and data with Microsoft Dynamics AX. Services and AIF is composed of a number of concepts. Distinguishing between these concepts will help provide a building block for understanding the full capability of Services and AIF. This lesson briefly introduces the concepts in Services and AIF, which will be explained in detail in later chapters. The following table shows the key concepts of Services and AIF. Feature Application Integration Framework Description The Application Integration Framework (AIF) helps users integrate Microsoft Dynamics AX 2012 with other systems that are inside and outside of the enterprise by allowing for the exchange of data through formatted XML, and other formats through

Concepts

1-2

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework


Feature Services Description Application Object Server (AOS) is the Windows Communication Foundation (WCF) service host for Microsoft Dynamics AX 2012 services that are exposed to users and applications on an intranet. To consume services over the Internet, you must host services on Internet Information Services (IIS). Services that are hosted on IIS use the WCF message routing service. IIS routes all service requests to AOS. All service requests are processed on AOS, regardless of whether they originate on the Internet or an intranet. AOS then returns a response to the service consumer through IIS. Exchanges that are configured to use web services are processed synchronously and are therefore not queued. Service operations are the capabilities that are offered by a service, and include: create Service groups delete find findKeys getKeys getChangedKeys read

Service operations

update A service group is a collection of services that are intended to be managed together. Each service group is associated with one WSDL rather than having one WSDL for each

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

1-3

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Feature Integration ports Description In Microsoft Dynamics AX 2012, integration ports provide simplified administration of services and Application Integration Framework (AIF). Integration ports replace the AIF endpoints and related concepts that were used in previous releases of Microsoft Dynamics AX. Each integration port can expose one or more service operations, and each integration port has a unique Uniform Resource Identifier (URI) that identifies the address of the port. The following list shows the available integration ports: Basic Inbound Port Enhanced Inbound Port In Microsoft Dynamics AX 2012 services and Application Integration Framework (AIF), integration ports use adapters. These adapters enable Microsoft Dynamics AX to communicate by using various transport protocols. Microsoft Dynamics AX 2012 provides the following four adapters that represent predefined bindings: HTTP Messages NetTCP MSMQ (Microsoft Message Queuing) In Microsoft Dynamics AX 2012 services and Application Integration Framework (AIF). messages use the SOAP specification, even for MSMQ and File System adapters. A message is a self-contained unit of data that can consist of several parts. These parts include an envelope, body, and header. When AIF receives and processes an inbound message, it generates an outbound message AIF requires XML documents to follow a specific XML Schema Definition (XSD). XSD files (which have a .xsd file name extension) are meta-documents that describe the format, or schema of XML documents that declare the namespace of the XSD. Each schema includes rules about the hierarchical arrangement of XML elements, which elements must be present in the document,

Adapters

Schemas

1-4

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework


Feature Transforms Description To accommodate for the fixed schema that is required by AIF, the following transforms were introduced. eXtensible Stylesheet Language Transform (XSLT) - XML-based language to transform an XML document to a different XML document. .NET assembly - Custom logic to allow a programmer to perform tasks such as converting a .csv to an .xml

Refactored Services
In Microsoft Dynamics AX 2012 Microsoft improved services with the following key areas: Simple setup and configuration A first class programming model Aligning with industry standards Richer integration of specific features Performance enhancements

Simple Setup and Configuration


In Microsoft Dynamics AX 2012, user interfaces were simplified. In previous versions of Microsoft Dynamics AX, there were 17 top-level concepts on menus. Microsoft Dynamics AX 2012 has four top-level concepts. Inbound ports Outbound ports Value substitution maps Web sites Microsoft Dynamics AX 2012 applies the "Progressive Disclosure" principal to accomplish a more simplistic setup and configuration, while adding more capabilities. With this applied principal, administrators are only provided options when they need them. For example: Service contract customizations are available when you configure enhanced inbound ports, but not when you configure basic inbound ports. In addition to a simplified user interface, the following changes were made to simplify the experience by using and administering services and AIF in Microsoft Dynamics AX 2012.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

1-5

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Change Services hosted on the AOS IIS services hosted without a .NET Business Connector Description The Application Object Server (AOS) is the WCF service host for Microsoft Dynamics AX 2012 services. Services that are hosted on AOS are mainly intended to be consumed from the In the previous release of Microsoft Dynamics AX, IIS-hosted services required .NET Business Connector to communicate with the AOS. In Microsoft Dynamics AX 2012, IIShosted services use the WCF routing service instead of the .NET Business Connector. The business connector proxy user account is still required for running the IIS application pool, and it must match the user business connector proxy user account that is specified in Microsoft Dynamics AX system accounts and the business connector proxy user account that The AutoDeploy property on service groups allows these groups to be deployed without administrator interaction.

First Class Programming Model


Some of the steps that have been taken to transform services into a first class programming model include the following: System services like Query service, Metadata data service, and user session service have been added No custom code is needed to expose X++ logic as a service because declarative attributes are now available to help the developer do this "Always On" service groups work out-of-the-box Document service code generation transparently handles the Microsoft Dynamics AX 2012 data model changes

AutoDeploy property on service groups

Align with Standards


Microsoft Dynamics AX 2012 provides expanded support for Windows Communication Foundation (WCF), beyond the basic HTTP and HTTPS bindings. The proprietary BizTalk Server adapter that is used in the previous releases of Microsoft Dynamics AX is no longer available. Instead, Microsoft Dynamics AX 2012 provides equivalent functionality through native WCF functionality. However, custom adapters that were developed by customers and partners by using the AIF adapter framework continue to be supported in this release.

1-6

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework


New Features
Services and AIF for Microsoft Dynamics AX 2012 include feature improvements, which are shown in the following table. Feature Service groups Integration ports Description With service groups, a developer can group related services together. Integration ports provide a simple interface to control data that is going into and coming out of services and AIF. Data that is not XML, for example, a commadelimited file, can now be imported into and exported from Microsoft Dynamics AX. In Microsoft Dynamics AX 2012, you can submit large amounts of data by using the batch XML schema. This schema allows you to group single messages into message sets that can be submitted together by using a single XML document. In Microsoft Dynamics AX 2012, you can configure the database to keep track of when changes happen at the table level. When so configured, you can use the getChangedKeys service operation to retrieve entity keys for only those documents that have changed based on Several improvements were made to enhance the overall performance of services and AIF in Microsoft Dynamics AX 2012. Microsoft Dynamics AX 2012 offers a robust and flexible security framework. Users are granted access to Microsoft Dynamics AX based on their assigned role. Services and AIF rely on WCF for additional security. You can change the WCF configuration to make necessary security settings that are required by Microsoft Dynamics AX services. WCF is responsible for authenticating the user. Service-level authorization is defined by the A new table links message and exception log data. You can do a full-text search for all records in the following AIF forms: Exceptions

Support for non- XML files Batched messagin g Change tracking

Performanc e improved Security

Improved troubleshootin g

Microsoft Official Training Materials for Microsoft Dynamics

Your use of this

content is subject to your current services agreement

1-7

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Feature Support data model changes Description The document services framework supports the data model changes that are implemented in Microsoft Dynamics AX 2012.

Performance Enhancements
The following list describes enhancements in services and AIF that result in improved performance: Compiled CIL is used to process Services. To achieve scale and redundancy, you can configure AOS servers with the Network Load Balancing (NLB) for Microsoft Dynamics AX services. The AOS-clustering solution affects only the RPC- based connections and does not allow you to load balance Microsoft Dynamics AX services. Client applications can access services through the WCF runtime without using .NET Business Connector, which was required for services and AIF in previous releases of Microsoft Dynamics AX. A deployment on an intranet does not require IIS because services are now hosted on the AOS by default. You can host services on IIS for requests that originated from the Internet; however, the routing service on IIS dispatches these requests to the AOS host. All service requests, regardless of the origin, are processed on the AOS. The services framework uses connection pooling to reduce the overhead of creating and destroying a session on service calls. All of the services references are placed in a single web services description language (WSDL) file. The single helps helps developers reuse types when they are consuming Microsoft Dynamics AX services.

Architecture
Microsoft Dynamics AX exposes its functionality through services that are based on Windows Communication Foundation (WCF) and hosted on Application Object Server (AOS) by default, or Internet Information Services (IIS) with extra configuration. All services requests, regardless of their origin, are handled by the WCF runtime that is hosted on AOS. External applications and client applications on the local area network consume Microsoft Dynamics AX services by accessing them directly from AOS.

1-8

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework


These clients and applications include Microsoft Dynamics AX components such as the Microsoft Dynamics AX client, Office Add-ins for Microsoft Dynamics AX, and Enterprise Portal for Microsoft Dynamics AX. Internet-based external applications and clients can access the Microsoft Dynamics AX services through IIS. IIS routes the incoming requests for Microsoft Dynamics AX services to AOS.

Integrations
Most Microsoft Dynamics AX 2012 implementations will require integrating with one or more other systems. Some examples of outside systems that would require integration to Microsoft Dynamics AX 2012 include: An ERP in another division A corporate website A shipping station Creating and maintaining these integrations can be one of the more difficult tasks that are performed in an implementation, and careful planning should be performed to ensure smooth implementation and operation of these integrations. Services and Application Integration Framework (AIF) provides a capable platform for implementing these integrations.

Integration by Using Services


Integrations to external systems are best implemented by using the services programming model. Although the weakly-typed and stronglytyped .NET interop to X++ can be used for the integration development pattern, we do not recommend the use of these technologies for integration. Their firewall unfriendliness, combined with their dependencies on Business Connector assemblies make these technologies unfit for most integration scenarios. If the functionality that you need is not available in a service that ships with Microsoft Dynamics AX 2012, you can use the declarative attributes to expose existing X++ classes and methods as a service interface.

Service Types
To support a range of options for customization and programmability, including writing integrations, Microsoft Dynamics AX provides the following types of services: Custom Services are services that you create to expose X++ logic through a service interface. You can use the business logic with inbound or outbound transfers.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

1-9

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Document Services represent data and business logic within Microsoft Dynamics AX. You can use or customize the over 70 standard Axd document services that are included with Microsoft Dynamics AX. If none of the standard document services meet your needs, you can create a new document service by using the AIF Document Service Wizard. System Services cannot be customized. The Query Service, Metadata Service, and User Session Service are Windows Communication Foundation (WCF) services that are included with Microsoft Dynamics AX. The services provide access to data that is returned in queries, metadata for AOT objects such as tables and extended data types (EDTs), and data about the calling user such as default language and default company.

Integration Planning
Planning is an important part of any data integration effort. When you integrate Microsoft Dynamics AX with other systems, one of the first steps is the planning phase. In this phase, the implementation team must define high-level requirements and make decisions about the design of the integration. After these requirements are defined, the partner, IT staff, and development staff can work together to define the best way to implement the exchange in Application Integration Framework (AIF). The decisions that must be made about the design of the integration fit into two primary categories: decisions about the data and decisions about the environment. Data - Central to integration is the data. While planning the integration, you must make many decisions about the data that is being exchanged and the associated business rules. This phase often involves the expertise and knowledge of business users, because these users understand the meaning of the data and can define the requirements for integration. Environment - Configuration requirements define the environment that is used for integrations. Factors that affect these requirements include the network configuration, the hardware and software configuration of the external system, and the level of trust between Microsoft Dynamics AX and the external system.

1-10

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework


Before integrations are created, we recommend that the implementation team consider the questions that are described in the following table. Question What data will need to be exchanged? Effect on the Design This information helps you determine whether you can take advantage of an existing document service. If you cannot, you might have to create a new document service or a new custom service, or you might have to use one of the system This information helps you determine whether you must use an inbound or outbound integration port. This information helps you determine how to configure a document exchange. Integrations that pull data into Microsoft Dynamics AX 2012 will need to use an integrating technology other than Services This information helps you determine whether any customizations must be made to existing AIF documents. This information helps you determine whether AIF value mapping, .NET transformations, or XSLT transformations must be used.

Is the data sent from Microsoft Dynamics AX to an external system, or is the data received by Microsoft Dynamics AX from an external system? Is the integration based on the "pull" model or the "push" model? In the "pull" model, the external system requests data from Microsoft Dynamics AX. In the "push" model, an event in the application causes data to be sent to the external Is there any business logic that needs to be implemented for this integration that would not be found in existing AIF documents? Do the documents that are sent or received need to be transformed? Do the transformations have to be performed before data is sent or when data is received? What is the extent of the data transformations? Are the transformations performed by Does the external system have any restrictions about how data is exchanged? In other words, the external system can only create .csv documents, and it can only save them to the local Is the external system an inhouse system or an external trading partner?

This information helps you determine the type of transport adapter that is required for the exchange. This information helps you determine how users and security must be configured.

Microsoft Official Training Materials for Microsoft Dynamics

Your use of this

content is subject to your current services agreement

1-11

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Question What is the availability of the systems that are being integrated? What are the requirements for real- time data What is the volume of transactions? Effect on the Design This information helps you determine whether you must use synchronous or asynchronous adapters. This information helps you determine which adapters you must use. The information also helps you determine the scale of the deployment, such as the number of computers that run Application Object Server

Integration Planning Process


Typical integration scenarios use document-based exchanges. Whether you require integration with internal legacy systems or external trading partners, planning for the integration involves common key steps. 1. In a typical integration scenario, users who have business expertise first determine the requirements for document exchanges. These are requirements from a business perspective. The business users work with the implementation team to determine the following requirements: o The data that must be exchanged o Any business logic that is related to that data o The external systems with which data must be exchanged o The conditions under which data is sent from or received by Microsoft Dynamics AX 2. The system implementer works with the IT staff to determine the hardware and software requirements for Application Integration Framework (AIF). The system implementer analyzes the existing environment and recommends any new hardware or software that must be installed. 3. The IT staff installs and configures any hardware and software that are required to support AIF, and sets up the required authentication, encryption, and authorization. 4. A developer programs the document exchange. The developer can either customize the AIF documents or create new documents to meet the requirements of the business users. The configuration of AIF partly depends on the network environment. Therefore, the developer can work with the IT staff to implement an integration scenario. 5. The IT staff monitors the document exchanges and troubleshoots any errors that are generated.

1-12

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework


The following figure provides a high-level view of the process that is used to integrate Microsoft Dynamics AX with other systems.

FIGURE 1.1 INTEGRATION PLANNING PROCESS

Skills Required
The following are the skills and expertise that is needed to fully take advantage of services and AIF: X++ development C# and Visual Studio Internet Information Services (IIS) administration, if IISbased web services are deployed Windows Communication Foundation (WCF)

Microsoft Official Training Materials for Microsoft Dynamics

Your use of this

content is subject to your current services agreement

1-13

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Integration concepts, such as enterprise application integration (EAI), business-to-business (B2B), and synchronous and asynchronous transports Microsoft .NET Framework 4.0 Microsoft Message Queuing (MSMQ), if used

Summary
Services and AIF for Microsoft Dynamics AX 2012 provide a first class programming experience for integrations and creating applications. These technologies allow data to be passed into external systems from Microsoft Dynamics AX 2012, and into Microsoft Dynamics AX 2012 from external systems, by using XML and other formats. In Microsoft Dynamics AX 2012, services and AIF were refactored for simplicity, alignment with industry standards, and to add more capabilities. These changes include: Reducing high level concepts from 17 to 4 Adding features that allow services and AIF to be used for more than integrations Support for WS-* compliant services Service groups Support for non XML files Batched messaging Change tracking

1-14

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework

Test Your Knowledge


Test your knowledge with the following questions. 1. Categorize the following features: 1. Service Groups 2. Integration port 3. Support for non-XML files 4. Performan ce improved 5. Support data model changes 6. Improved troubleshooti ng 7. Change tracking 8. Batched messaging a. Service groups help a developer group related services together. b. In Microsoft Dynamics AX 2012, you can submit large amounts of data by using the batch XML schema. This schema helps you group single messages into message sets that can be submitted together by using a single XML document. c. In Microsoft Dynamics AX 2012, you can configure the database to keep track of when changes happen at the table level. When so configured, you can use the getChangedKeys service operation to retrieve entity keys for only those documents that have changed based on certain criteria, such as a specified date and time. d. Integration ports provide a simple interface to control data going into and coming out of services and AIF. e. Several improvements were made to enhance the overall performance of services and AIF in Microsoft Dynamics AX 2012. f. The document services framework supports the data model changes that are implemented in Microsoft Dynamics AX 2012. g. In Microsoft Dynamics AX 2009, the troubleshooting and logging of AIF was performed at the service operation level. In Microsoft Dynamics AX 2012, services and AIF troubleshooting and logging is performed at the integration port level. h. Data that is not XML, for example, a comma- delimited file, can now be imported into and exported from Microsoft Dynamics AX.

2. What is the preferred method for integrating to Microsoft Dynamics AX 2012? ( ) .NET Interop ( ) .NET Business Connector ( ) Services

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

1-15

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this chapter 1.

2.

3.

1-16

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 1: Introduction to Services and Application Integration Framework

Solutions
Test Your Knowledge
1. Categorize the following features: a 1. Service Groups d 2. Integration port h 3. Support for non-XML files e 4. Performan ce improved f 5. Support data model changes g 6. Improved troubleshooting c 7. Change tracking b 8. Batched messaging a. Service groups help a developer group related services together. b. In Microsoft Dynamics AX 2012, you can submit large amounts of data by using the batch XML schema. This schema helps you group single messages into message sets that can be submitted together by using a single XML document. c. In Microsoft Dynamics AX 2012, you can configure the database to keep track of when changes happen at the table level. When so configured, you can use the getChangedKeys service operation to retrieve entity keys for only those documents that have changed based on certain criteria, such as a specified date and time. d. Integration ports provide a simple interface to control data going into and coming out of services and AIF. e. Several improvements were made to enhance the overall performance of services and AIF in Microsoft Dynamics AX 2012. f. The document services framework supports the data model changes that are implemented in Microsoft Dynamics AX 2012. g. In Microsoft Dynamics AX 2009, the troubleshooting and logging of AIF was performed at the service operation level. In Microsoft Dynamics AX 2012, services and AIF troubleshooting and logging is performed at the integration port level. h. Data that is not XML, for example, a comma- delimited file, can now be imported into and exported from Microsoft Dynamics AX.

2. What is the preferred method for integrating to Microsoft Dynamics AX 2012? ( ) .NET Interop ( ) .NET Business Connector () Services

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

1-17

Application Integration Framework and Services in Microsoft Dynamics AX 2012

1-18

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture

CHAPTER 2: ARCHITECTURE
Objectives
The objectives are: Review high level flows in Services and Application Integration Framework (AIF). Discuss the topology of the Services and AIF model. Describe moving service configurations by using integration ports in AIF. Discuss the new process of change tracking. Review the transforms that are available for customization in banking. Demonstrate Excel Document Service Registration. Review support data model changes in Microsoft Dynamics AX 2012. Application Integration Framework (AIF) helps companies integrate Microsoft Dynamics AX with external business processes and partners through the exchange of XML over various transport media. As mentioned in the "Architecture lesson" of Chapter 1: Introduction to Services and Application Integration Framework all services are WCF based and hosted on AOS. When intranet communication is needed for services that are using IIS, the requests are routed to AOS for processing. Inbound and outbound messages can take advantage of message transforms or value substitutions when they are configured to do this.

Introduction

Microsoft Official Training Materials for Microsoft Dynamics

Your use of thi

content is subject to your current services agreement

2-1

Application Integration Framework and Services in Microsoft Dynamics AX 2012


The following diagram illustrates the services and AIF architecture.

FIGURE 2.1 SERVICES AND AIF ARCHITECTURE

High Level Features and Concepts


The process flows in Microsoft Dynamics AX2012 are managed by integration ports, simplifying the administration of services and the AIF. This replaces AIF endpoints and related concepts that were used in previous releases of Microsoft Dynamics AX. This lesson will review those high level processes and illustrate the following flowing features and concepts. Synchronous and asynchronous transports Basic and enhanced ports Inbound and outbound message exchanges Service types

2-2

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture
Service operations Service groups

Synchronous and Asynchronous Transports


AIF supports synchronous and asynchronous transports for exchanging XML documents with external systems. In synchronous mode, requests are tightly coupled to responses, and the same connection is used for the request and the response. In this case, AIF immediately processes the request and then sends a response. In asynchronous mode, requests are sent through a queue, called the gateway queue. Queued messages are processed at a later time. In this case, responses are delayed, but large volumes of messages can be processed more efficiently, and message processing can be controlled by changing various configuration settings.

Basic Integration Ports


Basic integration ports are exposed through a specific Windows Communication Foundation (WCF) endpoint on the Application Object Server (AOS) host. Only a developer can create a new basic integration port. When a developer creates a service group in the Application Object Tree (AOT), a basic inbound integration port is also automatically created if the autoDeploy property is set to yes. The basic inbound integration port is then associated with the service group. Some basic integration ports, such as those that are used for system services, are auto deployed and enabled by default.

Enhanced Integration Ports


If you want advanced integration capabilities that you can use to customize the behavior of an integration port, you must create an enhanced integration port. Enhanced integration ports provide the following capabilities that basic integration ports do not provide: Services can be hosted on either AOS or Internet Information Services (IIS). A variety of protocols are supported through WCF adapters. These protocols include HTTP and NetTCP. Enhanced integration ports also support a file system adapter that lets you use file paths as addresses and a MSMQ adapter. You can configure pre-processing and post-processing of service requests and service responses, for instance through configurable transformations. You can customize service and data contracts by selecting the set of service operations that are exposed when you create the data policies. You can specify advanced security and troubleshooting settings.

Change tracking is supported

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-3

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Inbound and Outbound
Inbound ports are used by external systems to call Microsoft Dynamics AX AIF and services. This kind of exchange is called an inbound exchange. For example, during an inbound exchange, an external system can send a sales order so that the sales order can be saved to the Microsoft Dynamics AX database. AIF can also be used by Microsoft Dynamics AX to call external systems. For example purchase orders can be sent electronically to an external system by using an outbound exchange. Some outbound exchanges can be triggered by an inbound message. For example, an external system might send an inbound request for information about a specific product and receive product information from an outbound message. This kind of exchange is called an outbound exchange.

How Documents are Exchanged


AIF provides an extensible framework for the exchange of XML documents with external systems. The framework supports synchronous and asynchronous transports. In synchronous mode, requests are tightly coupled to responses. This means that the submitter of the request must wait for a response from AIF before proceeding. In this case, AIF immediately processes the request and then sends a response. In asynchronous mode, requests are placed into a queue, called the gateway queue. Queued messages are processed at a later time and AIF sends a response when processing is completed. In this case, responses are delayed, but large volumes of messages can be processed more efficiently, and message processing can be controlled by changing various configuration settings. AIF can be used to send data into Microsoft Dynamics AX. This kind of exchange is called an inbound exchange. For example, during an inbound exchange, an external system might send a sales order so that the sales order can be saved to the Microsoft Dynamics AX database. AIF can also be used to retrieve data from Microsoft Dynamics AX. This kind of exchange is called an outbound exchange. For example, during an outbound exchange, an external system might send a request for a purchase order and receive the purchase order. The inbound and outbound exchanges can be categorized in the following ways: Send data Microsoft Dynamics AX sends documents to an external system. Send data in response to requests Microsoft Dynamics AX receives requests for documents from another authorized system, and retrieves the requested information, such as a document or a list of documents, from the Microsoft Dynamics

AX database. Microsoft Dynamics AX then returns the information to the requesting system, and the appropriate filtering and security are applied. The request message contains the entity keys or a query that specifies the data that the external system is requesting.

2-4

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture
Receive and create data Microsoft Dynamics AX receives documents from another authorized system and creates new records in the Microsoft Dynamics AX database.

Parallelism
To improve performance for data exchange by using asynchronous adapters, AIF supports parallelism. Parallelism specifies that inbound messages are processed by one or more AOSs without regard to the order in which they are received or produced. This helps you scale out message processing by adding multiple AOSs. Note that you can enable parallelism only for inbound channels. Parallel processing in AIF is implemented on a channel-by-channel basis. Follow these steps to implement parallel processing. 1. Click System Administration > Setup > Services and Application Integration Framework > Inbound Port or System Administration > Setup > Services and Application Integration Framework > Outbound Port. 2. Select a channel and select the Process requests in parallel check box. Conversational parallelismalso known as ordered parallelismmeans that you can specify certain messages to be processed sequentially in a channel, even when parallelism is enabled for that channel. This is done by including a special XML element called <ConversationId> in the messages that require sequential processing. All messages with the same ConversationId will then be processed sequentially. NOTE: If you do not select the Parallel processing field in the Channels form, all inbound messages for a particular endpoint will be processed sequentially and the <ConversationId> element in a message is ignored.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-5

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Service Types
Microsoft Dynamics AX, together with AIF, enables building integrations with other systems. By using the programming model for Microsoft Dynamics AX services, you can customize the document services that are included with Microsoft Dynamics AX 2012, create new custom services. To support a range of option for customization and programmability, Microsoft Dynamics AX provides the following types of services: Document Services - Services that represent data and business logic within Microsoft Dynamics AX. You can use or customize the over 70 standard Axd document services that are included with Microsoft Dynamics AX. If none of the standard document services meet your needs, you can create a new document service by using the AIF Document Service Wizard. Each document is represented by a class; the name of a document class is preceded by Axd. For example, AxdSalesOrder is the name of the document and also the name of the document class. Custom Services - Services that you create to expose X++ logic through a service interface. You can use the business logic with inbound or outbound transfers. System Services - Services that cannot be customized. The Query Service, Metadata Service, and User Session Service are Windows Communication Foundation (WCF) services that are included with Microsoft Dynamics AX. They provide access to data that is returned in queries, metadata for AOT objects such as tables and extended data types (EDTs), and data about the calling user such as default language and default company.

Document Service Operations


A service operation is a named set of functionality that is offered by a service. A service can expose multiple service operations. The service operations that a service exposes can include custom service operations. For example, the sales order document services service operation that creates a new sales order is named SalesSalesOrderService.create. Service operations include: create, delete, find, findkeys, getkeys, getchangedkeys, read, and update NOTE: When you configure an integration port, you must know which service operations have to be exposed from the port.

2-6

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture
Service Groups
Developers can group services and service operations that are managed and consumed together into a service group. All the services in a service group are published through a basic port, in a single WSDL file. The WSDL contains all service and data contracts for the service operations of the service group, which simplifies developing the code that consumes services. NOTE: A Web Service Description Language (WSDL) file defines the operations that are available for a service. Developers can create a service group in the Application Object Tree (AOT). Developers can use the AutoDeploy property to specify whether the service groups that they create are automatically deployed and activated when they are created. Developers must manually deploy and activate any service groups that are not automatically activated. NOTE: Service groups are associated only with basic integration ports.

Topology
There are certain factors to consider when you plan the topology of services and Application Integration Framework (AIF).

Adapters
In Microsoft Dynamics AX 2012 services and Application Integration Framework (AIF), integration ports use adapters. These adapters enable Microsoft Dynamics AX to communicate by using various transport protocols. Microsoft Dynamics AX 2012 provides the following four adapters that represent predefined bindings: HTTP adapter - This adapter enables synchronous exchanges through web services on Internet Information Services (IIS), which can expose services on a network or the Internet. NOTE: Web Services should in general never be deployed by using basic HTTP binding. HTTPS bindings or similar, should be selected even for internal use. When you use the HTTP binding, all data will travel unencrypted and can be read by anyone on the same segment on the network. NetTCP adapter - This adapter enables synchronous exchanges by using support for WS-* standards over the Transmission Control Protocol (TCP) transport.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-7

Application Integration Framework and Services in Microsoft Dynamics AX 2012


MSMQ adapter - This adapter enables asynchronous exchanges through message queues. To use this adapter, you must install Message Queuing, which is also known as MSMQ, on a network computer. You must also create at least one public queue to configure the MSMQ Adapter for Microsoft Dynamics AX. File System adapter - This adapter enables asynchronous exchanges through file system directories. You must enable and configure at least one file system directory, or folder, for messages. Inbound messages and outbound messages require separate folders. NOTE: Microsoft Dynamics AX 2012 no longer includes a BizTalk adapter. Earlier versions of Microsoft Dynamics AX required a BizTalk adapter for integration with Microsoft BizTalk Server. However, BizTalk Server can now connect to AIF through standards-based adapters. For more information, see Exchanging documents between BizTalk Server and AIF (http://go.microsoft.com/fwlink/?LinkID=247431&clcid=0x409 ) and the Using Microsoft BizTalk Server 2010 to Exchange Documents with Microsoft Dynamics AX (http://go.microsoft.com/fwlink/? LinkID=247479&clcid=0x409 )whitepaper.

Performance Improvements
The following list describes enhancements in services and AIF that result in improved performance: To achieve scale and redundancy, you can configure AOS servers with the Network Load Balancing (NLB) for Microsoft Dynamics AX services. The AOS-clustering solution affects only the RPC- based connections and does not allow you to load balance Microsoft Dynamics AX services. For more information, refer to Configuring network load balancing for services (http://go.microsoft.com/fwlink/? LinkID=247480&clcid=0x409 ). Client applications can access services directly on AOS; IIShosted services use the WCF routing service and no longer depend on the .NET Business Connector, which was required for services and AIF in previous releases of Microsoft Dynamics AX. The services framework uses connection pooling to reduce the overhead of creating and destroying a session on service calls.

When to Use IIS Hosting


To consume services over the Internet, you must host services on Internet Information Services (IIS). IIS uses the message routing

service to route all service requests to AOS where all service requests are processed.. AOS then returns a response to the service consumer through IIS. Microsoft Dynamics AX deploys services that are hosted on IIS to a subfolder of the virtual directory that is associated with the web site that you provide.

2-8

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture

Usability
New usability features of services and Application Integration Framework (AIF) are added to Microsoft Dynamics AX 2012. The following are components of the new features. Moving service configurations by using integration ports in AIF Change tracking based on date and time of changes Templates for the transforms for Banking Configure services for Office add-ins

Office Add-ins
The new add-in for Microsoft Excel and Microsoft Word help users to view, analyze, and update information in Microsoft Dynamics AX. The Microsoft Excel add-in has built-in support for consuming document services for updating data.

Excel Document Service Registration


Data in Microsoft Excel can be modified by using any document service that has a Create or Update service operation, and that uses a file adapter or net.tcp. Before using a document service, you must register it, add it to an inbound integration port, activate the port, and then expose the service. Only the following document services from Microsoft Dynamics AX 2012 are supported without modification in the Excel Add-in: BudgetTransaction EMSMeterReading EMSSubstanceFlow GeneralJournal ProductionPickingList ProjectHourJournalS SysImportBusSector VendGroup VendRequestSignup Additional services can be constructed to extend the scenarios in which Excel can be used to update, create, and delete business data in Microsoft Dynamics AX. NOTE: The configuration of integration ports for Excel import is a specific example of the procedures that are used to configure any integration port.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-9

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Moving Service Configurations
Microsoft Dynamics AX 2012 uses integration ports to manage integration scenarios in services and AIF. To move service configurations from test environments to production environments, you must meet specific prerequisites and complete the following tasks: Export the service metadata from the source environment, which is the test environment. This metadata includes AOT code, service details, and so on. Export configuration data about integration ports from the source environment. The data is exported as a .dat file. Import the exported metadata into the destination environment, which is the production environment. Import the integration port data into the destination environment.

Prerequisites to Export/Import Configuration Data


Before you migrate configuration data from a test environment to a production environment, ensure that you meet the following prerequisites: Create a file share. For file-based integrations, the account for the AOS must have read/write permissions for the file share. The file share must not be an administrative share, such as shares that contain a dollar sign ($). The user who is importing the port configurations into the destination environment must have privileges as an AIF administrator. This means that the user must have the AifAdmin privilege. All customizations must first be added to the source environment, and the application must compile without errors. All ports must be activated and tested. For ports that are based on NetTCP and HTTP, the Web Service Description Language (WSDL) files must be published. Additionally, a client must be able to start the service through service calls. For ports that are based on the file system adapter or the MSMQ adapter, the corresponding scenario must be tested.

2-10

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture
Procedure: Export the Integration Port Configuration Data
Use the following procedure to export the integration port configuration data. 1. Create a new definition group for exports. Click System administration > Common > Data export/import > Definition groups. a. Click New. b. Enter a unique name for the group into the Definition group field. c. Optionally enter a description. d. Click the Options tab and clear all the check boxes. e. Click the Include table groups tab and clear all the check boxes. f. Click OK. 2. Select tables for the definition group by clicking Select tables. a. Click Add, and then for inbound ports, select AifInboundPort in the Name of table field. b. Select Include document references and Specify related tables check boxes. c. Click the Select related tables button. On the Select related tables form, select the desired related tables to include and then click Close. d. Optionally, add export criteria by selecting the Apply criteria check box, and then click Export criteria. Enter the desired filter criteria and then click OK. e. Close the Select tables form. 3. Export the data to a local or network file share by clicking Export to on the Definition groups form. Select the file name and path, and then select the file type. Click OK to export the data to the specified file. 4. Close the Definition group form. 5. Repeat steps 1 through 4, using AifOutboundPort in the Name of table field in step 2.a instead of AifInboundPort. NOTE: During export, you might receive the following message: "TableDirPartyCollection was not found." If you receive this message, add export criteria, which is described in Step 3 of the "Export the Integration Port Data" procedure, to export only new and customized ports.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-11

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Procedure: Import the Integration Port Configuration Data
In the destination environment, use the following steps to import the file for the integration port data that you exported from the source environment. 1. Open the Import options form. Click System administration > Common > Data export/import > Import. 2. If you exported only selected ports by using export criteria, select Update existing record on the Advanced tab. Otherwise, existing ports in the destination environment are deleted. When you have finished importing the data, you must deactivate the imported ports, register services, register basic ports, and update the configuration details for each port. For example, you would update URIs based on paths in the production environment, and then activate the ports. For more information on completing these steps, refer to Exporting and importing AIF integration port configurations (http://go.microsoft.com/fwlink/?LinkID=247481&clcid=0x409 ). NOTE: This process will need to be completed once for each exported file in the Export the Integration Port Data procedure.

IMPORTANT: If the production environment is part of a cluster, you must restart all AOS instances to guarantee that all configurations are updated.

Change Tracking
In Microsoft Dynamics AX 2012, you can configure the database to keep track of when changes happen at the table level. When so configured, you can use the getChangedKeys service operation to retrieve entity keys for only those documents that have changed based on certain criteria, such as a specified date and time. Change tracking must be enabled in the database for the database tables that are used by the document service. To do this, you will need to configure change tracking. To retrieve the entity keys for documents that were changed, you must publish the getChangedKeys service operation through an integration port. Additionally, you will need to create a document filter and add filtering criteria. NOTE: You can use change tracking only if the document service is exposed through an inbound enhanced integration port.

IMPORTANT: You must create at least one document filter. Otherwise, no entity keys are returned from the getChangedKeys service operation.

2-12

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture
Once enabled, you can use change tracking in two ways: Submit an XML document to AIF that specifies the getChangedKeys action in the message header. Call the getChangedKeys method on a document service class. Only the entities that are changed on or after the _changedDateTime parameter are returned. The response message contains a list of entity keys. These keys represent the documents that have been changed according to the criteria that you specified, such as documents that were changed after a certain date and time. NOTE: For more information on configuring change tracking refer to Configuring AIF for change tracking (http://go.microsoft.com/fwlink/? LinkID=247482&clcid=0x409 ).

Templates for Banking


Application Integration Framework (AIF) provides framework that can help you generate payment files by using document services. This is an advantage over the previous system where the base classes were extended and customized to select appropriate data from transactional tables. If the parameters changed, then there would need to be recoding. Document services now help you to exchange data with external systems by sending and receiving data in XML documents. There are two primary areas of functionality in this process: the transport components and the business logic components. The transport components handle the transfer of business logic in and out of the system by using XML documents. The elements of the transport layer define how data is exchanged, including the source of the data, the destination of the data, and how it is transported. The business logic component of document exchange consists of the data, its format, and the business rules that govern the data. This business logic is exposed by two sets of classes: the base classes and the document service classes in the XML Document Framework. To provide framework for current and future payment formats, you can create a single query that exposes all the fields that are required for all the outbound payment formats. Use the AIF Document query wizard to generate the service and document object, data object, and Axd document classes. To enable payment generation by using AIF, use the customer and vendor payment services to expose the payment generation data for AIF outbound processing service. These services are based on Microsoft Dynamics AX queries. Customer/Vendor payment query captures all the necessary data to generate customer/vendor electronic payment files. Use the AIF document service wizard to generate the service document and data object

classes. An XSLT can be applied on this master data to transform the AIF XML file to the payment file for a specific payment format.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-13

Application Integration Framework and Services in Microsoft Dynamics AX 2012


For every payment format that you intend to generate by using AIF, you need to have a corresponding XSLT file. This XSLT is based on the format that is specified by the bank. These XSLTs can be can be created by using a simple text or XML editor. You can also use visual studio and BizTalk mapper. For payment files that are not XML, you need to apply an outbound transformation to convert the XML results to flat file. Outbound transforms can be of any type and they post-process the generated XML file to obtain the desired payment file. For the Microsoft Dynamics AX administrator, he or she has access to outbound port setup and can create an outbound port and define payment processing data for a payment format. The administrator can chose the outbound folder and the XSLT for the specific payment format. For a end user, the experience is quite similar to generating the payments by using file I/O. The user only needs to choose payment format and the format specific data that is required for the specific instance of payment creation process. Generating payments by using services provides flexible and extensible framework helps you to effortlessly easily plug and remove payment formats. The application integration framework provides capabilities, like outbound transforms, to help you plug in additional XSL or binary transformations to generate the desired payment files. In the event of any change to payment formats, the XSLT can be modified outside of Microsoft Dynamics AX. Any new payment formats can be added by creating the XSLT and adding it to the outbound port.

Support for Data Model Changes


In Microsoft Dynamics AX 2012, the services framework is enhanced to use several of the infrastructure features that are added in Microsoft Dynamics AX. Each document service is built on top of a query that is used to produce the data contract for that service as a document. The services framework handles scenarios to produce more user-friendly data contracts. These scenarios include the following: Replacing a surrogate foreign key with the natural key for a specific table relationship so that the final service contract has user-friendly readable fields instead of Surrogate Foreign Keys (SFK). Handling the queries that contain tables with dimension columns in the data sources. The framework has support to serialize or desterilize the dimension columns across the service boundary. Understanding table inheritance. Handling tables with date effective fields. The create and update document service wizards have been updated to generate code that includes the previous changes.

2-14

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture

Summary
Application Integration Framework (AIF) helps companies integrate Microsoft Dynamics AX and communicate with external business processes and other enterprise applications within and outside the boundaries of the business through the exchange of XML over various transport media.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-15

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Test Your Knowledge


Test your knowledge with the following questions. 1. Which of the following can not be a basic port? ( ) Outbound ( ) Inbound ( ) Endpoint ( ) Startpoint 2. Which of the following Axd document service operations are available in AIF? (Select all that apply) ( ) Create ( ) Read ( ) Update ( ) keysFind 3. Which of the following is not a service type? ( ) Custom services ( ) Document services ( ) NetTCP services ( ) System services 4. Which of the following best describes synchronous and asynchronous transports? (Select all that apply) ( ) Requests are tightly coupled to responses. ( ) Requests are placed into a queue, called the gateway queue. ( ) Invoke business logic by using preprocessing options. ( ) Requests develop new file links by using post-processing.

2-16

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 2: Architecture

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this chapter 1.

2.

3.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

2-17

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Solutions
Test Your Knowledge
1. Which of the following can not be a basic port? () Outbound ( ) Inbound ( ) Endpoint ( ) Startpoint 2. Which of the following Axd document service operations are available in AIF? (Select all that apply) () Create () Read () Update () keysFind 3. Which of the following is not a service type? ( ) Custom services ( ) Document services () NetTCP services ( ) System services 4. Which of the following best describes synchronous and asynchronous transports? (Select all that apply) () Requests are tightly coupled to responses. () Requests are placed into a queue, called the gateway queue. ( ) Invoke business logic by using preprocessing options. ( ) Requests develop new file links by using post-processing.

2-18

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade

CHAPTER 3: INSTALLATION AND UPGRADE


Objectives
The objectives are: Discuss the installation process and the special considerations for Services and AIF in Microsoft Dynamics AX 2012.

Introduction

Review the upgrade considerations for Services and AIF. Knowing the installation and upgrade considerations for Services and Application Integration Framework (AIF) in Microsoft Dynamics AX 2012 is critical for successful implementation.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-1

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Installation
Installation and configuration of Services and AIF has changed. In Microsoft Dynamics AX 2012, the Application Object Server (AOS) is the Windows Communication Foundation (WCF) service host for Microsoft Dynamics AX services, and web services on IIS is an optional component. Additionally, the BizTalk adapter has been depreciated in favor of using the Windows Communication Framework (WCF)-based adapters that are included with BizTalk.

IIS
Installing Microsoft Dynamics AX web services on IIS is optional. The Application Object Server (AOS) is the Windows Communication Foundation (WCF) service host for Microsoft Dynamics AX services that are available to users and applications across an intranet. To make Microsoft Dynamics AX services available over the Internet, you must host them on Internet Information Services (IIS). If you do not need to expose the Microsoft Dynamics AX services over the Internet or need any of the additional bindings that IIS provides, you do not need to install services on IIS.

Before Installing Web Services on IIS


Verify that the following steps are completed before you install the Microsoft Dynamics AX web services on IIS: On the computer where you will install the web services, run the prerequisite validation utility to verify that system requirements have been met. NOTE: For more information on the prerequisite validation utility refer to the Microsoft Dynamics AX 2012 Installation Guide (http://go.microsoft.com/fwlink/?LinkID=247483&clcid=0x409 ). Create a domain account that will be used as the Business Connector proxy account. This account might also be the one that is used for reporting service accounts and for the IIS Application pool identity. Each account that must run as a service requires the following properties: o Be a dedicated account (used only for the specific purpose) o Have a password that does not expire o Have minimal access to network resources o Be able to log on as a service

3-2

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


Make sure that you have the required permissions to install the web services, which requires you to be a member of the following: o The Administrators group on the local computer where you are installing Web Services on IIS o The System administrator role in Microsoft Dynamics AX 2012 CAUTION: Do not install web services on IIS on a server that is a network domain controller.

Procedure: Install the Web Server (IIS) Role


When you run the prerequisite validation utility it presents the option to configure the Web Server role. However, the prerequisite validation utility does not install the ASP.NET role service. Use the following steps to install the ASP.NET role service: Start the Server Manager. Expand the Server Manager (computer_name) node. Right-click Web Server (IIS) and then click Add Role Services. On the Select Role Services dialog, expand the Web Server (Installed) > Application Development (Installed) node and then select ASP.NET. Click Next and go through the wizard pages. Restart the server.

NOTE: This procedure has already been completed in the Hyper-V image.

Procedure: Create an IIS Website


Create a website that Setup will use to install the Microsoft Dynamics AX web services. You can create a new website or use an existing one, such as the Default Web Site on IIS. If you install the Microsoft Dynamics AX web services on an IIS that also hosts a SharePoint web front end or other web services, be sure to avoid port-binding conflicts.

Procedure: Install Web Services on IIS


Use the following steps to install web services on IIS: 1. Double-click D:\Setup.exe. 2. Under Install, click Microsoft Dynamics AX components. 3. If the setup support files have not yet been installed on this computer, the Select a file location page is displayed. The Setup support files are required for installation. Provide a file location or accept the default location and then click

Next. On the Ready to install page, click Install.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-3

Application Integration Framework and Services in Microsoft Dynamics AX 2012


NOTE: In the Hyper-V image, setup install files have already been installed. 4. Click Next. 5. In the Modify Microsoft Dynamics AX installation page, click Add or modify components, and then click Next. 6. On the Add or modify components page, select Web services on IIS and then click Next. 7. On the Prerequisite validation page, resolve any errors. When no errors remain, click Next. 8. On the Specify Business Connector proxy account information page, enter the password for the proxy account that is used by the .NET Business Connector. Click Next. NOTE: The proxy account for the .NET Business Connector in the HyperV image is "CONTOSO\SQLService" and the password is "Pa$$w0rd". 9. On the Configure IIS for Web services page, accept default values or provide information for the website, application pool, and virtual directory. Setup will create a virtual directory and an application pool for the Microsoft Dynamics AX web services under the selected website. The application pool will run as the .NET Business Connector proxy user that you entered in the previous step.

IMPORTANT: You must restart IIS after Setup installs the web services. Select Restart IIS after installation is complete to automatically restart IIS. 10. Click Next to continue. 11. On the Specify an AOS account page, provide the service accounts for the AOS instances that you will use with web services on IIS. Click Next to continue. 12. On the Prerequisite validation results page, resolve any errors. When no errors remain, click Next. 13. On the Ready to install page, click Install. 14. After the installation is complete, click Finish to close the wizard.

Procedure: Configure IIS

For IIS 7, use the following steps to configure the application pool that is associated with the Microsoft Dynamics AX 2012 web services for IIS 7. This step is required to set the correct version of the .NET Framework. 1. Click Start > Administrative Tools > Internet Information Services (IIS) Manager. 2. Click SEA-DEV > Application Pools.

3-4

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


3. In the Application Pools pane, right-click MicrosoftDynamicsAXAif60 application pool, and click Basic Settings. 4. In the Edit Application Pool dialog box, select .NET Framework 4.0 or a later version, such as V4.0.30319. Select Integrated from the Managed pipeline mode list. Notice that the Start application pool immediately option is selected. Click OK to return to IIS Manager. 5. Click SEA-DEV . 6. Right-click SEA-DEV and then click Stop. 7. Right-click SEA-DEV and then click Start. For IIS 6, make sure that the virtual directory for the Microsoft Dynamics AX web services is associated with version 4 of .NET Framework. Refer to IIS 6.0 documentation for instructions.

Procedure: Register the Website in Microsoft Dynamics AX 2012


Use the following steps to register the website in Microsoft Dynamics AX. 1. Open Microsoft Dynamics AX 2012. 2. Click System administration > Setup > Services and Application Integration Framework > Web sites. 3. On the Web sites form, create a new record and provide appropriate values for the Name, Virtual directory share path, Description, and URL fields. NOTE: On the Hyper-V image a record will already be created with the following URL and virtual directory share path. URL: http://sea-dev:8080/MicrosoftDynamicsAXAif60 Virtual directory share path: \\SEA-DEV\MicrosoftDynamicsAXAif60 (file://sea- dev/MicrosoftDynamicsAXAif60) 4. Click Validate. Verify that the Infolog dialog confirms that the website is configured properly, and that you can access the computer and the website. NOTE: When you install web services on IIS, a record for the new website is added to AifWebsites table. If you uninstall web services on IIS, this record is not deleted from the table. This record can cause a warning to be displayed if you reinstall web services on IIS. You can manually delete the record from the AifWebsites table or simply ignore the warning.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-5

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Creating Additional Web Sites
You can create additional websites if you require them. For example, you might have to expose a web service through a web server that is installed on a different computer than the instance of Application Object Server (AOS). When adding a website, consider the following: You must set the appropriate permissions for a new virtual directory so that Microsoft Dynamics AX can access the file share. The group that is named Microsoft Dynamics AX Web Service Administrators must have full access to the new virtual directory and file share. If this group does not exist as a local group on the new computer, you must create it. You must then add, as a user, the domain account for all AOS instances that require access. For these changes to take effect, you must restart all AOS instances that you added to the group. When you install web services on IIS, a record for the new website is added to the AifWebsites table. If you uninstall Web services on IIS, this record is not deleted from the table. Because this record still exists, you might receive a warning if you later reinstall Web services on IIS. You can either manually delete the record from the AifWebsites table or ignore the warning.

MSMQ
Microsoft Message Queuing (MSMQ) is a technology that enables applications that are running at different times to communicate across heterogeneous networks and systems that might be temporarily offline. MSMQ provides guaranteed message delivery, efficient routing, security, and priority-based messaging. It can be used to implement solutions for asynchronous and synchronous messaging scenarios. To send documents by using Message Queuing, you must install it on a computer on the network and create at least one public queue. To receive documents by using Message Queuing, you must install Message Queuing and create at least one queue.

MSMQ Limitations
Messages that are processed by the MSMQ adapter have a size limit of 4 megabytes (MB). For this reason, we do not recommend using Message Queuing to import data in bulk, such as by using the AIF batched-

message schema.

3-6

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


Installing MSMQ
Any computer that communicates through Message Queuing, including computers that run AOS, must have Message Queuing installed. Windows servers must have the Application Server role added. For application servers, select the following options: Incoming Remote Transactions Outgoing Remote Transactions Windows servers must have the Application Server Features added. For Message Queuing > Message Queuing Services, select the following options: Message Queuing Server Directory Service Integration HTTP Support For Microsoft Dynamics AX AIF scenarios, Message Queuing must be installed in Domain mode, which connects to the Active Directory service. Do not install Message Queuing in Workgroup mode on computers that exchange messages through AIF by using the MSMQ adapter. NOTE: Microsoft Dynamics AX requires that incoming messages be signed. If you need to send signed messages from Microsoft Dynamics AX, such as to other Microsoft Dynamics AX installations, you must run the AOS service under an Active Directory domain account. By default, the AOS service runs under the Network Service account. When AOS is running under the Network Service account, it cannot send signed messages because the Network Service account is not in Active Directory.

Demonstration: Set Permissions for MSMQ


This demonstration shows how to set up permissions for MSMQ. Grant permissions for a computer object to the Servers object in Active Directory Domain Services before installing the Routing Service feature on a computer that is not a domain controller. 1. Enable Read, Write, and Allow Create all child objects access to necessary computers. a. Go to Start > Administrative Tools > Active Directory Sites and Services. b. Expand Sites > Default-First-Site-Name , right click Servers, and then and then click Properties. c. Click the Security tab of the Servers Properties dialog box.

d. Click the Add button to display the Select Users, Computers, Service Accounts, or Groups dialog box.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-7

Application Integration Framework and Services in Microsoft Dynamics AX 2012


e. Click the Object Types button to display the Object Types dialog box, click to enable Computers and then click OK. f. In theEnter the object names to select field type "SEADEV" and then click OK. g. Enable the following permissions for this computer object: o Allow Read o Allow Write o Allow Create all child objects h. Click Advanced to display the Advanced Security Settings for Servers dialog box. i. Select the SEA-DEV object from the list of permission entries and then click the Edit button. j. Select This object and all descendant objects from the Apply to drop-down list k. Click OK to close all dialogs. 2. Give Network Service allow access to Create MSMQ Configuration Objects. a. Go to Start > Administrative Tools > Active Directory Users and Computers. b. Select View > Advanced Features. c. Select View > Users, Contacts, Groups and computers as containers. d. Go to Contoso > Domain Controllers. e. Right-click SEA-DEV and then click Properties. f. Click Security and then Advanced. g. Click Add. h. In Enter the object name to select type "Network Service" and then click OK. i. Select Allow for the Create MSMQ Configuration objects permission . j. Click OK to close all dialogs.

Demonstration: Install MSMQ

Use the following procedure to install Message Queuing 4.0 on Windows Server 2008 or Windows Server 2008 R2 for Services and AIF. 1. Click Start > Administrative Tools > Server Manager. 2. In Server Manager, click Roles > Application Server. 3. Right-click Application Server and then click Add Role Services.

3-8

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


4. Click Incoming Remote Transactions and then click Outgoing Remote Transactions. 5. Click Next and then click Install. 6. Click Close. 7. In Server Manager, click Features. 8. In the right-hand pane under Features Summary, click Add Features. 9. In the resulting window, expand Message Queuing. 10. Expand Message Queuing Services. 11. Click Directory Services Integration (for computers that are joined to a Domain) and then click HTTP Support. NOTE: Click Yes, I've set the required permissions, in the Have you set the required permissions in Active Directory Domain Services? message box. 12. Click Next and then click Install. 13. Click Close.

Configure the Distributed Transaction Coordinator


The Distributed Transaction Coordinator (MSDTC) service coordinates transactions in Message Queuing queues. You must start and configure MSDTC on servers that use Message Queuing with AIF.

Demonstration: Configure the Distributed Transaction Coordinator


To configure MSDTC for Services and AIF, follow these steps: 1. Click Start > Administrative Tools > Component Services to open the Component Services window. 2. Expand Component Services > Computers > My Computer > Distributed Transaction Coordinator. 3. Right-click Local DTC and then click Properties. 4. On the Security tab, select the following check boxes and then click OK : o Network DTC Access o Allow Remote Clients o Allow Inbound o No Authentication Required o Enable XA Transactions

5. In the "The MSDTC service will be stopped and restarted. All dependent services will be stopped. Applications using MSDTC may need to be restarted to use the new settings. Please press yes to proceed." dialog click Yes.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-9

Application Integration Framework and Services in Microsoft Dynamics AX 2012


6. In the "The MSDTC service has been restarted" dialog click OK. 7. Restart the server. (Click Start > Log off, then Restart) NOTE: Click Yes in the dialog that states "The MSDTC service will be stopped and restarted. All dependent services will be stopped. Applications using MSDTC may need to be restarted to use the new settings. Please press yes to proceed." Click OK to the dialog stating "The MSDTC service has been restarted."

Remote Connection to MSMQ


To enable remote communication with queues, you must configure the MSMQ adapter's security mode. This mode is not configured by default. In the configuration file for the MSMQ adapter, the <security> element of the <binding> element that has the "MsmqIntegrationSendBinding" attribute must be configured as follows: <binding name="MsmqIntegrationSendBinding"> <security mode="Transport"> <transport msmqAuthenticationMode="WindowsDomain" msmqProtectionLevel="Sign"/> </security> </binding> NOTE: If you have installed the WCF Configuration Editor tool, you can change these settings by using the tool.

Configure MSMQ
In Windows Server 2008 R2, Message Queuing is managed either by using Computer Management, or if the Message Queuing Directory Service Integration feature is installed, by using Active Directory Users and Computers. Message Queuing is located under the specified computer object in Active Directory Users and Computers. Additionally, if the Message Queuing Directory Service Integration feature is installed, then certain aspects of Message Queuing in Active Directory can be managed from Active Directory Sites and Services. NOTE: More information about MSMQ can be found at the Message Queuing (http://go.microsoft.com/fwlink/?LinkID=247484&clcid=0x409 ) TechNet site.

3-10

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


BizTalk
Microsoft Dynamics AX 2012 no longer includes a BizTalk adapter. Earlier versions of Microsoft Dynamics AX required a BizTalk adapter for integration with Microsoft BizTalk Server. However, BizTalk Server can now connect to AIF through Windows Communication Framework (WCF)-based adapters. NOTE: More information on installing and configuring BizTalk Server 2010 can be found at http://msdn.microsoft.com/enus/library/aa560434.aspx (http://go.microsoft.com/fwlink/? LinkID=247485&clcid=0x409 ) and in the "Using Microsoft BizTalk Server 2012 to Exchange Documents with Microsoft Dynamics AX" (http://go.microsoft.com/fwlink/?LinkID=247489&clcid=0x409 ) whitepaper.

Configure Network Load Balancing


Regardless of the type of AOS load balancing that is put in place, all traffic for services is routed to the first AOS instance in the list of servers that belong to the cluster. To enable load balancing for services, you must instead use Windows Server Network Load Balancing (NLB).

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-11

Application Integration Framework and Services in Microsoft Dynamics AX 2012


NOTE: For information about NLB refer to the Network Load Balancing Deployment Guide (http://go.microsoft.com/fwlink/? LinkID=247490&clcid=0x409 )on the TechNet website.

FIGURE 3.1 NETWORK LOAD BALANCING SERVICES

Network Load Balancing Considerations


When you set up systems to load balance the traffic for Microsoft Dynamics AX Services, keep the following points in mind: If load balancing is configured without a load-balancing AOS instance, all AOS computers should also participate in the NLB cluster. If a dedicated load-balancing AOS instance is used, do not include the dedicated AOS instance in the NLB cluster. Any client that consumes Microsoft Dynamics AX Services must use the virtual name or IP address of the NLB cluster to make service calls. These clients include the following: o The Microsoft Dynamics AX client program o Custom client applications o Clients that consume Web services over the Internet.
3-12

M i c r o s o f t O f f i c i a l T r a i n i n g M a t e r i a l s f o r M i c r o s o f t D y n a m i c s

of this content is subject to your current services agreement

Y o u r u s e

Chapter 3: Installation and Upgrade


This includes clients that consume web services through an Internet Information Services (IIS) web farm The following Microsoft Dynamics AX features must use NLB as the load-balancing mechanism when high availability of service is required: o Kanban schedule board form o Microsoft SQL Server Reporting Services o Office Add-ins for Microsoft Dynamics AX NLB manages host instances, but it does not manage AOS instances. Therefore, when a host instance fails, NLB removes the failed host instance from the cluster. However, when an AOS instance fails, NLB does not remove the host instance from the cluster. Instead, NLB continues to try to route traffic to the failed AOS instance. Therefore, you must implement a monitoring solution to detect when an AOS instance fails, so that you can appropriately deal with the failure. For example, Microsoft System Center Operations Manager (SCOM) (http://go.microsoft.com/fwlink/? LinkID=247491&clcid=0x409) provides this kind of system management facilities.

Procedure: Configure Network Load Balancing


To configure NLB for Microsoft Dynamics AX, follow these general steps: NOTE: This procedure will not be performed in the classroom because there is only one machine. 1. On each computer that is participating in the load-balancing cluster, install an AOS instance. 2. On a client computer, install the Microsoft Dynamics AX client program. 3. On each server computer in the cluster, configure NLB. 4. On the client computer, create a new client configuration by using the Microsoft Dynamics AX Client Configuration Utility. 5. On the Connection tab of the utility, modify the server instance so that it uses the virtual name or IP address of the NLB cluster. 6. Save the configuration and close the utility. 7. On the client computer, use Regedit to add the two values that are listed in the following table to the HKEY_LOCAL_MACHINE\Software\Microsoft\Dynamics\6.0\ Con figuration\new_configuration_name registry subkey. This will

require adding the new_configuration_name key.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-13

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Name Description wcflbservername A string value that contains the virtual name of the NLB cluster. wcflbwsdlport A string value that contains the port number that is used to retrieve Web Services Description Language 8. On the client computer, reopen the Microsoft Dynamics AX Client Configuration Utility. 9. Click the Configure Services button on the Connection tab to open the Microsoft Service Configuration Editor. This step updates the Windows Communication Foundation (WCF) configuration so that it uses endpoint addresses that point to the virtual name or IP address of the NLB cluster. 10. Save the WCF configuration file and close the editor. 11. In the Microsoft Dynamics AX Client Configuration Utility, click Manage and then save the configuration information as an .axc file. You can use this file as the standard file for configuring any client that connects to the NLB cluster to consume services. 12. Install any remaining components. 13. For each new client instance that you install, use the .axc file that you saved to specify the configuration. During setup, you can specify the path of the configuration file on the Specify a location for configuration settings page. NOTE: After you configure NLB, the Address field in the integration port forms display the NLB virtual name instead of the AOS name for new integration ports that you create.

Considerations for Services that are Hosted by IIS


When you activate an integration port that uses the HTTP adapter, Application Integration Framework (AIF) creates a folder that has a name that matches the name of the integration port under the root folder of the site on the computer that runs IIS. You specified the name of this computer either during the installation of Web services on IIS or in the Web sites form. The subfolder that AIF creates contains several files that are related to the deployment of the integration port. These files include a file that is named web.config. For IIS servers that connect to NLB clusters that load balance Microsoft Dynamics AX Services, you must modify the

web.config file for the website of each HTTP integration port.

3-14

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


For web farms, you must copy the configuration file and the associated service assemblies to each IIS server in the cluster. If you do not modify this file, the service URL on the WSDL page does not point to the NLB virtual name. Instead, the service URL contains the name of an individual AOS instance. To modify the web.config files, add or modify the section that is shown in the following example XML code. You must replace the text "IIS_Port_Number" with your IIS port number. <behaviors> <serviceBehaviors> <behavior name="routingData"> <useRequestHeadersForMetadataAddress> <defaultPorts > <add scheme="http" port="IIS_Port_Number" /> </defaultPorts> </useRequestHeadersForMetadataAddress> </behavior> </serviceBehaviors > ... </behaviors>

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-15

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 3.1 - Configure Services to Use IIS


In this lab, you will configure services to use IIS. Scenario Simon, the System Implementer, needs to configure services to use IIS so that these services can be accessed by using the Internet.

Challenge Yourself!
Use the provided information to configure services to use IIS.

Need a Little Help?


1. Install Web Services on IIS. 2. Configure IIS. 3. Register the website on Microsoft Dynamic AX 2012.

Step by Step
1. Double-click D:\Setup.exe. 2. Under Install, click Microsoft Dynamics AX components. 3. If the Setup support files have not yet been installed on this computer, the Select a file location page is displayed. The Setup support files are required for installation. Provide a file location or accept the default location and then click Next. On the Ready to install page, click Install. NOTE: In the Hyper-V image setup install files have already been installed. 4. Click Next on the Welcome page. 5. In the Modify Microsoft Dynamics AX installation page, click Add or modify components, and then click Next. 6. On the Add or modify components page, select Web services on IIS and then click Next. 7. On the Prerequisite validation page, resolve any errors. When no errors remain, click Next. 8. On the Specify Business Connector proxy account information page, enter the password for the proxy account that is used by the .NET Business Connector. Click Next.

NOTE: The proxy account for the .NET Business Connector is "CONTOSO\SQLService", and the password is "Pa$$w0rd" in the course Hyper- V image.

3-16

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


9. On the Configure IIS for Web services page, accept default values or provide information for the website, application pool, and virtual directory. Setup will create a virtual directory and an application pool for the Microsoft Dynamics AX web services under the selected website. The application pool will run as the .NET Business Connector proxy user that you entered in the previous step.

IMPORTANT: You must restart IIS after Setup installs the web services. Select Restart IIS after installation is complete to automatically restart IIS. 10. Click Next to continue. 11. On the Specify an AOS account page, provide the service accounts for the AOS instances that you will use with web services on IIS. Click Next to continue. NOTE: The AOS service account is "CONTOSO\AX_AOS_Service" in the course Hyper-V image 12. On the Prerequisite validation results page, resolve any errors. When no errors remain, click Next. 13. On the Ready to install page, click Install. 14. After the installation is complete, click Finish to close the wizard. NOTE: In they Hyper-V image AIF on IIS will install with warnings because it is being installed on a domain controller. The installer creates a local group called "Microsoft Dynamics AX Web Service Administrators," but because this is a domain controller is created as a group on the domain. The installer then attempts to set permissions to <Local computer>\"Microsoft Dynamics AX Web Service Administrators", but fails because it is a domain group. 1. Click Start > Administrative Tools > Internet Information Services (IIS) Manager. 2. Click SEA-DEV > Application Pools. 3. In the Application Pools pane, right-click MicrosoftDynamicsAXAif60 application pool and then click Basic Settings. 4. In the Edit Application Pool dialog box, select .NET Framework 4.0 or a later version, such as V4.0.30319. Select Integrated from the Managed pipeline mode list. Notice that the Start application pool immediately option is selected. Click OK to return to IIS Manager.

5. 6. 7. 8.

Click SEA-DEV. Right-click SEA-DEV and then click Stop. Right-click SEA-DEV and then click Start. Open Microsoft Dynamics AX 2012.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-17

Application Integration Framework and Services in Microsoft Dynamics AX 2012


9. Click System administration > Setup > Services and Application Integration Framework > Web sites. 10. On the Web sites form, create a new record and provide appropriate values for the Name, Virtual directory share path, Description, and URL fields. The default URL is http://computername:8101/MicrosoftDynamicsAXAif60 (http://computername:8101/MicrosoftDynamicsAXAif60). The default share path for the virtual directory is \\computername\MicrosoftDynamicsAXAif60. (file://computername/MicrosoftDynamicsAXAif 60.) NOTE: On the course Hyper-V image, a record has already been created with the following URL and virtual directory share path. URL: http://sea-dev:8080/MicrosoftDynamicsAXAif60 Virtual directory share path: \\SEA-DEV\MicrosoftDynamicsAXAif60 (file://sea- dev/MicrosoftDynamicsAXAif60) 11. Click Validate. Verify that the Infolog dialog confirms that the website is configured properly and that you can access the computer and the website. NOTE: In the Hyper-V image Validate will fail because the installer did not give the "CONTOSO\Microsoft Dynamics AX Web Service Administrators" group full control to the C:\Program Files\Microsoft Dynamics AX\60\AifWebServices folder.

3-18

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade

Lab 3.2 - Install MSMQ


In this lab, you will install and configure MSMQ Scenario Simon, the System Implementer, needs to install and configure MSMQ.

Challenge Yourself!
Use the provided information to install and configure MSMQ.

Need a Little Help?


1. 2. 3. 4. Set Permissions for MSMQ Enable MSDTC features Enable MSMQ features Set MSDTC permissions

Step by Step
NOTE: The steps for Lab 3.2: Install MSMQ are the same as the steps in the Installation lesson. 1. Enable Read, Write, and Allow Create all child objects access to necessary computers. a. Go to Start > Administrative Tools > Active Directory Sites and Services. b. Expand Sites > Default-First-Site-Name , right click Servers, and then and then click Properties. c. Click the Security tab of the Servers Properties dialog box. d. Click the Add button to display the Select Users, Computers, Service Accounts, or Groups dialog box. e. Click the Object Types button to display the Object Types dialog box, click to enable Computers and then click OK. f. In the Enter the object names to select field type "SEADEV" and then click OK. g. Enable the following permissions for this computer object: o Allow Read o Allow Write o Allow Create all child objects h. Click Advanced to display the Advanced Security Settings for Servers dialog

box.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-19

Application Integration Framework and Services in Microsoft Dynamics AX 2012


i. Select the SEA-DEV object from the list of permission entries and then click the Edit button. j. Select This object and all descendant objects from the Apply to drop-down list k. Click OK to close all dialogs. 2. Give Network Service allow access to Create MSMQ Configuration Objects. a. Go to Start > Administrative Tools > Active Directory Users and Computers. b. Select View > Advanced Features. c. Select View > Users, Contacts, Groups and computers as containers. d. Go to Contoso > Domain Controllers. e. Right-click SEA-DEV and then click Properties. f. Click Security and then Advanced. g. Click Add. h. In the Enter the object name to select field, type "Network Service" and then click OK. i. Select Allow for the Create MSMQ Configuration objects permission . j. Click OK to close all dialogs. 3. Click Start > Administrative Tools > Server Manager. 4. In Server Manager, click Roles > Application Server. 5. Right-click Application Server and then click Add Role Services. 6. Click Incoming Remote Transactions and then click Outgoing Remote Transactions under Distributed Transactions. 7. Click Next and then click Install. 8. Click Close. 9. In Server Manager, click Features. 10. In the right-hand pane under Features Summary, click Add Features . 11. In the resulting window, expand Message Queuing. 12. Expand Message Queuing Services. 13. Click Directory Services Integration (for computers that are joined to a Domain).

14. Click HTTP Support. NOTE: Click Yes, I've set the required permissions, in the Have you set the required permissions in Active Directory Domain Services? message box. 15. Click Next and then click Install.

3-20

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


16. Click Close. 17. Click Start > Administrative Tools > Component Services to open the Component Services window. 18. Expand Component Services > Computers > My Computer > Distributed Transaction Coordinator. 19. Right-click Local DTC and then click Properties. 20. On the Security tab, select the following check boxes and then click OK : o Network DTC Access o Allow Remote Clients o Allow Inbound o No Authentication Required o Enable XA Transactions 21. In the "The MSDTC service will be stopped and restarted. All dependent services will be stopped. Applications using MSDTC may need to be restarted to use the new settings. Please press yes to proceed." dialog click Yes. 22. In the "The MSDTC service has been restarted" dialog click OK. 23. Restart the server. (Click Start > Log off, then Restart)

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-21

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Upgrade
Services and AIF changed significantly in Microsoft Dynamics AX 2012. The upgrade process handles many of these changes, but there are places where manual intervention is necessary. This lesson describes how Services and AIF are upgraded automatically and where manual intervention is necessary.

Before Upgrade
Before upgrading, you should be familiar with Services and AIF. Process Messages on the Source System Before you run the upgrade process, make sure that all AIF messages have been processed on the system that is being upgraded. Check the following locations to verify that all messages have been processed: All inbound message locations - These locations include file system directories, Message Queuing queues, and any locations where AIF receives inbound messages. The queue manager - All messages in the queue manager are unprocessed and must be deleted. Click System administration > Periodic > Services and Application Integration Framework > Queue manager. Upgrade Considerations The enhancements to Services and AIF in Microsoft Dynamics AX 2012 cause significant changes in functionality, configuration, database schemas, and document schemas (or .xsd files). When you plan an upgrade from an earlier version of Microsoft Dynamics AX, consider the following guidelines: You must recompile and test all interfaces that used the earlier version of Microsoft Dynamics AX to make sure that the interfaces work with Services in Microsoft Dynamics AX 2012. Customizations that relate to services must be brought forward. In Microsoft Dynamics AX 2012, the MSMQ and BizTalk adapters are replaced with equivalent functionality that is provided by Windows Communication Foundation (WCF). You must recompile any automated integration processes that used these adapters. In BizTalk, you should change your port definitions to use the BizTalk WCF adapters and review your orchestrations and message definitions for necessary updates.

3-22

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


The upgrade framework changes AIF endpoints and related configurations to integration ports in Microsoft Dynamics AX 2012. When the upgrade process is complete, you must review and configure these integration ports before using Microsoft Dynamics AX 2012 Services and AIF functionality.

Data Upgrade Checklist


Application Integration Framework (AIF) is used to exchange data between Microsoft Dynamics AX and external systems. During the upgrade process, the Data upgrade checklist includes a step for the upgrade of AIF code. Click System administration > Setup > Checklists > Data upgrade checklist. Then, in the checklist pane, expand Finalize upgrade. Click Upgrade AIF code. This step might take a while. When the step is completed, check the Infolog to verify that no errors occurred. This step includes the following two processes: Code upgrade - This process creates new service classes, data classes, and service nodes in the Application Object Tree (AOT). Data upgrade - This process upgrades all AIF-related records in the database. IMPORTANT: The upgrade of AIF code and data is a two-step process. You must successfully upgrade the AIF code before you can upgrade the AIF data.

Upgrade Process
The process that Microsoft Dynamics AX 2012 uses to upgrade AIF code is complex, and involves several procedures. Code Upgrade The step for the upgrade of AIF code upgrades existing Axd <Document> classes and methods. During the code upgrade, the following classes are upgraded: The Axd <Document> classes that are included with Microsoft Dynamics AX Custom Axd <Document> classes Custom classes that implement the AifServicable interface Data Upgrade During the data upgrade, AIF data in the Microsoft Dynamics AX database is upgraded. Configuration settings for AIF endpoints are copied to configuration settings for integration ports.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-23

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Upgrade Changes
The following table describes how key concepts and configuration settings change when you upgrade from Microsoft Dynamics AX 2009 to Microsoft Dynamics AX 2012. Microsoft Dynamics AX 2009 feature AIF endpoints Microsoft Description Dynamics AX 2012 feature Integration ports The concept of integration ports replaces the concept of AIF endpoints. The Inbound ports form and the Outbound ports form replace the AIF configuration forms. Endpoints that exposed the Microsoft Dynamics AX functionality are converted to inbound integration ports. Endpoints that submitted messages are converted to outbound integration ports. AIF endpoints become integration ports that have a similar name. The upgrade framework combines the endpoint name and the company name to create the name of the integration port. For example, an about endpoint in This feature Information endpoint is not converted. constraints is not copied to Microsoft Dynamics AX 2012. You must use the legal values framework and the forms for inbound and outbound integration ports to configure constraints. Configure each integration port to apply service and parameter

Endpoint constraint s

3-24

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


Microsoft Dynamics AX 2009 feature Endpoint data and action policies Microsoft Dynamics AX 2012 feature The schema and operation constraints are applied to the integration ports. Description

AIF adapters

AIF channels

AIF pipelines

Information about data and action policies is not copied. In Microsoft Dynamics AX 2009, data and action policies were applied at the action level. In Microsoft Dynamics AX 2012, data and action policies are applied at the level of the integration port. Therefore, you must use the forms for inbound and outbound integration ports to define your data and action policies after the upgrade. NOTE: In earlier versions of Microsoft Dynamics AX, you were required to assign data policies to each endpoint action Integration ports Information about AIF adapters is not copied. Use the forms for integration ports to associate adapters with integration ports. Address of Information about AIF channels is integration not copied. Use the forms for ports inbound and outbound integration ports to configure the address and response address for each integration port. In earlier versions of Microsoft Dynamics AX, you could associate an endpoint with multiple channels or addresses. In Microsoft Dynamics Integration AIF pipelines are automatically port pipelines upgraded to integration port pipelines.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-25

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Microsoft Dynamics AX 2009 feature Service code attributes Microsoft Dynamics AX 2012 feature Microsoft Dynamics AX 2012 Services framework Description

The configuration is always company specific.

By default, the configuration is not companyspecific.

During the upgrade process, the service code is marked with the appropriate attributes, such as create, read, or find. This step enables the auto-inference feature in Microsoft Dynamics AX 2012 to work with the upgraded code. IMPORTANT: You must configure each upgraded service to assign appropriate attributes. In earlier versions of Microsoft Dynamics AX, each AIF endpoint was associated with a specific company. In Microsoft Dynamics AX 2012, integration ports do not have to be associated with a specific company. However, you can use the forms for inbound and outbound integration ports to restrict service calls to a specific company. For an inbound message, the services framework retrieves the company ID from the message header. If the message header does not contain a company ID, the

3-26

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


Microsoft Dynamics AX 2009 feature Service referenc e Microsoft Description Dynamics AX 2012 feature Microsoft Visual In Microsoft Dynamics AX 2012, references to external Studio project web services are no longer directly added to the AOT. Instead, these references should be created in a Visual Studio project which can then be added to the AOT. It is possible to import service references into Microsoft Dynamics AX 2012 from Microsoft Dynamics AX 2009. If you choose to do this, you might see the following errors during the importing process. You can safely ignore these errors and use the service reference: Specified web references root directory does not

After Upgrade
After upgrading, you must configure the SysEntryPointAttribute attribute and validate the migration of AIF endpoints.

Procedure: Configure the SysEntryPointAttribute


Microsoft Dynamics AX 2012 does not automatically assign the SysEntryPointAttribute attribute to service classes that are upgraded. Follow these steps for each service that you are upgrading. 1. In the AOT, expand the Services node, and find the service that is being upgraded. Open the Properties pane, find the corresponding class name for the service, and note the class name. 2. In the AOT, expand the Classes node, and find the entry for the class that you found in the previous step. 3. For each service operation in the class, add a SysEntryPointAttribute attribute that uses a value of true or false. We recommend that you set the value to true, so that the service operation accepts the permissions that are assigned to it by the role-based security framework in Microsoft Dynamics AX.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-27

Application Integration Framework and Services in Microsoft Dynamics AX 2012


The following example code shows how to add the attribute to the create operation of the SalesSalesOrderService class.
[AifDocumentCreateAttribute, SysEntryPointAttribute(true)] public AifEntityKeyList create(SalesSalesOrder _salesSalesOrder) { return this.createList(_salesSalesOrder); }

Procedure: Validate the Migration of AIF Endpoints


Use the Microsoft Dynamics AX 2012 forms for inbound and outbound integration ports to validate and configure the AIF endpoints that you migrated. 1. Open the Microsoft Dynamics AX client. 2. Initialize AIF to register adapters and services: a. Click System administration > Setup > Checklists > Initialization checklist. b. Expand the Initialize system node. c. Click Set up Application Integration Framework. 3. Open each form for the configuration of integration ports: a. Click System administration > Setup > Services and Application Integration Framework > Inbound ports. b. Click System administration > Setup > Services and Application Integration Framework > Outbound ports. 4. Review the list of integration ports to make sure that the AIF endpoints have been migrated as integration ports. 5. For each integration port, validate the migrated settings and provide any settings that were not migrated: a. In the Address group, select an appropriate adapter in the Adapter field. b. Click Configure to configure the adapter that you selected. c. In the URI field, select an appropriate value for the URI. d. Expose the service operations. Select Expose service operations and then click Service operations. e. Manually configure data policies and legal values. Select Customize documents and then click Data policies. f. Use the Processing options FastTab to configure processing settings. Processing settings include settings that control the behavior when errors are encountered in a

batch. These settings also control the preprocessing of requests and post-processing of responses.

3-28

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade


g. Use the Troubleshooting FastTab to configure troubleshooting settings. Troubleshooting settings include those that control the logging mode and the propagation of errors. h. Use the Security FastTab to configure security settings. Security settings include those that control restrictions on authorized users and trusted intermediary users. These settings also control whether the integration port is restricted to a specific company. i. In a browser, open the Microsoft Dynamics AX web service, and confirm that the web server returns the WSDL page. Use the following URL to open the Web service:
http://<Server name>:<Services WSDL port>/DynamicsAx/Services/ServiceName?wsdl

NOTE: By default, Microsoft Dynamics AX uses port 8181.

Summary
Understanding installation and upgrade for Services and AIF is an important aspect of using Services and AIF in Microsoft Dynamics AX 2012. The following list shows the high level concepts that must be understood. Services and AIF are installed on the AOS by default, but the NetTCP services that are published through the AOS are only available on the intranet. Services should be published on IIS to be available on the Internet. MSMQ must be installed and configured to work with AIF. Balancing does not apply to Services. To load balance services, NLB must be implemented. The upgrade process runs in two steps: one for data and one for code. After the upgrade process runs, the upgrade needs to be validated.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-29

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Test Your Knowledge


Test your knowledge with the following questions. 1. In which situations can you use AIF Services hosted on an AOS? ( ) When using Web Services over the internet ( ) When using NetTcp Services over the intranet ( ) All of the above ( ) None of the above 2. Which adapter is used to communicate with BizTalk in Microsoft Dynamics AX 2012? ( ) MSMQ ( ) BizTalk ( ) HTTP 3. Can load-balanced AOS clusters balance network traffic for services. ( ) Yes ( ) No 4. What are the two steps that are used by the upgrade process? (Select all that apply) (Select all that apply) ( ) Schema Upgrade ( ) Data Upgrade ( ) Code Upgrade ( ) Port Upgrade

3-30

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 3: Installation and Upgrade

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this chapter 1.

2.

3.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

3-31

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Solutions
Test Your Knowledge
1. In which situations can you use AIF Services hosted on an AOS? ( ) When using Web Services over the internet ( ) When using NetTcp Services over the intranet ( ) All of the above () None of the above 2. Which adapter is used to communicate with BizTalk in Microsoft Dynamics AX 2012? ( ) MSMQ ( ) BizTalk () HTTP 3. Can load-balanced AOS clusters balance network traffic for services. ( ) Yes () No 4. What are the two steps that are used by the upgrade process? (Select all that apply) (Select all that apply) ( ) Schema Upgrade () Data Upgrade () Code Upgrade ( ) Port Upgrade

3-32

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration

CHAPTER 4: ADMINISTRATION
Objectives
The objectives are: Set up batch for AIF and Services. Describe the types and options for integration ports. Review the adapters that are available in services and Application Integration Framework. Administering services and AIF requires setting up and maintaining AIF batch jobs, setting up integration ports, and understanding the types of adapters available.

Introduction

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-1

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Set Up Batch
Application Integration Framework (AIF) uses its gateway queue to handle asynchronous message routing in an orderly way. To move message into and out of the gateway queue, AIF requires a Microsoft Dynamics AX batch job that runs a particular set of services. The following are the four services that move documents through the gateway queue, listed in the order that they should run: 1. AIFGatewayReceiveService this service communicates with the adapters, receives messages from their external source locations, and puts them into the gateway queue to wait for processing. 2. AIFInboundProcessingService this service takes incoming messages from the gateway queue and then processes the documents according to the rules that are specified by the inbound port. 3. AIFOutboundProcessingService this service processes an outbound document according to the rules that are specified by the integration port and then adds the envelope XML code to create a fully-formed AIF message. The service then places the message into the gateway queue to send. 4. AIFGatewaySendService this service sends the messages to the correct external destinations. These services should run in a specific order because they depend on each other. For example, the gateway receive service must run before the inbound processing service. Otherwise, the inbound processing service will have no data to process until the next time it runs. Typically, these services run as four tasks in one batch job. You can create other batch job configurations, depending on your business requirements. For example, to schedule the AIF services to run at different time intervals, you can divide the services among multiple batch jobs. When you create the batch job, you can specify the order in which the services run by specifying conditions for the tasks.

Demonstration: Create an AIF Batch Group


Batch groups are used to group and run selected tasks on a specific batch server. This example creates an "AIF" batch group to hold the AIF batch job. 1. 2. 3. 4. 5. Click System administration > Setup > Batch group. Press CTRL+N to create a new batch group. In the Group field, type "AIF". In the Description field, type "AIF batch group". Click Batch servers.

4-2

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
6. In Remaining servers, click 01@SEA-DEV and then click the back arrow (<) button. 7. Notice that 01@SEA-DEV is now in Selected servers.

FIGURE 4.1 SELECT SERVERS

8. Click Close.

Demonstration: Set Up Batch


Follow these steps to set up the "AIF" batch job for the CEU company. NOTE: In the Hyper-V image delete the contents of C:\TEMP to avoid file adapter errors later related to an inbound port pointing to C:\TEMP. 1. Create a batch job: a. Click System administration > Inquiries > Batch jobs > Batch jobs. b. Press CTRL+N to create a new batch job. c. In the Job Description field, type "AIF". d. Press CTRL+S to save the job. 2. Click View tasks. 3. Create a batch task named "AIFGatewayReceiveService". a. Press CTRL+N to create a new task. b. In the Task description field, type "AIFGatewayReceiveService ".

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-3

Application Integration Framework and Services in Microsoft Dynamics AX 2012


c. In the Company Accounts field, type "CEU". d. In the Class name field, select AIFGatewayReceiveService in the drop-down. e. In the Batch group field, type "AIF". 4. Create a batch task named "AIFInboundProcessingService". a. Press CTRL+N to create a new task. b. In the Task description field, type "AIFInboundProcessingServic e". c. In the Company Accounts field, type "CEU". d. In the Class name field, select AIFInboundProcessingService in the dropdown. e. In the Batch group field, type "AIF". f. Click the Has conditions grid and then press CTRL+N to create a condition. g. In the Task ID field, select the task for AIFGatewayReceiveService in the dropdown. h. Accept the default Expected status of Ended. 5. Create a batch task named "AIFOutboundProcessingService". a. Return to the task grid. b. Press CTRL+N to create a new task. c. In the Task description field, type "AIFOutboundProcessingServic e". d. In the Company Accounts field, type "CEU". e.In the Class name field, select AIFOutboundProcessingService in the drop-down. f. In the Batch group field, type "AIF". g. Click the Has conditions grid and then press CTRL+N to create a condition. h. In the Task ID field, select the task for AIFInboundProcessingService in the dropdown. i. Accept the default Expected status of Ended. 6. Create a batch task named "AIFGatewaySendService". a. Return to the task

grid. b. Press CTRL+N to create a new task. c. In the Task description field, type "AIFGatewaySendService". d. In the Company Accounts field, type "CEU". e. In the Class name field, select AIFGatewaySendService in the drop-down. f. In the Batch group field, type "AIF".

4-4

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
g. Click the Has conditions grid and then press CTRL+N to create a condition. h. In the Task ID field, select the task for AIFOutboundProcessingService in the drop-down. i. Accept the default Expected status of Ended. 7. Click Close.

FIGURE 4.2 BATCH TASKS

8. Set the batch job recurrence a. Select the AIF batch group. b. Click Recurrence. c. In the Count field under Recurring pattern section, type "1". NOTE: A recurrence of one minute is set so that testing time is reduced. d. Click OK to close Recurrence. 9. Change the batch job status. a. Select the AIF batch group. b. Click Functions > Change status and then click Waiting. 10. Click Close.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-5

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 4.1 - Set Up Batch


In this lab, you will set up batch for services and AIF. Scenario Simon, the Systems Implementer, needs to set up batch for services and AIF.

Challenge Yourself!
Use the provided information to set up batch for services and AIF.

Need a Little Help?


1. Create an AIF batch group. 2. Ensure that the AIF batch group is being processed by a batch server. 3. Create a batch job. 4. Add batch tasks to process AIF requests to the batch job. 5. Set the batch job status to waiting.

Step by Step
NOTE: In the Hyper-V image delete the contents of C:\TEMP to avoid file adapter errors later related to an inbound port pointing to C:\TEMP.

NOTE: The steps for Lab 4.1: Set Up Batch are the same as the steps in the Set Up Batch lesson. 1. Create a batch group: a. Click System administration > Setup > Batch group. b. Press CTRL+N to create a new batch group. c. In the Group field, type "AIF". d. In the Description field, type "AIF batch group". e.Click Batch servers. f. In Remaining servers, click 01@SEA-DEV and then click the back arrow (<) button. g. Notice that 01@SEA-DEV is now in Selected servers. h. Click Close. 2. Create a batch job:

a. Click System administration > Inquiries > Batch jobs > Batch jobs. b. Press CTRL+N to create a new batch job.
4-6

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
c. In the Job Description field, type "AIF". d. Press CTRL+S to save the job. e. Click View tasks. 3. Create a batch task called "AIFGatewayReceiveService". a. Press CTRL+N to create a new task. b. In the Task description field, type "AIFGatewayReceiveService ". c. In the Company Accounts field, type "CEU". d. In the Class name field, select AIFGatewayReceiveService in the drop-down. e. In the Batch group field, type "AIF". 4. Create a batch task called "AIFInboundProcessingService". a. Press CTRL+N to create a new task. b. In the Task description field, type "AIFInboundProcessingServic e". c. In the Company Accounts field, type "CEU". d. In the Class name field, select AIFInboundProcessingService in the dropdown. e. In the Batch group field, type "AIF". f. Click the Has conditions grid and then press CTRL+N to create a condition. g. In the Task ID field, select the task for AIFGatewayReceiveService in the dropdown. h. Accept the default Expected status of Ended. 5. Create a batch task called "AIFOutboundProcessingService". a. Return to the task grid. b. Press CTRL+N to create a new task. c. In the Task description field, type "AIFOutboundProcessingServic e". d. In the Company Accounts field, type "CEU". e. In the Class name field, select

f. g. h. i.

AIFOutboundProcessingService in the drop-down. In the Batch group field, type "AIF". Click the Has conditions grid and then press CTRL+N to create a condition. In the Task ID field, select the task for AIFInboundProcessingService in the drop-down. Accept the default Expected status of Ended.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-7

Application Integration Framework and Services in Microsoft Dynamics AX 2012


6. Create a batch task called "AIFGatewaySendService". a. Return to the task grid. b. Press CTRL+N to create a new task. c. In the Task description field, type "AIFGatewaySendService". d. In the Company Accounts field, type "CEU". e. In the Class name field, select AIFGatewaySendService in the drop-down. f. In the Batch group field, type "AIF". g. Click the Has conditions grid and then press CTRL+N to create a condition. h. In the Task ID field, select the task for AIFOutboundProcessingService in the dropdown. i. Accept the default Expected status of Ended. 7. Click Close. 8. Set the batch job recurrence a. Select the AIF batch group. b. Click Recurrence. c. In the Count field under Recurring pattern section, type "1". NOTE: A recurrence of one minute is set so that testing time is reduced. d. Click OK to close Recurrence. 9. Change the batch job status. a. Select the AIF batch group. b. Click Functions > Change status and then click Waiting. 10. Click Close.

4-8

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration

Integration Ports
In Microsoft Dynamics AX 2012, integration ports provide simplified administration of services and Application Integration Framework (AIF). Integration ports replace the AIF endpoints and related concepts that were used in previous releases of Microsoft Dynamics AX. Each integration port can expose one or more services, and each integration port has a unique Uniform Resource Identifier (URI) that identifies the port's address. Each integration port also has a direction. An integration port can be either an inbound or an outbound integration port. An inbound integration port is a destination for messages that originate from outside Microsoft Dynamics AX. An outbound integration port is a destination for messages that originate from your Microsoft Dynamics AX system. Inbound integration ports can be one of two types: basic or enhanced. NOTE: Labs and demonstrations that cover creating and configuring integration ports are found in Chapter 6: Working with Services.

Basic Inbound Port


A basic inbound port is used by an external system to call a NetTcp Microsoft Dynamics AX service with minimal configuration. A basic inbound port is created when a service group is deployed. A service group can be deployed manually by right-clicking on the service group and clicking Deploy Service Group, or automatically by setting the AutoDeploy property to Yes. Some basic integration ports, such as those that are used for system services, are always deployed and enabled by default. A basic inbound port provides the configuration options shown in the following table. Option Port name Port description Adapter Description Name of the port Description of the port The type of adapter that the integration port uses to provide the transport mechanism for messages. Some adapters can use an additional The URI that points to the source that the integration port uses.

URI

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-9

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Option Logging mode Description You can store copies of documents that are exchanged and then view them by using the History form. Select the logging mode. The following options are availabl e: Original document select this option to store only the original document. All document versions select this option to store a separate version of the document every time that the document is modified by a pipeline. Message header only select this option to store only the message header for each document.

Enhanced Inbound Port


An enhanced inbound port is used by an external system to call a Microsoft Dynamics AX service through an adapter when advanced configuration is necessary. Enhanced inbound ports are manually created and deployed and provide the configuration options that are shown in the following table. Option Port name Port description Adapter Description Name of the port Description of the port The type of adapter that the integration port uses to provide the transport mechanism for messages. Some adapters can use an additional response address. The URI that points to the source that the integration port uses. Select the service operations that are available on the integration port. Specify XML Schema Definition language (XSD) restrictions and field-level legal values for documents that are handled through the integration port.

URI Service operations Data policies

4-10

M i c r o s o f t O f f i c i a l T r a i n i n g M a t e r i a l s f o r M i c r o s o f t D y n a m i c s

of this content is subject to your current services agreement

Y o u r u s e

Chapter 4: Administration
Option Batch error processing Description Select the behavior when an error is encountered in a batched request for processing. Batched requests are separate requests that use the same message-set identifier. The following options are available: Continue Halt Select this check box to specify that requests are processed in parallel. Select this check box to enforce schema validation. Select this check box to enable the create service operation to update an existing document if it Specify the transforms for requests. Specify or configure pipeline components for each service request operation. Specify or configure pipeline components for each service response operation. Specify the transforms for responses. Specify the translation of values for field data, based on business rules. For example, internal item numbers can be translated to either vendor- specific item numbers or industry-standard numbers, depending on Specify query constraints for the getKeys and getChangedKeys service operations.

Parallel processing XML validation Replace existing documents on create Inbound transforms Inbound pipeline Outbound pipeline Outbound transforms Value mapping

Document filters

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-11

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Option Logging mode Description You can store copies of documents that are exchanged and then view them by using the History form. Select the logging mode. The following options are available: Original document select this option to store only the original document. All document versions select this option to store a separate version of the document every time that the document is modified by a pipeline. Message header only select this option to store only the message header for each document.

Include exceptions in fault Respond after error in asynchronous request Restrict to company Restrict users Trusted intermediary users

Logging disabled select this option to turn logging off. When you select this Specify that X++ error messages from the service are displayed to port users. Specify that the port automatically sends error messages as responses in asynchronous scenarios. Select the company to which you want to grant exclusive access to the port. Limit use of the integration port to specified users or user groups. Authorize trusted intermediaries. Typically, trusted intermediaries are middleware components, such as installations of Microsoft BizTalk Server, which help keep inbound requests secure.

4-12

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
Outbound Port
An outbound port is used by Microsoft Dynamics AX to call an external system. Outbound ports are created by using System administration > Setup > Services and Application Integration Framework > Outbound Ports or by using System administration > Setup > Services and Application Integration Framework > Electronic payment services > Outbound ports for electronic payment. NOTE: The Outbound ports for electronic payment form is used to send payments in several standard formats. For more information, refer to the Configuring an outbound integration port for payments (http://go.microsoft.com/fwlink/?LinkID=247492&clcid=0x409 ) walkthrough. An outbound port provides the configuration options that are shown in the following table Option Port name Adapter Description Name of the port The type of adapter that the integration port uses to provide the transport mechanism for messages. Some adapters can use an additional response address. The URI that points to the source that the integration port uses. Select the service operations that are available on the integration port. Specify XML Schema Definition language (XSD) restrictions and field-level legal values for documents that are handled through the Select this check box to enforce schema validation. Select the type of character encoding to use by default, such as UTF8. Specify or configure pipeline components for each service response operation. Specify the transforms for responses. Specify the translation of values for field data, based on business rules. For example, internal item numbers can be translated to either vendorspecific item numbers or industry-standard numbers, depending on the trading partner.

Port description Description of the port

URI Service operation s Data policies

XML validation Default encoding format Outboun d pipeline Outbound transform s Value mapping

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-13

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Option Logging mode Description You can store copies of documents that are exchanged and then view them by using the History form. Select the logging mode. The following options are available: Original document select this option to store only the original document. All document versions select this option to store a separate version of the document every time that the document is modified by a pipeline. Message header only select this option to store only the message header for each document.

Activate a Port
Activating an integration port allows a port to process transactions, while deactivating an integration port stops a port from being able to process transactions. No setting changes can be made on an active integration port. To change settings, deactivate the integration port. Make the required changes, and then activate the port. CAUTION: Activating an integration port causes all integration ports on the Application Object Server (AOS) to reactivate. You should avoid clicking the Activate button when integration ports are processing messages. CAUTION: Inactivating an integration port causes all integration ports on the Application Object Server (AOS) to reactivate. You should avoid clicking the Deactivate button when integration ports are processing messages.

Include exceptions in fault Restrict to company

Logging disabled select this from option to turn Specify that X++ error messages the service are displayed to port users. Select the company to which you want to grant exclusive access to the port.

4-14

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
Trusted Intermediary
Trusted intermediaries are typically used for business-to-business data exchanges. A trusted intermediary is a type of submitting user that can act on behalf of another user, such as a claims user. A trusted intermediary is not a type of Microsoft Dynamics AX user. Instead, trusted intermediaries are typically middleware applications, such as Microsoft BizTalk Server or Electronic Data Interchange (EDI) services. These applications are represented by Microsoft Dynamics AX users or user groups that are authorized to submit inbound requests to an integration port. By using trusted intermediaries, you can delegate authentication to a trusted source, whereas authorization continues to be managed by Microsoft Dynamics AX through the role-based security framework. Trusted intermediaries are associated with integration ports. You can define custom intermediaries when configuring an integration port. A trusted intermediary must always be an Active Directory user, never a claims user. A trusted intermediary can impersonate any other Microsoft Dynamics AX user, even a claims user. When the submitting user is a trusted intermediary, AIF provides authorization to the user that is defined in the message header by the <LogonAsUser> element. Otherwise, this element is ignored. NOTE: When you use a trusted intermediary, make sure that the trusted intermediary represents a known, valid partner or a trusted system.

Adapters
In Microsoft Dynamics AX 2012 services and Application Integration Framework (AIF), integration ports use adapters. These adapters enable Microsoft Dynamics AX to communicate by using various transport protocols. Microsoft Dynamics AX 2012 provides the following four adapters that represent predefined bindings: HTTP adapter provides for synchronous message exchanges by using an HTTP or HTTPs transport. NetTCP adapter provides for synchronous exchanges by using WS-* standards support over the Transmission Control Protocol (TCP) transport. This adapter corresponds to the WCF-NetTcp binding in Windows Communication Foundation (WCF). MSMQ adapter provides support for queuing by using Message Queuing as a transport. Message Queuing is also known as MSMQ. Message Queuing is a type of asynchronous communication. This adapter corresponds to

the WCF-NetMsmq binding in WCF. File system adapter provides support for the asynchronous exchange of documents through file system directories.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-15

Application Integration Framework and Services in Microsoft Dynamics AX 2012


NOTE: Asynchronous adapters, including MSMQ and the File system adapter, require AIF batch jobs to be set up and using the AIF queue manager. Synchronous adapters, including HTTP and NetTCP, do not require AIF batch jobs to be set up, and do not use the AIF queue manager.

Registering Adapters
An adapter must be registered before it can be used. Adapters that are included with Microsoft Dynamics AX are automatically registered during installation. Whenever a new adapter is added to the Application Object Tree (AOT), you must register the adapter to make it available in the configuration forms for enhanced integration ports. Services and Application Integration Framework (AIF) require that you register adapters, services, and service groups any time that you change them in the Application Object Tree (AOT).

Procedure: Register Adapters


To register adapters, follow these steps. 1. Click System administration > Setup > Checklists > Initialization checklist. 2. Expand the Initialize system node. 3. Click Set up Application Integration Framework. NOTE: This operation can take some time to be completed.

Select Adapters
After adapters have been registered, you must select the adapters that you want to use for integration. In the Address group or the Response address group, click the arrow in the Adapter field, and then select an adapter in the list. You can select the appropriate adapter for your connection when you configure an enhanced integration port. For example, in an outbound scenario, the chart of accounts can be sent from Microsoft Dynamics AX to two external systems. The first system can be configured to receive messages by checking for files in a specific file system directory. For this system, the integration port uses the file system adapter. The second system can be configured to use Message Queuing to receive messages. Message Queuing is also known as MSMQ. For this system, the integration port uses the MSMQ adapter.

4-16

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
In this outbound scenario, both messages are first put in the gateway queue in Microsoft Dynamics AX. To start and stop processing in the queues, you can use the Microsoft Dynamics AX batch job feature. When a batch job starts, it retrieves messages from the queue. The batch job sends the first message to the first system by using the appropriate file system directory. The batch job also sends the second message to the appropriate MSMQ queue for the second system. An example of an inbound scenario is creating a sales order. For an inbound integration port, you can provide a response address where AIF sends the results of processing an inbound message. For example, when an inbound message creates a sales order, a response message contains the sales order ID of the new sales order, if the inbound message is completed successfully. Responses can also contain error information. To provide a response address, select the check box in the Response address group. For an inbound integration port, you can select the same adapter type or different adapter types for inbound messages and responses.

Specify URIs
Before you can configure an adapter, you must specify its URI. The format of the URI varies, depending on the type of adapter that you selected: If the adapter type is File system adapter, the URI is the file system path of the directory where the port retrieves documents if the address is an inbound address, or where the port saves documents if the address is an outbound or response address. To select a directory, click the arrow in the URI field, and then browse to a folder. Make sure that your AOS service account has the appropriate read or write permissions for the directory. NOTE: When you submit multiple documents to a port that uses the file system adapter, the documents are processed in order based on their file names. To control the order in which documents are processed, use file names that include a sequencing scheme, such as "PO_0001" and "PO_0002". If the adapter type is NetTcp, the URI is automatically provided by Microsoft Dynamics AX, based on the port name. You can view the URI after you save the port configuration by pressing CTRL+S, for example. If the adapter type is MSMQ, the URI is based on the queue that you select. To select a queue, click the arrow in the URI field, and then select a queue in the list. The server must be configured to provide Message Queuing services, and queues must be defined before they can be used by the integration

port.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-17

Application Integration Framework and Services in Microsoft Dynamics AX 2012


If the adapter type is HTTP, the URI is the Internet address of a web site that you added by using the Web sites form. To select a web site, click the arrow in the URI field. Then, in the Select web site form, click the arrow in the Web site field, and then select a site in the list.

Configure Adapters
After you specify the URI of the adapter that you selected, you can configure the adapter. In the Address group or the Response address group, click Configure . One of the following configuration forms opens: o For the file system adapter, the File system adapter configuration form opens. You should specify a Microsoft Dynamics AX user account as the default message owner when file ownership cannot be resolved deterministically by using the Use default owner for Administrators group adapter configuration. For example, when User Account Control (UAC) is enabled in Windows, files that were created by an administrator account will have the Owner attribute in the file properties set to the Windows Administrators group. Similarly, files that were created from a process that is running on a network service will have NT AUTHORITY\NETWORK SERVICE as the file owner. NOTE: Instructions for how to change the default file owner can be found in the "Call a Document Service with the File Adapter" lesson in Chapter 6: Working with Services. For adapters that are based on Windows Communication Foundation (WCF), the WCF configuration form contains the WCF Configuration Editor tool, SvcConfigEditor.exe, if it is installed. The types of adapters that are based on WCF include NetTcp, HTTP, and MSMQ. The WCF Configuration Editor tool is installed as a component of some versions of Windows SDK and by Microsoft Visual Studio 2010. This tool provides a graphical user interface (GUI) that you can use to create and modify configuration settings for WCF services.

4-18

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
If the WCF Configuration Editor tool is not installed, the WCF configuration file opens in Notepad. You can change the WCF configuration information by modifying the XML code in Notepad. Save the file when you are done.

Sequential and Parallel Processing in Services and AIF


When you use asynchronous adapters, performance can be affected by the rate at which messages move through the gateway queue for Application Integration Framework (AIF). In asynchronous scenarios, messages are periodically retrieved from file folders or Message Queuing, and include batched messages. The frequency at which messages are retrieved and then processed is determined by a batch job's recurrence setting. To improve the performance of message processing when you use asynchronous adapters, AIF supports parallel processing, which distributes the processing of inbound messages across one or more instances of Application Object Server (AOS). Therefore, you can scale out message processing by using multiple AOS instances. However, you can enable parallel processing only for inbound integration ports. To enable parallel processing of messages, select the Process requests in parallel check box on the Processing options FastTab of the Inbound ports form. Clear the check box to use sequential processing. This check box affects single and batched message types. By default, when you enable parallel processing, the number of messages that AOS can process in parallel is set to 1000. The MaximumInboundParallelMessages macro defines the number of inbound messages that are processed in parallel. You can change this setting by changing the corresponding AIF macro in the Application Object Tree (AOT). You must have a developer license to access the AOT. The following macro is defined in the AIF subnode. Sometimes, the order in which messages are processed is important. For example, new customer accounts must be created before customer sales orders can be processed. You can specify that certain messages must be processed sequentially by an integration port, even when parallel processing is enabled for that port. In each document that must be processed in parallel, include a special XML element that is named Conversation ID. All messages that have the same conversation ID are processed sequentially by any port for which parallel processing is enabled. The Conversation ID element has no effect when messages are processed by ports for which parallel processing is not enabled.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-19

Application Integration Framework and Services in Microsoft Dynamics AX 2012


The following table summarizes processing behavior. Message type Parallel processing is Single message Message processing is distributed across one or more AOS instances. The order of processing is not deterministic. Batched Batched messages message are separated into s single messages. Message processing is then distributed across one or more AOS instances. The order of processing is Conversations Single messages that have the same conversation ID are processed by the same AOS instance, in alphabetical order by file name, during each occurrence of the Parallel processing is disabled Messages are processed by a single AOS instance, in alphabetical order by file name, during each occurrence of the batch job. Batched messages are separated into single messages. Messages are then processed by a single AOS instance, in alphabetical order by file name, during each occurrence of the batch job. The Conversation ID element is ignored.

Batched Messaging
Microsoft Dynamics AX document services and Application Integration Framework (AIF) enable large amounts of data to be processed at the same time. A batched message is a single document that contains multiple, individual messages that are grouped together so that they can be processed as a unit. Batched messages can be processed only by using the file system adapter. Batched messages use the batch schema. This XML schema provides the <Batch> element, which can contain one or more <Envelope> elements. Each <Envelope> element contains a single AIF message. Each single AIF message in the batch must be smaller than 10 MB. The namespace of the batch schema is http://schemas.microsoft.com/Microsoft Dynamics/2009/06/documents/Batch. You can retrieve the Extensible Stylesheet Definition (XSD) file for the batch schema from the following location where you installed Microsoft Dynamics AX:

4-20

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
Program files\Microsoft Dynamics AX\60\Server\MicrosoftDynamicsAX\bin\Application\Share\Include\Mess ageSe t.xsd The optional <Batch> element contains the two attributes that are described in the following table. Name Batch ID Description A string value that is unique for a particular batched message. The messages in the batch are processed in parallel when the port is configured for parallel processing.

Batched Message Processing

Conversation A string value that several inbound messages can have in common. The conversation ID is a signal to ID AIF to process only one message in the conversation group at a time.

After a batched message is received, Microsoft Dynamics AX splits the document into its component requests, and then processes each request separately. If the integration port is configured to send responses, each component request receives a separate, corresponding response message. Each response message contains a <RequestMessageId> element. This element contains the GUID from the corresponding <MessageId> element in the header of the original request. The following diagram shows how batched messages are processed by AIF. Notice that the batched message is de-batched after the inbound transform stage, and that the request messages remain separate from that time forward.

FIGURE 4.3 BATCH IDS AND CONVERSATION IDS

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-21

Application Integration Framework and Services in Microsoft Dynamics AX 2012


A batch ID associates various messages that are contained in the same message set. Messages that have the same batch ID are processed as a group. Additionally, these message are processed in parallel if the Process requests in parallel setting for the integration port is selected, and the Upon error in batched requests: setting is set to Continue. Refer to the "File" topic for more detail. You can use conversation IDs to order the processing of requests. Messages that have the same conversation ID are processed together, in alphabetical order by file name. However, a conversation ID cannot be used to make a connection between messages that are contained in separate batched requests. In other words, a batched message can be part of a conversation, but every message that is contained in a batched message is part of the same conversation.

File
The file system adapter enables asynchronous exchanges through file system directories. To use the file system adapter, you must enable and configure at least one file system directory, or folder, messages. If both inbound messages and outbound messages are used, separate folders are required. Instructions for configuring the file adapter can be found in Chapter 6: Working With Services. NOTE: The AOS service must have read and write access to the inbound directory and to the outbound directory if it is configured. IMPORTANT: By default, AIF uses the file owner to determine which Microsoft Dynamics AX user to process the AIF request. Also, Windows Server 2008 defaults the file owner to the local administrators group if a user is in the local administrators group. To process files that are associated with the local administrators group, use the Use Default owner for Administrators group option.

MSMQ
The MSMQ adapter enables asynchronous exchanges through message queues. To use this adapter, you must install Message Queuing (MSMQ) on a computer on the network. You must also create at least one public queue to configure the MSMQ Adapter for Microsoft Dynamics AX. NOTE: Instructions for installing MSMQ can be found in Chapter 3: Installation and Upgrade Lab 3.2: Install MSMQ, and instructions for configuring MSMQ including creating queues, can be found in Chapter 6: Working with Services.

4-22

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
Enabling Prioritization of Messages
To enable prioritization of messages when you are using Message Queuing: Use only non-transactional queues. Transactional queues do not support message prioritization. In the configuration file for the MSMQ adapter, or by using the WCF Configuration Editor tool, specify True for the ExactlyOnce setting for the relevant MSMQ integration bindings.

Web Services
AIF supports HTTP and NetTcp adapters for synchronous exchanges of data by using web service communication. The HTTP adapter enables synchronous exchanges through web services on Internet Information Services (IIS), which can expose services on a network or the Internet. Web services on IIS require IIS 7.0. You can deploy AIF web services on a dedicated IIS server or a dedicated IIS farm. Alternatively, you can share an IIS server or IIS farm with other Microsoft Dynamics AX components, such as Workflow, Enterprise Portal for Microsoft Dynamics AX, and report server. We recommend that you deploy AIF web services on a dedicated IIS server or a dedicated IIS farm. The NetTcp adapter enables synchronous exchanges through web services on the AOS, which can expose services on a company's intranet. These adapters enable synchronous exchanges by using support for WS* standards over the Transmission Control Protocol (TCP) transport. You can use this adapter to expose services on a network. NOTE: NetTcp is the only adapter that is supported by system services. NOTE: Instructions for configuring the web service adapters can be found in Chapter 6: Working with Services.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-23

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Summary
Some of the key concepts that are required to administer services and AIF include: An AIF batch job must be set up and running for MSMQ and File System adapters to process transactions. The AIF batch job must contain the following batch tasks: o AIFGatewayReceiveService o AIFInboundProcessingService o AIFOutboundProcessingService o AIFGatewaySendService Inbound integration ports can be basic or enhanced. Outbound integration ports are always enhanced. Integration ports must be activated to process transactions. Services and AIF come with four adapters: o File System o MSMQ o NetTcp o HTTP

4-24

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration

Test Your Knowledge


Test your knowledge with the following questions. 1. Which step allows a port to process transactions? ( ) Select an adapter ( ) Activate ( ) Ctrl+N ( ) Selecting service operations 2. Put the following batch tasks in the order they should run: Step: _: AIFOutboundProcessingService : AIFInboundProcessingService _: AIFGatewaySendService : AIFGatewayReceiveService 3. Categorize the following items: 1. Port name 2. Adapter 3. URI 4. Service operations 5. Data policies 6. Value mapping 7. Logging mode 8. Inbound pipeline a. You can store copies of documents that are exchanged and then view them by using the History form. Select the logging mode. b. Specify XML Schema Definition language (XSD) restrictions and field-level legal values for documents that are handled through the integration port. c. The type of adapter that the integration port uses to provide the transport mechanism for messages. Some adapters can use an additional response address. d. Specify or configure pipeline components for each service request operation. e. Select the service operations that are available on the integration port. f. The URI that points to the source that the integration port uses. g. Specify the translation of values for field data, based on business rules. For example, internal item numbers can be translated to either vendor- specific item numbers or industry-standard numbers, depending on the trading partner. h. Name of the port.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-25

Application Integration Framework and Services in Microsoft Dynamics AX 2012


4. When should an adapter be registered?

5. Which of the following are web services adapters? (Select all that apply) ( ) File System ( ) HTTP ( ) NetTcp ( ) MSMQ

4-26

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this chapter 1.

2.

3.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-27

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Solutions
Test Your Knowledge
1. Which step allows a port to process transactions? ( ) Select an adapter () Activate ( ) Ctrl+N ( ) Selecting service operations 2. Put the following batch tasks in the order they should run: Step: 3 : AIFOutboundProcessingService 2 : AIFInboundProcessingService 4 : AIFGatewaySendService 1 : AIFGatewayReceiveService 3. Categorize the following items: h 1. Port name c 2. Adapter f 3. URI e 4. Service operations b 5. Data policies g 6. Value mapping a 7. Logging mode d 8. Inbound pipeline a. You can store copies of documents that are exchanged and then view them by using the History form. Select the logging mode. b. Specify XML Schema Definition language (XSD) restrictions and field-level legal values for documents that are handled through the integration port. c. The type of adapter that the integration port uses to provide the transport mechanism for messages. Some adapters can use an additional response address. d. Specify or configure pipeline components for each service request operation. e. Select the service operations that are available on the integration port. f. The URI that points to the source that the integration port uses. g. Specify the translation of values for field data, based on business rules. For example, internal item numbers can be translated to either vendor-specific item numbers or industrystandard numbers, depending on the trading partner. h. Name of the port.

4-28

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 4: Administration
4. When should an adapter be registered? MODEL ANSWER: Whenever a new adapter is added to the Application Object Tree (AOT), you must register the adapter to make it available in the configuration forms for enhanced integration ports. 5. Which of the following are web services adapters? (Select all that apply) ( ) File System () HTTP () NetTcp ( ) MSMQ

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

4-29

Application Integration Framework and Services in Microsoft Dynamics AX 2012

4-30

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts

CHAPTER 5: DEVELOPMENT CONCEPTS


Objectives
The objectives are: Describe the Service Types that are available in Services and AIF. Review the Document Services Service Type. Define the Custom Services Service Type. Describe the System Services Service Type. Review the communication format that AIF uses to transmit data. Explain how to manipulate requests in the AIF Pipeline. Use the Business Operations Framework. Describe how services are secured in Microsoft Dynamics AX 2012. Development in Service and Application Integration Framework involves being familiar with the following concepts: You can use a transport layer to pass data between integration ports Transforms, custom calls, and value mappings can be performed between when an integration port receives a document and when that document is returned The types of services that are available and how they can be customized How to use the Business Operations Framework (BOF) The type of security Services and AIF use NOTE: In the Hyper-V image lab files for this chapter are located at E:\Labfiles\Chapter 5.

Introduction

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-1

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Service Types
Microsoft Dynamics AX supports integration with the Application Integration Framework (AIF) components by using the Microsoft Dynamics AX services programming model. With this programming model, you can customize the document services that are included with Microsoft Dynamics AX, create new custom services, and consume external web services. To support a range of options for customization and programmability, Microsoft Dynamics AX provides the following types of services: Document Services: represent data and business logic within Microsoft Dynamics AX. You can use or customize the over 70 standard Axd document services that are included with Microsoft Dynamics AX. If none of the standard document services meet your needs, you can create a new document service by using the AIF Document Service Wizard.

Each document is represented by a class; the name of a document class is preceded by Axd. For example, AxdSalesOrder is the name of the document and also the name of the document class. The terms "document" and "Axd document" and "document class" can be used interchangeably. Custom Services: services that you create to expose X++ logic through a service interface. You can use the business logic with inbound or outbound transfers. System Services: these services cannot be customized. The Query Service, Metadata Service, and User Session Service are Windows Communication Foundation (WCF) services included with Microsoft Dynamics AX. They provide access to data returned in queries, metadata for AOT objects such as tables and extended data types (EDTs), and data about the calling user such as default language and default company.

With Microsoft Dynamics AX you can use external web services from X+ + code and web services that are hosted by Microsoft Dynamics AX from .NET Framework languages such as Microsoft Visual C#. Microsoft Dynamics AX supports application integration and data exchange in intranet and Internet-facing scenarios. Services that are based on WCF classes are hosted on the AOS for applications to integrate within a company's intranet. To use or expose services over the Internet, you must install and use Internet Information Services (IIS).

5-2

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Distinguish Between Service Types
Microsoft Dynamics AX provides three types of services that can be used by Microsoft Dynamics AX components and third-party applications. You can use system services out-of-the-box to retrieve data in a query, metadata for objects in the AOT, and information about the calling user. You can use document services to exchange data for business entities that are defined by the standard documents in Microsoft Dynamics AX. For any custom requirements for application integration, you can customize existing documents or create new document services and custom services. The following table outlines the defining characteristics of a Document Service. Characteristic Service Definition and Data Contracts Deployment Mode Hosted Location Transport Protocol Usage Description Auto-generated based on underlying query and options that are entered in the AIF Document Service Wizard Integration Ports AOS or IIS Any supported adapter Use to expose a business entity through a service interface All AIF framework artifacts can be applied on these services

The following table outlines the defining characteristics of a Custom Service. Characteristic Service Definition and Data Contracts Deployment Mode Hosted Location Transport Protocol Usage Description Defined by the developer Integration Ports AOS or IIS Any supported adapter Use to expose any custom entity (including simple business entities) through a service interface AIF framework supports transforms but not pipelines, schema constraints, or other data processing options

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-3

Application Integration Framework and Services in Microsoft Dynamics AX 2012


The following table outlines the defining characteristics of a System Service. Characteristic Service Definition and Data Contracts Deployment Mode Hosted Location Transport Protocol Usage Description Fixed and cannot be changed Stand-alone service that is running at fixed address on the AOS AOS only Only NetTcp adapter Use to return metadata, data in a query, or user information Metadata includes information about AOT objects in Microsoft Dynamics AX such as tables, services, extended data types (EDTs), enums, and so on

Exposing Business Entities as Services


Microsoft Dynamics AX includes over 70 document services. The document services framework provides the AIF Document Service Wizard, which generates a document service from the query that defines the business entity. To expose business logic through services, you can use serialization with the Data Contract class and custom attributes. The following tables contain information that can help you to decide whether to use document services or custom data contract-based services. Entity Complexity Service Type Document Services Description The AIF Document Service Wizard handles queries of any complexity and size and generates the service seamlessly. For example, some queries contain data sources and relationships that include dimensions, polymorphism, date-effective information, and so on. The document

5-4

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Service Type Custom Services Description Custom services are suitable when the entity complexity is low. The schema can be written as a data contract class and relevant data member attributes set. If tables and relationships are used in a data contract, then any feature around dimensions, polymorphism, and so on, must be handled in code by the developer.

Performance requirements Service Type Document Services Description The incoming XML is passed to the document services framework, which parses the XML to validate the Axd schema, and then invokes the relevant operation. The framework enables customization to Custom services use the underlying .NET XML Serializer to serialize and de-serialize the XML into a data contract object. No other logic is present. For simple entity schemas, this approach is faster than document services. For complex schemas, you might have to write a lot of custom

Custom Services

Integration requirements Service Type Document Services Description All integration stack elements such as pipelines, transforms, and schema constraints can be applied to document Schema constraints and value substitution are not honored for custom services. However, transforms that convert between the AifXMLMessage format and other formats and pipelines for preprocessing

Custom Services

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-5

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Flexibility in service contracts Service Type Document Services Description Because the document service is derived from a query, changes to the query object or the data source schema might require a change to the service contract. The tight coupling between the service contract and the underlying query-table schema could be limiting for certain scenarios. Also, general modifications to the involved Microsoft Dynamics AX tables (new fields, and so on) will automatically cause The data contracts are written by developers and can be controlled to make sure that the underlying schema changes do not have any effect on them. The control that a developer has in defining the service contracts can be good for service

Custom Services

Microsoft Office Add-ins support Service Type Document Services Description Office Add-in tools, included with Microsoft Dynamics AX, have built-in support for using document services for No preinstalled integration with Office add-ins exists.

Custom Services

The following table summarizes some of the key scenarios for all service types in Microsoft Dynamics AX. Service Type Custom Services Common Scenarios Use to expose simple business entities as a service, or to expose custom logic from Microsoft Dynamics AX. Use to expose business entitles with varying degrees of complexity, or to support a medium- to-complex integration scenario involving business entities. Use to implement read operations for any Microsoft Dynamics AX, ad-hoc, or existing AOT query.

Document Services

System Service: Query Service

5-6

Microsoft Official Training Materials for Microsoft Dynamics

Y o u r u s e o f t h i s c o n t e n t i s s u b j e c t t o y o u r c u r r e n t s e r v i c e s a g r e e m e n t

Chapter 5: Development Concepts


Service Type System Service: Metadata Service Common Scenarios Use to retrieve information about the structures in Microsoft Dynamics AX for a client application. For example, if you want to return information about a table such as what indexes exist on that table you can use the metadata service. Use to retrieve information about the user session.

System Service: User Session Service

Document Services
In Microsoft Dynamics AX, the Application Integration Framework (AIF) includes a set of services that is based on documents (such as a sales order, a customer, and so on). These services use the existing Axd<Document> classes that are included with Microsoft Dynamics AX. This set of services is called document services. In AIF, data is exchanged with external systems through business logic that is exposed as services. An exchange starts with a document service. The document service calls functionality in a document class that contains the Microsoft Dynamics AX business logic. The service exposes service operations that can be called by an external system and take one or more documents as a parameter. The document is serialized into XML, and header information is added to create a message that can be transferred in to or out of Microsoft Dynamics AX.

XML Document Framework


The programmatic foundation of documents is the XML Document Framework. This framework consists of the classes that implement the business logic for individual documents in Microsoft Dynamics AX. The XML Document Framework contains the following types of classes: Document service classes Axd<Document> classes (also known as an Axd class) Ax<Table> classes In Microsoft Dynamics AX, all the data is stored in database tables and a close relationship exists between the data model and the way that data is manipulated through forms and presented in reports. Therefore, it is imperative that you have a detailed understanding of the data model when you use an application that exchanges data with Microsoft Dynamics AX. Additionally, you should be familiar with any business logic that is applied in forms and reports so that you can maintain data consistency and integrity.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-7

Application Integration Framework and Services in Microsoft Dynamics AX 2012


To solve this problem, the document service classes expose service operations (create, delete, find, findKeys, getKeys, getChangedKeys, read, and update) and provide an external application object interface. The document service classes represent data as business entities so that the calling application can exchange data with Microsoft Dynamics AX without any knowledge of the underlying tables. The document services call functionality in the Axd<Document> classes. The Axd<Document> classes contain the business logic for related entities. For example, the AxdSalesOrder class orchestrates the creation, updates, and deletions in a number of related tables such as the SalesTable, or SalesLine tables. The Ax<Table> classes are a further abstraction of a single table and encapsulate the business logic that is associated with creation and modification of records in the database table. The Axd<Document> classes use the Ax<Table> classes to manipulate data in the database. The "Microsoft Dynamics AX Classes in the XML Document Framework" figure illustrates how the Axd<Document> and Ax<Table> classes interact in a document exchange.

FIGURE 5.1 MICROSOFT DYNAMICS AX CLASSES IN THE XML DOCUMENT FRAMEWORK

The XML Document Framework classes are the basis of the document services that come with Microsoft Dynamics AX. You can use these document services as is or customize them for your business requirements. The XML Document Framework also helps you create new document services that are based on your own business logic. In AIF, a document is a representation of the data model in Microsoft Dynamics AX, meaning that a document reflects the data as it exists in the application. For example, the sales order document contains a sales order header with the sales order data and the corresponding sales order lines. This document structure reflects the existing records in the application.

5-8

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Standard Document Services
Microsoft Dynamics AX contains many standard document services. Each service supports a particular business process. You can customize these standard documents or create custom documents that suit your individual business processes. The following Document services are included with Microsoft Dynamics AX 2012. Service Operation key: C - Create R - Read UUpdate D - Delete F - Find FK - FindKeys GK - GetKeys GCK - GetChangedKeys Name Advance shipping notice Exchange rates Description Service Operations R CR C

Sent to the customer when the sales order packing-slip updated. You can send your exchange rates to another subsidiary. Free-text invoice Creates a sales order in the application. This document has significantly fewer restrictions on input data than the Sales Order document. Inventory Updates inventory amounts and counting journal balances with inventory document information from a third-party Inventory on hand External users can receive current information about onhand inventory amounts. Inventory Creates an inventory profit and loss record that is based on profit and loss information from a third-party journal warehouse management system.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-9

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Name Inventory transactio ns Inventory transfer journal Packing slip Description Describes the inventory transactions document. Updates the inventory warehouse data from a third-party warehouse management system. Creates a packing slip record. The packing slip record is based on the data from a thirdparty warehouse management Sends a picking list to a thirdparty warehouse management system. Describes the price discount agreement document. Sends a compiled price list to a customer. The price list is based on the trade agreements and discounts for the specific Creates a purchase invoice that is based on the associated purchase order. Sends a purchase requisition to a vendor. Sends an invoice to a customer. The invoice is based on the customer's sales order data. Creates a new sales order record. External systems can read, update, create, and delete alternative addresses. External systems can read, create, update, and delete contact persons. External systems can read, create, update, and delete customers. External systems can read, create, update, and delete customer groups. Allows for a two-way collaboration of the item master for the objective of synchronization in a businessto- business relation. Service Operations R C

Picking list Price discount agreement journal Price list

R C R

Purchase invoice

Purchase requisitio n Sales invoice

R R

Sales order Address

CRUD CRUD

Contact person Customer Customer group Item

CRUD CRUD R CR

5-10

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Name Item dimension combination Payment terms Product groups Description External systems can read information about combinations of item dimensions, such as, color and size. Delivers a list of payment terms. Service Operations R

R R R R CR

external systems to read information about product groups. systems can read Shipping methods External information about shipping methods. External systems can receive Warehouse information about a warehouse. Bill of materials Allows for synchronization of a (BOM) bill of materials with external systems, for example, when production is outsourced to a Cash discount Delivers a list of cash discounts that are available to a specific user. Credit card Allows for the import of corporate credit card Customer Payment transactions. You can create customer payment Journal records based on a customer invoice. Expense report You can enter and submit expense reports. Fixed asset Delivers a list of assets and allows for the creation of new fixed asset records. Fixed Delivers a list of the asset asset conditions. Fixed asset conditions condition describe the physical status of a fixed asset, such as good, new, refurbished, improved, or used. Fixed asset group Delivers a list of the asset groups. Fixed asset location Delivers a list of the asset locations. Locations describe where a fixed asset resides and can include an address. Delivers a list of the asset major types. Fixed asset major types are high-level asset groupings, that are used for

R C C CR CRU

R R

Fixed asset major type

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-11

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Name Inventory profit/loss journal Ledger journal Description Service Operations C

Product picking list Project hour journal Project invoice

Return order Return order acknowledgme nt Route card

External systems can create profit and loss journals. This makes it possible Delivers a list of general journals, CR and allows for the creation of new general journals with ledger account types that support multicurrency Creates a production picking C list journal. Subcontractors can report item consumption. External systems can create C project hour journals. Project invoice for Danish e- R invoice. Creates an electronic invoice for the Danish tax authorities. Users can enter customer CUD return orders. R C

You can send a return order acknowledgement to the customer. Creates a production route card journal. A subcontractor can report progress (hours spent, good quantity, error quantity, Sales invoice You can send an invoice to a customer or to a service that creates and mails invoices. Sales e-invoice Sales invoice for Danish einvoice. Creates an electronic invoice for the Danish tax Service agreement Allows for the exchange of electronic service agreements including the service agreement header andthe lines. Service order Allows for exchange of electronic service orders including the service order header Vendor Allows for synchronization of vendor data with external systems. Vendor group Allows for synchronization of vendor groups with external systems.
5-12 Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

CRUD

CRUD CRUD

Chapter 5: Development Concepts


Name Vendor payment Description Service Operations R CRUDF, FK, GCK, GK C, GCK, GK

Delivers payment information for a specific vendor. Budget Users can create, read, update, Transaction and delete budget register entries Catalog Import Users (Vendor, Purchasing agent. or Purchasing manager) can maintain the vendor's imported catalog in Microsoft Customer Customer electronic payment Electronic service Payment Document Users can submit Handling unattached documents and push them into workflow for association with records. Product Master Allows for read and write of Dimension Values product dimension values for a product master. Product Service External systems can read or write products into shared product repository. Meter External systems can record reading meter readings in the service environmental sustainability dashboard. Substance flow External systems can record substance flow transactions in the environmental sustainability dashboard. EU sales Allows for the generation of EU list sales list files, which are used for reporting reporting to government Warehouse Item External systems can create and retrieve warehouse items. Barcode Service External systems can retrieve barcode information for a Create Inventory released External product. systems can create Transfer Order inventory transfer orders. Inventory Transfer External systems can post inventory transfer orders. Order Posting Read Inventory Transfer Order External systems can read inventory transfer orders.

FR C

CRF, FK, GCK, CRF, FK, GCK, C, GCK, GK

R, F, GCK, GK CRF, FK, GCK, RF, FK, GCK, GK C, GCK, GK C, GCK, GK RF, FK, GCK, GK

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-13

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Name Request For Quote Reply Request For Quote Send Purchase Requisition Description Service Operations UF, GCK, GK RF, FK, GCK, GK Cancel, CRDF, FK, GCK, GK CRUF, FK, GCK, GK RF, FK, GCK, GK Find, GCK, GK F, GCK, GK RF, FK, GCK, GK CRUDF, FK, GCK, GK F, GCK, GK

Customers can receive vendor quotes in response to a request for quote. can send requests for Customer quote to vendors. Allows for the creation, retrieval, and cancellation of purchase requisitions. Request For Quote Customers can manage request for quote documents. Sites Sales Quotation Journal External systems can read sales quotation journals.

Line Discount List External systems can retrieve line discount lists. Multiline Discount List Sales Confirmation Sales Quotation Total Discount External systems can retrieve multiline discount lists. External systems can read sales order confirmations. External systems can read, create, update, and delete sales quotations. External systems can retrieve total discount lists.

Document Service Classes


In AIF, data is exchanged in XML format. The AIF classes are responsible for serializing the data to or from XML for use by the transport layer. These classes include the document services classes, the Axd<Document> classes, and the Ax<Table> classes. The source of data for each document is a query (the Axd document query). The query controls the content and structure of the data in the document.

5-14

Microsoft Official Training Materials for Microsoft Dynamics

Y o u r u s e o f t h i s c o n t e n t i s s u b j e c t t o y o u r c u r r e n t s e r v i c e s a g r e e m e n t

Chapter 5: Development Concepts


Service Classes
The document services classes include the service class and the related data object classes. Service class - exposes the AIF business logic to external callers through these service operations: create, delete, find, findKeys, getKeys, getChangedKeys, read, and update. The service classes provide the interface for reading, creating, updating, and deleting data in Microsoft Dynamics AX. Each service class has a corresponding service node in the AOT under the Services node. The service in the AOT exposes the service class methods as service operations. The service operations take one or more data object classes as parameters. Data object class - represents a class that can be serialized to XML and de-serialized from XML. The data object class encapsulates the XML data and provides an object interface to the data. As a result developers can work with the data by using objects and properties instead of XML. The data object class that contains the data is passed as a parameter in the service operations.

Axd<Document> Classes
The Axd<Document> classes present XML data as an electronic document. Each class represents a single document in Microsoft Dynamics AX. Also Axd<Document> classes aggregate data from a number of internal Ax<Table> classes to form the document content. In addition, Axd<Document> classes perform the actual serialization and deserialization of the inbound and outbound XML documents, respectively. The term Axd<Document> class is a general reference to specific classes that implement actual document logic. For example, AxdSalesOrder is an instance of an Axd<Document> class. Each document class inherits from the AxdBase base class, as shown by the following AxdSalesOrder class: class AxdSalesOrder extends AxdBase { } By default, all methods of the AxdBase class are enabled when a document class is created. To disable a method, you must override it and return an error. For example, the AxdPurchaseInvoice.read method is disabled, as shown in the following code.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-15

Application Integration Framework and Services in Microsoft Dynamics AX 2012


public XML read(AifEntityKey _entityKey, AifSchemaInfo _schemaInfo, AifEndpointActionPolicyInfo _actionPolicyInfo, AifConstraintList _constraintList, AifPropertyBag _aifPropertyBag) { throw error(strfmt("@SYS94880")); } NOTE: Any changes to classes services calls require CIL generation, because services always execute as managed code.

Ax<Table> Classes
The Ax<Table> classes (previously known as AxBC classes) provide an object interface to the individual tables. The Axd<Document> classes always use the Ax<Table> classes to read from or write to the underlying tables. For example, the AxdSalesOrder document class uses the AxSalesTable class to access the SalesTable table.

Add Defaulting to an AX<Table> Class


If default field values are not set by table methods, the Ax<Table> classes can set default field values that are not set by the calling code. If you must bypass default fields when you insert a record with the Ax<Table> class, the code that is calling an Ax<Table> class must explicitly set the defaulting procedures to false. Table fields can be defaulted in the Ax<Table> class by overriding the setTableFields method. This code example is from the AxSalesTable.setTableFields method. protected void setTableFields() { SalesTableLinks salesTableLinks; ; super(); useMapPolicy = false; this.setCashDisc(); this.setCommissionGroup(); this.setContactPersonId(); this.setCurrencyCode(); this.setCustAccount(); this.setCustGroup(); this.setDeliveryAddress(); this.setDeliveryCity(); this.setDeliveryCountryRegionI d(); this.setDeliveryCounty(); this.setDeliveryName();

this.setDeliveryState();

5-16

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


this.setDeliveryStreet(); this.setDeliveryZipCode (); this.setDimension(); this.setDlvMode(); this.setDlvReason(); this.setDlvTerm(); this.setEmail(); // Code ommitted.

The following code shows the accessor method parmCashDisc in AxSalesTable, which only sets the SalesId field if the default is not set on the SalesTable. protected void setSalesId() { NumberSequenceReference numberSequenceReference; if (this.isMethodExecuted(funcName())) { return; } if (this.isSetMethodsCalledFromSave()) { if (this.isFieldSetExternally(fieldNum(SalesTable, SalesId))) { if (!this.salesTable()) { numberSequenceReference = SalesParameters::numRefSalesId(); this.checkNumber(numberSequenceReference.numberSequenceTable(),fi eldNu m(SalesTable,SalesId),this.parmSalesId()); if (numberSequenceReference.NumberSequenceId && numberSequenceReference.numberSequenceTable().Continuous) { NumberSeq::newReserveNum(numberSequenceReference).reserve(this.p armSal esId()); } } } else { if (this.isFieldSet(fieldNum(SalesTable, SalesId))) { return; } if (!this.parmSalesId()) { this.parmSalesId(NumberSeq::newGetNum(SalesParameters::numRefSale

sId()).

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-17

Application Integration Framework and Services in Microsoft Dynamics AX 2012


num()); } } } }

Validation in an AX<Table> Class


AX<Table> classes maintain referential integrity in the database and make sure that any field-level business rules or record-level business rules are adhered to, such as number sequences and application business logic. The class call the validatefield and validatewrite methods for the tables that they insert into, and allow a programmer to overwrite the validatewrite method on the AX<Table> class to allow for validation that is specific to that class. For example the validatewrite on the AXInventJournalTrans checks to ensure that counting journals are not modified while the items are being counted. protected void validateWrite() { InventDim localInventDim = this.axInventDim().currentRecord() as InventDim ; super(); if (this.parmJournalType() == InventJournalType::Count) { if (InventItemLocation::isCountingStarted(this.parmItemId(), this.axInventDim().currentRecord(), this.parmJournalId())) { throw error(strFmt("@SYS59534", this.parmItemId(),localInventDim.InventLocation Id)); } } }

Axd<Document> Queries
An Axd<Document> query describes the structure of the XML document and controls the data that is retrieved from Microsoft Dynamics AX. The document query is a standard query in the AOT under the Queries node, and it functions as a data source, just as a query does for a form or report. Fields that are disabled in the query are not retrieved from the database because the query is run when the data is being serialized or deserialized in the document class.

5-18

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


The queries for the documents that that are included with Microsoft Dynamics AX have the same name as the Axd<Document> class with which they are associated. For example, the query for the AxdPurchaseRequisition document class is also named AxdPurchaseRequisition. In an Axd<Document> class, the document query is returned from the AxdBase.getQuery method. The getQuery base class method is called because it is not overridden in the derived document classes. This method defaults the query name to the name of the document class, as shown in the following code. If you create your own document classes, this method can be overridden. public QueryName getQueryName() { ; if (!queryName) { queryName = classId2Name(classidget(this)); } return queryName; } Within each document class, the query is stored and accessed by using the AifQueryCriteria class. It can store the query as an existing Microsoft Dynamics AX query or as a list of criteria elements. However, the class can contain only one type of query. If the AifQueryCriteria class represents a named query, you cannot add query criteria to it. If the class contains multiple criteria elements, criteria on the same field will be ORed whereas criteria on different fields will be ANDed.

Send Framework
The send framework is used when the document's recipient cannot be determined from the document's context. As a result, the sendElectronically method is neither created nor used on the main table that is associated with the document query. When the send framework is used, the sendDocument or sendMultipleDocuments method is called from the Main method on the AxdSend <Document> class. The AxdSendContext Class is passed as an argument to the sendDocument or sendMultipleDocuments methods. Some documents that use the send framework require the AxdSendContext class to bypass RLS while others do not. The following table shows outbound documents that use the send framework. Document Price List Document class AxdSendPriceList AxdSendContex t class is called Yes

Chart of Accounts

AxdSendChartofAccounts

No

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-19

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Document Dimensions Exchange Rates Document class AxdSendDimension AxdSendExchangeRates AxdSendContex t class is called No No

Document Services Schemas


The document schema defines what data elements can participate in a data exchange and the rules for those elements. The document schema structure is based on the query that is associated with the document. The schema for the document is generated by iterating through the document query that defines the document's structure. The schema uses the names of the Ax<Table> classes and their properties to name the XML elements. The document data is mapped directly from the query to the XML schema, but with the following exceptions: Hidden fields, disabled fields, and data sources in the document query are excluded from the schema. The name of the root element in the schema is derived from the Axd<Document> class name by removing the Axd prefix. The document query can have only one root data source. All properties that are associated with the Axd<Document> class are included in the schema. Document properties contain document-level data that is stored in the document class but is not part of the document query. For example, the documentPurpose (original or copy) and the senderId (the sending company within the application) properties are included in the document schema. The document query field list always controls which fields are included in the schema and are therefore serialized. However, if the Ax<Table> class is present, only fields that have a corresponding parm <Field> method on the Ax<Table> class are serialized. Calculated fields (display fields) are always serialized.

5-20

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Document Services Wizard
The AIF Document Service Wizard guides you through the process of creating an Application Integration Framework (AIF) service. You can create a service when you want to expose X++ business logic that does not already exist as a service in Microsoft Dynamics AX. This wizard simplifies and automates the development of service interfaces, service implementations, and data objects. The AIF Document Service Wizard performs the following actions: Analyzing the document class query for any best practices issues and optionally correcting them. Generating the following classes for the service: o Ax<Table> classes for tables in the query where Ax<Table> classes do not yet exist. The Ax<Table> classes inherit from the AxInternalBase class. o A document service class contains code that is the default implementation of the selected create, read, update, delete, find, findKeys, getKeys, or getChangedKeys document service operations. The default implementation might be sufficient and would therefore not have to be changed. This class inherits from the AifDocument Class. o The <Document> class has generated code and should not be customized. This class inherits from the AifDocument Class. o The Axd <document> class has generated code that is the default implementation of the selected create, read, update, delete, find, findKeys, getKeys, or getChangedKeys document service operations. The default implementation is sufficient for simple implementations and does not have to be customized. For other scenarios, this class must be customized to expose document specific business logic. This class inherits from the AxdBase Class. Updating any existing Ax<Table> classes for tables that are used in the query. Generating a Microsoft Dynamics AX project that contains the following: o Ax<Table> classes for tables in the query where Ax<Table> classes do not yet exist. The Ax<Table> classes inherit from the AxInternalBase class. o The document query. o The generated classes. o A design view of the service. o Axd<document> DCT macro - contains constants for data object types. This macro is used by the data object classes.

o DataContainerTypes macro- includes all Axd<document> DCT macros in the system.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-21

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Procedure: Running the AIF Document Service Wizard
To run the AIF Document Service Wizard, use the following steps: 1. Open Microsoft Dynamics AX 2012. 2. Click Ctrl+Shift+W. 3. Click Tools > Wizards > AIF Document Service Wizard, or click Tools > Application Integration Framework > Create Document Service. The Welcome screen appears. 4. Click Next. 5. In the Select document parameters screen, in the Query field, select the Axd<Document> query. The Document name will default. 6. Type a descriptive name in the Label field. 7. Click Next. 8. In the Select code generation parameters screen, the the class names default based on the query you selected. 9. Select the service operations that the service will expose. TIP: Be sure to select all the service operations that you might need for the document service that you are creating. If you want to add more service operations after exiting the wizard you, will have to create a new document service that has a different name and add the service operations to it. 10. Click Next. 11. In the Generate code screen, review the artifacts that will be generated. Click Generate. 12. The Completed screen shows the artifacts that the wizard created. The service, Axd<Document> class, and the Ax<Table> classes have been created and are located in the AOT under the Classes node. The AIF Document Service Wizard adds a method to the document class for all actions that are not exposed by the class, and the method will return an error. For example, if you open one of the methods that you did not expose by the class, the generated code will resemble the following. public AifDocumentXml findList(AifQueryCriteria _queryCriteria, AifSchemaInfo _xsdInfo, AifConstraintListCollection_constraintListCollection, AifPropertyBag _aifPropertyBag) { throw error(strfmt("@SYS94920")); } The wizard also adds "TODO" statements in the generated code; these are code blocks that might require some action by the developer.

5-22

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Procedure: Generate the Document Schema
The document schema, or XSD, defines the structure and format of the XML that is serialized or de-serialized by the document class. In AIF, the schema for each document is generated by iterating through the query that is associated with the document class. The document schema defines the XML rules for the document. When you use the AIF Document Service Wizard to create a service, it automatically creates an X++ job that you can run to generate the document schema. Use the following steps to generate the document schema for the service. 1. Press Ctrl+Shift+P to open the Projects form. 2. Expand the Private node and then double-click the Axd<Document> project. This project contains all the objects that were created by the AIF Document Service Wizard that are related to the new service. 3. Double-click the GenerateXSDSchema_Axd<Document> job to open it in the X++ code editor. 4. Press F5 to run the job.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-23

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 5.1 - Add Validation and Defaulting to a Web Service


In this lab, you will add validation to an AX<Table> class.

Scenario Simon, the Systems Implementer, needs to validate that birthdays are added for all customers that were created by using the AXCustTable class.

Challenge Yourself!
Use what you have learned to validate that birthdays are added for all customers created using the AXCustTable class.

Need a Little Help?


1. Overwrite the ValidateWrite method on AXCustTable.

Step by Step
1. Open Microsoft Dynamics AX 2012. 2. Click Ctrl+Shift+W to open a development workspace. 3. Right-click AOT > Classes > AXCustTable and then click Override method > More... > More... > ValidateWrite. 4. Change validate write to the following code and then click save: protected void validateWrite() { super(); if (this.parmBirthDate_IT() == dateNull()) { throw error("Birthday is required for web entry"); } }

NOTE: A hard-coded error message was used to make this example easier to read. The best practice is to use a label rather than hard-coded strings.

5-24

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts

Lab 5.2 - AIF Document Service Wizard


In this lab, you will use the AIF Document Service Wizard. Scenario Simon, the Systems Implementer, wants to use the AXDlvMode query to read information from the DlvMode table.

Challenge Yourself
Generate a new document service for the AxdDlvMode query by using the AIF document services wizard.

Need a Little Help?


1. Run the AIF document service wizard. 2. Generate the document schema.

Step by Step
1. Open Microsoft Dynamics AX 2012. 2. Click Ctrl+Shift+W. 3. Click Tools > Wizards > AIF Document Service Wizard, or click Tools > Application Integration Framework > Create Document Service. The Welcome screen appears. 4. Click Next. 5. In the Select document parameters screen, in the Query field, select the AxdDlvMode query. The Document name will default. NOTE: For this lab enter "DlvMode1" in Document name. 6. Type a descriptive name in the Label field. 7. Click Next. 8. In the Select code generation parameters screen, the class names default based on the query you selected. 9. Select the "read" service operation. TIP: Be sure to select all the service operations that you might need for the document service that you are creating. If you want to add more service operations after exiting the wizard you will have to create a new document service that has a different name and add the service operations to it.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-25

Application Integration Framework and Services in Microsoft Dynamics AX 2012


10. Click Next. 11. In the Generate code screen, review the artifacts that will be generated. Click Generate. NOTE: This might take a few minutes. 12. The Completed screen shows the artifacts that the wizard has created. 13. Click Finish. 14. Press Ctrl+Shift+P to open the Projects form. 15. Expand the Private node and then double-click the AxdDlvMode1. Under the Private node, locate the new AxdDivMode project. This project contains all the objects that were created by the AIF Document Service Wizard that are related to the new service. 16. Double-click the GenerateXSDSchema_AxdDlvMode1 job to open it in the X++ code editor. 17. Press F5 to run the job.

5-26

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts

Custom Services
In Microsoft Dynamics AX, you can use custom services to expose X+ + functionality to external clients. No additional code is required to expose any existing X++ classes. Microsoft Dynamics AX provides standard attributes that can be set on the DataContract class and its members to automatically serialize and de-serialize data that is sent and received across a network connection. Many predefined types, such as collections and tables, are also supported. Use custom services when the schema for the entity can be written as a simple data contract class and relevant data member attributes set. If tables and relationships are used in a data contract, you must create code for a more complex feature such as dimensions. You can use all functionality of transforms for data processing with custom services. CAUTION: The service operation names Create, Find, Update, and Delete are reserved for use only in AIF Document Services. Use of those service operation names in a custom service will generate an exception and might cause the system to time out when you try to call the service from an external client.

Data Contracts
Microsoft Dynamics AX supports the use of .NET and X++ types as data contracts for service operation input and return parameters. This helps you to pass complex data types without having to explicitly implement XML serialization and deserialization. The data contract serialization and deserialization is handled by Windows Communication Foundation (WCF).

System Services
System services are Windows Communication Foundation (WCF) services that are included with Microsoft Dynamics AX. These services help clients interact with and retrieve system information. The system services include the following: Metadata service Helps you query for data about the structure of your installation. You can retrieve metadata for labels, menus, menu items, tables, extended data types, data types, enums, queries, web menus, web menu items, info parts, cues, dimensions, form parts, web controls, service groups, and services.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-27

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Use the metadata service when you want to return information about the structures in Microsoft Dynamics AX to a client application. For example, if you want to return information about a table such as what indexes exist on that table, you can use the metadata service. Query service helps you issue a query for data without using an Application Integration Framework (AIF) document service or creating a custom service. The query service returns data in a dataset and implements a paging mechanism so that you can manage queries that return large amounts of data. When calling the query service, you can specify the query to run in one of three different ways: o Static query is already defined in the AOT under the Queries node. o User-defined query is defined by using the QueryMetadata class which is found in the metadata service. o Dynamic query is defined in an X++ class that extends the AifQueryBuilder class. All query logic is contained in the query builder class User session service helps you return information about the current Windows user. You can return information such as the users default language, default company, default company time zone, and so on. All three of these services have the following properties: Automatically installed Hosted by the Application Object Server (AOS) by default Always available A Windows Communication Foundation (WCF) service that adheres to WCF protocols and standards

Metadata Service
The metadata service returns information about AOT objects in Microsoft Dynamics AX such as tables, services, extended data types (EDTs), enums, and so on. The metadata service has two types of service operations: Service operations that return names or keys return the names or keys for all queries, tables, menus, and so on. The names are returned in a string array.

5-28

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


The name of the metadata service operation specifies the names that are returned. For example, the GetQueryNames method returns a string array of names for all queries in the installation. Service operations that return metadata take a string array of names, an integer array of IDs, or an array of key objects (such as MenuItemKeys[ ]) and return the metadata for those objects. Each of these service operations returns an array of metadata objects. NOTE: For more information about metadata service types, refer to the Metadata Services (http://go.microsoft.com/fwlink/? LinkID=247494&clcid=0x409 )topic on Technet.

Query Service
The query service is one of the Microsoft Dynamics AX system services that helps you issue a query for data without using an Application Integration Framework (AIF) document service or creating a custom service. The query service returns data in a dataset and implements a paging mechanism so that you can manage large amounts of data that are returned by a query. The query service runs the query that you specify and returns the data in a dataset. The three types of queries that you can call with the query web service are: Static query is already defined in the Application Object Tree (AOT) under the Queries node. When calling the query service by using a static query, you pass in the query name as a string. User-defined query is defined by using the QueryMetadata class. Dynamic query is defined in an X++ class that extends the AifQueryBuilder class. All query logic is contained in the query builder class. Use a dynamic query when you want to perform the following tasks: o Using the query service to call a complex query that cannot be created by using a static query or a userdefined query o Assuming full control over the query behavior and results When you use the query service to call a static or user-defined query, the query service handles the details of how the query is run, for example, the dataset name is defaulted to the name of the query. If using the SysQueryBuilder class, you can specify the dataset name in the

getDataSetName method. NOTE: For more information on the query service, refer to the Query Service (http://go.microsoft.com/fwlink/?LinkID=247495&clcid=0x409 ) topic on Technet.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-29

Application Integration Framework and Services in Microsoft Dynamics AX 2012


User Session Service
In Microsoft Dynamics AX, the user session service returns information about the calling user such as his or her default language, default company, default company time zone, and so on. The user session service has two service operations: GetAccessRights returns an AccessRight array that contains the permissions that the calling user has to a specified access controlled item. For example, you can use this service operation to return the permissions that the calling user has to menus, tables, and so on. GetUserSessionInfo - returns a UserSessionInfo class. This class contains properties that return the actual user information for the current user, as shown in the following table. Property AXLanguage Description Returns a string that specifies the users default language, as defined in the User options Company Returns form. a string that specifies the users default company, as defined in the User options form. CompanyTimeZone Returns a TimeZone class that specifies the time zone for the users default company, as defined in the User options form. The company time zone is in the Company information form. CurrencyInfo Returns a CurrencyInfo class that specifies the default currency code that is associated with the users default company, as defined in the User options form. The company currency code is in the UserPreferredCalendar Returns a PreferredCalendar class that specifies the users preferred calendar, as defined in the User options form. In the User options form, the User preferred calendar field is only visible if the users language is set to Arabic. UserPreferredTimeZone Returns a TimeZone class that specifies the time zone for the user, as defined in the User options form. NOTE: For more information refer to the User Session Service (http://go.microsoft.com/fwlink/?LinkID=247496&clcid=0x409 ) topic on Technet.

5-30

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts

How AIF Exchanges Data


AIF uses XML encoding for communication into and out of Microsoft Dynamics AX 2012. The XML documents must follow a specific XML Schema Definition (XSD), which can be found by using the Web Service Definition Language (WSDL). Schemas define the format and content of the message. Each message contains metadata and data. The metadata is the data that is not document-specific and includes the envelope, the header, entity keys, and so on. The message metadata is used by AIF to determine which service and action to call. The message data is specific to a particular document, such as what is showing in the following example:
<?xml version="1.0" encoding="utf-8" ?> <Envelope xmlns="http://schemas.microsoft.com/dynamics/2011/01/docume nts/Message"> <Header> <MessageId>{8448d530-d1e4-4c69-92f133aeaacbc0ea}</MessageId> <Action>http://schemas.microsoft.com/dynamics/2008/01/servi ces/SalesOrderService/create</Action> </Header> <Body> <MessageParts> <SalesOrder xmlns="http://schemas.microsoft.com/dynamics/2008/01/docume nts/SalesOrder"> <SalesTable > <CustAccount>2014</CustAccount> <PurchOrderFormNum>PO</PurchOrderFormNum> <ReceiptDateRequested>2011-1111</ReceiptDateRequested> <SalesLine > <ItemId>10003</ItemId> <SalesQty>18</SalesQty> <SalesUnit>Pcs</SalesUnit> </SalesLine> </SalesTable> </SalesOrder> </MessageParts> </Body> </Envelope>

Microsoft Official Training Materials for Microsoft Dynamics

Your use of this

content is subject to your current services agreement

5-31

Application Integration Framework and Services in Microsoft Dynamics AX 2012


There are various schemas that define the format and content of messages in AIF, as shown in the following table. Schema Messag e schema s Documen t schema Description Define the format and content of the message metadata. This includes elements such as the envelope, the header, query criteria, entity key lists, and so on. The message schemas are included with Microsoft Dynamics AX. Defines the format and content of the business data in a message. This schema contains all the fields that can participate in a data exchange. Any message that comes into AIF must validate against the document schema. You can save the XSD for any document with any port-specific customizations

XSD
Each document in AIF has a set of schemas that defines the structure and format of the XML that the document can serialize and de-serialize. This is called the document XML Schema Definition (XSD) or the schema. The document schema defines the structure and format for all possible fields in the document. NOTE: When creating an integration port for an exchange, you can enable different fields for each document, which will be reflected in the schema.

Document XSD
In AIF, the schema for each document is generated by iterating through the query that is associated with the document class. For example, the PurchPurchReqService document service class is associated with the AxdPurchaseRequisition document class and a query by the same name. The data source for this query contains multiple nested tables with the VendPurchOrderJour table at the parent level. When an XML document is sent or received in AIF, the XML is validated against the document schema. Microsoft Dynamics AX generates the schema internally by calling the getSchema method as shown in the following diagram.

5-32

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


NOTE: The document schema is generated directly from the document query. During schema generation, if an Ax<Table> class exists for a table in the query, the elements in the schema that represent the source table fields are built from that Ax<Table> class; otherwise, the elements are built from the source table that is referenced in the query

FIGURE 5.2 DOCUMENT SCHEMA PROCESS FLOW

XSD Naming Conventions


The following table shows the conventions used by AIF when naming schema elements. These conventions are used to ensure that none of the schema element names conflict with other names such as the document name, query name, and so on. Elemen t prefix <none> AxdEntity_ Element type Document Data source Description None A complexType element is generated for each data source in the query. In the schema, each data source name must be unique, so the name is prefixed by "AxdEntity_", for example, An <xsd:simpleType> element is generated for each field or property of an extended data type that is to be included in the XML document if that field or property is not derived from a Container data type. The name of the generated <xsd:simpleType> is the name of the extended data type prefixed with "AxdExtType_", for

AxdExtType_

Extended data types

Microsoft Official Training Materials for Microsoft Dynamics

Your use of this content is

subject to your current services agreement

5-33

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Elemen t prefix AxdUnion_ Element type Unions Description If the extended data type, for which a <xsd:simpleType> element is being created, is subject to value mapping, then the field element will reference an <xsd:union> between the data type of the field and the type that represents the external values. This element is a union between the data type of the value mapped field and the type that represents the external values, as shown in the following schema XML. <xsd:simpleType name="AxdUnion_AxdExtType_< Ex tendedDataTypeName>_AxdType _E xtCodeValue"> A schema element is created for each field or property of an extended data type that is to be included in the XML document if that field or property is not derived from a Container data type and has an ArrayLength greater than 1. This element has the format of None A schema element is generated for each reference data source that is used by each data source in the query to contain any surrogate foreign keys used. The element has the form of

AxdArray_

Arrays

AxdEnum_

Enumerations

AxdEntityKey Surrogate key _

5-34

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Mapping Data Types
In a document schema, the following X++ data types are mapped to their corresponding XSD types. X++ data type string XSD type xsd:string, maxLength=StringSize (maxLength=max(StringSize,50) in case of value mapping) xsd:int xsd:time, ISO format: HH:MM:SS (Time stamp if global::isTypeTime is true) xsd:long xsd:decimal, fractionDigits=NoOfDecimals xsd:date, ISO format: YYYY-MM-DD xsd:datetime xsd:string, enumeration=<EnumName>, ... xsd:string, pattern=[0-9A-Fa-f]{8}-... xsd:string, Base64 encoded

integer time int64 real date utcdatetime enum GUID BLOB

Excluded Field List


The following fields are excluded in all AIF XML documents. These fields are not imported during the inbound action and are not exported during outbound actions. Fields starting with Del_ Fields marked with status of Not visible

Non-Editable Fields
In an inbound message, the XML cannot contain data for fields that are non- editable in the table (the AllowEdit property is set to No). That is, for each non- editable table field, the field element must not be in the inbound XML or the field element must be filtered out in the endpoint action data policy.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-35

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Null Values
The following are special considerations for null values. Outbound Null Values - null values are not serialized for outbound documents. Arrays can contain empty elements and will be serialized. Inbound Null Values - empty string elements are interpreted as zero-length strings and not null values when you are processing an inbound document. o Use <element xsi:nil="true"/> to specify a null value.

Time Values
When .NET serializes time values to XML, it includes fractional seconds and an offset. For example, .NET could create an XML element similar to the following: <AxTime>23:18:29.8108671-08:00</AxTime> AIF will accept an XML time value in this format. However, when it deserializes a time value, the fractional seconds and offset are truncated and the value will contain hours, minutes, and seconds (hh:mm:ss). AIF de-serializes the previous time value to the following: <AxTime>23:18:29</AxTime> Some documents contain time zone elements. The valid time zone values are specified in the document schema.

AIF Messages
When AIF receives and processes an inbound message, it generates an outbound message in response that has a <Header> tag section and a <Body> tag section. The XML tag names in the <Header> are mostly the same across all messages. The tag names in the <Body> section vary between different inbound messages, and between different outbound messages. The tags that are required in the <Body> section depend on which service option is specified in the <Action> tag in the <Header> section.

5-36

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Example: Inbound Read Message
To illustrate how the different schemas are used in AIF, consider the scenario in which a client reads a customer record, modifies that record, and then sends it back to AIF to update the database. The client application must first create a read request message that is sent into AIF by any one of the supported transport methods In the message header, the Action tags must specify the CustomerService service and the read service operation. The Action tag is used by AIF to identify the service and the service operation that should be called as a result of the message. The message metadata, such as the envelope and the header, must conform to the Message.xsd schema that is included with Microsoft Dynamics AX. The CustomerService.read service operation takes an _entityKeyList parameter, so this information must also be in the inbound message and conform to the EntityKeyList.xsd schema that is included with Microsoft Dynamics AX and shown in the following code.
<?xml version="1.0" encoding="utf-8"?> <Envelope xmlns="http://schemas.microsoft.com/dynamics/ 2011/01/documents/Message"> <Header> <MessageId>{fa34cd6c-c7ee-4788-a304be3754c7eae5}</MessageId> <Action>http://schemas.microsoft.com/dynamics/ 2008/01/services/CustomerService/read</Action> <ConversationId></ConversationId> </Header> <Body> <MessageParts> <EntityKeyList xmlns="http://schemas.microsoft.com/dynamics/ 2006/02/documents/EntityKeyList"> <EntityKey xmlns="http://schemas.microsoft.com/dynamics/ 2006/02/documents/EntityKey"> <KeyData> <KeyField> <Field>AccountNum</Field> <Value>4507</Value> </KeyField> </KeyData> </EntityKey> </EntityKeyList> </MessageParts> </Body> </Envelope>

Within the EntityKeyList tags in the message, one or more EntityKey tags could contain the IDs of the records to be read. The EntityKey tags must conform to the EntityKey.xsd that is included with Microsoft Dynamics AX. When AIF receives the correctly formatted message, it will send back a message that contains the customer data.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-37

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Example: Inbound Update Message
The client system takes the customer data, makes modifications, and then creates a message to send back to AIF. This message specifies the updates that will be made in the database. In the message header, the Action tags must specify the CustomerService service and the update service operation. Again, the update message metadata must conform to the Message.xsd schema. The CustomerService.update service operation takes two parameters: _entityKeyList - a list of IDs for the customers that are to be updated. _custCustomer - one or more customer records to be updated. The inbound update message will contain the entity key list and the updated customer data. Just as in the read message, message metadata and the data within the EntityKeyList tags must conform to the Message.xsd schema. The data for each customer record and each customer address record to be updated is enclosed in Customer tags. The message content in between these tags must conform to the document schema. The document schema defines the format for each specific document. In this case, the documentspecific XML must conform to the customer document schema. The following XML is an example of an inbound update message to update a customer group and department dimension. <?xml version="1.0" encoding="UTF-8"?> <Envelope xmlns ="http://schemas.microsoft.com/dynamics/2011/01/documents/Message"> <Header> <MessageId></MessageId> <Action>http://schemas.microsoft.com/dynamics/2008/01/services/Custo merSer vice/update</Action> </Header> <Body> <MessageParts xmlns ="http://schemas.microsoft.com/dynamics/2011/01/documents/Message"> <EntityKeyList xmlns ="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKeyLi st"> <EntityKey xmlns ="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey" > <KeyData >

<KeyField > <Field>AccountNum</Field> <Value>1101</Value> </KeyField > </KeyData > </EntityKey >

5-38

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


</EntityKeyList > <Customer xmlns ="http://schemas.microsoft.com/dynamics/2008/01/documents/Customer"> <ValidAsOfDateTime>2011-1029T08:11:50Z</ValidAsOfDateTime> <CustTable class ="entity" action ="update"> <_DocumentHash>47d6ff0fc52fd53de82f9df0dc1d37e4</_Document Hash> <CustGroup>20</CustGroup> <DefaultDimension> <Values xmlns ="http://schemas.microsoft.com/dynamics/2008/01/sharedtypes"> <Value > <Name>CustomDepartment</Name> <Value>030</Value> </Value > </Values > </DefaultDimension> </CustTable > </Customer> </MessagePart s> </Body > </Envelope>

Generate the Schema for a Document in an Exchange


When you configure a document exchange by creating an integration port, you associate document service operations with that port. For each one of these document service operations, you can specify which fields are enabled on the Data policies form. Therefore, the document schema for each exchange can be a subset of the full document schema, depending on which fields are enabled.

Procedure: View a Schema for a Document Exchange


The following procedure shows how to view the schema for a document exchange. 1. Open either the Inbound ports form or the Outbound ports form. To open these forms, follow one of these steps: o Click System administration > Setup > Services and Application Integration Framework > Inbound

ports. o Click System administration > Setup > Services and Application Integration Framework > Outbound ports. 2. On the Service contract customizations FastTab for one of the inactive ports, select Customize documents and then click Data policies to open the Document data policies form. NOTE: Service contracts are only available on enhanced ports. 3. In the Document name field, click a document name.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-39

Application Integration Framework and Services in Microsoft Dynamics AX 2012


4. Click View schema to view the schema for the document that uses the field-level restrictions on the Document data policies form. 5. To save the schema, click Save as, select a file location, and then click Save.

Shared-Types Schema
The shared-types schema defines the enums and extended data types (EDTs) that are used by a document service. The shared-types schema consolidates all the data types into one schema that is imported by all document service schemas. The namespace for the shared-types schema is http://schemas.microsoft.com/dynamics/2008/01/sharedtypes. If you publish a new service that contains a new enum or EDT, the sharedtypes schema is automatically updated. The shared-types schema is imported by the WSDL. NOTE: Automatic updates to the shared-types schema could cause schema mismatches. If you want to view the shared-types schema, view the schema for any service from either the Inbound ports or the Outbound ports form. Click View imported schemas to view the shared-types schema. IMPORTANT: If providing a document XSD to an external party, you have to provide the shared-types schema also. This is because the sharedtypes schema is imported by the XSD, and without the shared-types schema, the external user is not able to utilize the service XSD.

Locating the WSDL for Services


All Microsoft Dynamics AX services that are exposed on an integration port and hosted by the Application Object Server (AOS) are contained in a single Web Services Definition Language (WSDL) file. The WSDL URI address resembles: http://<machine name or NLB cluster name>:8101/DynamicsAx/Services/LedgerJournalService. The default port for the root WSDL is 8101 if you have only one AOS instance. However, if you have multiple AOS instances, the port number depends on which AOS is hosting the services. The WSDL port number is generated by using 8100 + AOS ID. You can find the AOS ID by going to the Services form. To open the Services form in Windows Server 2008, go to Start > Administrative Tools > Services. The service name is Microsoft Dynamics AX Object Server <version>$<AOSID>-MicrosoftDynamicsAx.

5-40

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Procedure: Viewing the WSDL for a Service
You can view the WSDL for services on any inbound or outbound port. The following example uses an inbound port. 1. Open the Inbound ports form. Click System administration > Setup > Services and Application Integration Framework > Inbound ports. 2. Copy the WSDL URI in the Address section for any active inbound port. 3. Open Internet Explorer. 4. In the address bar, paste the URL of the root WSDL, for example, http://ContosoServer:8101/DynamicsAx/Services/LedgerJourn alServ ice. The WSDL contents appear in the Internet Explorer page.

Customizing the AIF Pipeline


Application Integration Framework (AIF) provides the flexibility to manipulate a message as it comes in-to or goes out of Microsoft Dynamics AX through inbound or outbound ports. These capabilities include the ability to transform the incoming document by using .net assemblies, or XSL transform, to add custom code to the pipeline, and to perform value mapping with value substitution maps or business rules. The options for customizing the AIF pipeline are as follows: Inbound port (inbound pipeline) o Inbound transforms o Inbound pipeline (includes Value substitution maps) o Value mapping Inbound port (outbound pipeline) o Outbound pipeline (includes Value substitution maps) o Outbound transforms o Value mapping

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-41

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Outbound port (outbound pipeline) o Outbound pipelines (includes Value substitution maps) o Outbound transforms o Value mapping

FIGURE 5.3 DATA FLOW IN AN ENHANCED INTEGRATION PORT

Transforms
Transforms provide an extensible framework that developers can use to apply Extensible Stylesheet Language Transformations (XSLT) or .NETbased transforms to messages. .Net-based transforms can convert messages to or from any proprietary format. Microsoft Dynamics AX services and AIF can process XML documents only if the documents comply with the service XSD. If an incoming document is based on XML but uses a different schema, you can use Extensible Stylesheet Language (XSL) to transform the document to the AIF schema. If an incoming document is not based on XML, such as a comma- delimited file, you can use a .NET Framework assembly to convert the file to the AIF schema. CAUTION: We do not recommend adding multiple instances of the same .NET assembly to the Manage transforms form by using a different name for each instance. When multiple instances of the .NET assembly are listed in the form, each instance refers to the same .dll file. Changes to the .dll file will affect all ports that reference the transform, regardless of the transform's name in the Manage transforms form. You can apply transformations, or transforms, to documents that are processed by an inbound or outbound integration port. In inbound integration ports, you can specify transforms for inbound messages or outbound responses. In outbound integration ports, you can specify transforms for outbound messages. Transforms for inbound exchanges are run before transforms for outbound exchanges. Transforms process the whole message. Therefore, the body and headers of the message are processed.

5-42

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


IMPORTANT: You must apply a transform whenever an inbound document does not match the AIF schema. If connecting to BizTalk, you can chose to use its transformation facilities instead.

Procedure: Manage Transforms


Before you can use a particular transform, you must add it to the database by using the Manage transforms form. You can also use this form to modify or delete the information about a transform. To add a new transform on an integration port, use the following steps. NOTE: You must be logged in-to Windows Server as an administrator to add a new transform. 1. Open the Manage transforms form by following one of these steps: a. Click System administration > Setup > Services and Application Integration Framework > Inbound ports. Select an enhanced port. Expand Processing Options and then select Transform all requests. Click Inbound transforms. Then, on the Action Pane, click Manage transforms. o Click System administration > Setup > Services and Application Integration Framework > Inbound ports. Select an enhanced port. Expand Processing Options and then select Transform all responses. Click Outbound transforms. Then, on the Action Pane, click Manage transforms. o Click System administration > Setup > Services and Application Integration Framework > Outbound ports. Select an outbound port. Expand Processing Options and then select Transform all responses. Click Outbound transforms. Then, on the Action Pane, click Manage transforms. o In the MorphX development environment, click Tools > Application Integration Framework > Manage transforms. 2. Click New. 3. Enter a name and description for the transform. 4. In the Type field, select the type of transform that you want to add to the database: o XSL Add an XML-based transform that is contained in an .xsl or .xslt file. o .NET assembly Add a .dll file that is created by using the .NET Framework.

5. Click Load. 6. Browse to the file that contains the transform and then click Open.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-43

Application Integration Framework and Services in Microsoft Dynamics AX 2012


NOTE: You can use the Transform details group to view the XSLT code or information about the .NET Framework assembly for the transform that you loaded. 7. To save the data, press CTRL+S or close the form.

Procedure: Apply Transforms


To apply a transform to an inbound or outbound port, follow these steps. 1. Click System Administration > Setup > Services and Application Integration Framework > Inbound port or click System Administration > Setup > Services and Application Integration Framework > Outbound ports. 2. For inbound transforms, select Transform all requests. For outbound transforms, select Transform all responses. 3. Click Inbound transforms or Outbound transforms. Depending on the button that you clicked, either the Inbound transforms form or the Outbound transforms form opens. These forms are identical, except each instance contains only the transforms that are applied to the type of exchange that you are modifying, either inbound or outbound. You can use these forms to add a new transform, delete a transform, or modify a transform for the port. 4. Click New. 5. In the Transform name field, select a transform. This field contains the names of transforms that you added to the database in the previous section by using the Manage transforms form. 6. If you apply multiple transforms to the port, you can change the order in which the transforms are processed. To move a transform higher in the order, select the name of the transform and then click Move up. To move a transform lower in the order, select the name of the transform and then click Move down. 7. Close the form.

Custom Pipeline
You can use pipelines to add custom processing to documents that are processed by an inbound or outbound integration port. In inbound integration ports, you can use pipelines for inbound requests or outbound responses. In outbound integration ports, you can use pipelines for outbound messages. For inbound exchanges, pipelines are run after transforms. For outbound exchanges, pipelines are run before transforms. Pipelines process only the body of the message.

5-44

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Custom pipelines are classes that implement the AifPipelineComponentInterface interface. The three classes that are available at shipment are: AIFValueSubstitutor - substitutes the value of a string field for another. AIFXMLTransform - performs XSLT transforms. CatVendorXmlTransform - creates and maintains procurement catalogs.

Procedure: Add a Pipeline Component


To add a component to a pipeline, follow these steps. 1. For inbound pipelines, select Preprocess service operation requests. For outbound pipelines, select Postprocess service operation responses. 2. Click Inbound pipelines or Outbound pipelines. 3. Depending on the button that you clicked, either the Inbound pipelines form or the Outbound pipelines form opens. These forms are identical, except each instance contains only the pipeline components that are applied to the type of exchange that you are modifying, either inbound or outbound. You can use these forms to add a new component to the pipeline, delete a component from the pipeline, or modify a component in the pipeline. 4. Click New. 5. In the Service operation ID field, select a service operation. NOTE: There must be service operations that are configured for the selected integration port for this form to display service operations. 6. Each pipeline component is associated with a specific service operation. You can associate multiple pipeline components to each service operation. 7. In the Class name field, select a component. The form might take some time to search for available components. 8. In the Purpose field, enter the reason that you are using the component. 9. Press CTRL+S to save the data. 10. Click Configure to modify settings for the component that you added. Each type of component has a different configuration form.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-45

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Value Substitution Maps
In Microsoft Dynamics AX services and Application Integration Framework (AIF), a value substitution map defines a relationship between two values: An internal value, which is stored by Microsoft Dynamics AX An external value, which is contained in a document that is used in an AIF-based transaction A lookup table contains lookup entries that map internal values to external values. To create, delete, or modify lookup tables, you can use the Value substitution maps form. The way that values are substituted depends on the direction of the document transfer: For inbound transfers, the value that you enter in the Internal value field replaces the value that you enter in the External value field. For outbound transfers, the value that you enter in the External value field replaces the value that you enter in the Internal value field. By using lookup tables, you can substitute one value for another in any field that has a corresponding extended data type (EDT). Each lookup table is associated with a single EDT, but you can create multiple lookup tables for the same EDT. Not every field in a service schema is associated with an EDT. The Pipeline value substitution form displays a list of the EDTs that are associated with elements for a service operation that you have configured for value substitution. You can also use the Pipeline value substitution form to associate a lookup table with a document field.

Procedure: Create a Lookup Table


To create a lookup table, follow these steps. 1. Click System administration > Setup > Services and Application Integration Framework > Value substitution maps. 2. Click New. 3. In the Lookup table ID field, enter a unique identifier for the lookup table. 4. (Optional) In the Name field, enter a descriptive name for the lookup table. 5. In the Extended data type name field, select the EDT that you want to use for value substitution. 6. On the Lookup entries FastTab, click Add.

7. In the Internal value field, enter the internal value. 8. In the External value field, enter the corresponding external value. 9. Press CTRL+S to save the lookup entry.

5-46

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


10. Repeat steps 6 through 9 for each value substitution entry that you want to create in the lookup table for the EDT that you selected. 11. When you have finished creating lookup entries, close the form.

Procedure: Use a Lookup Table


The following procedure shows how to use a lookup table. 1. Follow the steps in "Procedure: Add a Pipeline Component" to add a pipeline component with the class AifValueSubstitutor. 2. In the Element name field of the Pipeline value substitution form, find the name of the element for which you want to enable value substitution. 3. In the corresponding Lookup table ID field, select the unique identifier of the lookup table that you created. The only lookup tables that are available are the tables that you defined for the EDT that is associated with the element. The associated EDT is displayed in the Extended data type name field. 4. Repeat steps 2 through 3 for each value substitution that you want to enable for the service operation. 5. Close the forms.

Pipeline XSLT Transform


To configure the AifXmlTransform component, use the Pipeline XSLT transform form. In this form, you can select an XSLT ID and specify how the XSLT is used.

Procedure: Use Pipeline XSLT Transforms


Before you can configure the AifXmlTransform component, you must add at least one transform to the database, or XSLT repository, by using the XSLT repository form. You can also use this form to modify, view, or delete an XSLT in the repository. To add a new transform to the XSLT repository, follow these steps. 1. Follow the steps in "Procedure: Add a Pipeline Component" to add a pipeline component with the class AIFXmlTransform. 2. Click Configure. 3. In the Pipeline XSLT transform form, click Import XSLT. The XSLT repository form opens. 4. In the XSLT repository form, click New to add a new record. 5. In the XSLT ID field, enter a unique ID for the transform. 6. Click Import. 7. Browse to the file that contains the XSLT style sheet that you want to add to the XSLT repository, and then click Open.

8. To view the XML code for the XSLT that you imported, click View. 9. Close the form.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-47

Application Integration Framework and Services in Microsoft Dynamics AX 2012


10. In the Pipeline XSLT transform form, select an XSLT ID in the XSLT ID field. 11. For inbound ports, you can limit the XSLT transform to a specific parameter for the service operation. Click Apply transform to parameter, and then select a method parameter in the Parameter name field. 12. To enable scripts in the pipeline XSLT transform to run, click Scripting enabled. CAUTION: Scripts can pose a security risk. Enable scripting only for XSLT transforms that come from trusted sources. 13. Close the form.

Catalog Import
To create and maintain procurement catalogs on your procurement site, you can allow vendors to submit catalog maintenance request (CMR) files by using the vendor self-service portal. Before a vendor can use the vendor self-service portal to import catalog files, you must set up an integration port by using Application Integration Framework (AIF). Only users who are assigned to the System Administrator role can configure integration ports. This task is only one of the steps that are required to enable imported catalogs. Before you can configure a port to receive CMR files from vendors, you must set up a root folder where all the files are stored.

Procedure: Use Pipeline XSLT Transforms


The catalog import service requires a special component that processes CMR documents. To enable this component, follow the steps in "Procedure: Add a Pipeline Component" to add a pipeline component with the class CatVendorXmlTransform.

Value Mapping
During value mapping, field data values are translated based on business rules. For example, you can translate internal item numbers to vendor-specific item numbers or industry-standard numbers, depending on the trading partner. Value mapping can be performed on inbound and outbound XML documents, and is configured on each port. Value mapping creates a translation index between a field in Microsoft Dynamics AX and an external field in the

document. This index gives you more flexibility when you must handle various internal, vendor-based, or industry-based codes.

5-48

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Value mapping can use the document values that are shown in the following table. Setting Not specified Our Description Do not apply a value map. This is the default setting. Use the code for the document value that the company uses internally, and that is a part of the company's internal tables. Examples of internal codes are item numbers, customer account numbers, and vendor account numbers. Use a custom external code instead of the code in the document. For example, in the Handling vendor numbers group, you can select a value for an external vendor code in the Vendor code For items, use the external item number. For items, use a bar code value. Select a bar code by using the Bar code group. For currency codes, use the International Standards Organization (ISO) 4217 currency code.

External code

External item number Bar code

ISO currency code The following table describes the data values that you can map. Category Partners Addresses Data Vendor code Customer code Country/region code Country code State code Zip/postal Item number code Warehouse code Unit code Currency code Mode of delivery code Delivery terms codes Charges code Sales tax code

Items Units Other base data

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-49

Application Integration Framework and Services in Microsoft Dynamics AX 2012


For value mapping, the general configuration options that are shown in the following table are available on the Setup tab in the Value Mapping form. Option Validate input Description In services and AIF, data in an inbound XML document is usually validated by the Ax<Table> classes. Input validation guarantees that restrictions on the referential integrity, number sequence, and business logic are enforced. Input validation also prevents the insertion of incorrect data into the application. If you disable input validation, data from an inbound XML document is inserted into Microsoft Dynamics AX, regardless of the Defaulting sets predefined values in an inbound document if the document does not contain these values. If you disable defaulting, an inbound XML document is processed, regardless of whether the document contains required field values. As a result, some required fields may not contain values. If required fields do not contain values, the document

Use defaulting

5-50

M i c r o s o f t O f f i c i a l T r a i n i n g M a t e r i a l s f o r M i c r o s o f t D y n a m i c s

of this content is subject to your current services agreement

Y o u r u s e

Chapter 5: Development Concepts


Option Configure outbound properties Description You can limit the number of documents or entity keys that are returned from a request. By limiting the number of records that are returned, you reduce the size of the XML document that Application Object Server (AOS) processes. For example, you might want to limit documents when the read and find service operations are called. These service operations typically return complete documents, and the number of records that are returned is unknown when the request is made. Therefore, large data sets might be returned. To limit the number of documents that are returned, follow these steps. 1. In the Value mapping form, click the Setup tab. 2. In the Limit number of documents field, select Yes. 3. If you want to limit the number of documents to 1,000, which is the default, select Default in the Limitation type field. If you want to use a limit other than 1,000, select Specified.

Procedure: Configure Value Mapping


To configure value mapping, follow these steps: 1. Select Apply value mapping. 2. Click Value mapping to open the Value mapping form. 3. In each Document value field, select the document value that you want to use. 4. Perform general configuration. 5. Close the form.

Microsoft Official Training Materials for Microsoft Dynamics

Your use of this content is

subject to your current services agreement

5-51

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Business Operations Framework


In Microsoft Dynamics AX 2012, the RunBase framework has been depreciated in favor of the Business Operations Framework. The features of the Business Operations Framework include the following: Allows menu-driven or batch processing of services Calls services in synchronous or asynchronous mode Automatically creates a customizable UI based on the data contract Encapsulates code to operate on the appropriate tier (prompting on the client tier, and business logic on the server tier)

Creating a Business Operation Framework Service


To create a Business Operation Framework service, the following steps must be performed. 1. Create a data contract class 2. Identify the parameters that were passed to the service 3. Register the class as a Business Operation Framework service 4. Customize the automatically-generated UI for the class (optional)

Procedure: Create a Data Contract Class


Create one or more classes to define the parameters for the operation. The X++ attribute [DataContractAttribute] identifies the class as a data contract class. 1. Click Ctrl+Shift+W to open a new development workspace. 2. Right-click AOT > Classes and then click New Class. 3. Double-click AOT > Classes > Class1 and then paste the following code:
[DataContractAttribute] class SimpleDataContract { int property1; }

4. Click Ctrl + S to save the class.

5-52

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Procedure: Identify Parameters
The X++ attribute [DataMemberAttribute] identifies the property accessor methods, which are the parameters to the service call. 1. In the SimpleDataContract class that was created in the previous procedure, click Ctrl + N to create a new method. 2. Paste the following code:
[DataMemberAttribute] public int property1(int _property1 = property1) { property1 = _property1; return property1; }

3. Click Ctrl + S to save the class.

Procedure: Create the Service Class


After the data contract classes are defined, creating the service operation is simple. 1. 2. 3. 4. 5. Click Ctrl+Shift+W to open a new development workspace. Right-click AOT > Classes, and then click New Class. Right-click AOT > Classes > Class1, and then click Rename. Rename the class to "SimpleService" Double-click AOT > Classes > SimpleService and then click Ctrl + N to create a new method. 6. Paste the following code:
public str operation1(SimpleDataContract _dataContract) { str returnValue; returnValue = strfmt('Input was %1', _dataContract.property1()); return returnValue; }

7. Click Ctrl + S to save the class.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-53

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Procedure: Create a Service for the Service Class
To create a service for the service class, follow these steps: 1. In the AOT, right-click Services > New Service. 2. Right-click the new service > Rename, and then enter "SimpleService" as the new name of the service. 3. Right-click SimpleService > Properties. 4. In the Class property, select the name of service class. For this procedure, select SimpleService. 5. In the AOT, expand the SimpleService node to show the Operations node. 6. Right-click Operations > Add Operation to show the Add service operations form. 7. Select the Add check box next to each operation that you want to add, and then click OK. 8. Right-click SimpleService and then click Save.

Procedure: Create a Service Group and Deploy the Service


The following steps show how to create a service group for the service and deploy the service group. 1. In the AOT, right-click Service Groups and then click New Service Group. 2. Right-click the new service group > Rename and then enter "SimpleServiceGroup" as the new name of the service node reference. 3. Right-click SimpleServiceGroup and click New Service Node Reference . 4. In the Service property, select the name of the service. For this procedure, select SimpleService. NOTE: An alternative way to add BOFService1 as a service node reference is to open two AOT windows and then drop BOFService1 onto AxClient. 5. Right-click Service Groups > Simple Service and then click Deploy Service Group. This deploys the service to the server. After the deploy operation finishes, a dialog box displays the published service groups. NOTE: There can be a small delay before the deploy operation completes.

5-54

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Calling a Business Operations Framework Service
A Business Operation Framework service can be called in four ways as shown in the following table. Call type Menu Item How to call a Business Operations Framework Service by using this call type. 1. Create an Action Menu Item 2. Set the ObjectType to Class 3. Set the Object to SysOperationServiceController 4. Set the Parameters to <ServiceClassName>.<MethodName> (for the previous procedure, use Use code similar to the following: static void Job2(Args _args) { SimpleDataContract parameters = new SimpleDataContract(); SimpleService service = new SimpleService(); str returnValue; parameters.property1(99); returnValue = service.operation1(parameters); info(returnValue); } 1. Set the EnumTypeParameter to SysOperationExecutionMode 2. Set the EnumParameter to Synchronous 1. Set the EnumTypeParameter to SysOperationExecutionMode 2. Set the EnumParameter to Asynchronous

Batch

Synchronously

Asynchronously

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-55

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 5.3 - Business Operations Framework


In this lab, you will create and use a service by using the business operation framework. Scenario Simon, the Systems Implementer, needs to create a process by using the Business Operations Framework.

Challenge Yourself!
Use the provided information to create a process by using the Business Operation Framework.

Need a Little Help?


1. 2. 3. 4. 5. 6. Create a data contract Identify parameters Create the service class Create a service Create a service group and deploy the service Call the service

Step by Step
1. Click Ctrl+Shift+W to open a new development workspace. 2. Right-click AOT > Classes and then click New Class. 3. Double-click AOT > Classes > Class1 and then paste the following code:
[DataContractAttribute] class SimpleDataContract { int property1; }

4. Click Ctrl + S to save the class. 5. In the SimpleDataContract class, click Ctrl + N to create a new method. 6. Paste the following code:

5-56

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


[DataMemberAttribute] public int property1(int _property1 = property1) { property1 = _property1; return property1; }

7. 8. 9. 10. 11. 12.

Click Ctrl + S to save the class. Click Ctrl+Shift+W to open a new development workspace. Right-click AOT > Classes and then click New Class. Right-click AOT > Classes > Class1 and then click Rename. Rename the class "SimpleService". Double-click AOT > Classes > SimpleService and then click Ctrl + N to create a new method. 13. Paste the following code:
[SysEntryPointAttribute] public str operation1(SimpleDataContract _dataContract) { str returnValue; returnValue = strFmt('Input was %1', _dataContract.property1()); } return returnValue;

14. Click Ctrl + S to save the class. 15. In the AOT, right-click Services > New Service. 16. Right-click the new service > Rename, and then enter "SimpleService" as the new name of the service. 17. Right-click SimpleService > Properties. 18. In the Class property, select the name of service class. For this exercise, select SimpleService. 19. In the AOT, expand the SimpleService node to show the Operations node. 20. Right-click Operations > Add Operation to show the Add service operations form. 21. Select the Add check box next to each operation that you want to add, and then click OK. 22. Right-click SimpleService and then click Save. 23. In the AOT, right-click Service Groups and then click New Service Group. 24. Right-click the new service group > Rename and then enter "SimpleServiceGroup" as the new name of the service node reference.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-57

Application Integration Framework and Services in Microsoft Dynamics AX 2012


25. Right-click SimpleServiceGroup and click New Service Node Reference . 26. In the Service property, select the name of the service. For this exercise, select SimpleService. NOTE: An alternative way to add SimpleService as a service node reference is to open two AOT windows and then drop SimpleService onto SimpleServiceGroup. 27. Right-click Service Groups > Simple Service Group and then click Deploy Service Group. This deploys the service to the server. After the deploy operation finishes, a dialog box displays the published service groups. NOTE: There can be a small delay before the deploy operation completes. 28. In the AOT, expand Menu Items, Right click Action and click New Menu Item 29. Set the ObjectType to Class. 30. Set the Object to SysOperationServiceController. 31. Set the Parameters to <ServiceClassName>.<MethodName> (for the previous procedure use SimpleService.operation1). Services and AIF provide an interface to allow outside programs to interact with Microsoft Dynamics AX 2012. It is important to ensure that access to this capability is limited to the programs and service operations desired.

Security

Role-Based Security
Microsoft Dynamics AX 2012 introduces role-based security as its security system. In role-based security, access is not granted to individual users, only to security roles. Users are assigned to roles. A user who is assigned to a security role has access to the set of privileges that is associated with that role. A user who is not assigned to any role has no privileges. In Microsoft Dynamics AX, role-based security is aligned with the structure of the business. Users are assigned to security roles based on their responsibilities in the organization and their participation in business processes. The administrator grants access to the duties that users in a role perform, not to the program elements that they must use.

5-58

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Entry Points
An entry point is the object that triggers a user action to start a particular function, such as a form or a service. In Microsoft Dynamics AX, there are three different types of entry points: menu items, Web content items, and service operations. To use a service the submitting user must be a member of a role that has access to the appropriate entry points.

Security Architecture for Web Services


Security in AIF is enforced through a combination of WCF, IIS, Active Directory, and role-based security in Microsoft Dynamics AX. 1. The client calls a service method, such as the Customer.read method, and passes the entity key of the requested customer in a SOAP message. 2. The request is received by the IIS where the AIF services are hosted. IIS retrieves the user credentials, depending on the authentication mechanism that is specified in the service configuration. IIS then tries to map the security credentials to a valid domain user. By default, Microsoft Dynamics AX configures WCF to use the basicHttpBinding binding and message security so that the user credentials are contained in the message's SOAP header. IIS authenticates the user as a valid user in Active Directory. NOTE: You can use more secure bindings than the default basicHttpBinding. 3. The request is passed to AIF, which performs additional authentication by verifying that the user meets the following criteria: o The user is a valid Microsoft Dynamics AX user. o The user has the appropriate permissions, through role-based security, to start the operation. 4. After AIF determines that the user has access to the service, the message is processed. At run time, standard AIF security guarantees that the user has access to the data that is exposed by the service.

AIF Users
The following types of users can work with services and AIF: Submitting user Authorized port user Claims user

Trusted intermediary user Proxy user

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-59

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Submitting User
The submitting user submits the message to Microsoft Dynamics AX. The submitting user must be an authenticated Microsoft Dynamics AX user. The following table explains the process that AIF uses to determine the submitting user. Data Submitting user exchange File system adapter The submitting user is the owner of the message request file as returned by the Windows GetFileSecurity (OWNER_SECURITY_INFORMATION) function. You can specify a default message owner that AIF uses when file ownership cannot be resolved deterministically. MSMQ adapter The submitting user is the sender of the message as set on the SenderId property of the message. Web services The submitting user is the Windows identity of the caller.

Authorized Port User


When you configure an integration port, you can restrict access to the port to a list of authorized users.

Claims User
A claims user is a type of Microsoft Dynamics AX user. Claims users are authenticated by an external system, not by Application Object Server (AOS). To gain authorization to access services, a claims user must be authenticated and then impersonated by a trusted intermediary user.

Trusted Intermediary User


Trusted intermediaries are typically used for business-to-business data exchanges. A trusted intermediary is a type of submitting user that can act on behalf of another user, such as a claims user. A trusted intermediary is not a type of Microsoft Dynamics AX user. Instead, trusted intermediaries are typically middleware applications, such as Microsoft BizTalk Server or Electronic Data Interchange (EDI) services. These applications are represented by Microsoft Dynamics AX users or roles that are authorized to submit inbound requests to an integration port. By using trusted intermediaries, you can delegate authentication to a trusted source, whereas authorization continues to be managed by Microsoft Dynamics AX through the role-based security framework.

5-60

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Trusted intermediaries are associated with integration ports. You can define custom intermediaries when configuring an integration port. A trusted intermediary must always be an Active Directory user, never a claims user. A trusted intermediary can impersonate any other Microsoft Dynamics AX user, even a claims user. When the submitting user is a trusted intermediary, AIF provides authorization to the user that is defined in the message header by the <LogonAsUser> element. Otherwise, this element is ignored. IMPORTANT: When you use a trusted intermediary, make sure that the trusted intermediary represents a known, valid partner or a trusted system.

Proxy User
If a proxy is used, .NET Business Connector can connect on behalf of Microsoft Dynamics AX users when authentication is performed by an AOS instance.

Roles, Duties, and Privileges


Users who have the roles that are described in the following table can configure integration port settings for services and AIF. Role Informatio n technology manager AOT name SysServerI T Manager Description This role has the following two duties that are related to services and AIF: AifIntegrationMaintain, which provides the privileges that are required for typical AIF tasks, such as configuring integration ports, viewing the message queue, and reviewing history information AifSyncConfigure, which A user who has this role is a super user, and therefore has full permission for every operation in Microsoft Dynamics AX.

System administrat or

SYSADMIN -

Every service operation is associated with an entry point privilege. This privilege provides permissions for the tables that the service reads or modifies. For example, the SalesSalesOrderServiceCreate service operation is associated with the SalesSalesOrderServiceCreate privilege. The ServiceOperation duty provides privileges for all service operations. Other duties provide privileges for specific service operations, depending on the responsibilities of the duty and its

associated roles. For example, among the privileges that the DOCommerceOnlineSalesOrderMaintain duty provides is the SalesSalesOrderServiceCreate privilege.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-61

Application Integration Framework and Services in Microsoft Dynamics AX 2012


To understand the relationships between roles, duties, privileges, and permissions, refer to the Security node of the Application Object Tree (AOT).

Security Best Practices


Maintaining data security is imperative when you use services and Application Integration Framework (AIF) to exchange data with other systems. When you configure AIF, use the following security-related recommendations. Make sure that data that is sent to and from AIF integration ports is encrypted and can be accessed only by authenticated and authorized users. All data transmissions must be secured, so that no one can read or modify the data during transmission. Authentication and encryption are especially important for business-to-business scenarios in which data is transmitted over the public Internet. For HTTP ports, you can add HTTPS settings through IIS. For more information refer to the Securing Services (http://go.microsoft.com/fwlink/? LinkID=247497&clcid=0x409 ) topic on MSDN When you transmit messages by using the file system adapter or the MSMQ adapter, make sure that the file shares and queues are secured and can be accessed only by authorized users. You can help secure the file shares and queues by using specialized security software that encrypts data and guarantees that only authorized users can access a file location. The Microsoft Dynamics AX system administrator must restrict access to AIF by assigning users only to the roles that those users require Be aware that all actions in Microsoft Dynamics AX that involve inbound documents are performed in the context of a valid Microsoft Dynamics AX user. Be sure to help secure the location on the file system to which you export messages from the Queue manager form. These messages might contain confidential information. Restrict the use of integration ports to authorized users and companies. In this way, an integration port can send or receive data only for specific customers, vendors, or warehouses, and you can avoid spoofing attacks. Trusted intermediary users can submit AIF requests on behalf of authorized port users. To restrict the data fields that can be read or modified through an integration port, use data policies. Add external components only from a trusted and reliable source, such as a Microsoft Partner or independent software vendor (ISV). External components include document classes,

adapter classes, and pipeline components. Pipeline components are X++ classes that are called during processing of the AIF pipeline.

5-62

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


Before you add an Extensible Stylesheet Language Transformation (XSLT) as part of pipeline processing, make sure that the XSLT is secured. Also make sure that the XSLT can handle documents that contain incorrect or malicious data. Thoroughly test any transformations to make sure that they do not contain code that can run and cause exploitable errors on the system. By default, scripting is disabled on the component that is used for XSLT transforms to help protect your system against scripting attacks.

Security Best Practices for Web Services


Use the following additional security-related recommendations when you configure AIF Web services: By default, AIF Web services implement basicHttpBinding. This binding is configured to use the message-level security that is offered through Windows Communication Foundation (WCF). We recommend that administrators follow the standard WCF configuration in Internet Information Services (IIS). Restrict access to the files for AIF Web services. When AIF Web services are installed, Setup creates a network share to the content directory where the files for AIF Web services are located. We recommend that you restrict access to this network share. a. Open the Computer Management application. Click Start > Administrative Tools > Computer Management. b. Under Local Users and Groups, click the Groups folder. c. Right-click the Microsoft Dynamics AX Web Service Administrators local group, and then select Properties. d. In the Members field, verify that only accounts for Application Object Server (AOS) are members of the group. e. If you are using the default permissions in Windows Server 2008, all domain users have Read and Execute permissions for the content directory where the Web services are installed. If you are not using default permissions, you might have to grant access to the share by using one of the following methods: create a local Windows group that has access to the directory, and add users of AIF Web services to this group, or add users of AIF Web services to the local Users group of the computer.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-63

Application Integration Framework and Services in Microsoft Dynamics AX 2012


All data that is exchanged with external Web services must be exchanged over secure channels to prevent tampering, spoofing, and so on. Data is exchanged with external Web services when, for example, an external Web service is consumed from X++. We recommend that confidential and business-critical information be exchanged with external Web services only through communication channels that provide secure authentication, message confidentiality, and integrity. Never use unknown or untrusted external Web services. When you use a Web service, always make sure that the service is the correct one. To verify the identity of Web services, use a secure identification/authentication mechanism. Development in Services and Application Integration Framework requires an understanding of the following development concepts of this platform. Documents passed to and from Services and AIF must adhere to a predefined XML schema Documents that are entering and leaving integration ports can be manipulated in the following ways: o XSD transform o .NET assembly transform o Value substitution o Custom pipeline classes Three service types are provided by Microsoft Dynamics AX 2012: o Document Service o Custom Service o System Service The business operations framework replaces runbase batch and is based on services Security is a critical aspect when you are programming services

Summary

5-64

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts

Test Your Knowledge


Test your knowledge with the following questions. 1. Put the following steps in order: Step: _: The request is received by the IIS where the AIF services are hosted. IIS retrieves the user credentials. _: The request is passed to AIF, which validates that the user is a valid Microsoft Dynamics AX user with appropriate permissions to start the operation. _: After AIF determines that the user has access to the service, the message is processed. _: The client calls a service method, such as the Customer.read method, and passes the entity key of the requested customer in a SOAP message. 2. Which one of the following documents define the structure and format of all possible fields for an AIF XML document? ( ) XSD schema ( ) CSV master ( ) XML source ( ) AIF structure management document 3. Categorize the following items: 1. Excluded field list 2. Noneditable fields 3. Outbound null values 4. Inbound null values 5. Time zone storage 6. Time values a. Null values are not serialized for outbound documents. Arrays can contain empty elements and will be serialized. b. XML cannot contain data for fields that are non-editable. c. Empty string elements are interpreted as zero-length strings and not null values when processing an inbound document. d. The valid time zone values are specified in the document schema. e. AIF accepts XML with fractional seconds. However, when it de-serializes a time value, the fractional seconds and offset are truncated and the value will contain hours, minutes, and seconds (hh:mm:ss). f. Fields starting with Del_ Fields

marked with status of Not visible

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-65

Application Integration Framework and Services in Microsoft Dynamics AX 2012


4. What is a shared-type schema?

5. How many document services are provided in Microsoft Dynamics AX 2012? ()5 () 70 () 20 ( ) 500 6. Which tasks can be performed in the AIF pipeline? (Select all that apply) ( ) xsl transforms ( ) .NET assembly transforms ( ) Value mapping ( ) Custom logic 7. What are the service types that are available in Microsoft Dynamics AX 2012? (Select all that apply) ( ) Development Service ( ) Custom Service ( ) Document Service ( ) System Service 8. What framework did the Business Operations Framework replace? ( ) Application Integration Framework ( ) Send Framework ( ) RunBase Framework ( ) FormLetter Framework

5-66

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


9. What are the available system services? (Select all that apply) ( ) Metadata service ( ) Query service ( ) Architecture service ( ) User session service 10. What is a custom service?

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-67

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this chapter 1.

2.

3.

5-68

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts

Solutions
Test Your Knowledge
1. Put the following steps in order: Step: 2 : The request is received by the IIS where the AIF services are hosted. IIS retrieves the user credentials. 3 : The request is passed to AIF, which validates that the user is a valid Microsoft Dynamics AX user with appropriate permissions to start the operation. 4 : After AIF determines that the user has access to the service, the message is processed. 1 : The client calls a service method, such as the Customer.read method, and passes the entity key of the requested customer in a SOAP message. 2. Which one of the following documents define the structure and format of all possible fields for an AIF XML document? () XSD schema ( ) CSV master ( ) XML source ( ) AIF structure management document 3. Categorize the following items: f 1. Excluded field list b 2. Noneditable fields a 3. Outbound null values c 4. Inbound null values d 5. Time zone storage e 6. Time values a. Null values are not serialized for outbound documents. Arrays can contain empty elements and will be serialized. b. XML cannot contain data for fields that are non-editable. c. Empty string elements are interpreted as zero- length strings and not null values when processing an inbound document. d. The valid time zone values are specified in the document schema. e. AIF accepts XML with fractional seconds. However, when it de-serializes a time value, the fractional seconds and offset are truncated and the value will contain hours, minutes, and seconds (hh:mm:ss). f. Fields starting with Del_ Fields marked with status of Not visible

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

5-69

Application Integration Framework and Services in Microsoft Dynamics AX 2012


4. What is a shared-type schema? MODEL ANSWER: The shared-type schema defines the enums and extended data types (EDTs) that are used by a document service. The shared-type schema consolidates all the data types into one schema that is imported by all the document service schemas. 5. How many document services are provided in Microsoft Dynamics AX 2012? ()5 () 70 ( ) 20 ( ) 500 6. Which tasks can be performed in the AIF pipeline? (Select all that apply) () xsl transforms () .NET assembly transforms () Value mapping () Custom logic 7. What are the service types that are available in Microsoft Dynamics AX 2012? (Select all that apply) ( ) Development Service () Custom Service () Document Service () System Service 8. What framework did the Business Operations Framework replace? ( ) Application Integration Framework ( ) Send Framework () RunBase Framework ( ) FormLetter Framework 9. What are the available system services? (Select all that apply) () Metadata service () Query service ( ) Architecture service

() User session service

5-70

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 5: Development Concepts


10. What is a custom service? MODEL ANSWER: A custom service is a service which exposes existing X++ functionality to external clients with no additional code required.

Microsoft Official Training Materials for Microsoft Dynamics

Your use of

this content is subject to your current services agreement

5-71

Application Integration Framework and Services in Microsoft Dynamics AX 2012

5-72

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services

CHAPTER 6: WORKING WITH SERVICES


Objectives
The objectives are: Call an external service from X++. Use the NetTcp adapter to call a custom service. Create a new document exchange by using the NetTcp adapter. Create a new document exchange by using the file system adapter. Use the NetTcp adapter to synchronously exchange documents between BizTalk and AIF. Create an MSMQ queue and exchange documents by using the queue. Create a reference to the metadata service, and then call and retrieve data from the service.

Introduction

Set up the AIF components for an outbound exchange, and then create and test an outbound exchange. The labs, demonstrations, and procedures in this chapter reinforce the concepts that were covered in previous chapters. This chapter will give you the information necessary to use the following major functions in Services and AIF: Call an external service Create and call a custom service by using a basic port o Create a custom service o Create and deploy a service group o Call the service Call a document service by using NetTcp o Create an inbound port o Send a Sales Order o Inquire about an Item Call a document service with the file system adapter o Create files and folders with appropriate permissions o Create an inbound port

o Send a Sales Order o Inquire about an Item

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-1

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Create a synchronous document exchange between BizTalk and AIF Exchange documents by using the MSMQ Adapter o Create a queue o Create an inbound port o Send a Sales Order Call the MetaData service Call the User Session service Create and deploy outbound exchanges o Create a query o Use the AIF Document Service Wizard o Create an outbound port o Modify a form to send electronically NOTE: In the Hyper-V image lab files for this chapter are located at E:\Labfiles\Chapter 6.

Call an External Service


The Microsoft Dynamics AX programmability model supports services. This means that you can consume web services from X++ code, making external functionality available in your Microsoft Dynamics AX application. Some web services are provided free of charge, while others have licensing models that require you to pay a fee. In Microsoft Dynamics AX, external web services can enable the following scenarios: Accessing currency exchange rates Getting shipping rates from multiple carriers Retrieving availability of parts from external suppliers Calculating local tax values To consume an external web service, you must first create a service reference for it in a Microsoft Visual Studio project, and then add it to the AOT by using Visual Studio Tools. After creating a reference to the external web service, you can write code to invoke it from X++ and see the available methods with IntelliSense.

6-2

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Procedure: Create the Service Reference
To create a service reference, follow these steps: NOTE: These procedures require a Bing Application ID, and therefore will not be done in the classroom. 1. Open Visual Studio 2010 and then create a new Visual C# Class Library project. 2. Type "BingSearch.ServiceReferences" for the project Name. 3. In the Solution Explorer window, right-click the project name and then click Add Service Reference. 4. Type the URL for the web service in the Address field. The URL for the Bing API web services is http://api.bing.net/search.wsdl? AppID=[YOUR_BING_APPID]&ver sion=2.2, where [YOUR_BING_APPID] is the Application ID that you received from the http://www.bing.com/developers site. 5. Click Go to locate the service and then click OK. 6. Right-click the project name and then click Add BingSearch.ServiceReferences to AOT. 7. Select the BingSearch.ServiceReferences project. In the Properties, verify that the properties are set as shown in the following table. Property Deploy to EP Value No Deploy to Client Yes Deploy to Server Yes

Procedure: Verify the Service Reference


Use the following steps to verify the service reference. 1. In the Microsoft Dynamics AX client, open the Developer Workspace. 2. In the AOT, move to Visual Studio Projects > C Sharp Projects to view BingSearch.ServiceReferences. NOTE: The service reference is available when the project has been added successfully to the AOT.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-3

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Procedure: Write X++ to Call the Service Reference
The following steps explain how to write X++ to call the service reference. 1. In the AOT, right-click the Jobs node and then click New Job to open the Jobs Editor. 2. The following example code creates a job called CallBingService.
// This job uses an external service to run a Bing search // The search string is Dynamics AX static void CallBingService(Args _args) { // Replace the string [YOUR_BING_APPID] with your Application ID. #define.AppId([YOUR_BING_APPID]) // This is the variable for the service client. ClrObject clientType; // This is the variable for the service client type. BingSearch.ServiceReferences.BingV2ServiceReference.BingPor tTypeClient _client; // These are the variables for web query objects. BingSearch.ServiceReferences.BingV2ServiceReference.SearchR equest request; BingSearch.ServiceReferences.BingV2ServiceReference.SourceT ype[] sourceTypes; BingSearch.ServiceReferences.BingV2ServiceReference.SearchR esponse response; BingSearch.ServiceReferences.BingV2ServiceReference.WebResp onse webResponse; BingSearch.ServiceReferences.BingV2ServiceReference.WebResu lt[] webResults; BingSearch.ServiceReferences.BingV2ServiceReference.WebResu lt webResult; int integer; str string; System.Exception ex; new InteropPermission(InteropKind::ClrInterop).assert(); // Use a try/catch block to catch errors immediately as CLR exceptions in the job. try { //Construct and configure the service client by retrieving the X++ type for the service and using the AifUtil class/ // Retrieve the X++ type for the Bing service client object. clientType = CLRInterop::getType("BingSearch.ServiceReferences.BingV2Ser

6-4

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


viceReference.BingPortTypeClient"); // Use the AifUtil class to create an instance of the service client object. _client = AifUtil::CreateServiceClient(clientType); // Create the search request. request = new BingSearch.ServiceReferences.BingV2ServiceReference.SearchR equest(); request.set_AppId(#AppId); // Note the search request string is Dynamics AX request.set_Query("Dynamics AX"); sourceTypes = new BingSearch.ServiceReferences.BingV2ServiceReference.SourceT ype[1](); sourceTypes.SetValue(BingSearch.ServiceReferences.BingV2Ser viceReference.SourceType::Web, 0); request.set_Sources(sourceTypes); // Configure the response for output. response = _client.Search(request); webResponse = response.get_Web(); // Get the search results. webResults = webResponse.get_Results(); webResult = webResults.GetValue(0); // Display the first result in the InfoLog. integer = webResponse.get_Total(); info(strFmt("%1 total web results.", integer)); integer = webResults.get_Count(); info(strFmt("%1 results in response.", integer)); info(""); info("First result:"); string = webResult.get_Title(); info(strFmt("Title: %1", string)); string = webResult.get_Description(); info(strFmt("Description: %1", string)); string = webResult.get_Url(); info(strFmt("Url: %1", string)); } // Catch any exceptions. catch(Exception::CLRError) { // Handle the exception and display message in the InfoLog. ex = CLRInterop::getLastException(); info(ex.ToString()); } }

IMPORTANT: Replace the string [YOUR_BING_APPID] in the #define statement with the application ID that you received from the Bing developer site.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-5

Application Integration Framework and Services in Microsoft Dynamics AX 2012


3. Click Go to run the job. 4. Review the results of the service reference calls and then close the Infolog .

Create and Call a Custom Service by Using a Basic Port


A basic port can help you publish a service with minimal effort. The following are the required steps to publish a basic port: 1. 2. 3. 4. Find or create a service. Create a service group. Add a service to the service group. Publish the service group.

NOTE: The demonstrations in this lesson need to be performed in order.

Demonstration: Create a Custom Service


To create a custom service, follow these steps. 1. Open Microsoft Dynamics AX 2012. 2. Click the Ctrl+Shift+W keyboard shortcut to open a new development workspace. 3. Right-click AOT > Classes and then click New Class. 4. Right-click the new class, click Rename, and then type "Greetings". 5. Right-click AOT > Classes > Greetings and then click New > Method. 6. Replace the contents of method1 with the following:
[SysEntryPointAttribute] public str helloName(str _name) { return strFmt('Hello %1', _name); }

7. 8. 9. 10.

Click the Ctrl+S keyboard shortcut to save changes. Close the code editor. Right-click AOT > Services then click New Service. Right-click the new service, click Rename, and then type "Greetings" . 11. Right-click AOT > Services > Greetings then click Properties. 12. Set the Class property to Greetings.

6-6

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


13. Click the Ctrl+S keyboard shortcut to save changes. 14. Right-click AOT > Services > Greetings > Operations and then click Add operation. 15. Select Add for the "helloName" Operation method name and then click OK. 16. Click the Ctrl+S keyboard shortcut to save changes.

Demonstration: Create a Service Group


To create a service group, follow these steps. 1. Right-click AOT > Service groups and then click New Service Group. 2. Right-click the new service group, click Rename, and then type "GreetingsGroup ". 3. Click the Ctrl+D keyboard shortcut to open a second AOT. 4. Drag AOT > Services > Greetings in the second AOT to AOT > Service groups > GreetingsGroup . 5. Right-click AOT > Service groups > GreetingsGroup and then click Properties. 6. Set the AutoDeploy property to Yes. 7. Click the Ctrl+S keyboard shortcut to save changes. 8. Right-click AOT > Service groups > GreetingsGroup and then click Deploy Service Group.

FIGURE 6.1 DEPLOYMENT

9. Close the Infolog.

Demonstration: Validate Service Deployment


To validate that the service deployed, follow these steps. 1. Browse to the Microsoft Dynamics AX client. 2. Go to System Administration > Setup > Services and Application Integration Framework > Inbound ports. 3. Notice that the GreetingsGroup record exists and has a green checkmark indicating that it has been activated. 4. Note the address that is displayed in the WSDL URI text box. 5. Close Inbound ports.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-7

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Demonstration: Call a Custom Service by Using NetTcp
To call a custom service by using NetTcp, follow these steps. 1. Open Visual Studio 2010. 2. Click File > New > Project. 3. Select Visual C# and then select Console application. 4. In Name, type "GreetingsGroup" and then click OK. 5. In Solution Explorer, right-click the project name and then click Add Service Reference. 6. In the Address text box, enter the WSDL URI from the port that you created in the previous section. For example: http://SEA-DEV:8101/DynamicsAx/Services/GreetingsGroup 7. Click Go. Wait for Visual Studio to find the service.

FIGURE 6.2 ADD SERVICE REFERENCE

8. Click OK. 9. Open Program.cs. In the code editor, replace the empty Main function with the following C# code:

6-8

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


static void Main(string[] args) { ServiceReference1.GreetingsClient GreetingsClient = new ServiceReference1.GreetingsClient(); string response; try { response = GreetingsClient.helloName(null, "world"); Console.WriteLine("Response: " + response); Console.WriteLine("Press any key to continue"); Console.Read();

} catch (Exception e) { Console.WriteLine("Exception: " + e.Message); GreetingsClient.Abort(); } GreetingsClient.Close();

10. Click Debug > Start Debugging and then notice the response. 11. Close Visual Studio.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-9

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 6.1 - Create and Call a Custom Service by Using a Basic Port
In this lab, you will create a custom service to add two numbers and then deploy the service by using the service group's autoDeploy property. Scenari o Simon, the System Implementer, needs to create a custom service to add two numbers and then deploy the service by using the service group's autoDeploy property.

Challenge Yourself!
Use the information provided to create a custom service to add two numbers, then deploy the service using the autoDeploy property of the service group.

Need a Little Help?


Create a custom service to add two numbers. 1. 2. 3. 4. Create a service group. Add a service to the service group. Publish the service group. Call the custom service by using NetTcp.

Step by Step
1. Open Microsoft Dynamics AX 2012. 2. Click the Ctrl+Shift+W keyboard shortcut to open a new development workspace. 3. Right-click AOT > Classes and then click New Class. 4. Right-click the new class, click Rename, and then type "Arithmetic". 5. Right-click AOT > Classes > Arithmetic and then click New > Method. 6. Replace the contents of method1 with the following: [SysEntryPointAttribute] public int intAdd(int _int1, int _int2) { return _int1 +_int2; } 7. Click the Ctrl+S keyboard shortcut to save changes.

8. Close the code editor. 9. Right-click AOT > Services and then click New Service.

6-10

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


10. Right-click the new service, click Rename, and then type "Arithmetic". 11. Right-click AOT > Services > Arithmetic and then click Properties. 12. Set the Class property to Arithmetic. 13. Click the Ctrl+S keyboard shortcut to save changes. 14. Right-click AOT > Services > Arithmetic> Operations and then click Add operation. 15. Select Add for the "intAdd" Operation method name and then click OK. 16. Click the Ctrl+S keyboard shortcut to save changes. 17. Right-click AOT > Service groups and then click New Service Group. 18. Right-click the new service group, click Rename, and then type "ArithmaticGroup". 19. Click the Ctrl+D keyboard shortcut to open a second AOT. 20. Drag AOT > Services > Arithmetic in the second AOT to AOT > Service groups > ArithmaticGroup. 21. Right-click AOT > Service groups > ArithmaticGroup and then click Properties. 22. Set the AutoDeploy property to Yes. 23. Click the Ctrl+S keyboard shortcut to save changes. 24. Right-click AOT > Service groups > ArithmaticGroup and then click Deploy Service Group. 25. Close the Infolog. 26. Go to the Microsoft Dynamics AX client. 27. Go to System Administration > Setup > Services and Application Integration Framework > Inbound ports. 28. Notice that the ArithmaticGroup record exists and has a green checkmark indicating that it has been activated. 29. Note the address that is displayed in the WSDL URI text box. 30. Close Inbound ports. 31. Open Visual Studio 2010. 32. Click File > New > Project. 33. Select Visual C# and then select Console application. 34. In Name, type "ArithmaticGroup" and then click OK. 35. In Solution Explorer, right-click the project name and then click Add Service Reference. 36. In the Address text box, enter the WSDL URI from the port that you created in the previous section. For example: http://SEA-

DEV:8101/DynamicsAx/Services/ArithmaticGroup 37. Click Go. Wait for Visual Studio to find the service.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-11

Application Integration Framework and Services in Microsoft Dynamics AX 2012


38. Click OK. 39. Open Program.cs. In the code editor, replace the empty Main function with the following C# code:
static void Main(string[] args) { ServiceReference1.ArithmeticClient ArithmeticClient = new ServiceReference1.ArithmeticClient(); int i, j; int response; Console.WriteLine("Enter a number"); i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter a second number"); j = Convert.ToInt32(Console.ReadLine()); try { response = ArithmeticClient.intAdd(null, i, j); Console.WriteLine("Response: " + response); Console.WriteLine("Press any key to continue"); Console.Read();

} catch (Exception e) { Console.WriteLine("Exception: " + e.Message); ArithmeticClient.Abort(); } ArithmeticClient.Close();

40. Click Debug > Start Debugging and then notice the response. 41. Close Visual Studio.

6-12

M i c r o s o f t O f f i c i a l T r a i n i n g M a t e r i a l s f o r M i c r o s o f t D y n a m i c s

of this content is subject to your current services agreement

Y o u r u s e

Chapter 6: Working With Services

Call a Document Service by Using NetTcp


The NetTcp adapter provides for synchronous communication by using the Transmission Control Protocol (TCP) transport. The following topics demonstrate how to use an inbound port with the NetTCP adapter to read a sales order from Microsoft Dynamics AX. In this walkthrough, you will create an inbound integration port and then use C# code to create a command-line program that reads a particular sales order. Before you can use any services in Microsoft Dynamics AX, the system must be configured. For example, in this demonstration, a sales order document is exchanged. Therefore, Microsoft Dynamics AX must be preconfigured to accept sales orders. For example, the system must contain at least one sales order. In addition, the sales order service must be registered. The basic steps include the following. 1. Verify that any system requirements and configuration prerequisites are complete. 2. Create and configure an inbound port by using the NetTcp adapter. 3. Create a NetTcp client application. 4. Read a sales order. NOTE: The demonstrations in this lesson need to be performed in order.

Demonstration: Create and Configure the Integration Port


When you create an integration port that uses the NetTCP adapter, AIF publishes a network Uniform Resource Identifier (URI) and a Web Services Description Language (WSDL) address. Together, these addresses provide access to the service operations that are exposed by the port. 1. Open System administration > Setup > Services and Application Integration Framework > Inbound ports. 2. Click New. 3. Name the new integration port SalesOrderReadNetTcp. 4. In the Adapter list in the Address group, select NetTcp. 5. On the Service contract customizations FastTab, click Service operations.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-13

Application Integration Framework and Services in Microsoft Dynamics AX 2012


6. In the Select service operations form, select SalesSalesOrderService.read in the Remaining service operations list. Click the left arrow to move the service operation to the Selected service operations list. Close the form.

FIGURE 6.3 SELECT SERVICE OPERATIONS

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.

Demonstration: Create a NetTcp Client Application


This demonstration shows how to create a simple client application that synchronously exchanges messages with the integration port. The client application code is written in the C# programming language. The sample application reads a sales order from Microsoft Dynamics AX and then displays the sales order ID and the customer account number. 1. Open Visual Studio 2010. 2. Click File > New > Project.

3. Select Visual C# and then select Console application.


6-14

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


4. In Name, type "SalesOrderReadNetTcp" and then click OK. 5. In Solution Explorer, right-click the project name and then click Add Service Reference. 6. In the Address text box, enter the WSDL URI from the port that you previously created. 7. Click Go. Wait for Visual Studio to find the service. 8. Click OK to close the dialog box. 9. Open Program.cs. In the code editor, replace the empty Main function with the following C# code:
static void Main(string[] args) { // Create the sales order objects // Service client ServiceReference1.SalesOrderServiceClient cl = new ServiceReference1.SalesOrderServiceClient(); // Sales order object to receive response ServiceReference1.AxdSalesOrder resp; // Create the entity key list for the request ServiceReference1.EntityKey[] readRespKeys = new ServiceReference1.EntityKey[1]; readRespKeys[0] = new ServiceReference1.EntityKey(); readRespKeys[0].KeyData = new ServiceReference1.KeyField[1]; readRespKeys[0].KeyData[0] = new ServiceReference1.KeyField(); readRespKeys[0].KeyData[0].Field ="SalesId"; // Ask the user for a sales order ID Console.WriteLine("Enter the sales order ID:"); // Add the result to the entity key value readRespKeys[0].KeyData[0].Value = Console.ReadLine(); try { // Try to read the sales order resp = cl.read(null, readRespKeys); table // Display the information from the first sales

Console.WriteLine("For sales order: " + resp.SalesTable[0].SalesId); Console.WriteLine("Customer Account is: " + resp.SalesTable[0].CustAccount); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); cl.Abort(); } cl.Close();

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-15

Application Integration Framework and Services in Microsoft Dynamics AX 2012


} Console.ReadLine();

10. Press F5 to run the project. 11. Enter a sales order SO-101224 and press Enter.

FIGURE 6.4 CONSOLE

12. Press Enter to exit and then close visual studio. If the sales order is successfully read, the application displays the sales order ID and the customer account number. Otherwise, the application displays an exception message.

6-16

Microsoft Official Training Materials for Microsoft Dynamics

Y o u r u s e o f t h i s c o n t e n t i s s u b j e c t t o y o u r c u r r e n t s e r v i c e s a g r e e m e n t

Chapter 6: Working With Services

Lab 6.2 - Call a Document Service by Using NetTcp


In this lab, you will call the inventitemservice.read document service with NetTcp. Scenario Simon, the System Implementer, needs to call the inventitemservice.read document service with NetTcp.

Challenge Yourself!
Use the provided information to call the inventitemservice.read document service with NetTcp.

Need a Little Help?


1. 2. 3. 4. Create an inbound port by using the NetTcp adapter. Create a visual studio .NET project. Register the web service that was created in step 1. Call the web service.

Step by Step
1. Open System administration > Setup > Services and Application Integration Framework > Inbound ports. 2. Click New. 3. Name the new integration port "ItemReadNetTcp". 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 InventItemService.read in the Remaining service operations list. Click the left arrow to move the service operation to the Selected service operations list. 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. Note the address that is displayed in the WSDL URI text box. 10. Close the Inbound ports form.

11. Open Visual Studio 2010.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-17

Application Integration Framework and Services in Microsoft Dynamics AX 2012


12. Click File > New > Project. 13. Select Visual C# and then select Console application. 14. In Name type "ItemReadNetTcp" and then click OK. 15. In Solution Explorer, right-click the project name and then click Add Service Reference. 16. The Add Service Reference dialog box opens. 17. In the Address text box, enter the WSDL URI from the port that you previously created. 18. Click Go. Wait for Visual Studio to find the service. 19. Click OK to close the dialog box. 20. Open Program.cs. In the code editor, replace the empty Main function with the following C# code:
static void Main(string[] args) { // Create the Item objects // Service client ServiceReference1.ItemServiceClient cl = new ServiceReference1.ItemServiceClient(); // Item object to receive response ServiceReference1.AxdItem resp; // Create the entity key list for the request ServiceReference1.EntityKey[] readRespKeys = new ServiceReference1.EntityKey[1]; readRespKeys[0] = new ServiceReference1.EntityKey(); readRespKeys[0].KeyData = new ServiceReference1.KeyField[1]; readRespKeys[0].KeyData[0] = new ServiceReference1.KeyField(); readRespKeys[0].KeyData[0].Field ="ItemId"; // Ask the user for an Item ID Console.WriteLine("Enter the Item ID:"); // Add the result to the entity key value readRespKeys[0].KeyData[0].Value = Console.ReadLine(); try { // Try to read the Item resp = cl.read(null, readRespKeys); // Display the information from the first Item Console.WriteLine("For Item Id: " + resp.InventTable[0].ItemId); Console.WriteLine("Name Alias is: " + resp.InventTable[0].NameAlias); } catch (Exception e) {

6-18

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Console.WriteLine("Exception: " + e.Message); cl.Abort();

} cl.Close(); Console.ReadLine();

21. Press F5 to run the project. 22. Enter "1000" for the Item ID and press Enter. 23. Press Enter to exit and then close visual studio.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-19

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Call a Document Service with the File Adapter


This lesson explains how to perform an asynchronous document exchange. In this scenario, a new sales order request is sent to AIF by using the file system adapter. Before you can use any services in Microsoft Dynamics AX, the system must be configured. For example, in the following demonstration, a sales order document is exchanged. Therefore, it must be preconfigured to accept sales orders. For example, the system must contain at least one customer and one released product, and the minimum related accounting and inventory tracking requirements must be in place. In addition, the sales order service must be registered. The basic steps include the following. 1. Verify that any system requirements and configuration prerequisites are completed. 2. Create file system directories for storing the source document and AIF responses. 3. Create, configure, and activate an inbound port. 4. Configure and start the AIF batch services. 5. Send the request. NOTE: The demonstrations in this lesson need to be performed in order. The following topics review the detailed steps that are required to use the file system adapter to exchange documents.

Demonstration: Create Folders for the File Adapter


Follow these steps to create folders for the file adapter to use. NOTE: Demonstrations in this section need to be performed in order, and they depend on Lab 4.1 Set up Batch in Chapter 4: Administration. 1. Create a new folder called "C:\AIF" if it has not already been created. 2. Create a new folder called "C:\AIF\SalesOrderCreateFileIN". 3. Right-click SalesOrderCreateFileIN and then click Properties. 4. Click Security and then click Advanced. 5. Click Change Permissions and then click Add.

6-20

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


6. In Enter the object name to select, type "AX_AOS_Service", and then press Enter. 7. Select Allow full control and then click OK on all open dialogs.

FIGURE 6.5 PERMISSIONS

8. Repeat steps 2-7 for "C:\AIF\SalesOrderCreateFileOUT".

Demonstration: Configure an Inbound Port for the File Adapter


To configure an inbound port for the file adapter follow these steps. 1. Open Microsoft Dynamics AX. 2. Open System Administration > Setup > Services and Application Integration Framework > Inbound Ports and then click New. 3. In Port name, type "SalesOrderCreateFile". 4. In Description, type "SalesOrderCreateFile". 5. In Adapter, select File System Adapter. 6. In the URI field, type "C:\AIF\SalesOrderCreateFileIN". 7. Click Configure. 8. Select Use default owner for Administrators group and select Admin.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-21

Application Integration Framework and Services in Microsoft Dynamics AX 2012


IMPORTANT: By default, AIF uses the file owner to determine which Microsoft Dynamics AX user to process the AIF request. Also, Windows Server 2008 defaults the file owner to the local administrators group if a user is in the local administrators group. To process files that are associated with the local administrators group, use the Use default owner for Administrators group option, and to process files that are associated with the network service account use the Use default owner for Network Service account option.

FIGURE 6.6 USE DEFAULT OWNER FOR ADMINISTRATORS GROUP

9. 10. 11. 12. 13. 14.

Click OK. Select Response address. In Adapter, select File System Adapter. In the URI field, type "C:\AIF\SalesOrderCreateFileOUT". Click Service operations. In Remaining service operations group, select SalesSalesOrderService.create and then click the less than (<) button. 15. Notice that SalesSalesOrderService.create has been added to Selected service operations group. 16. Click Close. 17. Select Customize documents and then click Data Policies. 18. In the Document data policies form, sort the table on the Element name column and then select Enabled for the following elements: o CustAccount (/SalesOrder/SalesTable/CustAccount) o ItemId (/SalesOrder/SalesTable/SalesLine/ItemId) HINT: Use filters to find these elements. 19. Click Close and then click Activate. 20. Close the infolog.

6-22

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Demonstration: Create an XML File
The sales order request is an XML-based document. For this example, you will use a sales order request that already complies with the sales order schema. The request document uses the AIF message schema as an envelope to contain the sales order request. NOTE: For asynchronous document exchanges, such as the one demonstrated in this scenario, you must configure an AIF batch job. This batch job periodically runs business logic through integration ports that are configured to use asynchronous adapters. To complete this demonstration, you must first complete "Demonstration: Setup Batch" in Chapter 4: Administration. 1. Open Visual Studio 2010. 2. Click File > New > File. 3. Select XML file and then click Open. 4. Copy the following XML code into the empty XML document. <?xml version="1.0" encoding="utf-8" ?> <Envelope xmlns="http://schemas.microsoft.com/dynamics/2011/01/docu ments/ Message"> <Header > <MessageId>{944EBD24-50ED-41BF-B7792DC90F00F350}</MessageId> <Action>http://schemas.microsoft.com/dynamics/2008/01/servi ces/S alesOrderService/create</Action> </Header > <Body > <MessageParts > <SalesOrder xmlns="http://schemas.microsoft.com/dynamics/2008/01/docu ments/ SalesOrder"> <SalesTable class="entity"> <CustAccount>2014</CustAccount> <PurchOrderFormNum>PO</PurchOrderFormNum> <ReceiptDateRequested>2011-1111</ReceiptDateRequested> <SalesLine class="entity">

<ItemId>1000</ItemI d> <SalesQty>18</SalesQt y> <SalesUnit>Pcs</SalesUnit> </SalesLine > </SalesTable > </SalesOrder > </MessagePart s> </Body > </Envelope>

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-23

Application Integration Framework and Services in Microsoft Dynamics AX 2012


IMPORTANT: The XML code includes an element titled <MessageId>, which contains a GUID. This GUID uniquely identifies the message. You must provide a new, unique GUID for each message that you send to AIF. 5. Save the file. Name the file SORequest.xml.

Demonstration: Send the Request and View the Response


Use the following steps to send the request and view the responses. 1. Save a copy of the file that you named SORequest.xml to the folder that you named "C:\AIF\SalesOrderCreateFileIN". NOTE: When you submit multiple documents to a port that uses the file system adapter, the documents are processed in order based on their file names. To control the order in which documents are processed, use file names that include a sequencing scheme, such as "SO_0001" and "SO_0002". 2. Wait for the batch job to retrieve the file from the folder. 3. Watch the folder that you named "C:\AIF\SalesOrderCreateFileOUT". After a few minutes, a response file will be saved to this folder by AIF. NOTE: You can monitor the progress of your message by reviewing System Administration > Periodic > Services and Application Integration Framework > Queue manager and System Administration > Periodic > Services and Application Integration Framework > Exceptions. 4. Open the response file to view the XML code. A valid XML response contains the number of the sales order that was created in the SalesId field. For example: <?xml version="1.0" encoding="UTF-8"?> <Envelope xmlns="http://schemas.microsoft.com/dynamics/2011/01/docu ments/ Message"> <Header > <MessageId>{0E92FD02-E17F-4CD0-BA863CC771C8C22D}</MessageI d> <Action>http://schemas.microsoft.com/dynamics/2008/01/servi ces/S

alesOrderService/create</Acti on> <RequestMessageId>{944EBD24-50ED-41BF-B7792DC90F00F350}</RequestMessageId> </Header > <Body > <MessageParts xmlns="http://schemas.microsoft.com/dynamics/2011/01/docu ments/

6-24

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Message" > <EntityKeyList xmlns="http://schemas.microsoft.com/dynamics/2006/02/docu ments/ EntityKeyList"> <EntityKey xmlns="http://schemas.microsoft.com/dynamics/2006/02/docu ments/ EntityKey"> <KeyData > <KeyField > <Field>SalesId</Fiel d> <Value>SO-101249</Value> </KeyField > </KeyData > </EntityKey > </EntityKeyList > </MessagePart s> </Body > </Envelope >

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-25

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 6.3 - Call a Document Service with the File Adapter


In this lab, you will call the inventitemservice.read document service with a file adapter. Scenario Simon, the System Implementer, needs to call the inventitemservice.read document service with a file adapter.

Challenge Yourself!
Use the provided information to call the inventitemservice.read document service with a file adapter. NOTE: This lab depends on Lab 4.1: Set up Batch in Chapter 4: Administration.

Need a Little Help?


1. 2. 3. 4. Create folders. Create an inbound port. Create an XML document to call the service. Put the file in the inbound directory.

Step by Step
NOTE: Demonstrations in this section need to be performed in order, and they depend on Lab 4.1 Set up Batch in Chapter 4: Administration. 1. Create a new folder called "C:\AIF" if it has not already been created. 2. Create a new folder called "C:\AIF\ItemReadFileIN". 3. Right-click ItemReadFileIN and then click Properties. 4. Click Security and then click Advanced. 5. Click Change Permissions and then click Add. 6. In Enter the object name to select, type "AX_AOS_Service" and then press Enter. 7. Select Allow full control and then click OK on all open dialogs. 8. Repeat steps 2- 7 for "C:\AIF\ItemReadFileOUT". 9. Open Microsoft Dynamics AX. 10. Open System Administration > Setup > Services and Application Integration Framework > Inbound Ports and then click New. 11. In Port name, type "ItemReadFile".

12. In Description, type "ItemReadFile".


6-26

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


13. 14. 15. 16. In Adapter, select File System Adapter. In the URI field, type "C:\AIF\ItemReadFileIN". Click Configure. Select Use default owner for Administrators group and select Admin. 17. Click OK. 18. Select Response address. 19. In Adapter, select File System Adapter. 20. In the URI field, type "C:\AIF\ItemReadFileOUT". 21. Click Service operations. 22. In the Remaining service operations group, select InventItemService.read and then click the less than (<) button. 23. Notice that InventItemService.read has been added to the Selected service operations group. 24. Click Close and then click Activate. 25. Close the infolog. 26. Open Visual Studio 2010. 27. Click File > New > File. 28. Select XML file and then click Open. 29. Copy the following XML code into the empty XML document.
<?xml version="1.0" encoding="utf-8"?> <Envelope xmlns="http://schemas.microsoft.com/dynamics/2011/01/docume nts/Message"> <Header> <MessageId>{97387992-EE19-4980-9D3042EB0DB61D8A}</MessageId> <Action>http://schemas.microsoft.com/dynamics/2008/01/servi ces/ItemService/read</Action> </Header> <Body> <MessageParts xmlns="http://schemas.microsoft.com/dynamics/2011/01/docume nts/Message"> <EntityKeyList xmlns="http://schemas.microsoft.com/dynamics/2006/02/docume nts/EntityKeyList"> <EntityKey xmlns="http://schemas.microsoft.com/dynamics/2006/02/docume nts/EntityKey"> <KeyData> <KeyField> <Field>ItemId</Field> <Value>1000</Value> </KeyField> </KeyData> </EntityKey> </EntityKeyList>

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-27

Application Integration Framework and Services in Microsoft Dynamics AX 2012


</MessageParts> </Body> </Envelope>

IMPORTANT: The XML code includes an element titled <MessageId>, which contains a GUID. This GUID uniquely identifies the message. You must provide a new, unique GUID for each message that you send to AIF. 30. Save the file. Name the file "ItemRequest.xml". 31. Save a copy of the file that you named ItemRequest.xml to the folder that you named "C:\AIF\ItemReadFileIN". NOTE: When you submit multiple documents to a port that uses the file system adapter, the documents are processed in order based on their file names. To control the order in which documents are processed, use file names that include a sequencing scheme, such as "SO_0001" and "SO_0002". 32. Wait for the batch job to retrieve the file from the folder. 33. Watch the folder that you named "C:\AIF\ItemReadFileOUT". After a few minutes, a response file will be saved to this folder by AIF. NOTE: You can monitor the progress of your message by reviewing System Administration > Periodic > Services and Application Integration Framework > Queue manager and System Administration > Periodic > Services and Application Integration Framework > Exceptions. 34. Open the response file to view the XML code. A valid XML response contains item information. The following is a partial example:
<?xml version="1.0" encoding="UTF-8"?> <Envelope xmlns="http://schemas.microsoft.com/dynamics/2011/01/docume nts/Message"> <Header> <MessageId>{57DD6ABD-6EA1-4E54-9A88-975AF8491324} </MessageId> <Action>http://schemas.microsoft.com/dynamics/2008/01/servi ces/ItemService/read</Action> <RequestMessageId>{97387992-EE19-4980-9D3042EB0DB61D8A}</RequestMessageId> </Header> <Body> <MessageParts

xmlns="http://schemas.microsoft.com/dynamics/2011/01/docume

6-28

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


nts/Message"> <Item xmlns="http://schemas.microsoft.com/dynamics/2008/01/docume nts/Item"> <DocPurpose>Original</DocPurpose> <SenderId>ceu</SenderId> <InventTable > <_DocumentHash>64e256bf1c85f2fdf0d3dd44f10415fe</_DocumentH ash> <ABCContributionMargin>A</ABCContributionMargin> <ABCRevenue>A</ABCRevenue> <ABCTieUp>C</ABCTieUp> <ABCValue>C</ABCValue> <AutoReportFinished>No</AutoReportFinished> <BOMManualReceipt>No</BOMManualReceipt> <BOMUnitId>ea</BOMUnitId> <CostModel>No</CostModel>

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-29

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Create a Synchronous Document Exchange between BizTalk and AIF


This lesson explains how so use the NetTcp adapter to synchronously exchange documents between BizTalk and AIF. In this example, BizTalk constructs a request to read a particular sales order and then sends the request to AIF for processing. NOTE: BizTalk can also be used to send documents asynchronously. The following prerequisites and assumptions are made for the following demonstration. Microsoft Dynamics AX must be preconfigured to accommodate sales orders. The request starts out as the entity key list that was sent by AIF as a previous response to a create request. The standard BizTalk pipelines are used for XML exchanges. The communication mode is synchronous. BizTalk initiates the request and AIF responds. NOTE: For more information on using BizTalk with AIF, refer to Exchanging documents between BizTalk Server and AIF (http://go.microsoft.com/fwlink/?LinkID=247498&clcid=0x409 ) and the Using Microsoft BizTalk Server 2010 to Exchange Documents with Microsoft Dynamics AX (http://go.microsoft.com/fwlink/? LinkID=247499&clcid=0x409 )whitepaper.

General Steps
To implement this scenario, follow these general steps: 1. Create the file system directories. 2. Create and configure an AIF enhanced integration port. 3. Create a new Visual Studio 2010 BizTalk project that references the service's published WSDL document and includes a map to create the service request document. 4. Configure the BizTalk Server Administration Console to add ports to the application that you deployed in the previous scenario. 5. Submit the XML document that contains a request to read the sales order. 6. View the XML document that contains the requested sales order.

6-30

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Procedure: Create and Configure an Inbound Port
To configure an inbound port for the file adapter follow these steps. NOTE: BizTalk is not configured to perform this set of procedures in the Hyper- V image. 1. Open Microsoft Dynamics AX. 2. Open System Administration > Setup > Services and Application Integration Framework > Inbound Ports and then click New. 3. In Port name, type "SalesOrderCreate". 4. In Description, type "SalesOrderCreate". 5. In Adapter, select NetTcp. 6. Click Service operations. 7. In the Remaining service operations group, select SalesSalesOrderService.create and then click less than (<) button. 8. Notice that SalesSalesOrderService.create has been added to the Selected service operations group. 9. Click Close. 10. Select Customize document and then click Data Policies. 11. In the Document data policies form, sort the table on the Element name column and then select Enabled for the following elements: o CustAccount (/SalesOrder/SalesTable/CustAccount) o ItemId (/SalesOrder/SalesTable/SalesLine/ItemId) 12. Click Close and then click Activate. 13. Close the infolog.

Procedure: Create a BizTalk Project


You can use Visual Studio 2010 to create the BizTalk project. To create the project, follow these steps. 1. 2. 3. 4. 5. 6. Open Visual Studio as administrator. In Visual Studio, click File > New > Project. In the Installed Templates pane, select BizTalk Projects. In the center pane, select Empty BizTalk Server Project. In the Name field, type "BizTalkSalesOrderCreate". Click OK.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-31

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Next you must run the WCF Service Consuming Wizard to generate the artifacts that you need for this scenario, including schema files and binding information files. To run the wizard, follow these steps. 1. In Solution Explorer, right-click the project name, point to Add, and then click Add Generated Items. 2. In the Add Generated Items dialog box, double-click Consume WCF Service. The WCF Service Consuming Wizard opens. 3. Click Next until you advance to the Metadata Endpoint page. 4. Enter the address of the URI of the WSDL document. This address is displayed in the Inbound ports form in Microsoft Dynamics AX. For example, enter: "http://SEA-DEV:8101/Microsoft DynamicsAx/Services/SalesOrderCreate" NOTE: The default WSDL port is 8101 and the URI ends with the name of the integration port. 5. Click Get and then click Next. 6. On the Import WCF Service Metadata Summary page, click Import. The wizard imports the service information and generates the schema and binding files. 7. Click Finish to close the wizard. The wizard creates an orchestration file, named TCP_Read_SO.odx, which you do not need for this scenario. You can delete this file.

Procedure: Create the Map


To create the request document, you must merge the entity key listwhich you received as a response when you created a sales orderinto a document that is based on the services schema. The goal is to contain the entity key list in the SalesOrderServiceReadRequest element while ensuring that the correct namespace is referenced for the services schema. To merge these documents, you can use a BizTalk map. Add a new map to your BizTalk project in Visual Studio. Accept the default file name, Map1.btm. 1. In Solution Explorer, right-click the project name, point to Add, and then click New Item. 2. Click Map and then click Add. 3. Click Open Source Schema. 4. Click BizTalkSalesOrderCreate > Schemas > BizTalkSalesOrderCreate_schemas_Microsoft_com_dynamic s_2 006_02_documents_EntityKey.xds and then click OK.

5. Click Open Destination Schema.

6-32

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


6. Click BizTalkSalesOrderCreate > Schemas > BizTalkSalesOrderCreate_schemas_Microsoft_com_dynamic s_2 008_01_services.xsd. 7. In Select Root Node for Target Schema, select SalesOrderServiceCreateRequest and then click OK. The mapping contained in the screen image provides a one-to-one mapping between the EntityKeyList elements in each schema, and their descendants. The schema on the left is the EntityKeyList schema. For example: TCPSalesOrderRead_schemas_microsoft_com_Microsoft Dynamics_2006_02_documents_EntityKeyList.xsd The schema on the right is the services schema. For example: TCPSalesOrderRead_schemas_microsoft_com_Microsoft Dynamics_2008_01_services.xsd

Procedure: Deploy the BizTalk Application


When you are finished creating the mapping, use Visual Studio to deploy the application by following these steps. 1. On the Deployment tab, provide a value for the Application Name field, such as "ReadSalesOrder". If you do not provide a name for your application, BizTalk will deploy the application by using a default name. It is a best practice to provide a unique name. 2. For Restart Host Instances, select True. It is important to restart the in-process host instances any time that you redeploy the application. Otherwise, cached information can cause unexpected behavior when you run your application. 3. On the Signing tab, specify a signing key. Deployed BizTalk assemblies must be strong-name signed. 4. After deployment configuration is complete, deploy the application. On the Build menu, click Deploy Solution. Visual Studio builds and then deploys the assembly that contains the schemas and maps.

Procedure: Configure the BizTalk Server Administration Console


You can use the console to host and run your BizTalk application. To configure the application, follow these steps. 1. Open the BizTalk Server Administration console. 2. Right-click the application name, point to Import, and then click

Bindings.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-33

Application Integration Framework and Services in Microsoft Dynamics AX 2012


3. Browse to the bindings file that the WCF Consuming Services Wizard created. For example, select TCPSalesOrderRead.BindingInfo.xml. 4. Click Open. You can view the imported bindings file information in the administration console, in the Resources node for your application. Next, you must create the BizTalk receive port by following these steps. 1. Right-click Receive ports and add a new one-way receive port. The Properties dialog box opens. You can use the default name or provide a name of your own. 2. Select Receive Locations and then click New. 3. In the Type list, select File. Then, click Configure. 4. In the File Transport Properties dialog box, click Browse and then browse to the folder that you named RecSOReq. Close the dialog box. 5. In the Receive Pipeline list, select XML Receive. Then, configure the pipeline to use the EntityKeyList schema from this project for the document specification. (This is an instance where the EntityKeyList schema exists in the project from the previous scenario, creating a namespace conflict.) 6. Close all of the dialog boxes. Next, you must create the BizTalk send-receive port. For this synchronous exchange, you must use a single send-receive port. This type of port sends the request to Microsoft Dynamics AX and then waits for the response before proceeding with the rest of the BizTalk document exchange process. Use the following steps to create the BizTalk send-receive port. 1. Right-click Send Ports and add a new, static, solicit-response port. The Properties dialog box opens. 2. In the Type list, select WCF-NetTcp. Then, click Configure. 3. In the WCF-NetTcp Transport Properties dialog box, replace the default address with the address for the AIF integration port. For example: net.tcp://Your_AOS_Name:8201/Microsoft DynamicsAx/Services/TCPSalesOrderRead. NOTE: The address that is displayed in the Inbound ports form in Microsoft Dynamics AX is not complete. You must replace the string "AOS_HOST_NAME" with the name of your AOS, followed by a colon and the port number 8201. This port number differs from the WSDL port number, which is 8101.

6-34

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


4. In the SOAP Action header text box, enter the following action string: http://schemas.microsoft.com/Microsoft Dynamics/2008/01/services/SalesOrderService/r ead 5. Close the dialog box. 6. In the Send Pipeline list, select XML Transmit. Then, configure the pipeline to use the AIF message schema. 7. In the Receive Pipeline list, select XML Receive. Next, you must add the map to the send-receive port, create the sendreceive port subscription, create a send port to save the response file, create the send port subscription, and then finally start the application. 1. In the SendPortProperties dialog box, click Outbound Maps. 2. Add a new map. In the Source Document list, select the EntityKeyList schema. 3. In the Map list, select Map1. 4. In the Target Document list, select the services schema. 5. Click Filters. 6. For Property, select BTS.ReceivePortName. Set the property value equal to the name of the receive port that you created. 7. Click OK to close the dialog box. 8. Right-click Send Ports and add a new, static, one-way send port. The Properties dialog box opens. 9. In the Type list, select File. Then, click Configure. 10. In the File Transport Properties dialog box, click Browse and then browse to the folder that you named RecSOResp. Close the dialog box. 11. In the Send Pipeline list, select Pass Thru Transmit. 12. Click Filters. 13. For Property, select BTS.SPName. Set the property value equal to the name of the solicit-response port that you created. 14. Click OK to close the dialog box. 15. In the BizTalk Server Administration console, start the application.

Procedure: Submit an XML Document and Receive the Response Message


The source document for this scenario is the processed response message from the previously described asynchronous scenario. This document contains an entity key list that contains the sales ID for the sales order that you created. The following XML code is an example of a processed response message:

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-35

Application Integration Framework and Services in Microsoft Dynamics AX 2012


<?xml version="1.0" encoding="utf-8"?> <EntityKeyList xmlns="http://schemas.microsoft.com/Microsoft Dynamics/2006/02/documents/EntityKeyList"> <EntityKey xmlns="http://schemas.microsoft.com/Microsoft Dynamics/2006/02/documents/EntityKey"> <KeyData> <KeyField> <Field>SalesId</Field> <Value>SO-100029</Value> </KeyField> </KeyData> </EntityKey> </EntityKeyList> Save a copy of this document in the folder that you named RecSOReq. When the processing is complete, the sales order document that you requested will appear in the folder that you named RecSOResp.

Exchange Documents by Using the MSMQ Adapter


The MSMQ adapter enables asynchronous communication by using the Message Queuing transport. The following topics demonstrate how to use an inbound port together with the MSMQ adapter to create a sales order in Microsoft Dynamics AX. In this demonstration, you will create an inbound integration port, and then use C# code to create a command-line program that sends an XML document to a message queue. For example, in this demonstration, a sales order document is exchanged. Therefore, Microsoft Dynamics AX must be preconfigured to accept sales orders. For example, the system must contain at least one sales order. In addition, the sales order service must be registered, and you must deploy Message Queuing for AIF. The basic steps include the following. 1. Verify that any system requirements and configuration prerequisites are complete. 2. Create a queue. 3. Create and configure an inbound port by using the MSMQ adapter. 4. Configure and start the AIF batch services. 5. Create a document for the request. 6. Create a Message Queuing client application. 7. Send a sales order. NOTE: The demonstrations in this lesson need to be performed in order.

6-36

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Demonstration: Create a Queue
Create a new public queue that is named CreateSO. NOTE: Demonstrations in this lesson need to be performed in order, and depend on Lab 4.1 Setup Batch in Chapter 4: Administration and Lab 3.2 Install MSMQ in Chapter 3: Installation and Upgrade. 1. Open Server Manager. 2. Right-click Features > Message Queueing > Public Queues and then click New > Public Queue. 3. Name the new queue "CreateSO".

FIGURE 6.7 QUEUE

4. Select the Transactional check box. 5. Click OK to close the dialog box. 6. Wait for the queue to appear in Server Manager. The queue might not appear immediately. 7. Right-click the queue and then click Properties. 8. Select the Authenticated check box. 9. Click Security and then click Add. 10. In the Enter the object names to select field type "AX_AOS_Service" and then click OK. 11. Select the AX_AOS_Service account and then click Allow under Full Control. 12. Click OK to close the dialog box.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-37

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Demonstration: Create and Configure an Inbound Port
The inbound integration port receives the sales order messages. To create a new inbound port, follow these steps. 1. Open Microsoft Dynamics AX. 2. Open System Administration > Setup > Services and Application Integration Framework > Inbound Ports and then click New. 3. In Port name, type "SalesOrderCreateMSMQ". 4. In Description, type "SalesOrderCreateMSMQ". 5. In Adapter, select MSMQ. 6. In the URI field, click the arrow. The Configure MSMQ form opens. 7. In the Queue name list, select the CreateSO queue. 8. If the queue does not appear in the list, click Find queues to update the list. 9. Click OK. 10. Click Service operations. 11. In the Remaining service operations group, select SalesSalesOrderService.create and then click the less than (<) button. 12. Notice that SalesSalesOrderService.create has been added to the Selected service operations group. 13. Click Close. 14. Select Customize document and then click Data Policies. 15. In the Document data policies form, sort the table on the Element name column and then select Enabled for the following elements: o CustAccount (/SalesOrder/SalesTable/CustAccount) o ItemId (/SalesOrder/SalesTable/SalesLine/ItemId) HINT: Use filters to find these elements. 16. Click Close and then click Activate. 17. Close the infolog.

6-38

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Demonstration: Create a Document for the Sales Order Request
The sales order request is an XML-based document. For this example, you will use a sales order request that complies with the sales order schema. The request document uses the AIF message schema as an envelope to contain the sales order request. NOTE: For asynchronous document exchanges, such as the one that is demonstrated in this scenario, you must configure an AIF batch job. This batch job periodically runs business logic through integration ports that are configured to use asynchronous adapters. To complete this demonstration, you must first complete "Demonstration: Setup Batch" in Chapter 4: Administration. 1. Copy the following XML code into an empty Notepad document. <?xml version="1.0" encoding="utf-8" ?> <Envelope xmlns="http://schemas.microsoft.com/dynamics/2011/01/docu ments/ Message"> <Header > <MessageId>{adb3a54c-f36d-4ed6-b349-6de056f19708} </MessageId> <Action>http://schemas.microsoft.com/dynamics/2008/01/servi ces/S alesOrderService/create</Action> </Header > <Body > <MessageParts > <SalesOrder xmlns="http://schemas.microsoft.com/dynamics/2008/01/docu ments/ SalesOrder"> <SalesTable class="entity"> <CustAccount>2014</CustAccount> <PurchOrderFormNum>PO</PurchOrderFormNum> <ReceiptDateRequested>2011-1111</ReceiptDateRequested> <SalesLine class="entity"> <ItemId>10003</ItemI d> <SalesQty>18</SalesQt y> <SalesUnit>Pcs</SalesUnit> </SalesLine

> </SalesTable > </SalesOrder > </MessagePart s> </Body > </Envelope>

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-39

Application Integration Framework and Services in Microsoft Dynamics AX 2012


IMPORTANT: The XML code includes an element titled <MessageId>, which contains a GUID. This GUID uniquely identifies the message. You must provide a new, unique GUID for each message that you send to AIF. 2. Save the file as SOCreate.xml. For this walkthrough, we recommend that you save this file to the C: root directory.

Demonstration: Create a Message Queueing Client Application


This demonstration shows how to create a simple client application that sends a message to a queue. The code for the client application is written in the C# programming language. The sample application creates an XML document object by reading the file that you previously saved. The sample application then sends the document object to the message queue. 1. Open Visual Studio 2010. 2. Click File > New > Project. 3. Select Visual C# and then select Console application. 4. In Name, type "SalesOrderCreateMSMQ" and then click OK. 5. In Solution Explorer, right-click the project name and then click Add Reference. 6. On the .NET tab, select System.Messaging and then click OK. 7. Open Program.cs. In the code editor, add the following code.
using System.Messaging; using System.Xml; Replace the empty Main function with the following C# code. static void Main(string[] args) { // The queue name. // Replace this name with the string from URI field // in the Inbound ports form. For this walkthrough, // only the server name should be different. String QName ="formatname:DIRECT=OS:SEA-DEV\\CreateSO"; // The path to the sales order XML file String XMLPath ="c:\\SOCreate.xml"; // Create the XML document object. XmlDocument doc = new XmlDocument(); doc.Load(XMLPath); // Create a new message. Message msg = new Message();

6-40

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


// Add authentication. msg.AttachSenderId = true; msg.UseAuthentication = true; msg.HashAlgorithm = HashAlgorithm.Sha; // Attach the document to the message. msg.Body = doc; // Create the queue object. MessageQueue myQ = new MessageQueue(QName); try { // Send a message to the queue // Create a transaction. MessageQueueTransaction myTransaction = new MessageQueueTransaction(); // Begin the transaction myTransaction.Begin(); // Send the message myQ.Send(msg, "Sales Order", myTransaction); // End the transaction myTransaction.Commit(); } catch (Exception e) { // Display the description of the exception Console.WriteLine(e.Message); } Console.Write("Done. Press ENTER to continue."); Console.In.ReadLine(); }

8. Build the project. 9. Press F5 to run the project. When the application has finished running, the message has been sent to the queue. The batch job retrieves the message from the queue and processes it through the inbound integration port that you created. Processing can require some time. To verify that the sales order was created, view the All sales orders form. To check for errors, view the Exceptions log.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-41

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Call the Metadata Service


System services are Windows Communication Foundation (WCF) services that are included with Microsoft Dynamics AX that enable clients to interact with and retrieve system information. The system services include the following: Metadata service Query service User session service The system services are hosted by the Application Object Server (AOS) by default, although they can be configured to be hosted in IIS. The system services are automatically installed as part of the setup process and are always available. NOTE: The demonstrations in this lesson need to be performed in order. The following topics demonstrate how to call the metadata service.

Demonstration: Add a Reference to the Metadata Service


In order to call the metadata service, you must first create a project in Visual Studio and add a reference to the service. To add a reference to the metadata service, follow these steps. 1. Open Visual Studio 2010. 2. Click File > New > Project. 3. Select Visual C# and then select Console application. 4. In Name, type "CallMetadataService" and then click OK. 5. In Solution Explorer, right-click References and select Add Service Reference . 6. In the Address field, enter the service's URL. For example, http://SEADEV:8101/DynamicsAx/Services/MetadataService. 7. Click Go. In the Services tree, you should see the AxMetadataService node. 8. Click OK.

6-42

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Demonstration: Call the Service and Retrieve Metadata
This demonstration shows how to write the code that calls the metadata service and returns the metadata for a single query. To call the metadata service, follow these steps: 1. Replace the code in the Program.cs file with the following code.
using using using using System; System.Collections.Generic; System.Linq; System.Text;

namespace CallMetadataService { class Program { static void Main(string[] args) { ServiceReference1.AxMetadataServiceClient client = new ServiceReference1.AxMetadataServiceClient(); try { // Gets the names of all queries in a string array. string[] queries = client.GetQueryNames(); // Loops through all the query names. foreach (string queryName in queries) { if (queryName =="AxdSalesOrder") { // Stores the name of the AxdSalesOrder query. string[] limitedNames = new string[1]; limitedNames[0] = queryName; // Writes the name of the query to the console. Console.WriteLine("Query named: {0}", queryName); // Gets the metadata for the AxdSalesOrder query. ServiceReference1.QueryMetadata[] queryMetadata = client.GetQueryMetadataByName(limitedNames); // Creates a query metadata object. ServiceReference1.QueryMetadata querySalesOrder = queryMetadata[0]; // Loops through the query data sources and writes them to the console. foreach

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-43

Application Integration Framework and Services in Microsoft Dynamics AX 2012


(ServiceReference1.QueryDataSourceMetadata queryDS in querySalesOrder.DataSources) { RecursivelyIterateDataSources(queryDS); } Console.ReadKey(true); } } client.Close(); } catch { client.Abort(); throw; } } static void RecursivelyIterateDataSources (ServiceReference1.QueryDataSourceMetadata parent) { Console.WriteLine("Query data source named: {0}", parent.Name.ToString()); // Loops through the query data sources and writes them to the console. foreach (ServiceReference1.QueryDataSourceMetadata queryDS in parent.DataSources) { RecursivelyIterateDataSources(queryDS); } } } }

2. Build the project. 3. Press F5 to run the project.

6-44

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


The program writes the name of the AxdSalesOrder query and the names of the query data sources to the console window. The output looks similar to the "Results" figure:

FIGURE 6.8 RESULTS

TIP: If you run the code and receive a message size exception, you might need to modify settings in the app.config file on the server and client. For more information, refer to the "Message Size Error in Troubleshooting System Services" topic in this chapter. The QueryMetadata class contains all the methods and properties for a single query. If you are working with other objects such as tables, you can access the data through the corresponding metadata object, for example, the QueryMetadata class. All of the metadata contracts are contained in the Microsoft.Dynamics.AX.Framework.Services.Metadata.Contracts namespace. TIP: A similar process is used when calling the query service or user session service. For more information and examples of calling these services, refer to the AIF System Services (http://go.microsoft.com/fwlink/?LinkID=247500&clcid=0x409 )page on MSDN.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-45

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 6.4 - Call the User Session Service


In this lab, you will call the user session service. Scenario Simon, the System Implementer, needs to call the user session service.

Challenge Yourself!
Use the provided information to call the user session service.

Need a Little Help?


1. Create a C# project in visual studio. 2. Add a service reference. 3. Call the service.

Step by Step
1. Open Visual Studio 2010 2. Click File > New > Project. 3. Select Visual C# and then select Console application. 4. In Name, type "CallUserSessionService" and then click OK. 5. In Solution Explorer, right-click References and select Add Service Reference . 6. In the Address field, enter the service's URL. For example, http://SEADEV:8101/DynamicsAx/Services/UserSessionService. 7. Click Go. In the Services tree, you should see the UserSessionService node. 8. Replace the main method in the Program.cs file with the following code.
static void Main(string[] args) { ServiceReference1.UserSessionServiceClient client = new ServiceReference1.UserSessionServiceClient(); ServiceReference1.UserSessionInfo userSessionInfo = client.GetUserSessionInfo(null); Console.WriteLine("User: " + userSessionInfo.UserId); Console.WriteLine("Language: " + userSessionInfo.AXLanguage); Console.WriteLine("Default Company: " + userSessionInfo.Company); Console.WriteLine("Company Time Zone: " + userSessionInfo.CompanyTimeZone);

Console.WriteLine("Default Currency: " +

6-46

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


userSessionInfo.CurrencyInfo.CurrencyCode); Console.WriteLine("Preferred Calendar: " + userSessionInfo.UserPreferredCalendar); Console.WriteLine("Preferred Time Zone: " + userSessionInfo.UserPreferredTimeZone); Console.ReadKey(true); }

9. Build the project. 10. Press F5 to run the project

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-47

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Create and Deploy Outbound Exchange


When AIF sends a document out of Microsoft Dynamics AX, the result can be an XML message that is transferred by using the outbound integration port. For example, when you use the file system adapter on an outbound integration port to send an AxdLedgerJournal document, the system creates an XML file in the outbound directory that you created. Depending on the fields that you have enabled for the document on the outbound port, the final XML message could vary. The following topics review how to set up the AIF components for an outbound exchange. In addition, you will create and then test a new outbound exchange. NOTE: The demonstrations in this lesson need to be performed in order.

Demonstration: Create a Document Query


This demonstration shows how to create a document query, a new service, and a document schema when you want to create a document service that is not included with Application Integration Framework (AIF). To create a document query, follow these steps. 1. Open a new development workspace. 2. Open the AOT window, right-click the Queries node, and then click New Query. 3. Expand the node for the new query that is created. 4. Right-click Data Dictionary and then click Open New Window. 5. In the second AOT window, expand the Tables node and drag the LedgerJournalTable table onto the Data Sources node under the new query in the first window. By default, all of the fields in the data source are included in the query. 6. Right-click the new data source and then click Properties. In the Properties sheet, rename the query data source name from LedgerJournalTable_1 to LedgerJournalTable. 7. In the first AOT window, expand the LedgerJournalTable node. Drag the LedgerJournalTrans table onto the LedgerJournalTable Data Sources node. 8. Right-click the new query and then click Properties. In the Properties sheet, rename the query data source table from LedgerJournalTrans_1 to LedgerJournalTrans.

6-48

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


9. Set the JoinMode property to OuterJoin. 10. Right-click Fields in the LedgerJournalTable node and then click Properties. Set the Dynamic property to Yes. This setting makes sure that all fields are returned and is required when a table participates in an inheritance relationship. 11. In the AOT, click the new query, and then in the Properties sheet, set the Name property to AxdLedgerJournal. BEST PRACTICE: The query name should always be the same as the document class name. This is especially true when you use the AIF Document Service Wizard to generate the service because it sets the document name to the name of the query by default. 12. In the AOT, expand the LedgerJournalTrans data source node, right- click Relations, and then select New Relation. By default, a relation is created between the LedgerJournalTable.JournalNum field and the LedgerJournalTrans.JournalNum field. This is because the data type for the JournalNum field is based on the LedgerJournalId extended data type which has a relation to the LedgerJournalTable. 13. Expand LedgerJournalTrans, right-click Fields, and then click Properties. 14. Set the Dynamic property to Yes. 15. Right-click the LedgerJournalTrans node and then click Properties. 16. Set the FetchMode property to 1:n. 17. Save the AxdLedgerJournal query.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-49

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Demonstration: Create a Service by Using the AIF Document Service Wizard
To create a new service by using the AIF document services wizard, follow these steps: 1. In the Developer Workspace, click Tools > Application Integration Framework > Create Document Service. The Welcome screen appears. 2. Click Next. In the Select document parameters screen, in the Query field, select the AxdLedgerJournal query. The default setting is the document name.

FIGURE 6.9 WIZARD

3. Click Next. In the Select code generation parameters screen, the Class names default setting is based on the selected AxdLedgerJournal query. 4. Select the Read and Create service operations that the service will expose. The AxdLedgerJournal class must support reading a single journal and its entries and creating a single journal and its entries. 5. Click Next. In the Generate code screen, you can review the artifacts that will be generated and then click Generate. 6. The Completed screen displays the artifacts that the wizard created. Click Finish.

6-50

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Demonstration: Generate the Document Schema for the Service
The document schema, or XSD, defines the structure and format of the XML that is serialized or deserialized by the document class. In AIF, the schema for each document is generated by iterating through the query that is associated with the document class. The document schema defines the XML rules for the document. When you use the AIF Document Service Wizard to create a service, it automatically creates an X++ job that you can run to generate the document schema. Use the following steps to generate the document schema for the service. 1. Press Ctrl+Shift+P to open the Projects form. 2. Expand the Private node, and then double-click the AxdLedgerJournal project. This project contains all of the objects created by the AIF Document Service Wizard that are related to the new service. 3. Double-click the GenerateXSDSchema_AxdLedgerJournal job to open it in the code editor.

FIGURE 6.10 PROJECT

4. Press F5 to run the job. You will not see any message indicating that the job has completed. When you run this job, it creates a file that contains the schema for all of the fields in the document. The file location is c:\XSDSchema_AxdLedgerJournal.xml. Now that the service has been generated, your scenario might require that you add custom business logic code to the document service classes. For simplicity, consider this service implementation as complete.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-51

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Demonstration: Create Folders for the File Adapter
Follow these steps to create folders for the file adapter to use. 1. Create a new folder called "C:\AIF" if it has not already been created. 2. Create a new folder called "C:\AIF\LedgerJournalFileOUT". 3. Right-click LedgerJournalFileOUT and then click Properties. 4. Click Security and then click Advanced. 5. Click Change Permissions and then click Add. 6. In the Enter the object name to select field type AX_AOS_Service and then press Enter. 7. Select Allow full control and then click OK on all open dialogs.

Demonstration: Create and Configure an Outbound Port


You can create and configure an outbound integration port to deploy a document in an outbound exchange. You must first create an outbound directory. Microsoft Dynamics AX puts the XML files that it creates in the outbound directory. When you are finished, you must create a port for the outbound directory. To do this, you would use an integration port to associate the file system adapter with the file system directory that you just created. NOTE: To complete this demonstration you must first complete the Call a Document Service with the File Adapter demonstration. To create and configure an outbound port, follow these steps. 1. Open System administration > Setup > Services and Application Integration Framework > Outbound ports. 2. Click New. 3. Name the new integration port "LedgerJournalFileOut". 4. In the Adapter list in the Address group, select File system adapter. 5. In the URI list, click the arrow to browse to the folder that you created, named "C:\AIF\LedgerJournalFileOUT". 6. On the Service contract customizations FastTab, click Service operations. 7. In the Select service operations form, select LedgerJournalService.read in the Remaining service operations list. Click the left arrow to move the service

operation to the Selected service operations list. 8. Close the form. 9. On the Service contract customizations FastTab, select Customize documents and then click Data policies.
6-52

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


10. In the Document data policies form, click Enable all. The XPath field determines which entity is the source of the data element. In the AxdLedgerJournal class, a data element can come from the document class , the LedgerJournalTable table, or the LedgerJournalTrans table. 11. Close the Document data policies form. 12. Expand the Troubleshooting FastTab and then select All document versions for Logging mode. 13. In the Outbound ports form, click Activate to activate the port. 14. Close the infolog.

Demonstration: Add Business Logic for the Outbound Exchange


After a new document is created and you have configured the integration port for the data that will be sent in an outbound exchange, you need to write code to initiate the document transfer. For this example, you will create a Send electronically button on the General journal form. The first step in writing the code to send a document is to identify the form from which the exchange will be initiated. The following steps describe how to get the form class name for the General journal form. To identify the General journal form, follow these steps. 1. Navigate to the General journal form. Click General Ledger > Journals > General journal. 2. In the Show field, select All. 3. Right-click a record in the General journal form and then click Personalize. 4. Click the Information tab in the Personalization form. The Form name field contains the name of the form, and in this case, it should be the LedgerJournalTable form. Click the Query tab to verify that the form table is LedgerJournalTable. In the following section, you will add a button to the LedgerJournalTable form to initiate the sending of the ledger journal document. The user can send the ledger journal as an original or a duplicate. To do this, the form must contain a MenuButton control with two MenuItemButton controls.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-53

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Demonstration: Add buttons to the Form
To add a button to the form for sending the document, follow these steps. 1. In the AOT, expand the Forms node and then expand the LedgerJournalTable node. 2. Expand Designs, expand Design, expand ActionPane: ActionPane, and then expand ActionPaneTab: ActionPaneTab. 3. Right-click ButtonGroup:ButtonGroup, select New control, and then click MenuButton. NOTE: The VendPurchOrderJournal form has the same button structure for sending a purchase order. You can use this form as a reference when implementing your own send button. On the VendPurchOrderJournal form, expand the Design node, expand Tab:Tab, expand TabPage:Overview, expand ActionPane:ActionPane, expand ActionPaneTab:ActionPanetab, expand ButtonGroup:OverviewButtonGroup, and then expand MenuButton:MenuSendXML to view the form controls. 4. Right-click the new MenuButton control, click Properties, and then set the following properties. a. Name = SendXMLMenu b. Text = Send electronically 5. In the AOT, right-click the MenuButton:SendXMLMenu button control, point to New control, and then click Button. This button specifies that the user is sending an original message. Set the following properties on the new Button control. a. Name = SendXMLOriginal b. Text = Original 6. In the AOT, right-click the MenuButton:SendXMLMenu button control, point to New control, and then click Button. This button will specify that the user is sending a duplicate message. Set the following properties on the new Button control and save your changes. a. Name = SendXMLDuplicate b. Text = Duplicate

6-54

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Demonstration: Create the canXMLBeSent Table Method
When the user clicks the Send electronically button, the clicked event calls two methods from the LedgerJournalTable table: canXMLBeSent sendElectronically These methods contain the code that sends the ledger journal document. The canXMLBeSent method ensures that an integration port has been configured for the selected document action. If there is no integration port configured, the code returns false. To add the canXMLBeSent method on the table, follow these steps. 1. In the AOT, expand the Data Dictionary node, expand Tables, and then expand LedgerJournalTable. 2. Right-click Methods and then click New method. 3. In the code editor, copy the following code into the new method.
boolean canXMLBeSent() { boolean ret; AifActionId actionId; AifEndpointList endpointList; AifConstraint aifConstraint = new AifConstraint(); AifConstraintList aifConstraintList = new AifConstraintList(); ; actionId = AifSendService::getDefaultSendAction(classnum(LedgerJournal Service), AifSendActionType::SendByKey); if(actionId) { aifConstraint.parmType(AifConstraintType::NoConstraint); aifConstraintList.addConstraint(aifConstraint); endpointList = AifSendService::getEligibleEndpoints(actionId, aifConstraintList); if(endpointList.getEndpointCount()>0) { ret = true; } } return ret; }

4. Click the Ctrl+S keyboard shortcut to save changes.

Microsoft Official Training Materials for Microsoft Dynamics

Your use of

this content is subject to your current services agreement

6-55

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Demonstration: Create the sendElectronically Table Method
The sendElectronically method gets the entity key for the selected journal, calls the method that retrieves the data, serializes that data into an XML message, and then sends the document to the gateway queue. To add code to the sendElectronically table method, use the following procedure: 1. In the AOT, in the LedgerJournalTable table, right-click the Methods node and then click New method. 2. In the code editor, copy the following code into the new method.
void sendElectronically(XMLDocPurpose _xMLDocPurpose, AifSendMode _aifSendMode = AifSendMode::Async) { AxdSendContext axdSendContext = AxdSendContext::construct(); AifEntityKey aifEntityKey = AifEntityKey::construct(); Map keyData; AifConstraintList aifConstraintList = new AifConstraintList(); AifConstraint aifConstraint = new AifConstraint(); ; keyData = SysDictTable::getKeyData(this); aifEntityKey.parmTableId(this.TableId); aifEntityKey.parmRecId(this.RecId); aifEntityKey.parmKeyDataMap(keyData); axdSendContext.parmXMLDocPurpose(_xMLDocPurpose); axdSendContext.parmSecurity(false); aifConstraint.parmType(AifConstraintType::NoConstraint) ; aifConstraintList.addConstraint(aifConstraint) ; AifSendService::submitDefault( clas snum(LedgerJournalService), aifEntityKey, aifConstraintList, _aifSendMode, axdSendContext.pack()); }

3. Click the Ctrl+S keyboard shortcut to save changes.

6-56

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


Demonstration: Override the Clicked Methods
In this section you will add code to the clicked events for the SendXMLOriginal and SendXMLDuplicate buttons. 1. In the AOT, expand the Forms node and then expand the LedgerJournalTable form. 2. Expand Designs, expand Design, expand ActionPane: ActionPane, and then expand ActionPaneTab: ActionPaneTab. 3. Expand ButtonGroup:ButtonGroup, expand MenuButton:SendXMLMenu, and then expand Button:SendXMLOriginal. 4. Right-click the Methods node, click Override Method, and then select Clicked. 5. In the code editor, enter the following code in the clicked event.
void clicked() { LedgerJournalTable ledgerJournalTableLocal; ; for (ledgerJournalTableLocal = LedgerJournalTable_ds.getFirst(true) ? LedgerJournalTable_ds.getFirst(true) : LedgerJournalTable; ledgerJournalTableLocal; ledgerJournalTableLocal = LedgerJournalTable_ds.getNext()) // Check to see if document can be sent. if (ledgerJournalTableLocal.canXMLBeSent()) { // Send the document. ledgerJournalTableLocal.sendElectronically(XMLDocPurpose::O riginal); } else { warning (strfmt("@SYS72175")); // TODO Add a ledger journal specific error message to the // label file. // warning (strfmt("@SYSnnnnn",ledgerJournalTableLocal.JournalNum)); } }

6. Click the Ctrl+S keyboard shortcut to save changes. 7. Repeat steps 3 through 6 for the MenuItemButton:SendXMLDuplicate control.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-57

Application Integration Framework and Services in Microsoft Dynamics AX 2012


8. In the clicked event of the MenutItemButton:SendXMLDuplicate button control, change XMLDocPurpose::Original to XMLDocPurpose::Duplicate.

Demonstration: Test the Outbound Exchange


For AIF to begin sending and receiving documents for adapter-based exchanges, the services that move documents through the queues must be running as batch jobs within Microsoft Dynamics AX. NOTE: To complete this demonstration, you must first complete "Demonstration: Set Up Batch" in Chapter 4: Administration. Use the following steps to test sending the document. 1. In the Developer Workspace, click Build > Generate Incremental CIL. 2. Open General ledger > Journals > General journal.

6-58

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


3. In the Show field, select All. 4. Click one of the journal lines and then click the Send electronically button. Click Original to send the original document.

FIGURE 6.11 GENERAL JOURNAL

5. Watch the folder that you named "C:\AIF\LedgerJournalFileOUT". After a few minutes, a response file will be saved to this folder by AIF. NOTE: You can monitor the progress of your message by reviewing System Administration > Periodic > Services and Application Integration Framework > Queue manager and System Administration > Periodic > Services and Application Integration Framework > Exceptions. The selected ledger journal and its lines are serialized into XML with header information and sent to the gateway queue. When the AIF batch services run, the message will be selected from the gateway queue and sent to the "C:\AIF\LedgerJournalFileOUT" directory that you created earlier.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-59

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 6.5 - Create and Deploy an Outbound Exchange


In this lab, you will create a button on Fleet Management Rentals to send an XML document by using the file system adapter. Scenario Simon, the System Implementer, needs to create a button on Fleet Management Rentals to send an XML document by using the file system adapter.

Challenge Yourself!
Use the provided information to create a button on Fleet Management Rentals to send an XML document by using the file system adapter.

Need a Little Help?


1. 2. 3. 4. 5. 6. Create a document query. Create a service by using the AIF document service wizard. Create folders for the file adapter. Create an outbound port. Add business logic to perform an outbound exchange. Test the exchange.

Step by Step
NOTE: Demonstrations in this section need to be performed in order, and they depend on Lab 4.1 Set up Batch in Chapter 4: Administration. 1. Open a new development workspace. 2. Open the AOT window, right-click the Queries node, and then click New Query. 3. Expand the node for the new query that is created. 4. Right-click Data Dictionary and then click Open New Window. 5. In the second AOT window, expand the Tables node and drag the FMRental table onto the Data Sources node under the new query in the first window. By default, all of the fields in the data source are included in the query. 6. Right-click the new data source and then click Properties. In the Properties sheet, rename the query data source name from FMRental_1 to FMRental. 7. Right-click Fields in the FMRental node and then click Properties.

Set the Dynamic property to Yes. This setting makes sure that all fields are returned and is required when a table participates in an inheritance relationship.

6-60

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


8. In the AOT, click the new query, and then in the Properties sheet, set the Name property to AxdFMRental. 9. Save the AxdFMRental query. Use the following steps to create a new service by using the AIF document services wizard. 1. In the Developer Workspace, click Tools > Application Integration Framework > Create Document Service. The Welcome screen appears. 2. Click Next. 3. In the Select document parameters screen, in the Query field, select the AxdFMRental query. 4. In Document Name, type "FMRentalService". 5. Click Next. In the Select code generation parameters screen, the Class names default setting is based on the selected AxdFMRental query. 6. Select the Read and Create service operations that the service will expose. The AxdFMRental class must support reading a single journal and its entries and creating a single journal and its entries. 7. Click Next. In the Generate code screen, you can review the artifacts that will be generated, and then click Generate. 8. The Completed screen displays the artifacts that the wizard created. Click Finish. Use the following steps to generate the document schema for the service 1. Press Ctrl+Shift+P to open the Projects form. 2. Expand the Private node and then double-click the AxdFMRentalService project. This project contains all of the objects that are created by the AIF Document Service Wizard that are related to the new service. 3. Double-click the GenerateXSDSchema_AxdFMRentalService job to open it in the code editor. 4. Press F5 to run the job. You will not see any messages indicating that the job has completed. When you run this job, it creates a file that contains the schema for all of the fields in the document. The file location is c:\XSDSchema_AxdFMRentalService.xml. Follow these steps to create folders for the file adapter to use. 1. Create a new folder called "C:\AIF" if it has not already been created. 2. Create a new folder called "C:\AIF\FMRentalOUT".

3. Right-click FMRentalOUT and then click Properties. 4. Click Security and then click Advanced.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-61

Application Integration Framework and Services in Microsoft Dynamics AX 2012


5. Click Change Permissions and then click Add. 6. In the Enter the object name to select field type "AX_AOS_Service" and then press Enter. 7. Select Allow full control and then click OK on all open dialogs. To create and configure an outbound port, follow these steps. 1. Open System administration > Setup > Services and Application Integration Framework > Outbound ports. 2. Click New. 3. Name the new integration port FMRentalFileOut. 4. In the Adapter list in the Address group, select File system adapter. 5. In the URI list, click the arrow to browse to the folder that you created, named "C:\AIF\FMRentalOUT". 6. On the Service contract customizations FastTab, click Service operations. 7. In the Select service operations form, select FMRentalServiceService.read in the Remaining service operations list. Click the left arrow to move the service operation to the Selected service operations list. 8. Close the form. 9. On the Service contract customizations FastTab, select Customize documents and then click Data policies. 10. In the Document data policies form, click Enable all. The XPath field determines which entity is the source of the data element. In AxdFMRental class, a data element can come from the document class, the FMRental table. 11. Close the Document data policies form. 12. Expand the Troubleshooting FastTab and then select All document versions for Logging mode. 13. In the Outbound ports form, click Activate to activate the port. 14. Close the infolog. To identify the All Rentals form, follow these steps. 1. Navigate to the All Rentals form. Click Fleet Management > Rentals > All Rentals > Edit. 2. Right-click a record in the Rental form and then click Personalize. 3. Click the Information tab in the Personalization form. The Form name field contains the name of the form, and in this case, it should be the FMRental form. Click the Query tab to verify that the form table is the FMRental table.

6-62

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services


To add a button to the form for sending the document, follow these steps. 1. In the AOT, expand the Forms node and then expand the FMRental node. 2. Expand Designs, expand Design, expand ActionPane: ActionPaneDetailsView, and then expand ActionPaneTab: HomeTabDetailsView. 3. Right-click ActionPaneTab: HomeTabDetailsView, select New control, and then click ButtonGroup. 4. Click the new ButtonGroup control, click Properties, and then set the following properties. a. Name = SendXMLMenu b. Caption = Send electronically 5. In the AOT, right-click the ButtonGroup:SendXMLMenu button control, point to New control, and then click Button. This button specifies that the user is sending an original message. Set the following properties on the new Button control. a. Name = SendXMLOriginal b. Text = Original 6. In the AOT, right-click the ButtonGroup:SendXMLMenu button control, point to New control, and then click Button. This button will specify that the user is sending a duplicate message. Set the following properties on the new Button control and save your changes. a. Name = SendXMLDuplicate b. Text = Duplicate 7. In the AOT, expand the Data Dictionary node, expand Tables, and then expand FMRental. 8. Right-click Methods, and then click New method. 9. In the code editor, copy the following code into the new method.
boolean canXMLBeSent() { boolean ret; AifActionId actionId; AifEndpointList endpointList; AifConstraint aifConstraint = new AifConstraint(); AifConstraintList aifConstraintList = new AifConstraintList(); ; actionId = AifSendService::getDefaultSendAction(classnum(FMRentalServi

ceService), AifSendActionType::SendByKey);

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-63

Application Integration Framework and Services in Microsoft Dynamics AX 2012


if(actionId) { aifConstraint.parmType(AifConstraintType::NoConstraint); aifConstraintList.addConstraint(aifConstraint); endpointList = AifSendService::getEligibleEndpoints(actionId, aifConstraintList); if(endpointList.getEndpointCount()>0) { ret = true; } } return ret; }

10. Click the Ctrl+S keyboard shortcut to save changes. 11. In the AOT, in the FMRental table, right-click the Methods node and then click New method. 12. In the code editor, copy the following code into the new method.
void sendElectronically(XMLDocPurpose _xMLDocPurpose, AifSendMode _aifSendMode = AifSendMode::Async) { AxdSendContext axdSendContext = AxdSendContext::construct(); AifEntityKey aifEntityKey = AifEntityKey::construct(); Map keyData; AifConstraintList aifConstraintList = new AifConstraintList(); AifConstraint aifConstraint = new AifConstraint(); ; keyData = SysDictTable::getKeyData(this); aifEntityKey.parmTableId(this.TableId); aifEntityKey.parmRecId(this.RecId); aifEntityKey.parmKeyDataMap(keyData); axdSendContext.parmXMLDocPurpose(_xMLDocPurpose); axdSendContext.parmSecurity(false); ; aifConstraint.parmType(AifConstraintType::NoConstraint) aifConstraintList.addConstraint(aifConstraint) ; AifSendService::submitDefault( classn um(FMRentalServiceService), aifEntityKey, aifConstraintList, _aifSendMode, axdSendContext.pack()); }

6-64

M i c r o s o f t O f f i c i a l T r a i n i n g M a t e r i a l s f o r M i c r o s o f t D y n a m i c s

of this content is subject to your current services agreement

Y o u r u s e

Chapter 6: Working With Services


13. Click the Ctrl+S keyboard shortcut to save changes. In this section you will add code to the clicked events for the SendXMLOriginal and SendXMLDuplicate buttons. 1. In the AOT, expand the Forms node and then expand the FMRental node. 2. Expand Designs, expand Design, expand ActionPane: ActionPaneDetailsView, and then expand ActionPaneTab: HomeTabDetailsView. 3. Expand ButtonGroup:SendXMLMenu, and then expand Button:SendXMLOriginal. 4. Right-click the Methods node, click Override Method, and then select Clicked. 5. In the code editor, enter the following code in the clicked event. void clicked() { FMRental FMRentalLocal; ; for (FMRentalLocal = FMRental_ds.getFirst(true) ? FMRental_ds.getFirst(true) : FMRental; FMRentalLocal; FMRentalLocal = FMRental_ds.getNext()) // Check to see if document can be sent. if (FMRentalLocal.canXMLBeSent()) { // Send the document. FMRentalLocal.sendElectronically(XMLDocPurpose::Original ); } else { warning (strfmt("@SYS72175")); // TODO Add a rental specific error message to the // label file. // warning (strfmt("@SYSnnnnn",FMRentalLocal.JournalNum)); } } 6. Click the Ctrl+S keyboard shortcut to save changes. 7. Repeat steps 3 through 6 for the Button:SendXMLDuplicate control.

8. In the clicked event of the Button:SendXMLDuplicate button control, change XMLDocPurpose::Original to XMLDocPurpose::Duplicate.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-65

Application Integration Framework and Services in Microsoft Dynamics AX 2012


9. In the Developer Workspace, click Build > Generate Incremental CIL. 10. Navigate to the All Rentals form. Click Fleet Management > Rentals > All Rentals > Edit. 11. Click one of the rental lines and then in the Send electronically Group click Original to send the original document. 12. Watch the folder that you named "C:\AIF\FMRentalOUT". After a few minutes, a response file will be saved to this folder by AIF. NOTE: You can monitor the progress of your message by reviewing System Administration > Periodic > Services and Application Integration Framework > Queue manager and System Administration > Periodic > Services and Application Integration Framework > Exceptions.

6-66

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services

Summary
The hands-on labs, procedures, and demonstrations in this chapter provide additional practice and instruction to reinforce the content of previous chapters.

Microsoft Official Training Materials for Microsoft Dynamics

Your use of this

content is subject to your current services agreement

6-67

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Test Your Knowledge


Test your knowledge with the following questions. 1. Put the following steps in order for creating and deploying an outbound exchange: Step: _: Create a document query _: Create a service by using AIF document service wizard : Add business logic to perform an outbound exchange _: Create an outbound port _: Test the exchange _: Create folders for the file adapter 2. What is the default URL for the user session service? () http://<Server>:8101/DynamicsAx/Services/UserSessionServic e ( ) http://<Server>/DynamicsAx/Services/UserSessionService () http://<Server>:2700/DynamicsAx/Services/UserSessionServic e 3. Which adapter uses the Use default owner for Administrators group parameter? ( ) NetTcp ( ) File System Adapter () MSMQ ( ) HTTP 4. When you add a service reference, what field in the Inbound Port form should be reference? ( ) WSDL URI ( ) Name ( ) Adapter ( ) URI

6-68

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 6: Working With Services

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this chapter 1.

2.

3.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

6-69

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Solutions
Test Your Knowledge
1. Put the following steps in order for creating and deploying an outbound exchange: Step: 1 : Create a document query 2 : Create a service by using AIF document service wizard 5 : Add business logic to perform an outbound exchange 4 : Create an outbound port 6 : Test the exchange 3 : Create folders for the file adapter 2. What is the default URL for the user session service? () http://<Server>:8101/DynamicsAx/Services/UserSessionServic e ( ) http://<Server>/DynamicsAx/Services/UserSessionService () http://<Server>:2700/DynamicsAx/Services/UserSessionServic e 3. Which adapter uses the Use default owner for Administrators group parameter? ( ) NetTcp () File System Adapter () MSMQ ( ) HTTP 4. When you add a service reference, what field in the Inbound Port form should be reference? () WSDL URI ( ) Name ( ) Adapter ( ) URI

6-70

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging

CHAPTER 7: TROUBLESHOOTING AND LOGGING


Objectives
The objectives are: Monitor Services and AIF capabilities. Debug services and review common errors.

Introduction
Troubleshooting and logging provides the following benefits: Developers can create more robust integrations Administrators can ensure that integrations function properly Resolving issues with integrations Services and AIF in Microsoft Dynamics AX 2012 introduces several capabilities to improve the troubleshooting and logging experience. Correlate exceptions ports and messages in the exception log Flexible error handling for large imports Support for batched messaging Troubleshooting options are moved to integration ports Debug services by using Microsoft Visual Studio 2010

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-1

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Correlate Exceptions, Ports, and Messages
You can view information about the related port, message, and message set on the Exceptions form.

Flexible Error Handling for Large Imports


Troubleshooting is done at the integration port level and can include multiple service operations. When large files are imported, error handling provides flexible options, including continue, halt, and rollback.

Batched Messaging
When batched messages are processed, error handling is determined by the configuration of the integration port. The Processing options FastTab setting determines how errors are managed during batch processing. In the Upon error in batched requests: field, select one of the following values: Continue continue processing messages after an error is encountered. Messages that cause errors might not be processed correctly. These messages remain in the gateway queue. Messages that do not cause errors continue to be processed and then they generate responses, if responses are appropriate. Check the exceptions log for detailed information about the messages that caused errors. Halt stop processing the rest of the messages in the batch after an error is encountered. The rest of the messages, along with the message that caused the error, remain in the gateway queue in the appropriate state. Check the exceptions log for detailed information about the error that interrupted the message processing. No more messages from the batch are processed. Messages that have been processed will generate responses, if responses are appropriate, and any resulting changes are committed to the database. Rollback stop processing the batched messages and undo any previously processed messages from the batch that contain the message that caused the error. All messages remain in the gateway queue in the appropriate state. Note that conversation IDs are not related to the settings for error handling on the integration port.

7-2

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging

Monitoring Services and AIF


After you set up data exchanges with external systems by using Application Integration Framework (AIF), you must maintain this integration. Microsoft Dynamics AX lets you manage your document exchanges throughout their life cycle and troubleshoot any issues that affect data transfers. The maintenance and management of document exchanges involve the following tasks: Configuring troubleshooting options Monitoring traffic and viewing the document history as documents pass through the framework Clearing and reviewing messages in the queues for adapter-based exchanges Viewing the exception logs when problems occur Modifying and resubmitting messages that contain formatting errors Stopping and starting the batch services when necessary

Configure Troubleshooting Options for Integration Ports


The troubleshooting settings in services and Application Integration Framework (AIF) are set up in either the Inbound ports form or the Outbound ports form. To open these forms, use the following steps: Click System administration > Setup > Services and Application Integration Framework > Inbound ports. Click System administration > Setup > Services and Application Integration Framework > Outbound ports. Use the Troubleshooting FastTab to specify settings that can help you diagnose issues in the configuration and operation of an integration port by using the following parameters: Logging Mode With this property, you can store copies of the XML code for documents that are exchanged by using AIF. Then, you can view these copies by using the History form. Include exceptions in fault Select this check box to specify that X++ and .NET Framework error messages from the service are included in fault messages. When you select this check box, the fault message includes detailed Infolog messages.

Respond after error in asynchronous request For inbound integration ports, select this check box to specify that the port automatically sends error messages as responses in asynchronous scenarios.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-3

Application Integration Framework and Services in Microsoft Dynamics AX 2012


NOTE: Only Logging Mode is available in a basic integration port. The Include exceptions in fault and Respond after error in asynchronous request parameters are only available with enhanced integration ports.

Logging Mode Options


In the Logging mode list, select the logging mode. The following options are available: Original document Select this option to store only the original document. All document versions Select this option to store a separate version of the document every time that it is modified by a pipeline. When you select this option, you can use the Document log form to view details about each step in the processing of the document. NOTE: Document versions are not logged for each integration-level or portlevel transform. Document versions are logged only for pipeline components. For example, you can use an XSLT in a pipeline if you want to log the various document versions that are the result of transformations. Message header only Select this option to store only the message header for each document. Logging disabled Select this option to turn logging off. When you select this option, no documents are entered in the document history. As a result, you cannot view correlation information.

View the Document History


Documents that are exchanged by using Application Integration Framework (AIF) are related to data in the Microsoft Dynamics AX database. An example of a document that might be exchanged would be a sales order. To exchange documents and data with external systems, AIF creates a message that contains header information and line record data. You can view information about documents and messages in the AIF History form. Selecting Message in the Display by field will show only information about the message. If you select Document in the Display by field, information about the message and the underlying document, such as the entity key, will display. Information about messages and the document history are organized by the service operation for each port. You can set the parameters for logging when you configure the troubleshooting options for ports.

7-4

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging


Procedure: View the General Document History
To view the general document history, follow these steps: Click System administration > Periodic > Services and Application Integration Framework > History. In the Display by field, you can filter the display by selecting either Message or Document. NOTE: Selecting Message will show the following information about the message: the port, service operation, message ID, company account's ID, and date and time that the message was created. Selecting Document will show information about the message, and the document's form name and entity key. Click the General tab to view the ID of the sent message. Click the Details tab to view the following information: o The direction of the message: inbound or outbound o The ID of the pipeline, if there is a pipeline o The Microsoft Dynamics AX user who is associated with the port and the submitting user The submitting user is associated with the process that submitted the message. The submitting user is either the Microsoft Dynamics AX user who submitted the message for the port or a trusted intermediary. o For outbound documents that are sent in response to read requests, the message ID for the original request o Address details, which include the adapter and URI that were used for the exchange Click Correlation to view the database record that corresponds to the message. Click Document logs to view the XML code for each version of the document as the document is transformed by each component in the pipeline. Click Clear document XML to clear all or some of the XML code for any version of the document that currently exists in the system. Clear the document history.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-5

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Procedure: View Data in a Document for a Message
To view the data that is associated with a message, follow these steps: 1. Click System administration > Periodic > Services and Application Integration Framework > History. 2. In the Display by field, select Message. 3. Select a message and then click Correlation. 4. In the Document correlation form, view the form name, table name, and entity key for the database record that is contained in the message that you selected. You can also view a record for each numbered version of the document and the related processing steps. 5. Click View to display the data in the default form for the document.

Procedure: Delete a Message


When deleting a message by using the History form, you delete that message from the AifMessageLog table. 1. Click System administration > Periodic > Services and Application Integration Framework > History. 2. In the Display by field, select Message. 3. Press ALT+F9 to delete the record from the document history.

Procedure: Clear the Document XML


To clear the XML documents in document history, follow these steps: 1. Click System administration > Periodic > Services and Application Integration Framework > History. 2. In the Display by field, select Document and then select a document. 3. Click Clear document XML. o To clear all the images of the XML document that exist in the system, click Clear all versions. o To clear all intermediate versions of the XML document, click Clear interim versions. For outbound documents, this action clears all versions except the one that has the highest version number. For inbound documents, this action clears all versions except the first version.

7-6

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging


Queue Manager
The Queue manager form displays information about messages in the Application Integration Framework (AIF) queues. This information includes the status of each message, such as the following: Ready In process This status is used for inbound messages only. Hold Error In transport process This status is used for outbound messages only. Malformed XML If the status of a message is set to Ready, you can change the status to Hold. If the status is set to Hold, you can change it to Ready. If the status is set to Error or Hold, you can delete or modify the message. NOTE: The Queue Manager only displays information for File and MSMQ adapters.

Procedure: View the Message Status and Details


To view the status of a message and other details, follow these steps: 1. Click System administration > Periodic > Services and Application Integration Framework > Queue manager. 2. On the Overview tab, view the port name, message ID, direction, status, company account's ID, service operation, and any error message that is associated with the message. 3. On the Details tab, view information about the submitting user, the ID of the Microsoft Dynamics AX user who is associated with the port, channel, status, bulk status, and the date and time that the message was created. 4. Click Refresh to update the information. 5. Click Document log to view information about the document that is contained in the message. The information that is displayed varies, depending on the logging options that were set for the port.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-7

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Procedure: Delete a Message
If a message remains unprocessed in the AIF queues, you can delete it in the Queue manager form. 1. Click System administration > Periodic > Services and Application Integration Framework > Queue manager. 2. Press ALT+F9 to delete the message. NOTE: You can delete the message only if the value in the Status field is Error, Malformed XML, or Hold.

Procedure: Modify and Resubmit a Message


If a message enters the queue but cannot be processed because of an error, you might be able to modify and resubmit the message. To resubmit a message, follow these steps. 1. If the status of the message is Error or Hold, click View message to view the message. Enter a file name and path and then save the message to an XML file. 2. Open the file that you just saved in any XML editor and then modify the file to correct the field or fields that have errors. 3. Click Import message to import the file. 4. Change the status of the message from Error or Hold to Ready. The queue can now start to process the message. Note that for message sets, changing the status will change the status for all messages in the message set.

Exceptions Log
The exceptions log contains a record of all errors that occur during document exchanges in Application Integration Framework (AIF). In the Exceptions form, you can view information about the module and subsystem where the error occurred and a description of the error. You can also view information about when the error was logged, the user who is associated with the error, and the form or business logic where the error occurred.

Procedure: View the Exceptions Log


To view the exception log , follow these steps: 1. Click System administration > Periodic > Services and Application Integration Framework > Exceptions.

2. On the Overview tab, select an exception record. 3. Click the General tab to view additional details about the exception.

7-8

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging


NOTE: If the log entry provides a resolution, the Resolve exception button can be used to resolve the exception. 4. Click Exception help to view more information about the exception, if more information is available.

Procedure: Clear the Exceptions Log


To clear the exceptions log, follow these steps: 1. Click System administration > Periodic > Services and Application Integration Framework > Exceptions. 2. On the Overview tab, select an exception record. 3. Press ALT+F9 to delete the exception record from the system. NOTE: You can use the SHIFT and CTRL keys to select multiple records in the list of exception records.

Starting and Stopping the Batch Job Services


For adapter-based exchanges, use the batch job functionality in Microsoft Dynamics AX to start and stop the following AIF services: AIFOutboundProcessingService AIFInboundProcessingService GatewaySendService GatewayReceiveService These services move messages into and out of the document processing queues. You might have to start and stop these services to troubleshoot issues or to change the settings for batch jobs, such as the recurrence. NOTE: If you want to run these batch processes instantly, while developing on AIF, you can create a job to run these classes.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-9

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Troubleshooting
The primary methods of troubleshooting Services and AIF are debugging and reviewing exception logs. This lesson provides instructions on debugging by using error logs.

Debugging Services
In Microsoft Dynamics AX, an example of a service is an X++ class that you can expose as a service by adding attributes to the class and its methods. Services that you create in Microsoft Dynamics AX are compiled into CIL and run on the server. Therefore, you must use the Visual Studio debugger to debug them. While developing a service class in X++, you can use the Microsoft Dynamics AX debugger to debug the functionality. Use Visual Studio to debug the code that calls the service. The following is the high-level process for debugging a service in Visual Studio: 1. In Visual Studio, open the project that calls the Microsoft Dynamics AX service. 2. In Application Explorer, locate the service operation that you are calling and then open the source code. 3. Set a breakpoint in the service code. 4. Attach the Visual Studio debugger to the Microsoft Dynamics AX server process (Ax32Serv.exe). 5. Press F5 to run the project. When the debugger reaches a breakpoint in the service, it will stop and you can then go through the service code. TIP: When debugging a service in Visual Studio, you cannot change the source code in the Visual Studio IDE. You must make the changes in X+ + and then deploy the integration port to regenerate the service .xpp files.

Demonstration: Create a Simple Application to Debug


To create a simple application to debug, follow these steps: 1. Open Microsoft Dynamics AX 2012. 2. Go to System administration > Setup > Services and Application Integration Framework > Inbound ports. 3. Select "LedgerServices" and then click Activate.

4. Click Start > All Programs > Microsoft Visual Studio 2010 > Microsoft Visual Studio 2010. 5. In Microsoft Visual Studio 2010, click File > New Project. 6. Select the Visual C# template.

7-10

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging


7. Select Console Application, enter a name for the project, and then click OK. 8. In Solution Explorer right-click references and then click Add service reference. 9. In Address, type "http://seadev:8101/DynamicsAx/Services/LedgerServices" and then click Go. 10. Click OK. 11. In Program.cs, replace "static void Main(string[] args) { }" with the following:
static void Main(string[] args) { ServiceReference1.GeneralJournalServiceClient client = new ServiceReference1.GeneralJournalServiceClient(); ServiceReference1.CallContext context = new ServiceReference1.CallContext(); context.Company ="ceu"; ServiceReference1.AxdLedgerGeneralJournal Journal = new ServiceReference1.AxdLedgerGeneralJournal(); ServiceReference1.AxdEntity_LedgerJournalTable[] tables = new ServiceReference1.AxdEntity_LedgerJournalTable[1]; ServiceReference1.AxdEntity_LedgerJournalTable table = new ServiceReference1.AxdEntity_LedgerJournalTable(); table.JournalName ="GenJrn"; tables[0] = table; Journal.LedgerJournalTable = tables; client.create(context, Journal); }

NOTE: Leave this project open for the "Debugging Services" demonstration.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-11

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Demonstration: Debugging Services
Use the following steps to debug a service. NOTE: This demonstration is dependent on the "Create a Simple Application to Debug" demonstration. 1. In Visual Studio, click View > Application Explorer. 2. In Application Explorer double-click Default > Classes > AxInternalBase > Save. 3. In AxInternalBase.save.xpp, right-click on the line public void save() and then click Breakpoint > Insert Breakpoint. 4. Click Tools > Attach to Process. 5. Select Show processes from all users and then select Show processes in all sessions. 6. In Available Processes, select Ax32Serv.exe and then click Attach. 7. In the "Attach Security Warning" dialog click Attach. 8. Wait until "Ready" is displayed in the lower left corner of Visual Studio. NOTE: The "AxInternalBase.Save.xpp" file will open and the breakpoint will be greyed out until the corresponding library is loaded. The breakpoint will not trigger until this is loaded. 9. Click View > Solution Explorer. 10. In Solution Explorer right-click your project and then click Debug > Start new instance. 11. Notice that AxInternalBase.save.xpp opens in a debugger.

7-12

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging


Common Error Messages
This topic describes how to troubleshoot common issues with document exchanges through the Application Integration Framework (AIF). Message Error message: Call to SSPI failed; see inner exception Details You can encounter this error message when you call a Microsoft Dynamics AX web service if Internet Information Services (IIS) is installed on a separate computer from the Application Object Server (AOS). In this case, if you view the inner exception, the message states, "Target Principal Name is incorrect." You can also encounter this issue when the AOS account is a user account on the domain. To resolve this issue, use the Setspn.exe Active Directory Domain Services management tool. Use the following command-line syntax: When you install web services on Internet Information Services (IIS), a record for the new website is added to the AifWebsites table. If you uninstall web services on IIS, this record is not deleted from the table. This record might cause a warning to be displayed if you reinstall web services on IIS. You can manually delete the record from the AifWebsites table or You must set the appropriate permissions for any new virtual directory in IIS so that Microsoft Dynamics AX can access the file share. The Microsoft Dynamics AX Web Service Administrators group must have full access to the new virtual directory and file share. If this group does not exist as a local group on the computer, you must create it. You must then add, as a user, the domain account If you activate or deactivate an integration port, all integration ports on the instance of AOS are reactivated. Do not activate or deactivate any integration port while messages are being processed.

Warning message: An error occurred while creating AifWebsites entry or Error message: Cannot create a record in Web sites (AifWebsites) Cannot access a web service

Message Processing is interrupted

Microsoft Official Training Materials for Microsoft Dynamics

Your use of

this content is subject to your current services agreement

7-13

Application Integration Framework and Services in Microsoft Dynamics AX 2012


Message File system adapter cannot open file Details Directories that are accessed by the file system adapter must grant appropriate access to the domain account under which the AOS runs. If the AOS runs under the NETWORK SERVICE account, you must grant permissions for that specific account. For example, granting full permissions to Everyone will not enable the file system adapter to access the files in the directory or network share that are accessed by the file system adapter if the AOS runs under the NETWORK SERVICE account. When defining a required element as part of a data policy, you must also select Validate document XML on the Processing options FastTab of the integration port. When XML validation is disabled, AIF does not apply data policies, which can cause unexpected results in This setting applies only when you use the file system adapter. You must be logged on to Windows Server as an administrator to add a new transform. For synchronous messages, use pipelines for preprocessing and post-processing of AIF messages. Use the AIFXmlTransform class as the pipeline component to apply XSLT transforms in the pipeline or to create a .NET Document filters are applied only to documents that have been configured for change tracking. Change tracking must be enabled for the database tables that the document service uses.

Data policies do not work

Open error in batched requests setting does not work Cannot add a new transform in the Manage transforms Transforms do not work with synchronous adapters

Document filters do not work

7-14

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging


Message Document versions are not logged Details Document versions are not logged for each integration-port-level transform. Document versions are logged only for pipeline components. For example, you can use an XSLT in a pipeline if you want to log the various document versions that are the result of transformations. To use this service operation, you must create at least one document filter. You can receive this error message when the timeout value that is specified in the Windows Communication Foundation (WCF) configuration is exceeded. To correct this problem, do not leave WCF connections open once you are finished using them. For example, be sure to call the Close method on client instances before they go out of scope. If you continue to experience timeout errors, change the timeout settings in the WCF adapter configuration in the The file system adapter in AIF does not support file types other than XML for outbound integration scenarios. Files that are handled by integration ports that use the file system adapter must use the .xml file-name extension for outbound

Service operation getChangedKeys returns no entity keys Error message: The open operation did not complete within the allotted timeout

Files that have filename extensions other than .xml do not work for outbound exchanges

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-15

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Lab 7.1 - Debugging Services


In this lab, you will debug a service. Scenario Simon, the System Implementer, wants to debug a service.

Challenge Yourself!
Use the provided information to debug a service.

Need a Little Help?


1. In Visual Studio, open the project that calls the Microsoft Dynamics AX service. 2. In Application Explorer, locate the service operation that you are calling and open the source code. 3. Set a breakpoint in the service code. 4. Attach the Visual Studio debugger to the Microsoft Dynamics AX server process (Ax32Serve.exe). 5. Press F5 to run the project. When the debugger reaches a breakpoint in the service, it will stop and you can then go through the service code.

Step by Step
NOTE: Lab 7.1: Debugging services has the same instructions as the Lesson: Troubleshooting demonstrations. 1. Open Microsoft Dynamics AX 2012. 2. Go to System administration > Setup > Services and Application Integration Framework > Inbound ports. 3. Select "LedgerServices" and then click Activate. 4. Click Start > All Programs > Microsoft Visual Studio 2010 > Microsoft Visual Studio 2010. 5. In Microsoft Visual Studio 2010, click File > New Project. 6. Select Console Application, enter a name for the project, and then click OK. 7. In Solution Explorer right-click references and then click Add service reference.

7-16

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging


8. In the Address field type "http://seadev:8101/DynamicsAx/Services/LedgerServices" and then click Go. 9. Click Ok. 10. In Program.cs replace "static void Main(string[] args) { }" with the following:
static void Main(string[] args) { ServiceReference1.GeneralJournalServiceClient client = new ServiceReference1.GeneralJournalServiceClient(); ServiceReference1.CallContext context = new ServiceReference1.CallContext(); context.Company ="ceu"; ServiceReference1.AxdLedgerGeneralJournal Journal = new ServiceReference1.AxdLedgerGeneralJournal(); ServiceReference1.AxdEntity_LedgerJournalTable[] tables = new ServiceReference1.AxdEntity_LedgerJournalTable[1]; ServiceReference1.AxdEntity_LedgerJournalTable table = new ServiceReference1.AxdEntity_LedgerJournalTable(); table.JournalName ="GenJrn"; tables[0] = table; Journal.LedgerJournalTable = tables; client.create(context, Journal); }

11. In Visual Studio, click View > Application Explorer. 12. In Application Explorer double-click Default > Classes > AxInternalBase > Save. 13. In AxInternalBase.save.xpp right-click on the line public void save() and then click Breakpoint > Insert Breakpoint. 14. Click Tools > Attach to Process. 15. Select Show processes from all users and then select Show processes in all sessions.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-17

Application Integration Framework and Services in Microsoft Dynamics AX 2012


16. In Available Processes, select Ax32Serv.exe and then click Attach. 17. In the Attach Security Warning dialog click Attach. 18. Wait until "Ready" is displayed in the lower left corner of Visual Studio. NOTE: The AxInternalBase.Save.xpp file will open and the breakpoint will be greyed out until the corresponding library is loaded. The breakpoint will not trigger until this is loaded. 19. Click View > Solution Explorer. 20. In Solution Explorer right-click your project and then click Debug > Start new instance. 21. Notice that AxInternalBase.save.xpp opens in a debugger.

7-18

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging

Summary
Troubleshooting Service and AIF in Microsoft Dynamics AX 2012 accommodates the refactor of services and enhanced capabilities. The troubleshooting capabilities in Services and AIF include: Correlating exceptions, ports, and messages in the exception log Providing error handling options for large imports Handling batched messaging Moving troubleshooting options to integration ports Providing a view into document history Providing a view to monitor documents in the queue Providing a way to view exceptions Debugging services by using Visual Studio 2010

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-19

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Test Your Knowledge


Test your knowledge with the following questions. 1. Categorize the following items: 1. Flexible error handling for large imports 2. Correlate exceptions, ports, and messages in the exception log 3. Document history 4. Queue manager 5. Exception log a. You can view information about the related port, message, and message set on the Exceptions form. b. Stores documents that are exchanged by using Application Integration Framework (AIF) and shows documents that are related to data in the Microsoft Dynamics AX database. c. A record of all errors that occur during document exchanges in Application Integration Framework (AIF). d. When large files are imported, error handling provides flexible options, such as continue, halt, and rollback. e. Displays information about messages in the Application Integration Framework (AIF) queues.

2. How is Visual Studio connected to Microsoft Dynamics AX 2012 to debug services? ( ) Automatically ( ) Attaching to Ax32.exe ( ) Attaching to Ax32Serv.exe ( ) Services are debugged by using the Microsoft Dynamics AX 2012 debugger 3. Which exchanges are affected by batch jobs that do not run? ( ) Adapter-based exchanges ( ) Web service exchanges

7-20

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

Chapter 7: Troubleshooting and Logging

Quick Interaction: Lessons Learned


Take a moment and write down three key points you have learned from this chapter 1.

2.

3.

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

7-21

Application Integration Framework and Services in Microsoft Dynamics AX 2012

Solutions
Test Your Knowledge
1. Categorize the following items: d 1. Flexible error handling for large imports a 2. Correlate exceptions, ports, and messages in the exception log b 3. Document history e 4. Queue manager c 5. Exception log a. You can view information about the related port, message, and message set on the Exceptions form. b. Stores documents that are exchanged by using Application Integration Framework (AIF) and shows documents that are related to data in the Microsoft Dynamics AX database. c. A record of all errors that occur during document exchanges in Application Integration Framework (AIF). d. When large files are imported, error handling provides flexible options, such as continue, halt, and rollback. e. Displays information about messages in the Application Integration Framework (AIF) queues.

2. How is Visual Studio connected to Microsoft Dynamics AX 2012 to debug services? ( ) Automatically ( ) Attaching to Ax32.exe () Attaching to Ax32Serv.exe ( ) Services are debugged by using the Microsoft Dynamics AX 2012 debugger 3. Which exchanges are affected by batch jobs that do not run? () Adapter-based exchanges ( ) Web service exchanges

7-22

Microsoft Official Training Materials for Microsoft Dynamics Your use of this content is subject to your current services agreement

You might also like