Chapter 10. .NET Business Connector

The objectives of this chapter are to:

  • Describe .NET Business Connector for Microsoft Dynamics AX, what it is intended to do, and how it relates to other integration components in Microsoft Dynamics AX 2009.

  • Introduce the new features in .NET Business Connector for Dynamics AX 2009.

  • Provide example scenarios that show how .NET Business Connector can be used.

  • Explain how to use .NET Business Connector to build managed applications that integrate with Dynamics AX 2009.

Introduction

.NET Business Connector for Microsoft Dynamics AX is a versatile platform component that you can use to build software applications that interact deeply with both the data and the business logic residing in Dynamics AX 2009.

This chapter compares .NET Business Connector with other integration components included with Dynamics AX 2009. It also explains the architecture of .NET Business Connector to help you understand how it functions. Several example scenarios demonstrate the variety of potential uses for .NET Business Connector. The managed classes used to build applications are described, and code examples are provided to illustrate their usage. The following new features of .NET Business Connector in Dynamics AX 2009 are introduced, and changes to the existing functionality are explained:

  • Support for cross-company queries

  • Changes in the process hosting in .NET Business Connector

  • Licensing changes that affect .NET Business Connector

  • The ability to pass .NET objects to Dynamics AX via .NET Business Connector

  • The capability to register managed callbacks through .NET Business Connector

Integration Technologies

Integrating enterprise resource planning (ERP) systems with other systems within and beyond an organization is a common requirement, and Dynamics AX provides a variety of ways to implement such integration. Figure 10-1 shows all the integration components in Dynamics AX 2009.

Integration components in Dynamics AX 2009

Figure 10-1. Integration components in Dynamics AX 2009

All the integration components interact with Dynamics AX through the Application Object Server (AOS). Dynamics AX 2009 supports a three-tier architecture (earlier versions supported both a two-tier and a three-tier architecture), which means that the integration components can interact with Dynamics AX only through the AOS. The majority of the integration components use the .NET Framework in some way, which is a reflection of Microsoft’s goal to make it easier for developers to use the .NET platform to develop solutions.

.NET Business Connector enables you to develop managed applications by using the .NET Framework and a CLR-compatible language to integrate with Dynamics AX. In Figure 10-1, the arrow from the .NET Framework to .NET Business Connector shows that the managed applications interact with Dynamics AX through .NET Business Connector. The most general-purpose integration component in Dynamics AX, .NET Business Connector is particularly appropriate for developing custom applications that require a large degree of flexibility and control over implementation.

You can also use the Application Integration Framework (AIF) to integrate Dynamics AX with other applications through standards-based interfaces and XML-based message exchange. AIF is built on top of the Microsoft technology stack; it supports publishing Dynamics AX services through various transport technologies, such as synchronous Windows Communication Foundation (WCF) Web services and asynchronous technologies (Microsoft Message Queuing [MSMQ], Microsoft BizTalk Server, and direct XML file exchange), for external service clients to consume. You can jump-start your integration projects with any of the 56 Dynamics AX services that ship with Dynamics AX 2009 or the AIF wizards that help you create new services. You can also use the AIF to send business documents from Dynamics AX to external locations. Finally, AIF helps you integrate external Web services—whether they are deployed in your company’s intranet or on the Internet—with your Dynamics AX application by consuming these Web services directly from X++. See Chapter 17, for more information on the AIF.

Inside .NET Business Connector

As we stated earlier, .NET Business Connector is a versatile platform component. It contains the Dynamics AX kernel and provides a runtime environment for executing X++ code and interacting with other elements in the AOT. Nearly the entire Dynamics AX development and runtime environment is based on X++, and the kernel is responsible for interpreting and executing this code, part of the reason .NET Business Connector is so powerful.

Logical Component Stack

In .NET Business Connector, the following three logical components (illustrated in Figure 10-2) interoperate to deliver functionality:

Logical component stack within .NET Business Connector

Figure 10-2. Logical component stack within .NET Business Connector

Managed Classes

The managed classes component is a set of .NET Framework–based classes that expose the functionality you can access through .NET Business Connector. It includes the following classes: Axapta, AxaptaBuffer, AxaptaContainer, AxaptaObject, and AxaptaRecord. (We describe each of these classes later in this chapter, in the section "Working with .NET Business Connector.") The functionality of the managed classes is mostly equivalent to the COM Business Connector, which will be discontinued in future versions of Dynamics AX. See the section "Migrating Applications" at the end of this chapter for more on the deprecation of the COM Business Connector.

Transition Layer

