Working with Microsoft Dynamics AX and .NET: Part 1

Exclusive offer: get 80% off this eBook here
Microsoft Dynamics AX 2009 Programming: Getting Started

Microsoft Dynamics AX 2009 Programming: Getting Started — Save 80%

Get to grips with Microsoft Dynamics AX 2009 development quickly to build reliable and robust business applications with this book and eBook

₨924.00    ₨184.80
by Erlend Dalen | December 2009 | .NET BPEL SOA Web Services

This article by Erlend Dalen, explains how you can use .NET classes in AX with the Common Language Runtime and how you can write .NET code that uses AX classes by using the .NET Business Connector for AX.

The topics covered in this article are:

  • A brief description of Common Language Runtime (CLR)
  • Adding .NET references to classes in AX
  • Using a .NET class in X++
  • Adding references to the .NET Business Connector
  • Using the .NET Business Connector in .NET classes

When you are done with this article, you should be able to use .NET classes as reference classes in AX through the Common Language Runtime (CLR). The article will also guide you through the process of creating a .NET class in Visual Studio, and how to use it in AX. You will also learn how to use AX logic from external applications by using the .NET Business Connector.

All the Visual Studio examples in this article are written in C#.

Common Language Runtime

You might have done some .NET development before looking into X++ right? Maybe you're even a .NET expert? If so, you must have heard of CLR before. The CLR is a component of .NET that enables objects written in different languages to communicate with each other. CLR can be used in AX to combine functionality from .NET classes and libraries, including the ones you have yourself created in .NET. However, you cannot consume AX objects in .NET by using the CLR. Instead, you will then have to use the .NET Business Connector.

To learn more about the CLR, check out the following link: http://msdn.microsoft.com/en-us/library/ddk909ch(VS.71).aspx

One very useful feature in AX when dealing with integration between AX and .NET is the way AX implicitly converts the most common data types. For the data types listed in the next table you do not need to convert the data manually. For all other data types, you will have to convert them manually.

.NET Common Language Runtime

X++

System.String

str

System.Int32

int

System.Int64

int64

System.Single

real

System.Double

real

System.Boolean

Boolean

System.DateTime

date

System.Guid

guid

Enums are stored as integers in AX and are treated as integers when they are implicitly converted between .NET and AX.    

We prove this by executing the next example that shows the conversion between System.String and str. The same can be done for any of the other data types in the above table.

 static void ImplicitDataConversion(Args _args)
{
System.String netString;
str xppString;
;

// Converting from System.String to str
netString = "Hello AX!";
xppString = netString;
info(xppString);
// Converting from str to System.String
xppString = "Hello .NET!";
netString = xppString;
info(netString);
}

X++ is case insensitive, except when dealing with CLR. This means that writing System.string in the previous example will result in     a compile error, whereas writing Str instead of str will not.

The result will look like this:

Microsoft Dynamics AX 2009 Programming: Getting Started

Adding a reference to a .NET class in AX

To be able to use .NET classes in AX you have to make sure that the .NET assembly that you would like to use in AX exists under the References node in the AOT. If you can't find it there, you have to add it by adding a reference to the DLL file that contains the assembly in the AOT under References.

When adding a reference node in the AOT you have to make sure that the DLL exists on all client computers. If there is a client computer in which the DLL does not exist, it will result in compile errors when compiling code on that client computer.

Assembly exist in the Global Assembly Cache

Follow these steps to add a reference that exists in the Global Assembly Cache:

  1. If the DLL has been added to the Global Assembly Cache, you can right-click on the Reference node in the AOT and select Add Reference.
  2. In the form that opens (see next screenshot), you should be able to find the desired DLL. Add it by clicking on the Select button.
  3. When you have selected the desired reference, click on the OK button. The assembly has now been added to the AOT, and can be used when writing X++ code.
  4.         

Microsoft Dynamics AX 2009 Programming: Getting Started

Assembly not in Global Assembly Cache

If the file does not exist in the Global Assembly Cache follow these steps:

  1. Click on the Browse button in the Add Reference form shown above and find the DLL file.
  2. Click on Open. If the DLL is a valid assembly it will be added to the AOT under References.

Another option is to add the DLL to the Global Assembly Cache first and select it as described in the previous section, Assembly exist in the Global Assembly Cache.

Microsoft Dynamics AX 2009 Programming: Getting Started Get to grips with Microsoft Dynamics AX 2009 development quickly to build reliable and robust business applications with this book and eBook
Published: December 2009
eBook Price: ₨924.00
Book Price: ₨425.00
See more
Select your format and quantity:

Using a .NET class in X++

After having added a reference to the .NET assembly you want to use in AX, you can start writing the X++ code that will use the assembly.

When referencing the classes in the assembly you will need to write the whole namespace and class name. In my example I'm using an assembly that has been added to the AOT in the SYS layer. The example shows a nice feature that enables AX to send info messages to the Windows Event Log.

This can be particularly useful when you would like to use the Windows Event Log to monitor AX batch Jobs.

