ax2012_enus_deviv_02.pdf

50
Chapter 2: Framework Features 2-1 CHAPTER 2: FRAMEWORK FEATURES Objectives The objectives are: Describe the concept of events and how they can be used in Microsoft Dynamics ® AX. Describe the various methods for integrating with Microsoft Dynamics AX. Describe the various types of services available in Microsoft Dynamics AX. Use a proxy class for .NET interop to X++. Access managed assemblies from X++. Explain how .NET Framework assemblies are deployed. Introduction There are many frameworks available in Microsoft Dynamics AX 2012. This chapter provides descriptions of some frameworks, subsystems and features in Microsoft Dynamics AX 2012. Frameworks are collections of design patterns, interfaces, and code that provide support to you as a developer. Eventing Eventing is a design pattern for customization that is designed to enable non- intrusive, maintainable customizations. This technology enables you to customize the system without extensively altering source code in the base application. Eventing enables customization behaviors to be implemented in event handlers. The event handler code is called in response to an event that is raised in the course of the business logic execution on the system. For more information about Eventing, refer to the "Event Handlers for Customization" topic in this chapter. Address System Addresses are handled by the Address subsystem. The global address book, or address subsystem, can help you understand the relationships among people and organizations that are associated with your organization. For example, a customer can also be a vendor in a marketing campaign, or a worker in your organization can also be a vendor. Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement

Upload: bachtiar-yanuari

Post on 01-Jan-2016

236 views

Category:

Documents


0 download

DESCRIPTION

dynamics Ax 2012 development 4 chapter 2

TRANSCRIPT

Page 1: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-1

CHAPTER 2: FRAMEWORK FEATURES Objectives

The objectives are:

• Describe the concept of events and how they can be used in Microsoft Dynamics® AX.

• Describe the various methods for integrating with Microsoft Dynamics AX.

• Describe the various types of services available in Microsoft Dynamics AX.

• Use a proxy class for .NET interop to X++. • Access managed assemblies from X++. • Explain how .NET Framework assemblies are deployed.

Introduction There are many frameworks available in Microsoft Dynamics AX 2012. This chapter provides descriptions of some frameworks, subsystems and features in Microsoft Dynamics AX 2012. Frameworks are collections of design patterns, interfaces, and code that provide support to you as a developer.

Eventing

Eventing is a design pattern for customization that is designed to enable non-intrusive, maintainable customizations. This technology enables you to customize the system without extensively altering source code in the base application.

Eventing enables customization behaviors to be implemented in event handlers. The event handler code is called in response to an event that is raised in the course of the business logic execution on the system.

For more information about Eventing, refer to the "Event Handlers for Customization" topic in this chapter.

Address System

Addresses are handled by the Address subsystem. The global address book, or address subsystem, can help you understand the relationships among people and organizations that are associated with your organization. For example, a customer can also be a vendor in a marketing campaign, or a worker in your organization can also be a vendor.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 2: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-2

NOTE: For more information about the address system refer to the "Global Address Book" topic in the Application Foundation Features chapter in this course.

Batch Journal Framework

The Batch Journal framework can be used to run a group of tasks that is created by using the RunBase framework.

TIP: There are individual tts transaction controls for each task.

The RunBase framework provides a standardized approach to creating processes and batch jobs in Microsoft Dynamics AX. The framework must be used for every job-style function in the application.

The framework is implemented by the RunBase application class and supplies many features that includes the following.

• Query • Dialog, with persistence of the last values entered by the user • Validate • Batch execution for users to schedule jobs. This functionality uses

the RunBaseBatch class and the pack() and unpack() methods with versioning.

• Progress bar • Run • Client/server-optimized