In the transition layer, .NET Framework objects and types are mapped to their Dynamics AX equivalents. This mapping occurs as part of both the request and the response processing in .NET Business Connector.

Interpreter

The interpreter is the part of the Dynamics AX kernel that is responsible for parsing and executing X++ code. Dynamics AX allows code to be executed locally in the kernel of .NET Business Connector or remotely in the kernel of the AOS. The interpreter manages local and remote code execution. It also manages connectivity to the AOS and other infrastructure, such as session management and security.

Run Time

At run time, .NET Business Connector interacts with the AOS. Figure 10-3 depicts the run-time interaction.

.NET Business Connector run-time interactions

Figure 10-3. .NET Business Connector run-time interactions

The following list describes the important interactions among .NET Business Connector, the AOS, and the Dynamics AX database:

  • .NET Business Connector authenticates against the AOS when the Axapta.Logon method is called. The credentials that .NET Business Connector passes to the AOS must correspond to an existing Dynamics AX user, who must be enabled and have the appropriate rights, granted through security keys, to use .NET Business Connector.

  • The AOS completes the authentication and establishes a session for the Dynamics AX user.

  • Other .NET Business Connector classes and methods are invoked as needed. Once the session is established, .NET Business Connector can be used to create, read, update, or delete (CRUD) Dynamics AX data. In addition, the X++ business logic that resides in the Dynamics AX metadata store, the application object data can be invoked and executed either on the AOS or in .NET Business Connector.

Web Interoperability

The Dynamics AX development environment includes a Web framework, the Enterprise Portal framework. (See Chapter 7, for more information about the Enterprise Portal framework.) This framework is used to develop the Web-based functionality in X++, which is then exposed in Enterprise Portal. Enterprise Portal uses .NET Business Connector to integrate with Dynamics AX, and .NET Business Connector can interoperate with Microsoft Internet Information Services (IIS) and Microsoft ASP.NET to provide access to the HTTP context information, including requests, responses, and view state, necessary to enable Web-based functionality.

Figure 10-4 illustrates how Web interoperability works.

.NET Business Connector Web interoperability

Figure 10-4. .NET Business Connector Web interoperability

Managed Web applications, including Enterprise Portal, execute in IIS within an application domain. Upon initialization, the application domain loads and instantiates .NET Business Connector. The managed application then uses .NET Business Connector to invoke Dynamics AX Web framework elements, such as Web menu items, Web forms, and Web reports. The X++ code stored in the application object data that defines these elements accesses the HTTP context as needed through the following classes (located in the AOT under System DocumentationClasses):

  • IISApplicationObject

  • IISContextObject

  • IISPostedFile

  • IISReadCookie

  • IISRequest

  • IISRequestDictionary

  • IISResponse

  • IISServer

  • IISSessionObject

  • IISStringList

  • IISVariantDictionary

  • IISViewState

  • IISWriteCookie

For example, you could write an X++ class to retrieve a variable from the HTTP context, which you could then use in another X++ class. In the following code example, the method takes a parameter, which is the name of the HTTP context variable, the value of which is obtained using IISRequest.

str getIISServerVariable(str 80 var)
{
    IISRequest request;
    str res;
    ;
    request = new IISRequest();
    res = request.serverVariables().itemTxt(var);
    return res;
}

If you want to develop a new, custom Web-enabled application that integrates with Dynamics AX and can access managed HTTP context information, you can use both ASP.NET and .NET Business Connector. The interoperability among IIS, ASP.NET, and .NET Business Connector allows you to access HTTP context information from X++ code that is part of your application.

Note

Note

To successfully run with Dynamics AX 2009, existing applications developed with the previous version of the COM Business Connector and ASP that accessed the unmanaged HTTP context must be migrated to ASP.NET.

Security

This section highlights the security mechanisms in place for .NET Business Connector and covers authentication, authorization (including security keys), and code access security.

Authentication

Integrated Windows authentication is implemented throughout Dynamics AX 2009, including .NET Business Connector. The managed classes use parameters that are specific to Integrated Windows authentication.

Authorization

.NET Business Connector has an associated set of Dynamics AX security keys that control access to different parts of its functionality. Table 10-1 describes these security keys. You can find more information about these keys in the Data Dictionary under Security Keys.

Table 10-1. Dynamics AX Security Keys

Security Key

Description

SysCom

Enables or disables the use of COM Business Connector and .NET Business Connector

SysComData

Controls the user’s level of access to data

SysComExecution

Controls access to execution rights of classes and jobs in .NET Business Connector

SysComIIS