First, we add a new static method called writeLogEntry to the Global class:

 static void writeLogEntry(Exception e, str caller, int line, str text)
{
// Use the standard .NET class EventLog from
// the System.Diagnostics assembly
System.Diagnostics.EventLog eventLog;
// Also use a .NET enumeration from the
// System.Diagnostics assembly
System.Diagnostics.EventLogEntryType entryType;
System.Exception clrException;
str stack;
Batch batch;
str batchInfo;
;
try
{
// Create a new object of the EventLog class
eventLog = new System.Diagnostics.EventLog();
eventLog.set_Source("Dynamics AX");
// Set the enumeration value based on the Exception
// type in AX
switch (e)
{
case Exception::Info :
entryType =
System.Diagnostics.EventLogEntryType::Information;
break;
case Exception::Warning :
entryType =
System.Diagnostics.EventLogEntryType::Warning;
break;
case Exception::Error :
entryType =
System.Diagnostics.EventLogEntryType::Error;
break;
}
// If the current user is running a batch job
// we can assume that the info message came
// from the batch job and add additional information
// to the event log

while select batch
where batch.Status == BatchStatus::Executing &&
batch.ExecutedBy == curuserid()
{
batchInfo += batch.GroupId + ': '+
classid2name(batch.ClassNumber) + 'n';
}
if (batchInfo)
eventLog.WriteEntry(strfmt("Batch info from AX: %1 nn
The message originated from :%2 nat line %3 nn
Message: %4", batchInfo, caller, line, text),
entryType);
else
eventLog.WriteEntry(strfmt("Info from AX: nn
The message originated from :%1 nat line %2 nn
Message: %3", caller, line, text), entryType);
}
catch(Exception::CLRError)
{
// If not able to write the info to the eventlog
// print an error in the print window instead.
print "EventWriter:
Unable to write entry to the windows eventlog";
}

Then we add a line of code at the end of the add method in the Info class so that the end of the method will look like this:

 writeLogEntry(_exception, conpeek(packedAction,2) , 
conpeek(packedAction,3), _txt);
this.addSysInfoAction(_helpUrl, actionClassId, packedAction);
}
return super(_exception, (buildprefix?getprefix():'')+_txt);
}

To test the feature, simply create a new Job that prints something to the infolog:

 static void TestEventLog(Args _args)
{
;
info("This is a test");
}

You will now see an infolog message in AX, and if you open the Windows Event Viewer you should see the following message in the list:

Microsoft Dynamics AX 2009 Programming: Getting Started

Double-clicking on the event will bring up information about the origin of the info and the message that was printed to the infolog in AX.

Microsoft Dynamics AX 2009 Programming: Getting Started

This example could easily be extended so you can enable or disable the feature for different users and select the level of messages to be sent to the EventLog.

.NET Business Connector

If you have external applications that need to integrate directly to AX logic you can easily achieve this by using the .NET Business Connector. A typical scenario can be that you would like your .NET application to execute some code in AX and have the result sent back to the .NET application.

The .NET Business Connector requires additional licenses. Make sure that the AX installation in which you want to make use  of the .NET Business Connector has the necessary licenses before you start developing the solution.

In standard AX, the .NET Business Connector is also used by the Enterprise Portal through the Web Parts in SharePoint so that they can expose AX data and logic directly to the Web. It is also used by the standard Application Integration Framework (AIF).

The way that the .NET Business Connector works is that it offers a set of .NET managed classes that .NET applications use in order to log on to AX and execute methods in AX classes.

Here is a list of the different managed classes that can be used in .NET when you want to integrate to AX through the .NET Business Connector. The list is taken from the Dynamics AX SDK.

Class name

Description

Axapta

The Axapta class contains methods that enable you to connect to AX, create AX objects, and execute transactions.

AxaptaBuffer

The AxaptaBuffer class contains methods that enable you to add data to, and retrieve data from an AX buffer.

AxaptaContainer

The AxaptaContainer class contains methods that enable you to read data from, and write data to, AX containers.

AxaptaRecord

The AxaptaRecord class contains methods that enable you to read, update, insert, and delete AX records. It also enables you to call table methods in AX.

AxaptaObject

The AxaptaObject class contains methods that enable you to call class methods in AX.

>> Continue Reading Working with Microsoft Dynamics AX and .NET: Part 2

[ 1 | 2]
Microsoft Dynamics AX 2009 Programming: Getting Started Get to grips with Microsoft Dynamics AX 2009 development quickly to build reliable and robust business applications with this book and eBook
Published: December 2009
eBook Price: ₨924.00
Book Price: ₨425.00
See more
Select your format and quantity:

About the Author :


Erlend Dalen

Erlend Dalen started working as a developer with the first version of Axapta in 1998. From 2000 he spent 2 years developing eCommerce, mobile, and integration solutions in Java for a Norwegian IT consultancy company. He has worked for Columbus IT since 2002, first as a senior developer in Norway and in USA and now as the technology manager of the Norwegian branch, where his responsibilities have been to implement new technology areas, creating an eCommerce solution for Dynamics AX, and being the technology solution architect in internal and customer projects.

Books From Packt


RESTful Java Web Services
RESTful Java Web Services

Joomla! 1.5 SEO
Oracle SOA Suite Developer's Guide
>

SOA Patterns with BizTalk Server 2009
SOA Patterns with BizTalk Server 2009

Programming Microsoft Dynamics NAV 2009
Programming Microsoft Dynamics NAV 2009

Expert Cube Development with Microsoft SQL Server 2008 Analysis Services
Expert Cube Development with Microsoft SQL Server 2008 Analysis Services

Microsoft Office Live Small Business: Beginner’s Guide
Microsoft Office Live Small Business: Beginner’s Guide

Software Testing with Visual Studio Team System 2008
Software Testing with Visual Studio Team System 2008

WCF Multi-tier Services Development with LINQ
WCF Multi-tier Services Development with LINQ


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software