NOTE: For more information about the RunBaseframweowrk, refer to the RunBase Framework (http://go.microsoft.com/fwlink/?LinkId=238164) page on MSDN.

Business Operation Framework

The Business Operation Framework (BOF) follows the Windows Communication Foundation (WCF) protocols and standards. With the BOF you can do the following.

• Enables menu-driven execution or batch execution of services. • Calls services in synchronous or asynchronous mode. • Automatically creates a customizable user interface (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).

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 3: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-3

For more information about the BOF, refer to the "Business Operation Framework" topic in this chapter.

Consistency Check Framework

The Consistency Check Framework helps validate the consistency of the data in the production database and helps fix the inconsistencies that it finds.

The framework consists of classes that have names ending in "ConsistencyCheck" (for example, InventConsistencyCheck). Each of the framework classes extends the SysConsistencyCheck class.

Dimension

You can use the Dimension subsystem to work with financial dimensions. Use the InventDim subsystem to work with inventory dimensions.

For more information about the financial dimensions subsystem, refer to the "Dimensions" topic in the Application Foundation Features chapter.

Document Management System

The document management system is automatically available everywhere in Microsoft Dynamics AX. Text notes and documents of any type and size can be attached to any record in Microsoft Dynamics AX.

Note fields should not be put on your own tables, instead use the document management system's text notes.

NOTE: If documents attached to a record are stored on a file share instead of in the database in Microsoft Dynamics AX, you must make sure that the correct access levels are set.

Infolog

Information and messages to the user are located in the Infolog. It also contains contextual information and supporting Help and actions. For more information see the "Using the Infolog (http://go.microsoft.com/fwlink/?LinkId=238165)" page on MSDN.

Number Sequence

Microsoft Dynamics AX has a number sequence framework to generate alphanumeric number sequences that are used to identify transaction documents such as sales orders.

NOTE: For more information, refer to the Number Sequences chapter in this course.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 4: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-4

Operation Progress

You can inform the user that a process will take some time by using the Operation Progress framework.

BEST PRACTICE: Use a progress indicator during operations that take more than two seconds.

Use an hourglass mouse pointer if the process takes two to seven seconds.

Use a progress bar if the process takes eight seconds or more.

NOTE: For more information, see the "How to: Create Progress Indicators (http://go.microsoft.com/fwlink/?LinkId=238166)" page on MSDN.

Reporting

SQL Server Reporting Services (SSRS) is the primary reporting platform for Microsoft Dynamics AX. The default, out of the box reports provided with Microsoft Dynamics AX run on the Reporting Services platform. The new report development environment takes advantage of extended SQL Server tools and components. The report development environment is fully integrated into Microsoft Visual Studio®.

NOTE: For more information, refer to the Reporting chapter in this course.

Application Integration

The capability to integrate Microsoft Dynamics AX with other systems inside and outside the enterprise is a common requirement. Application Integration Framework (AIF) provides this capability by enabling the exchange of data through formatted XML. This formatted XML is referred to as a document, and each document contains data and business logic. Documents are based on a document class and defined by using Microsoft Dynamics AX.

Microsoft Dynamics AX is shipped together with many standard document services that support common business processes. By using the capabilities that AIF provides, you can also customize existing document services or create your own document services.

NOTE: For more information about services, AIF, and the BOF, refer to the Application Integration Framework and Services in Microsoft Dynamics® AX course.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 5: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-5

Event Handlers for Customization This topic describes the concept of events and how they can be used in Microsoft Dynamics AX.

Microsoft Dynamics AX is rarely used without modification, because customers have their own set of requirements to implement the product. Because of this, partners have customized the product and this translates into costs for the customer. Partners also invest significant time in browsing and understanding the source code that is provided by Microsoft. When customization is needed, the partner modifies the code in the customer’s layer, and the runtime engine guarantees that the customization occurs. However, a problem exists because the customizations can be broken when Microsoft restructures code in a lower layer of the product when a newer version is released, and fixing customizations for the next version upgrade can be expensive for partners. Additionally, when a customer uses several Independent Software Vendors (ISVs) or partners there can be modifications to the same objects. When there are overlapping objects, this causes the same problem.

You can reduce the cost of creating and upgrading customizations by using events. Developers creating code customized by other users should create events in places where customizations typically occur. Then, those developers customizing the original functionality in another layer can subscribe to an event. When the customized functionality is tied to an event, the underlying application code can be rewritten and it will have little effect on the customization, because the same events are raised in the same sequence from one version to the next.

The Nature of Events

Object oriented programming paradigms map easily to the problem domains they try to model. For example, classes are entities that represent something in real life, and the names selected are typically accounts, people, and customers. Methods are used to change objects, and the names selected specify what operation is performed on the objects, such as deposit, hire, and invoice.

An event represents something that happens inside an object. Applicable event names are typically in the past, such as deposited, hired, and invoiced. Events will always occur, some are outside the scope of interest and some require taking action.

You can use events to support the following programming paradigms.

• Observation: Events can be used to look for exceptional behavior and generate alerts when such behavior occurs. An example of this type of event is regulation compliance systems. For example, if more than a designated amount of money is transferred from one account to another, the system triggers a workflow that asks for acceptance of the transaction.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 6: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-6

• Information dissemination: Events can deliver the correct information to the appropriate consumers at the most suitable time. Information dissemination is supported by publishing an event to anyone that wants to react to it.

• Decoupling: Events produced by one part of the application can be consumed by a completely different part of the application. There is no need for the producer to be aware of the consumers, nor do the consumers have to know details about the producer. One producer's event can be acted upon by any number of consumers. On the other hand, consumers can act upon any number of events from many producers.

TIP: There are some differences in how X++ and C# implement the event design pattern. For more information, refer to the "X++ and C# Comparison: Event (http://go.microsoft.com/fwlink/?LinkId=238167)" page on MSDN.

Terminology

X ++ events in Microsoft Dynamics AX 2012 are modeled after .NET eventing concepts. The following table lists the terms in Microsoft Dynamics AX 2012 related to events.

Term Definition Producer The producer is the logic that contains the code that

causes a change. It is an entity that emits events.

Consumer The consumer is the application code that represents an interest in being notified when a specific event occurs. It is an entity that receives events.

Event An event is a representation of a change that happened in the producer.

Event payload The event payload is the information the event carries with it. When a person is hired, for example, the payload might include the employee's name and date of birth.

Delegate A delegate is the definition of the information passed from the producer to the consumer when an event occurs.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 7: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-7

Coded Events

In X++, you can add delegates as members of a class. The syntax for defining a delegate is the same as the syntax used for defining a method, except for the following.

• The "delegate" keyword is used. • No "public" or any other accessibility specifier is allowed. • The return type must be "void." • The body must be empty; meaning, it cannot contain declarations or

statements.

For example, a delegate for an event that is raised when a person is hired could be expressed as follows.

delegate void hired(str name, UtcDateTime startingDate) {

}

TIP: You can right-click a class and select New > Delegate to create a new delegate or you can click the New icon from the Code Editor and type the code.

The following figure shows a class named HireWorkerEventSample that includes a delegate called hired that accepts a string and a date.

FIGURE 2.1 CLASS WITH DELEGATE SAMPLE

TIP: The lightning bolt icon indicates that this is a delegate and not an X++ method.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 8: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-8

When the application code has to signal that a new person is hired, it uses the delegate as a method call, supplying the event payload as parameters, as shown in the following code sample.

{ while select * from Employees where Employees.hiredDate == today { this.hired(employees.Name, employees.FirstWorkingDay); } }

NOTE: The code sample provided is only an example. This code will not compile in Microsoft Dynamics AX because there is no Employee table.

The parameters that are defined in the parameter profile can be any type allowed in X++. It is useful to pass an object instance, and to have the handlers modify the state of that object, so that the publisher can ask for values from the subscribers. Event handlers are run within the caller's transaction context. Subscribers can be added to the event in one of two ways—through modeling for example, in the Application Object Tree (AOT) or through X++ code execution.

Automatic Events

Automatic events are triggered by the environment as the result of something occurring. Currently, a developer can indicate an event is triggered when a method is called. This is described in the following sections.

Pre and Post are predefined events that occur when methods are called. The pre-event handlers are called before the execution of the designated method, and the post-event handlers are called after the method call has ended. It might be useful to understand this to augment the existing method with methods called before and after the normal body, as shown in the following figure.

Calls to the pre- and post-event handlers are inserted into the code generated for the delegate when that delegate is compiled. Therefore, there is no overhead penalty incurred by accessing metadata at runtime. In other words, the additional code in the pre and post handlers has the same overhead as adding the same code into the original method.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 9: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-9

The example in the following figure also demonstrates that if an exception is thrown in any of the pre-event handlers, neither the remaining handlers nor the method itself is invoked. If a method that has pre-event and, or post-event handlers throws an exception, the remaining post-event handlers are not invoked. If an exception is thrown in a post-event handler, the remaining handlers are not called. In any case, the exception propagates back to the caller as normal.

FIGURE 2.2 METHODS WITH AND WITHOUT HANDLERS

Each of the pre-event handlers can access the original values of the parameters and modify them as required. The post-event handlers can modify the return value of the called method.

Event Handlers

Event handlers are the methods that are called when the delegate is called, either directly through code (for the coded events) or from the environment (in the modeled events). The relationship between the delegate and the handlers can be maintained in the code or in the AOT.

Adding Handlers in the AOT

A developer must identify a static method to handle the event on the delegate. Only static methods can be used in this context. Event handlers can be added to the delegate by dragging the event handler to the delegate node that represents the event to be handled. The handler can be removed by using the Delete menu item available for any node in the AOT.

Adding Handlers in Code

Event handlers can be added to or removed from events by using special X++ syntax. The delegate name appears on the left side of the += (for adding) or the -= (for removing) operator. On the right side the keyword eventhandler is given, together with the qualified name of the handler to add or remove. The compiler will check that the parameter profiles of the delegate and the handler match.

You can subscribe to methods as event handlers in two locations in the AOT—under a delegate node or under a method node.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 10: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-10

Under a Delegate Node

A class node, such as AOT > Classes > MyClass, can have delegate nodes directly underneath it. The following rules apply to delegates in the AOT.

Under a Method Node

In the AOT, you can assign a method as an event handler for the pre-method event or the post-method event of another method. The event handler subscribes to an event of the host method.

The nodes that represent the subscription of an event handler to a host method are underneath the node for the host method. AOT elements such as classes, tables, and forms can have methods.

NOTE: Event handlers cannot subscribe to the classDeclaration of a class because they are not methods.

All event handlers that subscribe to a method must return void. Event handlers for host methods can use one of two parameter signatures.

• One parameter of the type XppPrePostArgs. • The same parameters that are on the host method that the event

handler subscribes to.

Procedure: Add an Event Handler in the AOT

To add an event handler in the AOT, follow these steps.

1. Create a new class that contains a delegate. 2. Create a new class that contains a static method with the logic to be

run. 3. Right-click the delegate and select New Event Handler Subscription. 4. Set the following properties on the event handler that is created:

a. Name = MyEventHandler b. Class = the class that you created in step 2.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 11: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-11

c. EventHandlerType = X++ d. Method = the static method that you created in step 2.

FIGURE 2.3 X++ EVENT HANDLER ADDED TO MYDELEGATE

Procedure: Add an Event Handler in Code

To add a static method event handler in code, follow these steps.

1. Create a new class that contains a delegate. 2. Create a new "subscriber" class that contains a static method with the

logic to be run. 3. Create a new static method in the class that contains the delegate. 4. Add code to the method to call the subscriber class. Use the

following code sample to guide you.

To add an instance method event handler in code, follow these steps.

1. Create a new class that contains a delegate. 2. Create a new "subscriber" class that contains an instance method

with the logic to be run. 3. Create a new instance method in the class that contains the delegate. 4. Add code to the method to call the subscriber class. Use the

following code sample to guide you.

private void AddStaticHandler() { this.MyDelegate += eventhandler (Subscriber::MyHandler); }

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 12: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-12

private void AddInstanceHandler() { Subscriber s = new Subscriber(); this.MyDelegate += eventhandler (s.InstanceHandler); }

Pre and Post Event Handlers

An event handler that is underneath a method node can run before or after the method runs. You control the timing by setting the CalledWhen property on the event handler node. The CalledWhen property has two values.

• Pre: The event handler runs before the method starts. • Post: The event handler runs after the method ends.

NOTE: In Microsoft Dynamics AX 2012, there is no option to assign pre and post event handlers to methods programmatically.

The XppPrePostArgs Class Parameter

A pre-method event handler that has only an XppPrePostArgs parameter can inspect and change the values of the parameters. The changes take effect before the parameters are passed to the host method that is being called. View the getArg and setArg methods.

When an XppPrePostArgs object is used, the values of the parameters and the return value can be changed by the event handler. The values can be changed even if the parameters and return type are value types, such as an integer or string. If a parameter or a return type is a reference to an object, the event handler can call methods on the object and could change the state of the object.

Matched Parameters without XppPrePostArgs

A pre-method or post-method event handler can have the same parameter signature as the host method that it subscribes to. This is the alternative to the event handlers having just one parameter of type XppPrePostArgs.

There are two types of parameters that are treated differently by event handlers:

• Value types, such as an integer or string • Reference types, such as an instance of a class

A pre-method event handler receives the same parameter values that the host method receives. However, this event handler cannot modify the value of any value type parameters that refer to the host method.

A post-method event handler receives the same parameter values that the host method received. However, this event handler does not receive the return value from the host method.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 13: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-13

Demonstration: Modify Parameter Values in a Pre-Method Event Handler

In Microsoft Dynamics AX, you can assign a static method to be an event handler that starts and ends immediately before a specific method on a class ends. This is known as a before-method event handler, or a pre-method event handler. In the AOT you assign the event handler as a node under the method node. The CalledWhen property on the event handler node must be set to Pre.

The before-method event handler can modify the parameter values that are passed by the caller method, before the called method receives them. To modify the pre-method event handler, follow these steps.

1. Create a new Class named TestClass. 2. Create a new method on the TestClass and use the following code

sample.

// Called by the job later in this example. public str formatWholeName (str _firstName, str _lastName) { return _lastName + ", " + _firstName; }

3. Create a new static method for the event handler and use the following code sample.

// CalledWhen = Pre. static public void formatWholeNameEhBefore(XppPrePostArgs ppArgs) { str firstName; firstName = ppArgs.getArg("_firstName");

if ("Dave" == firstName) { ppArgs.setArg("_firstName", "David"); } else if ("Bill" == firstName) { ppArgs.setArg("_firstName", "William"); } }