Controls whether .NET Business Connector is accessible to users when it’s running in the context of IIS

You can create sessions in .NET Business Connector either directly or indirectly. The direct approach uses the credentials of the current Dynamics AX user. The indirect approach uses the proxy impersonation mechanism whereby an AX user can be impersonated using the LogonAs API. You can control the use of .NET Business Connector in different user groups in Dynamics AX by configuring these security keys. If you do configure these security keys, they will apply only in sessions created directly.

Code Access Security

Code access security (CAS) was introduced in Dynamics AX 4.0. CAS is a mechanism intended to help Dynamics AX developers write code that invokes protected X++ APIs in a manner that minimizes the potential for them to be maliciously exploited. A protected API is an X++ API method that has been secured by using CAS. CAS also ensures that the protected APIs are executed only on the AOS, not on the Dynamics AX client or .NET Business Connector. CAS therefore restricts the X++ APIs that can be executed locally in .NET Business Connector. If an attempt to use a restricted API is made, a CAS exception is returned.

Usage Scenarios for .NET Business Connector

In this section, we provide several scenarios to demonstrate how you can use .NET Business Connector in real-world situations. The usage scenarios described fall into the following categories:

Client

In client-based scenarios, .NET Business Connector and the application that uses it are installed on a user’s computer. To make client setup easier, Dynamics AX 2009 allows the installation of just .NET Business Connector on the development machine.

Business Data Lookup Snap for Microsoft Office

The business data lookup snap is an add-in for Microsoft Office that was written using .NET Business Connector. It allows information workers to access and use Dynamics AX data from within Office applications. For example, customer information stored in Dynamics AX can be retrieved using this snap and inserted into a letter being written in Microsoft Word.

This type of integration has some specific requirements:

  • It must be possible to authenticate the current user as a valid, active Dynamics AX user.

  • It must be possible to take a user-selected Dynamics AX record and search string, and retrieve any matching records from Dynamics AX.

  • It must be possible to copy the retrieved data into the Office application being used.

The following actions are associated with the use of .NET Business Connector for the business data lookup snap:

  1. The business data lookup snap is added to Office.

  2. The snap authenticates the current user’s credentials using .NET Business Connector and establishes a Dynamics AX session.

  3. The selected Dynamics AX record and user-entered search criteria passed to the snap code are used to create a query that .NET Business Connector executes.

  4. If any records are returned to .NET Business Connector from the query, they are passed back to the snap.

To find out more details about the business data lookup snap, go to the CodePlex site and search for "Snap-ins for Microsoft Dynamics AX." Note that you must register to see the snap-ins.

PDA Synchronization Example

A potential client-based use of .NET Business Connector is for PDA synchronization. For example, you could develop an application that allows a PDA to collect information that can be uploaded to Dynamics AX. PDAs generally rely on some kind of synchronization manager; if this synchronization program is customizable, you can extend it to integrate with Dynamics AX.

The specific requirements for this type of integration follow:

  • It must be possible to verify that the current Windows user matches the identity of the device owner.

  • It must be possible to retrieve the data to be uploaded from the PDA or from the local file system if downloaded from the PDA.

  • It must be possible to validate and insert the downloaded data into the corresponding Dynamics AX tables.

The diagram in Figure 10-5 illustrates the topology of this integration.

PDA synchronization using .NET Business Connector

Figure 10-5. PDA synchronization using .NET Business Connector

The following actions are associated with the use of .NET Business Connector during PDA synchronization:

  1. The synchronization manager downloads data from the PDA and recognizes that it needs to be uploaded to Dynamics AX.

  2. The synchronization manager authenticates the current user’s credentials with .NET Business Connector and establishes a Dynamics AX session.

  3. Data read from the PDA is uploaded to Dynamics AX through .NET Business Connector. The data is validated using X++ business logic defined in Dynamics AX. Exceptions are reported as errors in the synchronization manager.

  4. Validated data is persisted in the Dynamics AX database.

