Your message has been sent.
This article has been saved to your account.
Go to my account
This article has been emailed to your Kindle.
Send this article
Complete the form below to send this article, Working with Microsoft Dynamics AX and .NET: Part 2, to a friend (or to yourself). We will never share your details (or your friend's) with anyone. For more information, read our Privacy Policy.
Read Part One of Working with Microsoft Dynamics AX and .NET: Part 1 here.
Add a reference to .NET Business Connector
In the next example, we create a new project in Visual Studio and add the reference to the project. You can skip this step if you already have a project where you would like to use the .NET Business Connector.
Open Visual Studio and create a new project as shown in the next screenshot:

When you click on OK, you will have a new C# file called Program.cs. Before we start writing any code in the file, we have to add the .NET Business Connector as a reference.
In the Solution Explorer right-click on the References node and select Add Reference.

In the form that opens select Microsoft.Dynamics.BusinessConnectorNet.dll under the Browse tab.
The file is found in the ClientBin catalog of your AX installation. The default path is:
C:Program FilesMicrosoft Dynamics Ax50ClientBin

Click on OK and note that the reference has now been added under the References node in the Solution Explorer.
Using the .NET Business Connector in .NET classes
In the next sections of this article we will look at some examples that show how we can use methods in the .NET Business Connector to call AX methods, insert data into AX tables, and read data from AX tables.
Calling a static class method in AX
You now have to go back to AX, open the AOT and find the Global class. Add the following method to the Global class:
static str AxHelloWorld()
{
return "HelloWorld!";
}
In the Visual Studio project we open the Program.cs file again and enter the following code that will create a connection to AX through the .NET Business Connector. We then call the method we created in the Global class before it prints the result to the console:
using System;
using Microsoft.Dynamics.BusinessConnectorNet;
namespace GetAxInfo1
{
class Program
{
/// <summary>
/// This class connects to AX throught the
/// .NET Business Connector and call the static method
/// AxHelloWorld in the Global class in AX.
/// The result is sent to the console (command prompt).
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Axapta ax;
Object axObject;
try
{
// Create a new Axapta object.
ax = new Axapta();
// Logon using the default settings
// in the AX configuration for the .NET
// Business Connector
ax.Logon(null, null, null, null);
// Call the static method and return the
// result to the axObject variable
axObject =
ax.CallStaticClassMethod("Global", "AxHelloWorld");
// Print the result to the console
Console.WriteLine("The message from AX is {0}",
axObject.ToString());
ax.Logoff();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
Execute the program by pressing Ctrl + F5. You should now see the following result in the console (command prompt) that opens up:

If you get a different result it might be because you haven't set up the .NET Business Connector correctly. If so, please refer to the installation guide to set it up properly. Also, check the Windows Event Viewer to see if there are any error messages that can lead you in the right direction.
Insert data into an AX table
As mentioned earlier in this article, you can use the methods in some of the marshaled classes in the .NET Business Connector to manipulate data. However, it is better to avoid this and instead have AX handle all data selection and manipulation. It would be even better to have your .NET application call a method in AX that does the job and returns the results back to the .NET application again. However, this is not always feasible, for instance, when you would like to insert records from your .NET application to an AX table. The next section will guide you through the steps needed to achieve this.
First, you should create a new project in Visual Studio as we did earlier in this article. In this example, we will call the new project "InsertAxRecord".
Then you have to add a reference to the .NET Business Connector.
In the Program.cs file (or whatever you call your file), you write something like this:
using System;
using Microsoft.Dynamics.BusinessConnectorNet;
namespace InsertAxRecord
{
class Program
{
static void Main(string[] args)
{
Axapta ax;
AxaptaRecord record;
try
{
// Create AX object and logon to AX
ax = new Axapta();
ax.Logon(null, null, null, null);
// Create a new AxaptaRecord object with
// the name of the table as input parameter
using (record = ax.CreateAxaptaRecord("CarTable"))
{
// Remember to clear the tablebuffer if
// you are inserting inside a loop
record.Clear();
record.InitValue();
// Set the fields in the table
record.set_Field("CARID", "XXX1");
record.set_Field("MODELYEAR", 1998);
record.set_Field("CARBRAND", "FORD");
record.set_Field("MODEL", "F1");
record.set_Field("MILEAGE", 89378);
// Insert the record
record.Insert();
}
// End the AX session
ax.Logoff();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
If you open the table browser and look at the contents of CarTable in AX now (find the table in the AOT and pressing Ctrl + O to open the table browser) you should see that the record has been added.

Read data from an AX table
For our next example we will repeat the procedure from the previous example, except that now we will read data from the table instead of writing to the table.
Start off by creating a new project and add the .NET Business Connector as a reference to the solution.
Enter the following code into the Program.cs file (or whatever you call your program):
using System;
using Microsoft.Dynamics.BusinessConnectorNet;
namespace ReadAxRecord
{
class Program
{
static void Main(string[] args)
{
Axapta ax;
AxaptaRecord record;
Object carId, carBrand, model, modelYear, mileage;
try
{
// Create AX object and logon to AX
ax = new Axapta();
ax.Logon(null, null, null, null);
// Create an AxaptaRecord object from the
// table that will be used
using (record = ax.CreateAxaptaRecord("CarTable"))
{
// Execute the statement entered as parameter
record.ExecuteStmt("select * from %1
where %1.CarBrand like 'BMW'");
// Loop through the result of the statement.
while (record.Found)
{
// Set our local variables to be
// equal to the fields in the table
// for the current record.
carId = record.get_Field("CARID");
carBrand = record.get_Field("CARBRAND");
model = record.get_Field("MODEL");
modelYear = record.get_Field("MODELYEAR");
mileage = record.get_Field("MILEAGE");
// Write the result to the console
Console.WriteLine(carId + "t" +
carBrand + "t" +
model + "t" +
modelYear + "t" +
mileage);
// Go to the next record in the result set
record.Next();
}
// End the AX session
ax.Logoff();
// Make sure the console stays up
// until a key is pressed
Console.ReadKey();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Execute the program by pressing Ctrl + F5 and take a look at the result. It should look something like this:

Exception classes
The .NET Business Connector also consists of a number of exceptions that AX can raise. These exceptions are controlled by exception classes that will help you determine further actions if an exception occurs. In the previous example I have only used the standard .NET exception class, but if you would like to write solid code you should consider using the exceptions from the .NET Business Connector instead.
|
Exception |
Description |
|
AlreadyLoggedOnException |
Thrown when logon to AX fails because the user is already logged on. |
|
AxBufferNotValidException |
Thrown when the AX buffer being referenced is not valid. |
|
AxContainerNotValidException |
Thrown when the AX container being referenced is not valid. |
|
AxObjectNotValidException |
Thrown when the AX object being referenced is not valid. |
|
AxRecordNotValidException |
Thrown when the AX record being referenced is not valid. |
|
BusinessConnectorException |
Thrown when an unexpected error has occurred with the Business Connector. |
|
ConnectionLostException |
Thrown when the connection to the AOS is lost. |
|
DebuggerStopException |
Thrown when the AX debugger has been stopped. |
|
ExecutionErrorException |
Thrown when an unexpected system exception has occurred. |
|
FatalErrorLoggedOffException |
Thrown when the AX session is closed due to an error. |
|
InitializationFailedException |
Thrown when the .NET Business Connector fails to initialize. |
|
InvalidReturnValueException |
Thrown when a return value is invalid. |
|
LogonAsGuestNotSupportedException |
Thrown when trying to logon as Guest from a non-web (IIS) scenario, for example, directly through .NET Business Connector. |
|
LogonFailedException |
Thrown during an AX logon failure. |
|
LogonSystemChangedException |
Thrown when logon to AX fails due to logon parameters not matching those currently in use for the Business Connector. |
|
LogonUserLockedOutException |
Thrown when the user attempting a logon is locked out due to exceeding the maximum number of logon attempts. |
|
MethodUnknownException |
Thrown when the method being referenced is not known by the system. |
|
NoIISRightsException |
Thrown when logon to AX fails because the user has not been granted the proper IIS rights. |
|
NoSecurityKeyException |
Thrown when a requested operation fails because the required security key does not exist. |
|
NotLoggedOnException |
Thrown when a requested operation cannot be performed because the user is not logged on. |
|
PermissionDeniedException |
Thrown when permission to execute an operation is denied. |
|
ServerCommunicationErrorException |
Thrown when communication between the client computer and the server fails. |
|
ServerOutOfReachException |
Thrown when communication with the server cannot be established. |
|
ServerOutOfResourcesException |
Thrown when the server terminates the session due to the server not having enough free resources. |
|
ServerUnavailableException |
Thrown when the server is unavailable. AX will attempt to connect to other servers listed in the client confguration. |
|
SessionTerminatedException |
Thrown when the server terminates the session. |
|
UnknownClassHandleException |
Thrown when the class being referenced does not exist. |
|
UnknownRecordException |
Thrown when the record being referenced does not exist. |
|
UnknownTextException |
Thrown when an unknown text exception has occurred. |
|
UnknownXPPClassException |
Thrown when an unknown X++ exception has occurred. |
|
XppException |
Thrown when an X++ exception has occurred. |
Summary
You should now be able to use .NET classes in AX and also use AX code in .NET classes.
When using .NET classes in AX you had to add the reference to the .NET class first and then use the code in the .NET class from X++ code. AX makes this possible by using a bridge to the Common Language Runtime.
When you want to use AX functionality in your .NET classes you first had to add a reference to the .NET Business Connector. Then you had to use the marshalled classes that the .NET Business Connector consists of in your .NET code in order to call class methods, manipulate data or read data from AX.
For more examples on how to use the .NET Business Connector to create cool features in other programs, take a look at the Microsoft Dynamics Snap for AX:http://www.codeplex.com/axsnap
The Microsoft Dynamics Snap for AX are free applications that exemplifies how Microsoft Office applications like Excel, Word, and Outlook can be used to integrate with AX.
One of the applications is Business Data Lookup. It enables users that work in Word, Excel, and Outlook to lookup information in AX and paste data back to the Microsoft Offce application.
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
|
|



Post new comment