4. Save the class. 5. Right-click the formatWholeName method and select New Event

Handler Subscription. 6. In the Properties window, set the following properties:

a. Name = PreHandler b. CalledWhen = Pre c. Class = TestClass

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 14: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-14

d. EventHandlerType = X++ e. Method = formatWholeNameEhBefore

7. Create a new job to run the new class and call the method. Use the

following code sample.

static void NameBefore(Args _args) { TestClass testClass; str formattedWholeName; testClass = new TestClass();

// Run a method that has a pre-method event handler, // one that starts and ends before the method starts. formattedWholeName = testClass.formatWholeName ("Dave", "Ahs");

// The Infolog displays the effect of the before-method event handler. info(strFmt ("%1 == the formatted formal name.", formattedWholeName)); }

/*** Output displayed in the Infolog: Ahs, David == the formatted formal name. ***/

8. Save the job, and then click Run.

Demonstration: Modify the Return Value in a Post-Method Event Handler

You can assign a static method to be an event handler that starts when a specific method on a class ends. This is known as an after-method event handler, or a post-method event handler. In the AOT, you assign the event handler as a node under the method node. The CalledWhen property on the event handler node must be set to Post.

The post-method event handler can modify the return value of the completed method, before the return value is given to the method caller.

1. In the TestClass created as a part of the "Modify Parameter Values in a Pre-Method Event Handler" demonstration, create a new method and use the following code sample.

public int numberOfExpectedAttendees (int _numOfInvites, int _numOfDeclines) { return _numOfInvites - _numOfDeclines; }

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 15: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-15

2. Create a new static method for the event handler and use the following code sample.

// CalledWhen = Post. static public void numberOfExpectedAttendeesEhAfter (XppPrePostArgs ppArgs) { int intAttendees; intAttendees = any2Int(ppArgs.getReturnvalue()); info(strFmt("%1 = intAttendees raw, in event handler.", intAttendees)); if (0 > intAttendees) { intAttendees = 0; ppArgs.setReturnValue(intAttendees); } }

3. Save the class. 4. Right-click the numberOfExpectedAttendees method and select

New Event Handler Subscription.5. 5. In the Properties window, set the following properties:

a. Name = PostHandler b. CalledWhen = Post c. . Class = TestClass d. . EventHandlerType = X++ e. . Method = numberOfExpectedAttendeesEhAfter

6. Create a new job to run the class and call the method. Use the following code sample.

static void Job2ReturnTestEhAfter(Args _args) { TestClass testClass9; int attendeeCountReturned; testClass9 = new TestClass();

// Run a method that has an event handler that starts after the method finishes. attendeeCountReturned = testClass9.numberOfExpectedAttendees(8, 13);

// The Infolog output displays the effect of the after-method event handler. info(strFmt ("%1 == the number of expected attendees.", attendeeCountReturned)); }

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 16: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-16

/*** Output displayed in the Infolog: 0 == the number of expected attendees. ***/

7. Save the job, and then click Run.

Tips for Events

When you consider working with events

• Define events the programmers customizing the behavior of the system should react to. You should identify natural customization points and use events to publish the relevant information to subscribers.

• Maintain the semantics implied by the event from one version to the next. Part of the usefulness of events comes from the preservation of the semantics of the events. As soon as an interface is defined, third parties will be able to leave their existing code unmodified if the semantics are left unchanged (even though the implementation behind might be modified).

• Document the events that you create well because this will help anyone who is performing the customization later.

• Favor defining events over creating pre and post events on methods. Events are strong interfaces, whereas methods are an implementation artifact—a method's responsibilities and parameters can change over time, and they can disappear completely if the developer so decides.

When you consider working with events do not

• Try to raise an event from outside the class in which the event is defined. The X++ compiler disallows raising events from outside the class by design.

• Make customizations that rely on the order in which event handlers are executed. No guarantees are made by the runtime environment about the order in which the event handlers are called.

Integration with Microsoft Dynamics AX Integration is the development pattern that involves enabling existing applications (not written exclusively for Microsoft Dynamics AX) to interact and work with Microsoft Dynamics AX across process boundaries. An example of integration is when a value added reseller (VAR) integrates with an existing legacy Customer Relationship Management (CRM) system to synchronize the customer list between Microsoft Dynamics AX and the legacy CRM system.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 17: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-17

Much of Microsoft Dynamics AX functionality is contained in X++ classes. The programming models are how you access that functionality. The following programming models are supported in Microsoft Dynamics AX 2012:

• X++ development • .NET languages development with weakly typed .NET interop to

X++ (Also referred to as .NET Business Connector) • .NET languages development with strongly typed .NET interop to

X++ (Also referred to as .NET Proxies) • Services

The integration components in all these methods interact with the Application Object Server (AOS), shown in the following figure.

FIGURE 2.4 MICROSOFT DYNAMICS AX INTEGRATION TECHNOLOGIES

IMPORTANT: Integrations to external systems are best implemented by using the services programming model. Although the weakly typed and strongly typed .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 together 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.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 18: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-18

The following topics provide further descriptions of each programming model.

X++ Development

X++ development is the programming model in which the developer directly adds or alters Microsoft Dynamics AX metadata and/or X++ source code. This model provides complete access to all the base functionality implemented in the lower layers in the system. This is the most commonly used programming model in Microsoft Dynamics AX development.

Advantages:

• The most powerful programming model because it provides complete access to all functionality in the system.

• Precise and fine-grained control over the scope of customizations.

Disadvantages:

• Steeper learning curve for .NET developers.

Weakly Typed .NET Interop to X++

The Business Connector presents a comprehensive but weakly typed programming model to access all the Microsoft Dynamics AX metadata and X++ business logic from .NET. This is the only mechanism available for .NET to X++ interop in Microsoft Dynamics AX 2009 and earlier versions. This model continues to be available and supported in Microsoft Dynamics AX 2012.

Advantages:

• Opens up Microsoft Dynamics AX development to the .NET community.

Disadvantages:

• Weakly typed programming model abstraction results in most problems being found at run time rather than at design time, which can lead to increased total cost of ownership (TCO).

Strongly Typed .NET Interop to X++

In Microsoft Dynamics AX 2012, the Visual Studio Tools provides access to a strongly typed programming model for Microsoft Dynamics AX metadata and X++ business logic. This is achieved through the generation of strongly typed .NET proxies on top of the newest version of the Business Connector.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 19: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-19

Advantages:

• Adapts Microsoft Dynamics AX development seamlessly into the .NET paradigm.

• Strongly typed programming model. • Results in more maintainable code. • Precise and targeted access to the Microsoft Dynamics AX system

functionality needed.

Disadvantages:

• Requires redistribution of Business Connector assemblies with the consuming .NET application.

• Not firewall friendly due to underlying dependency on Remote procedure call (RPC) protocols.

Services

Exposes Microsoft Dynamics AX functionality through WS-* standards-compliant service interfaces. In addition to exposing functionality through services that ship with Microsoft Dynamics AX 2012, Microsoft Dynamics AX 2012 also provides declarative language constructs (X++ attributes) and development tools so that you can quickly expose existing X++ business logic as services without additional coding.

Advantages:

• Standards-based service interfaces enable widening reach to many platforms, such as mobile platforms.

• Strongly typed programming model. • Firewall friendly. • We recommend that you use "chunky" interfaces that have fewer

methods that enable you to send the required data in fewer, larger, chunks, when possible.

• Runs in Common Intermediate Language (CIL) which provides the advantages of being able to run on any platform that supports CIL and improved security and reliability because the code is verified for safety at runtime.

Disadvantages:

• Typically, coarse-grained chunky service interfaces limit precision of functionality exposure--you may need to use a less specific method to meet your needs.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 20: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-20

Application Integration Framework

AIF provides an extensible framework within Microsoft Dynamics AX that enables the exchange of data. AIF consists of three primary components.

• Services: With AIF you can expose any business logic as a service to be consumed by other applications. Within Microsoft Dynamics AX you can create, customize, and publish services.

• Document services: A specific implementation of services in which the Microsoft Dynamics AX business logic is exposed through document services. Document services are typically used to exchange data with other systems.

NOTE: For more information about standard document services and how to create your own document services, refer to the Services and AIF development (http://go.microsoft.com/fwlink/?LinkId=238168) page on MSDN.

Document services exchange data in the form of XML documents. Document services provide the tools to build business-to-business (B2B) and application-to-application (A2A) integration between your system and trading partners or other external software systems. AIF includes many services that encapsulate common business functionality that you can use out of the box. Additionally, there is a wizard that you can use to create your own custom document services.

AIF document services have the following types of exchanges.

• Adapter-based exchange: An asynchronous document exchange that uses an adapter in Microsoft Dynamics AX. In this type of exchange, documents are moved through the system in queues and processed by the batch jobs. Adapter transports supported by AIF are Microsoft Message Queuing (also known as MSMQ) and file systems. If you use the Message Queuing adapter, you must have Message Queuing or installed on the AIF gateway computer.

• Web services-based exchange: A synchronous document exchange that uses web services. Because this type of exchange is synchronous, queues are not used. The web services can be generated automatically from the Microsoft Dynamics AX business logic. Developers with limited web experience can easily expose services through web services. AIF supports WCF services.

TIP: Internet Information Services (IIS) only needs to be installed if you are configuring an “Enhanced Inbound Port”. IIS is not required for basic ports, because they are hosted by the AOS itself.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 21: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-21

Microsoft Dynamics AX supports integration with the Application Integration Framework (AIF) components by using the Microsoft Dynamics AX services 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 option for customization and programmability, 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. The types of services are developed by using the Business Operation Framework (BOF). This is done by creating X++ classes that expose their logic through the use of attributes available within the BOF.

• 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 standard document services do not 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" are used interchangeably.

• System Services cannot be customized. The Query Service, Metadata Service, and User Session Service are Windows Communication Foundation (WCF)-based 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 consume external web services from X++ code, and consume web services hosted by Microsoft Dynamics AX from .NET Framework languages such as Microsoft Visual C#.

Microsoft Dynamics AX supports application integration and data exchange in both intranet and Internet-facing scenarios. Services that are based on WCF classes are hosted on the AOS for applications to integrate within the intranet of a company. To consume or expose services over the Internet, you must install and use IIS. For more information about Microsoft Dynamics AX web services on IIS refer to the Install web services on IIS (http://go.microsoft.com/fwlink/?LinkId=238169) page.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 22: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-22

Business Operation Framework

The Business Operation Framework (BOF) is the model-view-controller framework that synchronously or asynchronously controls the execution of immediate or batched business operation implementations. It lets you run services on Microsoft Dynamics AX by using the Windows Communication Foundation (WCF) framework.

BOF uses services to call from the client to the server so application “chattiness” is reduced. The BOF classes separate the user interface, business logic, and data contract logic. You can use BOF to write applications that have reduced client to server communication. Because BOF uses services, there is no calling from the client back to the server, and an open connection from the server to the client cannot be maintained. The user interface for input parameters can be auto-generated.

Features of the BOF include the following.

• Allows menu-driven execution or batch execution 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).

To create a Business Operation Framework service, you must follow these steps.

• Create a data contract class. • Identify the parameters that are passed to the service. • Register the class as a Business Operation Framework service. • Optionally customize the automatically generated UI for the class.

NOTE: For more information about services, AIF, and the BOF, refer to the Application Integration Framework and Services in Microsoft Dynamics® AX course.

NOTE: Additional examples of how to use the BOF can be found in the Workflow and Reporting chapters later in this course.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 23: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-23

Interop to X++ A proxy class is a .NET Framework class that provides access to one X++ item type of Microsoft Dynamics AX. You can build proxies for the following X++ item types:

• Classes: Both application and system classes. • Tables: Both application and system tables. • Enums: Both base and system enums.

CAUTION: You cannot build a proxy for an X++ interface. If you try, a proxy is generated for a .NET Framework class which at best approximates the interface. This incorrect translation into a class causes some common scenarios to fail, and it might create problems in future releases.

You can generate the proxy C# or Visual Basic source code by using the Application Explorer in Microsoft Visual Studio. Proxies are usually a better alternative to .NET Business Connector. .NET Business Connector requires your C# code to use a late-bound programming model. Proxies provide an early-bound programming model. With the early-bound model the Code Editor can provide IntelliSense, and it can also catch misspellings and other errors at compile time, that is, before the code is run.

There are different scenarios for constructing a proxy object from a proxy class that is written in C# or in another .NET Framework language. The following topics describe three possible scenarios.

Scenario: Implicit Construction by Parameter Passing

This scenario starts when an X++ job passes an X++ DictClass object to a C# method. The C# method takes a parameter type of a proxy for the X++ class DictClass. The system performs the marshaling by automatically constructing a proxy object from the DictClass object.

The X++ Job

static void StartInteropFromXppJob2a(Args _args) // X++ { DictClass dictClass2; int classId; str className;

classId = classnum(DateTimeUtil); dictClass2 = new DictClass(classId);

// Initiate interop from X++. className = CSharpDll.CSharpClass::CalledFromXppDc(dictClass2);

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 24: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-24

info(strFmt("%1 , %2", classId, className)); } /*** Output copied from the Infolog: 64900 , DateTimeUtil ***/

The C# Method

using System; // C# namespace CSharpDll { public class CSharpClass { static public string CalledFromXppDc (DictClass pxyDictClass) { return pxyDictClass.name(); } } }

Scenario: Use a Proxy Object as Input to Construct a Copy in a Different Namespace

A C# application can have two proxy classes to the same X++ class, because the two proxies could have different namespaces. This section describes a scenario where you construct an instance of one proxy from an instance of the other, despite the namespace difference.

In the following example, at run time your C# code has an instance of the proxy class Finance.TownBank. But your code must pass an Economics.TownBank object to a method. The namespaces do not match.

The solution is to construct an instance of the Economics.TownBank proxy class from the Finance.TownBank object. Your C# code can use the following proxy constructor for this.

public Bank(Microsoft.Dynamics.AX.ManagedInterop.Object axObject)

After the constructor is called, both proxies reference the same TownBank object in Microsoft Dynamics AX. If one proxy changes the state of the underlying TownBank X++ object, the other proxy sees the changes.

// C# method to create a proxy object from an equivalent proxy object. using System; public class TestTheProxy3 { public void CloneAProxy(Finance.TownBank finBank) { Economics.TownBank ecoBank; Economics.AuditManager auditMgr;

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 25: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-25

// Constructor call. ecoBank = new Economics.TownBank(finBank);

auditMgr = new Economics.AuditManager(); // Use the copy of the proxy, ecoBank. auditMgr.AuditABank(ecoBank); } }

NOTE: This code sample is theoretical and will compile if pasted directly into a C# Class Library. Additional code would be required for this example to work.

Scenario: Construct a Session Object in C#

A C# .exe program that is started from the console can construct an instance of the Microsoft.Dynamics.AX.ManagedInterop.Session class. Then the C# code can call the constructor on a proxy class.

The first step is to create the class library in Visual Studio. After you have created the class library project, you can then add a Microsoft Dynamics AX table to the project. Then you can create class methods that access that table.

In Visual Studio, you use Application Explorer to add an X++ element to a managed code project. This walkthrough illustrates the following tasks:

• Creating the class library, adding a Microsoft Dynamics AX table to the project, and accessing that table from code.

• Creating a console application project and testing the generated assembly.

To create the class library

1. To create a new class library project, click File > New> Project. 2. Under the Installed Templates tree, click Visual C# > Windows,

select the Class Library project type and then click OK. 3. Save the new project. 4. Add the project to the AOT by clicking File > Add ClassLibrary1

to AOT. Notice that the project icon changes in Solution Explorer. Alternatively, you can right-click the ClassLibrary1 project and click Add ClassLibrary1 to AOT.

To add a Microsoft Dynamics AX table to the project

1. Open the Application Explorer by clicking View > Application Explorer. Click the Data Dictionary > Tables node and locate the CustTable table.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 26: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-26

2. Click the CustTable table and drag it onto the project in Solution Explorer. Alternatively, you can right-click the table and then click Add to Project. In Solution Explorer, you can view the table and the proxy to the CustTable table that is created internally by the system. In the References node, you can view a reference to the assembly Microsoft.Dynamics.Ax.ManagedInterop.

TIP: You can add a system table or system class to your Visual Studio project even if the interface does not support the dragging of system objects. For example, to add the FormRun system class, first add any application class, such as the Bank class. Then rename the new proxy node from Class.Bank.axproxy to Class.FormRun.axproxy.

To create methods that use the table

Open the Class1.cs file and add the following code. This code contains two methods that each take two parameters and return data for the specified customer.

///C# code:

using System; namespace ClassLibrary1 { public class Class1 { public string GetCustomerPaymentMode(string accountNum, string dataAreaId) { string paymentMode = String.Empty; CustTable custTable = new CustTable(); // Search for the customer. custTable = CustTable.findByCompany(dataAreaId, accountNum); if (custTable.Found) { // Get the value for the customer's payment mode. paymentMode = custTable.PaymMode; } return paymentMode; } public bool GetCustomerCreditLimit(string accountNum, string dataAreaId) { bool hasCreditLimit = false; CustTable custTable = new CustTable(); // Search for the customer. custTable =

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 27: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-27

CustTable.findByCompany(dataAreaId, accountNum); if (custTable.Found) { // Get the value for whether the customer has a credit limit. hasCreditLimit = (custTable.MandatoryCreditLimit == NoYes.No ? false : true); } return hasCreditLimit; } } }

To create a console application project to test the assembly

1. In Solution Explorer, right-click the solution ClassLibrary1 and select Add > New Project.

2. Under the Installed Templates tree, click Visual C# > Windows, select the Console Application project type and then click OK.

3. In Solution Explorer, add a reference to the ClassLibrary1 project by right-clicking the References node under the ConsoleApplication1 project and then clicking Add Reference.

4. Click the Projects tab, select the ClassLibrary1 project and then click OK.

5. In Solution Explorer, add a reference to the managed interop assembly by right-clicking the References node under the ConsoleApplication1 project and then clicking Add Reference.

6. Click the Browse tab, locate the Microsoft.Dynamics.AX.ManagedInterop assembly and select OK. This assembly is located in the Client\Bin directory. For example, C:\Program Files (x86)\Microsoft Dynamics AX\60\Client\Bin. This reference is necessary to use the Session object.

To call methods to display output to the console application

1. Open the Program.cs file and add the following code. This code calls the GetCustomerPaymentMode and the GetCustomerCreditLimit methods from the class that you created and displays the values in the console window.

using System; using ClassLibrary1; using Microsoft.Dynamics.AX.ManagedInterop;

namespace ConsoleApplication1 { class Program { static void Main(string[] args) {

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 28: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-28

// Create a session using (Session session = new Session()) { session.Logon(null, null, null, null);

Class1 class1 = new Class1(); string accountNum ="3003"; string dataAreaId ="ceu"; string paymentMode = String.Empty; string hasCreditLimitText = String.Empty; bool hasCreditLimit;

// Find the customer payment mode and credit limit. paymentMode = class1.GetCustomerPaymentMode(accountNum, dataAreaId); hasCreditLimit = class1.GetCustomerCreditLimit(accountNum, dataAreaId); hasCreditLimitText = (hasCreditLimit == false ? " and does not have" : " and has");

// Write the data to the console Console.WriteLine("Customer " + accountNum + " in company " + dataAreaId + " has a payment mode of " + paymentMode + hasCreditLimitText + " a mandatory credit limit." ); Console.ReadLine(); } } } }

2. In Solution Explorer, set the console application to be the startup project by right-clicking ConsoleApplication1 and then clicking Set as StartUp Project.

To test the generated assembly

Run the application. If you have the sample data installed, the following output will appear in the console window.

Customer 3003 in the CEU company has a payment mode of CHCK and does not have a mandatory credit limit.

TIP: You might receive an error about the .NET target framework because both projects target the .NET Framework 4 by default but the Microsoft.Dynamics.AX.ManagedInterop assembly is a mixed-mode assembly that targets the 2.0 runtime.

To resolve this error, you have two options— you can change the target framework for both projects to .NET Framework 3.5 or you can add an attribute

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 29: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-29

to the app.config file of the console application project. To change the target framework, right-click each project in Solution Explorer and then click Properties. In the Target framework field, select .NET Framework 3.5.

If you want the console application project to target the .NET Framework 4, add the useLegacyV2RuntimeActivationPolicy attribute to the startup element in the app.config file and set it to true. For example, <startup useLegacyV2RuntimeActivationPolicy="true">.

.NET Target Framework Error

You might receive an error about the .NET target framework because both projects target the .NET Framework 4 by default. However, the Microsoft.Dynamics.AX.ManagedInterop assembly is a mixed-mode assembly that targets the 2.0 runtime. To resolve this error, you have two options— you can change the target framework for both projects to .NET Framework 3.5 or you can add an attribute to the app.config file of the console application project.

To change the target framework, right-click each project in Solution Explorer and then click Properties. In the Target framework field, select .NET Framework 3.5.

If you want the console application project to target the .NET Framework 4, add the useLegacyV2RuntimeActivationPolicy attribute to the startup element in the app.config file and set it to true. For example, <startup useLegacyV2RuntimeActivationPolicy="true">.

Proxies and Exception Mapping

When an X++ object throws an exception, the exception value is an integer element from the X++ Exception enum. If the X++ object is being managed by a proxy object in the .NET Framework, the thrown element value of the enum is automatically marshaled into an instance of a .NET Framework exception class. This class is designed to represent the enum element.

Name Pattern

There is a pattern of name correspondence between values of the X++ Exception enum and the .NET Framework exception classes that represent the enum values. There are 15 elements in the Exception enum. The following table shows three examples of the pattern. For example, the last row in the table shows that the enum element and the exception class are both named with the word Deadlock.

X++ Exception enum element

Word in common

.NET Framework exception class

Exception::Error Error Microsoft.Dynamics.AX.ManagedInterop.ErrorException

Exception::Warning Warning Microsoft.Dynamics.AX.ManagedInterop.WarningException

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 30: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-30

X++ Exception enum element

Word in common

.NET Framework exception class

Exception::Deadlock Deadlock Microsoft.Dynamics.AX.ManagedInterop.DeadlockException

Inheritance Hierarchy of the .NET Exception Classes

The following indented list of .NET exception classes shows the inheritance hierarchy of the ErrorException class. This is one of the exception classes that a proxy object might encounter if the underlying X++ object has a problem. The inheritance hierarchy is the same for the other exceptions such as Microsoft.Dynamics.AX.ManagedInterop.WarningException.

FIGURE 2.5 INHERITANCE HIERARCHY

Exceptions Note from the X++ Object

A proxy object can encounter exceptions that are not related to the behavior of its underlying X++ object. For example, if the AOS is stopped by the administrator, the proxy can encounter a Microsoft.Dynamics.AX.ManagedInterop.ServerUnavailableException. This ServerUnavailableException class extends the Microsoft.Dynamics.AX.ManagedInterop.ManagedInteropException class.

Interop from X++ Classes in assemblies that are managed by the common language runtime (CLR) can be accessed in X++ code. This feature of Microsoft Dynamics AX is called .NET interop from X++.

.NET interop from X++ is useful when you want your X++ code to access the functionalities in a CLR managed assembly. This includes assemblies that are installed with the .NET Framework. It also includes any assemblies that you create with a language such as C# or Visual Basic.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 31: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-31

Access Static and Instance Members of the .NET Framework Classes from X++

The X++ syntax for calling .NET Framework methods is different for calling static methods than it is for calling instance methods. In both cases, the dot character (.) is used to delimit all the namespaces of the fully qualified type name. However, for calling static .NET Framework methods, you must use a double colon (::) between the class name and the method name. This is consistent with the double colon that you use when you call static methods that are written in X++.

CAUTION: Starting in Microsoft Dynamics AX 2012, you rarely have to include a "hanging" semicolon before the first statement in your X++ methods. However, you must include the semicolon in X++ methods that call static methods in the .NET Framework when the call to the managed static method is the first one in the method.

In the following X++ code sample, the static and instance method calls are as follows.

• Static: System.Convert::ToString • Instance: netString.Substring

static void JobStaticInstanceSyntax95(Args _args) { System.Int32 netInt; System.String netString; str xppString; netInt = 123456;

// static netString = System.Convert::ToString(netInt);

// instance netString = netString.Substring(3,2);

xppString = netString; info(xppString);

/***** Actual infolog output Message (05:58:20 am) 45 *****/ }

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 32: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-32

Marshal Between X++ and CLR Primitive Types

In Microsoft Dynamics AX 2012, the X++ language does implicit conversion or marshaling between several X++ primitive types and their counterpart types managed by the CLR. This means that the X++ assignment operator, the single equal sign (=), can be used between certain pairings of an X++ type with a CLR type.

Implicit marshaling with the X++ assignment operator works in both directions, either from X++ types to CLR types, or from CLR to X++.

Why Marshaling is Useful

A .NET managed assembly might provide a useful method that returns a System.String object. You can call the method and capture the returned System.String in a variable of that type that you declare in your X++ code.

However, if your next step is to pass that string into an X++ method that takes a str, you must first marshal the System.String into a str.

Implicitly Marshaled Conversion Pairs

Each row in the following table lists a pairing of types that are implicitly marshaled by the X++ assignment operator.

NOTE: There is no implicit marshaling between the X++ utcdatetime and the .NET Framework System.DateTime type. For more information about how to convert between utcdatetime and System.DateTime, refer to the How to: Convert Between utcdatetime and System.DateTime (http://go.microsoft.com/fwlink/?LinkId=238170) page on MSDN.

X++ Type CLR Type

boolean System.Boolean

date System.DateTime

int System.Int32

in64 System.Int64

str System.String

guid System.Guid

real System.Single or System.Double

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 33: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-33

The following code sample shows the marshaling between the .NET Framework System.Boolean type and its X++ counterpart boolean.

static void JobBooleanMarshal(Args _args) // X++ job. { System.Boolean netBool; // .NET boolean xppBool; // X++ ; // Marshal .NET to X++. xppBool = false; netBool = true; xppBool = netBool; // Marshals. if (true == xppBool) { info("A1. Good, .NET was marshaled to X++."); } else { info("A2. Bad, .NET was not marshaled to X++."); }

// Marshal X++ to .NET. netBool = true; xppBool = false; netBool = xppBool; // Marshals.

xppBool = true; xppBool = netBool; if (false == xppBool) { info("B1. Good, X++ was marshaled to .NET."); } else { info("B2. Bad, X++ was not marshaled to .NET."); } }

/***** Actual infolog output

Message (01:08:32 pm) A1. Good, .NET was marshaled to X++. B1. Good, X++ was marshaled to .NET.

*****/

TIP: For additional code samples for marshaling between the .NET Framework types and the X++ counterparts, refer to the "How To: Marshal Between X++ and CLR Primitive Types (http://go.microsoft.com/fwlink/?LinkId=238171)" page on MSDN.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 34: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-34

IMPORTANT: Automatic marshaling works between the X++ int64 type and the .NET Framework type System.Int64, just as marshaling works between the X++ int and the .NET System.Int32.

An X++ int does not marshal to a System.Int64, or the reverse. A System.Int32 does not marshal to an X++ int64, or the reverse.

IMPORTANT: As an option in X++, str variables can be declared with a maximum length. The following str declaration sets the maximum length at eight. The assignment would end with the value of myStr being "12345678", with the "9" being truncated:

str 8 myStr ="123456789"; // The string is truncated, and the nine is removed.

The System.String type in the .NET Framework does not have a property that corresponds to the maximum length of an X++ str, and string truncation does not occur. This feature difference could lead to different behavior at run time in the following cases:

X++ str is marshaled to .NET Framework.

X++ is compiled to .NET Framework common intermediate language (CIL), and is run as CIL.

When X++ is run as p-code rather than as CIL, instances of str truncation can be logged by Microsoft Dynamics AX.

Operators for CLR Primitive Types

In X++, when you work with .NET CLR primitive data types, you can use the equal sign (=) assignment operator. However, no other operators can be used between two CLR primitives. For example, you cannot use the comparison operators, such as == or >. Also, you cannot use bitwise operators, such as & or |.

You cannot use a comparison operator with CLR primitive or value types because they are represented as reference types or objects in the system. A System.Int32 is an object that is converted to a value type temporarily during assignment statements. A System.Int32 remains a reference type when it is used with a comparison operator. Comparison operators such as >= are designed for use between value types.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 35: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-35

The following code sample shows that the X++ operator >= cannot be used meaningfully between two System.Int32 variables. The sample also shows that the .NET Framework has methods that provide the functionality of the comparison operators. The method System.Int32.CompareTo is shown.

static void JobOperatorsForNet(Args _args) { System.Int32 netInt99, netInt8; int xppCompare; ; netInt99 = 99; netInt8 = 8;

// Attempt with the >= operator.

if (netInt99 >= netInt8) { info("Unexpected."); } else { info("This proves the X++ >= operator cannot be used" + " meaningfully between two .NET Int32 variables."); }

// System.Int32.CompareTo method.

xppCompare = netInt99.CompareTo(netInt8); if (0 < xppCompare) { info(strfmt("xppCompare is %1, which means 99 > 8. Good.", xppCompare)); } else if (0 == xppCompare) { info(strfmt("xppCompare is %1, which means 99 == 8. Unexpected.", xppCompare)); } else // (0 > xppCompare) { info(strfmt("xppCompare is %1, which means 99 < 8. Unexpected.", xppCompare)); }

/***** Output Message (11:50:53 am) This proves the X++ >= operator cannot be used meaningfully between two .NET Int32 variables. xppCompare is 1, which means 99 > 8. Good. *****/ }

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 36: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-36

Compile and Run X++ that Calls CLR Manage Assemblies

When you write X++ code that calls into an assembly that is managed by the CLR of the .NET Framework, you must make sure that the X++ compiler can find the assembly.

How CLR Managed Assemblies are Found by the X++ Compiler

If your X++ code calls the .NET Framework class System.String, the X++ compiler finds the managed assembly because of two system configurations:

• In the AOT, there is a reference under the References node to the assembly that contains the class.

• The assembly is in the Global Assembly Cache.

The installation of Microsoft Dynamics AX includes references to some typically needed .NET Framework assemblies. If your X++ code calls into a CLR managed assembly that you wrote, you must follow these steps.

1. Copy your assembly into the client\bin\ directory under the Microsoft Dynamics AX installation directory.

TIP: Your full path might resemble C:\Program Files\Microsoft Dynamics AX\version\client\bin\.

2. In the AOT, right-click References, and then click Add Reference. 3. Click the Browse button. 4. In the Select file dialog box, select your assembly file, and then click

Open.

Running on a Tier that Has Your Assembly

Your X++ code might be unable to run on the AOS tier, even though your X++ code compiles successfully on the client. A copy of each assembly that is needed by your X++ code must exist on the AOS computer for your X++ code to run on the AOS tier.

To run your X++ code on the AOS tier, you must copy your assembly to the server\...\bin\ subdirectory on the AOS computer. This is located under the Microsoft Dynamics AX installation directory.

It is not required to provide any reference to the assembly because the X++ code is already compiled.

TIP: If you want to run CLR interop code on the server, you must assert CLRInterop permissions.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 37: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-37

CLR Interop Issues Across Tiers

CLRObject instances cannot be passed between Microsoft Dynamics AX tiers.

A method can run on particular tier either by virtue of the client or server modifier for static methods, or by virtue of the class being RunOn property being either client or server for instance methods.

For example, your server method named SS cannot return a .NET Framework object to another method named CC that calls SS from the client tier.

Example:

The following X++ code example has a server method that is called by a client method. The server method returns a .NET Framework object of type System.String. However, .NET Framework objects cannot be serialized and de-serialized by Microsoft Dynamics AX. Therefore they cannot be returned to a caller that is running on a different tier (in this case, the client tier).

This X++ code represents the server method that is called from the client:

public class RunOnTheServerClass { public static server System.String GetASystemStringMethod() { System.String sNet; // Enable CLR interop on a server method. new InteropPermission(InteropKind::ClrInterop).assert();

sNet ="The return value."; return sNet; } }

This X++ code represents the client job that calls the server method.

static void RunOnClientJob(Args _args) { System.String sNet; str strXpp; // This call fails. sNet = RunOnTheServerClass ::GetASystemStringMethod();

strXpp = sNet; info(strXpp); }

An attempt to run this code example causes an error because the CLRObject is not initialized.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 38: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-38

Catch Exceptions Thrown from CLR Objects

In Microsoft Dynamics AX, when your X++ code calls a .NET Framework methods make sure that your code is designed to handle exceptions. When your code catches exceptions it can relay valuable diagnostic information to the user.

The X++ code sample in this section calls methods that are in a .NET assembly. As recommended, these calls are inside a try block.

To demonstrate the exception handling, the sample intentionally tries to create a Windows event log source again that causes a duplicate name. The duplicate causes the system to throw a .NET exception. The sample shows how to obtain detailed diagnostic information from that exception.

The sample has a catch block for the X++ enum value Exception::CLRError. In that catch block, the following steps are performed.

1. ClrInterop::getLastException is called. 2. ex.get_InnerException is called.

The following X++ code sample demonstrates how to handle exceptions that are thrown from .NET methods.

// X++ static void JobCreateEventLog(Args _args) { #define.LogSource("Dynamics AX") #define.LogName("Dynamics AX Log") System.Exception ex; System.Diagnostics.EventLog eventLog; ; try { // Create the log if it does not already exist. if (!System.Diagnostics.EventLog::SourceExists(#LogSource)) { System.Diagnostics.EventLog::CreateEventSource(#LogSource, #LogName); }

// Next line is an intentional bug for this demonstration of CLR exceptions. // It causes an exception because of a name duplication. System.Diagnostics.EventLog::CreateEventSource(#LogSource, #LogName);

// Write to this newly created log source, if the process comes this far. eventLog = new System.Diagnostics.EventLog();

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 39: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-39

eventLog.set_Source(#LogSource); eventLog.WriteEntry("The exception should prevent this line from appearing in the Windows event viewer.", System.Diagnostics.EventLogEntryType::Warning); }

catch (Exception::CLRError) { ex = ClrInterop::getLastException(); if (ex != null) { ex = ex.get_InnerException(); if (ex != null) { error(ex.ToString()); } } } // Clean up. System.Diagnostics.EventLog::DeleteEventSource(#LogSource, #LogName); } /*** Messages displayed in the Infolog: System.ArgumentException: Source Dynamics AX already exists on the local computer. at System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) at System.Diagnostics.EventLog.CreateEventSource(String source, String logName) ***/

Additional Information

Use X++ Syntax for CLR Arrays

X++ has syntax that you can use to directly create and handle .NET Framework arrays. The syntax is an alternative to constructing instances of System.Array directly, and the underlying effect is the same. The syntax is easier to write than the verbose alternative of using a variable declared as .NET Framework type System.Array. For more information, refer to the How to: Use X++ Syntax for CLR Arrays (http://go.microsoft.com/fwlink/?LinkId=238172) page on MSDN.

Substitute Primitive Parameters Types between the CLR and X++

In Microsoft Dynamics AX, an X++ str type can be passed in a call to a .NET Framework method or X++ method that requires a System.String parameter as its input. However, substitutions in the other direction are not supported. An X++ method that requires an str parameter does not accept a System.String.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 40: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-40

The same rule applies to the other X++ primitive types and their .NET Framework counterparts. Therefore an X++ int parameter can be passed to a method that takes a System.Int32. However, a System.Int32 cannot be passed into a method that takes an X++ int. For more information, refer to the How to: Marshal Between X++ and CLR Primitive Types (http://go.microsoft.com/fwlink/?LinkId=238171)page on MSDN.

It does not matter whether the method that takes the parameter is a .NET Framework method or an X++ method.

Use the byref Keyword for CLR Interop

In X++, you use the byref keyword when you call a .NET Framework method that takes parameters by reference.

For more information about how the byref keyword works with value types and reference types, refer to the "Understanding the X++ Keyword byref for CLR Interop (http://go.microsoft.com/fwlink/?LinkId=238174)" page on MSDN.

Reflect on .NET Elements of X++ Methods

In Microsoft Dynamics AX, the DictMethod system class has reflection methods that can report on the .NET Framework types that an X++ method uses. The .NET Framework types can be used for parameters, local variables, the return type, and more. For more information about reflection, refer to the "Reflect on .NET Elements of X++ Methods (http://go.microsoft.com/fwlink/?LinkId=238175)" page on MSDN.

Deploy .NET Assemblies for Interop The topics in this section explain how the .NET Framework assemblies that you write are deployed for interoperation with Microsoft Dynamics AX.

References versus Visual Studio Projects for Assemblies in the AOT

This topic describes the developer scenarios that involve .NET Framework assemblies. You can find information about .NET Framework assemblies in the following locations in the AOT of Microsoft Dynamics AX:

• AOT > References • AOT > Visual Studio Projects

The AOS handles the items in these two AOT locations differently from one another.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 41: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-41

AOT > References

The information in the AOT > References nodes tells Microsoft Dynamics AX the names of assemblies that it must try to load when they are needed to support, compile, or run operations. The system looks for the assemblies first in the global assembly cache (GAC). If the assembly is not found there, the system then looks under the server\bin\ or client\bin\ directories.

This scenario starts with an existing .NET Framework assembly .dll file. It is not relevant how the .dll became available. The following list shows the sequence of events in this scenario:

1. You manually copy the .dll file into your client\bin\ directory. This step is unnecessary if the assembly is already in the GAC on your local computer.

2. In the AOT, right-click the References node, and then click Add reference. The Add reference form is displayed.

3. If the assembly is not in the list, click Browse to open the Select file form.

4. Browse to the client\bin\ directory and select your .dll file. Then click the Open button. The Select file form closes.

5. Back in the Add reference form, the .dll file that you selected is listed in the bottom grid. Select your .dll file.

6. Click OK. The form closes.

You can view your new entry under AOT > References.

AOT > Visual Studio Projects

The AOS and Microsoft Visual Studio work together to automate the deployment of an assembly and its corresponding project into the metadata stores of the AOS. After the AOS has this metadata, the AOS can distribute the assembly to clients as needed.

The following list shows the sequence of events when you use Visual Studio to write code and compile a .dll assembly file.

1. In Visual Studio you compile your .dll file. 2. Right-click your project node, and then click Add

YourProjectName to AOT. This causes your Visual Studio client to pass to the AOS textual and binary parameters that represent your .csproj and .dll files and other files. This adds your project under AOT > Visual Studio Projects.

Each successive compilation causes Visual Studio to again call the AOS to pass the latest files to the AOS.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 42: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-42

Ongoing Deployments

In the AOT > Visual Studio Projects scenario, you do not have to manually copy any assembly files to a location. The system handles all the file management. The AOS contains your assembly in the database that the AOS manages for storing metadata.

Later, when the .dll file is needed for a process that runs on the AOS, the AOS copies the .dll file from the database and stores the .dll file under the server\bin\VSAssemblies\ directory on its local hard disk drive. (The exact directory path might vary slightly between installations.)

NOTE: In production environments, the AOS has the security authority to write under its local server\bin\ directory, whereas clients on other computers typically do not.

If a client needs the .dll file to compile or run X++ code that references classes in the .dll file, the client calls the AOS for a copy of the .dll file.

Hot-Swapping of .NET Assemblies in the AOS

In your development environment, you can use the hot-swap feature of the AOS to use updated assembly .dll files without having to repeatedly stop and restart the AOS. Restarting the AOS closes the connections from other developer clients, which can be an inconvenience.

NOTE: The hot-swap feature applies only to assemblies that are used by X++ code that runs on the AOS, not for assemblies that are used on the client only.

The following sections explain the importance of application domains in the hot-swap feature. An application domain is an instance of the .NET Framework class named System.AppDomain.

Scenario: Hot-Swapping

The primary use for the hot-swap feature is in the following standard development cycle with Microsoft Visual Studio. This involves the AOT > Visual Studio Projects area, which is comparable to the Visual Studio Projects area of the Application Explorer window for Microsoft Dynamics AX in Visual Studio. The scenario begins with the following steps.

1. In Visual Studio, write the C# code for an assembly .dll that you will call from X++ code.

2. Compile the .dll. Add more code, and compile again.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 43: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-43

3. Add the Visual Studio project to the Application Explorer window. Do this by right-clicking the project in Solution Explorer window of Visual Studio, and then clicking Add YourProjectName to AOT. This action causes Visual Studio to send various project files to the AOS, including the assembly .dll file. The AOS saves the contents of these files in its metadata stores.

4. Start a new Microsoft Dynamics AX AX32.exe client. In some cases in which the project creates an .exe file instead of a .dll file, an alternative is to press the F5 key in Visual Studio to run the code. This also creates a client connection to the AOS.

5. In your AX32.exe client, run X++ code to test the new assembly .dll. Find a bug that requires a fix.

6. In Visual Studio, modify the C# code, and then compile the assembly again. Each compile action sends the updated binary .dll file contents to the AOS to replace the older version in the metadata stores.

7. Run X++ code to test the modified assembly.

A problem is encountered in the last step of the previous list. The AOS has already loaded the earlier version of the assembly. You can start the hot-swap feature to make the AOS load the updated version of the assembly for each new connection.

The following sections describe the scenarios for the two possible states of the hot- swap configuration option.

Scenario with Hot-Swapping Off

The hot-swap configuration value is set to off when Microsoft Dynamics AX is installed. Under this default, one application domain is created when the AOS starts. No additional domains will be created. All .NET Framework assemblies that are loaded into the AOS share the single domain. Also, the single domain is shared by all client connections.

To test the updated assembly, you must restart the AOS. Then connect an AX32.exe client to the AOS, and run the tests. Having to restart the AOS after every compilation is inconvenient. The inconvenience is increased if other developers are sharing the same AOS, because their connections are broken with each restart. Their connections can be from an AX32.exe client, and from Visual Studio.

You do not have to stop and restart the AOS when you want the AOS to load a new assembly that it has not loaded before.

Scenario with Hot-Swapping On

When the hot-swap configuration value is turned on, each new client connection to the AOS is assigned to a new application domain that is dedicated to that connection. Each connection has its own application domain. When you create new application domains, they do not affect other connections.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 44: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-44

Each new application domain is populated with the versions of assembly .dlls that are available to the AOS when the .dlls are loaded into the new domain. In any given application domain, no updates can be made to any assembly .dll that is already loaded into the domain.

In Visual Studio, after you modify your C# code and again compile the assembly .dll, you have to start a new AX32.exe client to gain access to the updated assembly for testing.

FIGURE 2.6 HOT-SWAPPING ON: EACH CLIENT HAS ITS OWN APPDOMAIN IN THE AOS

You can turn on the hot swapping feature of the AOS by following these steps:

1. Open the Microsoft Dynamics AX server configuration utility by clicking Start > Administrative Tools > Microsoft Dynamics AX 2012 Server Configuration. To change the server configuration, you must run the utility with administrative privileges.

2. On the Application Object Server tab, select Allow hot swapping of assemblies when the server is running.

3. Click OK. A prompt will display that asks whether you want to restart the AOS service. The change takes effect only after you restart the AOS.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 45: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-45

CAUTION: You should not use the hot-swap feature in your production environment. The AOS might consume lots of memory caused by an accumulation of application domains. Many assemblies would be loaded multiple times, which would waste memory resources.

Summary The Framework Features chapter introduced several different frameworks available in Microsoft Dynamics AX.

Developers creating code that is customized by other users should create events where customizations typically occur. Then, developers customizing the original functionality in another layer can subscribe to an event. When the customized functionality is tied to an event, the underlying application code can then be rewritten and it will have little effect on the customization, if the same events are raised in the same sequence from one version to the next.

There are many technologies that you can use to programmatically integrate Microsoft Dynamics AX with other applications so that you can integrate functionality or exchange data. These technologies include the following.

• Application Integration Framework (AIF) • .NET Business Connector • .NET Framework

You can use a proxy class for classes, tables, and enums. A proxy class is a .NET Framework class that provides access to one X++ item type of Microsoft Dynamics AX.

Additionally, you can use the .NET interop from X++ to access classes in assemblies that are managed by the CLR in X++ code, and you can use AOT > References or AOT > Visual Studio Projects to deploy your .NET assemblies for interop.

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 46: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-46

Test Your Knowledge Test your knowledge with the following questions.

1. What is the primary difference between using a reference versus a Visual Studio project to deploy a .NET assembly for interop?

2. TRUE or FALSE? An X++ int does not marshal to a System.Int64, or the reverse. A System.Int32 does not marshal to an X++ int64, or the reverse.

( ) TRUE ( ) FALSE

3. Match the eventing terms with their definitions.

_____ 1. The logic that contains the code that causes a change. _____ 2. The definition of the information passed from the producer to the consumer when an event occurs _____ 3. The application code that represents an interest in being notified when a specific event occurs. _____ 4. A representation of a change that happened in the producer. _____ 5. The information that the event carries with it.

a. Event b. Delegate c. Event payload d. Producer e. Consumer

4. TRUE or FALSE? You should only use the hot-swap feature in your production environment.

( ) TRUE ( ) FALSE

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 47: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-47

5. Which of the following methods can be used to subscribe to an event? (Select all that apply)

( ) Create an event handler underneath a method. ( ) Create an event handler underneath a delegate. ( ) In X++ by using the following command: [DelegateName] +=

EventHandler::[EventHandlerName] ( ) In X++ by using the following command" [EventHandlerName] +=

Delegate::[DelegateName]

6. You can build proxies for which of the following X++ item types? (Select all that apply)

( ) Base enumerations ( ) Extended data types ( ) Tables ( ) Classes

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 48: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-48

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

Page 49: AX2012_ENUS_DEVIV_02.pdf

Chapter 2: Framework Features

2-49

Solutions Test Your Knowledge

1. What is the primary difference between using a reference versus a Visual Studio project to deploy a .NET assembly for interop?

MODEL ANSWER:

AOT > References require ongoing deployments, whereas AOT > Visual Studio Projects do not require you to redeploy the .dll files.

2. TRUE or FALSE? An X++ int does not marshal to a System.Int64, or the reverse. A System.Int32 does not marshal to an X++ int64, or the reverse.

(•) TRUE ( ) FALSE

3. Match the eventing terms with their definitions.

d 1. The logic that contains the code that causes a change. b 2. The definition of the information passed from the producer to the consumer when an event occurs e 3. The application code that represents an interest in being notified when a specific event occurs. a 4. A representation of a change that happened in the producer. c 5. The information that the event carries with it.

a. Event b. Delegate c. Event payload d. Producer e. Consumer

4. TRUE or FALSE? You should only use the hot-swap feature in your production environment.

( ) TRUE (•) FALSE

5. Which of the following methods can be used to subscribe to an event? (Select all that apply)

(√) Create an event handler underneath a method. (√) Create an event handler underneath a delegate. (√) In X++ by using the following command: [DelegateName] +=

EventHandler::[EventHandlerName] ( ) In X++ by using the following command" [EventHandlerName] +=

Delegate::[DelegateName]

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement

Page 50: AX2012_ENUS_DEVIV_02.pdf

Development IV in Microsoft Dynamics® AX 2012

2-50

6. You can build proxies for which of the following X++ item types? (Select all that apply)

(√) Base enumerations ( ) Extended data types (√) Tables (√) Classes

Microsoft Official Training Materials for Microsoft Dynamics®

Your use of this content is subject to your current services agreement