This usage scenario shows how you could incorporate .NET Business Connector into the synchronization mechanism for a PDA, and how data entered on the PDA can be transferred to Dynamics AX. For more information on this approach, look at the mobile solutions that have been developed for Dynamics AX (http://www.microsoft.com/dynamics/ax/product/mobilesolutions.mspx). They include development tools for building mobile applications.

Web

Earlier in this chapter, we explained how .NET Business Connector interacts with the managed HTTP context, thus enabling Web applications, including Enterprise Portal, to access and use this context information. One of the primary processes in Enterprise Portal is page processing, which is a good example of how you can use a .NET Business Connector to enable a Web application. Refer to Chapter 7 for a detailed description of Enterprise Portal page processing and the role of .NET Business Connector.

Server

A final usage scenario uses .NET Business Connector on the server that hosts the AOS and the Dynamics AX database, as shown in Figure 10-6.

Server-based use of .NET Business Connector

Figure 10-6. Server-based use of .NET Business Connector

In this scenario, a non-Web-based managed application uses .NET Business Connector to integrate with Dynamics AX. This approach can be used for a variety of purposes, but one example is offline processing. Typically, a Dynamics AX user must be logged on to a computer to authenticate in Dynamics AX. In some cases, this isn’t possible. For example, the asynchronous integration offered by the AIF doesn’t require the originating user to be logged on to the machine where data is processed and inserted into Dynamics AX. However, this task must be executed using the correct user identity.

The solution is to use .NET Business Connector to impersonate a Dynamics AX user, which you can do in one of three ways:

  • Use the Logon API method and supply the original user’s credentials, assuming they are known and maintained securely.

  • Use the LogonAs API method and supply the credentials of the .NET Business Connector proxy user. The .NET Business Connector proxy user is a specifically created domain account used by the user impersonation mechanism in .NET Business Connector. For more details about this, review the online Help section "How to: Connect to Microsoft Dynamics AX Using the LogonAs Method."

  • Execute .NET Business Connector in a Windows process owned by the .NET Business Connector proxy user, and then call the LogonAs API method.

If you use one of these methods to log on to .NET Business Connector, you can develop server-based applications that can process data using the correct Dynamics AX user identity.

Working with .NET Business Connector

In this section, we take a closer look at building applications with .NET Business Connector, including the following topics:

Data Types and Mappings

. NET Business Connector makes it easier to develop managed applications that integrate with Dynamics AX by bridging two programming environments: the managed .NET Framework environment and the Dynamics AX X++ environment. Inevitably, some form of translation is required when passing objects and data between these two environments. Table 10-2 maps equivalent data types between the .NET Framework and Dynamics AX.

Table 10-2. Data Type Mappings

Dynamics AX Data Type

.NET Framework Data Type

String

System.String

Int

System.Int32

Real

System.Double

Enums

System.Enum

.NET Business Connector uses integers for enumerations.

Time

System.Int

You must convert this value to Dynamics AX time format. The value is the number of seconds since midnight.

Date

System.Date

You need to use only the date portion because time is stored separately in Dynamic AX.

Container

AxaptaContainer

Boolean (enumeration)

System.Boolean

Dynamics AX uses integers to represent Boolean values of true and false.

GUID

System.GUID

Int64

System.Int64

The managed class methods in .NET Business Connector explicitly support specific data types for parameters and return values. Refer to the Microsoft Dynamics AX 2009 software development kit (SDK) for more information.

Managed Classes

This section provides an overview of the managed classes in .NET Business Connector. You develop applications with .NET Business Connector by instantiating and using the public managed classes described in Table 10-3.

Table 10-3. .NET Business Connector Managed Classes

Class Name

Description

Axapta

Provides methods for connecting to a Dynamics AX system, creating Dynamics AX objects (class objects, record objects, container objects, and buffer objects), and executing transactions.

AxaptaBuffer

Represents an array of bytes and provides methods for manipulating the buffer contents. AxaptaBuffer objects can be added to AxaptaContainer objects.

AxaptaContainer

Provides methods for reading and modifying containers.

AxaptaObject

The managed representation of an X++ class. Instance methods can be called through it.

AxaptaRecord

Provides methods for reading and manipulating common objects (tables in the Dynamics AX database).

Examples of how these classes are used in an application are provided in the following section.

Processing Requests and Responses

Much like any integration component, .NET Business Connector processes requests and returns responses associated with the use of the managed classes by applications across all the established .NET Business Connector user sessions. The steps described in the following section traverse the logical component stack presented in Figure 10-2.

Request Processing

Figure 10-7 depicts the processing steps associated with a request made through the managed classes.

  1. A request is initiated by invoking a managed class.

  2. The request is received and marshaled across the transition layer (where .NET objects and data are converted from .NET to X++).

  3. The transition layer dispatches the request to the interpreter in .NET Business Connector.

  4. If the request involves executing X++ code, this code is run either locally or remotely on the AOS, depending on the directive associated with the code.

  5. After the request is processed, a response is generated.

Request processing in .NET Business Connector

Figure 10-7. Request processing in .NET Business Connector

Response Processing

Figure 10-8 depicts the processing steps associated with generating a response.

  1. The active request processed by .NET Business Connector completes, successfully or unsuccessfully.

  2. The interpreter instantiates and dispatches the response to the transition layer.

  3. The transition layer marshals the response to the managed classes (converting objects and data from X++ to .NET).

  4. The response is returned to the caller, which is the application that initially invoked .NET Business Connector.

Response processing in .NET Business Connector

Figure 10-8. Response processing in .NET Business Connector

The main variation in the request and response cycle is the location where the X++ code being invoked is executed. The declaration associated with the X++ code controls this location. By default, the X++ code runs where called—that is, from the interpreter where it is invoked. If the client keyword is used, execution is forced on either .NET Business Connector or the Dynamics AX client. If the server keyword is used, the AOS executes the code.

Exception Handling

.NET Business Connector has a large set of managed exceptions that can be raised at run time. This set of managed exceptions provides improved granularity, and therefore more flexibility, in handling those exceptions. Most notable are several remote procedure call (RPC)–related exceptions, which you can use to control error handling associated with the connectivity between .NET Business Connector and the AOS. As a general rule, .NET Business Connector does not catch unhandled exceptions (such as OutOfMemoryException). This type of exception is simply propagated to the calling application and prevents .NET Business Connector from masking or hiding such unhandled exceptions.

Refer to the Microsoft Dynamics AX 2009 SDK for more information on the data types, managed classes, and managed exceptions referenced in this section.

HelloWorld Example

How do you write C# code that uses .NET Business Connector? The simple example that follows (the .NET Business Connector equivalent of "Hello World") demonstrates logging on to Dynamics AX. To use the following code, you must be able to log on successfully using the Dynamics AX client. Also, .NET Business Connector must be installed from wherever you execute the code. Create a new project in Microsoft Visual Studio. In the New Project dialog box, select Console Application under Visual C#. This creates the project file structure and files, and presents you with a program named Program.cs. Paste the code in the following example between the curly brackets associated with the Main method. In Solution Explorer, right-click References and choose Add Reference. In the Add Reference dialog box, click the Browse tab. Use the file controls to navigate to the Dynamics AX ClientBin folder. Select Microsoft.Dynamics.BusinessConnectorNet.dll, and then click OK. This makes .NET Business Connector accessible to the C# application. Now you can build and run the solution.

using System;
using Microsoft.Dynamics.BusinessConnectorNet;
namespace Demo
{
    class HelloWorldFromBC
    {
        public static void Main(string[] args)
        {
            using (Axapta ax = new Axapta())
            {
                try
                {
                    ax.Logon(null, null, null, null);

                    Console.WriteLine("Hello World from Business Connector!");
                     Console.ReadKey();
                    // Logoff
                    ax.Logoff();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                }
            }
        }
    }
}

First, you must instantiate the Axapta class to authenticate, using one of the methods within Axapta. You use Logon method to provide authentication. If you don’t provide non-null parameter values, the following values, which you can override as needed, are used:

  • Current Windows user

  • Default Dynamics AX company for the user

  • Default language for the user

  • Default active configuration

A message appears on the console, and the Dynamics AX session is terminated using the Logoff method.

Accessing Data

To access data in Dynamics AX, you must use the AxaptaRecord class. The following example shows how to retrieve a list of inventory items that are classified as "raw material."

using System;
using Microsoft.Dynamics.BusinessConnectorNet;

namespace Demo
{
    // ListInvItemRecords
    // Shows how to retrieve and iterate through a list of Dynamics AX records
    class ListInvItemRecords
    {
        public static void Main(string[] args)
        {
            String invItemNameField = "ItemName";
            Object invItemName;
            String invItemIdField = "ItemId";
            Object invItemId;

            using (Axapta ax = new Axapta())
            {
                try
                {
                    // Logon
                    ax.Logon(null, null, null, null);

                    Console.WriteLine("*** List inventory item records");

                    // Instantiate the Dynamics AX record.
                    AxaptaRecord axRecord = ax.CreateAxaptaRecord("InventTable");

                    // Execute a query.
                    axRecord.ExecuteStmt(
                        "select * from %1 where %1.ItemGroupId == 'RawMat'");

                    // Loop through matching Dynamics AX records.
                    while (axRecord.Found)
                    {
                        invItemName = axRecord.get_Field(invItemNameField);
                        invItemId = axRecord.get_Field(invItemIdField);

                        Console.WriteLine(invItemId + "	" + invItemName);

                        axRecord.Next();
                    }
                    Console.ReadKey();
                    // Logoff
                    ax.Logoff();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                }
            }
        }
    }
}

Here are the important aspects of the code example:

  • Variables are declared to store the Dynamics AX record data that is retrieved and to hold the field names used.

  • Authentication is the same as in the HelloWorld example.

  • To begin working with a specific type of Dynamics AX record, you must first instantiate an AxaptaRecord object, and you must provide the name or ID of the record as an argument.

  • A query is executed against the Dynamics AX record using ExecuteStmt, which parses the query syntax and replaces the substitution variable (%1) with the name of the record. The query syntax is generic. Dynamics AX executes the query with the exact syntax appropriate for the database being used, whether Microsoft SQL Server or Oracle.

  • A while loop cycles through the records returned from Dynamics AX, which uses another method, Found, on AxaptaRecord to determine that matching records exist.

  • For each record, get_Field retrieves each field value and assigns a value to the appropriate variable declared earlier.

  • To proceed to the next record, the Next method is called.

  • Logoff is called to terminate the session.

This code sample shows one way of accessing data in Dynamics AX. Another approach uses the Query object, which is described in the upcoming section "Method 2: Using the Query Object." In addition to accessing data, you can also invoke X++ business logic directly from .NET Business Connector, as shown in the following section.

Querying Data Across Companies

When you log on to Dynamics AX with .NET Business Connector, you establish a session that is dedicated to one specific company that the Dynamics AX user has access to. (This is similar to selecting a company in the Dynamics AX client.) At times, however, an application you’re developing might need to access data that resides in a number of companies. For example, you might want to query vendors across all the companies in Dynamics AX. To address this need, Dynamics AX 2009 supports defining and executing cross-company queries from .NET Business Connector.

Cross-company queries can be executed in two ways. The first is to use the ExecuteStmt API. The second is to use the Query object. In the following subsections, we explain each approach, using code samples to demonstrate.

Method 1: Using ExecuteStmt

When using ExecuteStmt to query Dynamics AX, you can extend the scope of the query to cover more than one company. (Querying against just one company is the default behavior.) The following code sample shows how to do this.

using System;
using Microsoft.Dynamics.BusinessConnectorNet;

namespace Demo
{
    // ListVendors - shows how to retrieve and iterate through a list of Dynamics AX records
    // (assumes you have two companies: DMO and DMO2 – replace with your own
    // companies)

    class CrossCompanyQuery
    {
        public static void Main(string[] args)
        {
            String vendAccountNumField = "AccountNum";
            Object vendAccNum;
            String vendNameField = "Name";
            Object vendName;

            using (Axapta ax = new Axapta())
            {
                try
                {
                    // Logon
                    ax.Logon("DMO", null, null, null);

                    Console.WriteLine("*** List vendor records");

                    // Instantiate record
                    AxaptaRecord axRecord = ax.CreateAxaptaRecord("VendTable");

                    // Execute a query against VendTable

                    axRecord.ExecuteStmt(
                        "container c=['DMO','DMO2']; select crosscompany:c %1");

                    // Loop through found records
                    while (axRecord.Found)
                    {
                        vendAccNum = axRecord.get_Field(vendAccountNumField);
                        vendName = axRecord.get_Field(vendNameField);

                        Console.WriteLine(vendName + "	" + vendAccNum);
                        axRecord.Next();
                    }
                    Console.ReadKey();
                    // Logoff
                    ax.Logoff();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                }
            }
        }
    }
}

The key here is the special syntax within ExecuteStmt that permits multiple company IDs to be specified.

Method 2: Using the Query Object

The second method uses the Dynamics AX Query object, which provides a lot of flexibility for constructing and executing queries. The following code sample shows how a cross-company query is enabled by using this approach.

using System;
using Microsoft.Dynamics.BusinessConnectorNet;

namespace Demo
{
    // ListVendors - shows how to retrieve Dynamics AX records from multiple companies
    // using the Query object (assumes you have two companies: DMO, and DMO2
    // – replace with your own companies)
    class CrossCompanyQueryUsingQueryObject
    {
        public static void Main(string[] args)
        {
            String vendAccountNumField = "AccountNum";
            String vendNameField = "Name";
            AxaptaObject axQuery;
            AxaptaObject axQueryRun;
            AxaptaObject axQueryDataSource;

            using (Axapta ax = new Axapta())
            {
                try
                {
                    // Logon
                    ax.Logon("DMO", null, null, null);
                    Console.WriteLine(
                     "*** List vendor records from DAT and DMO using Query object");

                    // Get the table ID of the table to query
                    int vendTableId = (int)ax.CallStaticClassMethod("global",
                       "tablename2id", "VendTable");

                    // Instantiate the Query object
                    axQuery = ax.CreateAxaptaObject("Query");

                    // Add a data source
                    axQueryDataSource = (AxaptaObject)axQuery.Call(
                       "AddDataSource", vendTableId);

                    // Enable cross company query
                    axQuery.Call("AllowCrossCompany", true);

                    // Add two companies for the cross company query
                    axQuery.Call("AddCompanyRange", "DMO2");
                    axQuery.Call("AddCompanyRange", "DMO");

                    // Run the query!
                    axQueryRun = ax.CreateAxaptaObject("QueryRun", axQuery);

                    while ((bool)axQueryRun.Call("next"))
                    {
                        using (AxaptaRecord axRecord =
                           (AxaptaRecord)axQueryRun.Call("get", vendTableId))
                        {
                            Object vendAccNum = axRecord.get_Field(
                                vendAccountNumField);
                            Object vendName = axRecord.get_Field(vendNameField);
                            Console.WriteLine(vendName + "	" + vendAccNum);
                        }
                    }
                    Console.ReadKey();
                    // Logoff
                    ax.Logoff();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                }
            }
        }
    }
}

Notice that AllowCrossCompany has to be invoked to enable a cross-company query. The call to AddCompanyRange allows an arbitrary number of companies to be added to the query.

Invoking Business Logic

In addition to accessing data, you can also invoke business logic defined in Dynamics AX directly from .NET Business Connector. In this example, you call a method in an X++ class to update inventory item details in Dynamics AX based on data from a separate inventory management system. To do this, you use the CallStaticClassMethod method in the Axapta managed class, as shown in the following code.

using System;
using Microsoft.Dynamics.BusinessConnectorNet;

namespace Demo
{
    // UpdateInventoryQuantity - shows how to call a static X++ class method
    class UpdateInventoryQuantity
    {
        public static void Main(string[] args)
        {
            object returnValue;

            using (Axapta ax = new Axapta())
            {
                try
                {
                    // Logon
                    ax.Logon(null, null, null, null);

                    // InventoryManager is the class, updateInventoryQty
                    // is the method to be invoked
                    returnValue = ax.CallStaticClassMethod("InventoryManager",
                       "updateInventoryQty");

                    // Write a message according to the result of the
                    // class/method call
                    if ((Boolean)returnValue)
                        Console.WriteLine(
                            "Inventory quantity updated successfully");
                    else
                        Console.WriteLine("Inventory quantity update failed");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                }
            }
        }
    }
}

The X++ class returns a Boolean result in this case, which is then used to determine the next action in the application.

As you can see from these examples, developing applications that integrate with Dynamics AX using .NET Business Connector is relatively straightforward. Although real applications would use the managed classes more extensively, the approach to accessing data and invoking business logic would remain the same.

Enhanced CLR Interoperability with the Dynamics AX Interpreter and X++

As we stated earlier in the chapter, the reason Microsoft developed .NET Business Connector was to simplify the creation of applications that integrate with Dynamics AX by using the .NET Framework. Although the managed classes delivered with .NET Business Connector are a good first step to achieving this integration, CLR interoperability takes this integration one step further. In Dynamics AX 4.0, CLR interoperability represented the ability to access classes in assemblies managed by the .NET Framework CLR from X++. (For more information on CLR interop in Dynamics AX 4.0, go to http://msdn.microsoft.com/en-us/library/bb986586(AX.10).aspx.) Because CLR interoperability was built into the Dynamics AX 4.0 kernel, it was available to use from .NET Business Connector in that release. In Dynamics AX 2009, CLR interoperability from .NET Business Connector has been augmented with two capabilities: the ability to pass managed objects to Dynamics AX, and the ability to register managed callbacks. (For more on CLR interop in Dynamics AX 2009, refer to http://msdn.microsoft.com/en-us/library/cc598160.aspx.)

Passing Managed Objects to Dynamics AX

Building on the idea of accessing classes in .NET assemblies from X++, it is possible in Dynamics AX 2009 to pass managed objects into X++, and then act on them from there. This capability existed in Dynamics AX 4.0; however, it was limited to a specific set of managed types. Any attempt to pass a managed object anything other than one of the supported managed types generated an exception. In Dynamics AX 2009, the type mappings are the same; however, the managed types not explicitly supported are marshaled as CLRObjects. Table 10-4 summarizes the marshaling behavior by .NET type.

Table 10-4. .NET Type Marshaling Behavior

.NET Type

X++ Type

Base types (see Table 10-2.)

X++ equivalent

.NET Business Connector event delegate

ManagedEventDelegate

Other

CLRObject

The following code samples illustrate this functionality by showing how a strBuilder managed object is passed to an X++ method, the contents of which are then appended and returned to the calling C# application.

The first code sample is a static X++ method in Dynamics AX within a class called Class1.

public static str method1(System.Text.StringBuilder strBuilder)
{
    str s = "";

    if(strBuilder)
    {
        strBuilder.Append(" of passing arbitrary .net objects to X++");

        s = strBuilder.ToString();
    }
    return s;
}

The next code sample is the corresponding C# code.

using System;
using Microsoft.Dynamics.BusinessConnectorNet;

namespace Demo
{
    class PassingDynamicObjectsToDynamicsAX
    {
        public static void Main(string[] args)
        {
            using (Axapta ax = new Axapta())
            {
                try
                {
                    // Logon
                    ax.Logon(null, null, null, null);

                    string str = (string)ax.CallStaticClassMethod(
                       "Class1", "method1",
                       new System.Text.StringBuilder("This is a test"));

                    Console.WriteLine(str);
                    Console.ReadKey();

                    // Logoff
                    ax.Logoff();

                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                }
            }
        }
    }
}

Figure 10-9 displays the output, showing the combined string.

The output from running the sample code, which demonstrates passing managed objects to Dynamics AX by using .NET Business Connector

Figure 10-9. The output from running the sample code, which demonstrates passing managed objects to Dynamics AX by using .NET Business Connector

Registering Managed Callbacks

Another aspect of CLR interoperability is the ability to communicate events from X++ to managed code by using the new delegate functionality in .NET Business Connector. Enterprise Portal uses delegate functionality to enable ASP.NET user interface controls (such as data grids) to respond synchronously to changes in the underlying Dynamics AX data. In this case, managed callbacks ensure that the data displayed in the grid corresponds to the actual stored data. To implement a managed callback, follow these steps:

  1. Define an X++ event args class. (This is optional; you can also use the default one.)

  2. Create a managed event handler that expects the event args defined in step 1.

  3. Register the event handler by passing it to an X++ class that maintains it.

  4. When the condition is triggered, invoke the managed handler that you registered in step 3.

The following two code samples illustrate the use of managed callbacks. The first is a segment of X++ code that triggers the event and also extends the ManagedEventArgs to include some data that represents the payload from the managed callback.

// This X++ method triggers the event
public void method2(ManagedEventDelegate delegate)
{
    // Based on some condition, trigger the managed event handler

    delegate.invoke(this, new MyEventArgs("This is a test of managed event handler"));
}
// Define my own event args if the standard one is not good enough
class MyEventArgs extends ManagedEventArgs
{
    str strSpecificToMyEvent;
}
public void new(str data)
{
    strSpecificToMyEvent = data;
}
str eventData()
{
    return strSpecificToMyEvent;
}

The second sample is the C# managed event handler code triggered from the preceding X++ code.

using System;
using Microsoft.Dynamics.BusinessConnectorNet;
namespace Demo
{
    class RegisteringManagedCallbacks
    {
        // This is the managed event handler that will be triggered from X++
        static void ManagedEventHandler(AxaptaObject sender, AxaptaObject eventArgs)
        {
            Console.WriteLine(eventArgs.Call("eventData"));

            Console.ReadKey();
        }
        public static void Main(string[] args)
        {
            using (Axapta ax = new Axapta())
            {
                try
                {
                    ax.Logon(null, null, null, null);
                    AxaptaObject axObj = ax.CreateAxaptaObject("Class1");
                    axObj.Call("method2", new
                        AxEventHandlerDelegate(
                        RegisteringManagedCallbacks.ManagedEventHandler));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                }
            }
        }
    }
}

Figure 10-10 shows the output from running the sample code, where the managed callback payload is displayed.

The output from running the sample code, which demonstrates registering managed callbacks using .NET Business Connector

Figure 10-10. The output from running the sample code, which demonstrates registering managed callbacks using .NET Business Connector

Migrating Applications

The COM Business Connector has been deprecated in Dynamics AX 2009. It ships in Dynamics AX 2009, but it is being minimally supported and will be entirely removed in the next release of Dynamics AX. If you own or maintain existing applications that use the COM Business Connector, and they need to work with the next release of Dynamics AX, you should plan to migrate the applications to use .NET Business Connector. Refer to the guidelines for migrating applications that are provided in Inside Microsoft Dynamics AX 4.0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset