Tuesday 11 December 2012

Executing .NET code in Dynamics AX 2009: Solving error “the selected file is not a valid .NET assembly”


To increase the functionality of AX is possible to execute .NET code.
In general terms the idea is create a .dll with the .NET code and after add the .dll as reference in AX. After that you’ll be able of execute the .NET code in AX.

Just follow these steps:

1. Create a new project (I’m going to use Visual Studio 2010):

VisualStudio2010_NewProject

VisualStudio_NewDLLProject

Please be sure that you’ve selected the .NET Framework 3.5: if you select a newest one AX won’t work with your .dll:

VS2010_NewProject_NETFramework35

2. Create the .NET code you want to execute:
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <p>using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
     
    namespace MyDLL
    {
        public class TestingMyDLL
        {
            public void showMessage()
            {
                 
                MessageBox.Show("Executing .NET code with AX!");
            }
        }
    }</p><p> </p>
3. Build the solution:

VS2010_BuildSolutionDLL

4. Locate the .dll generated under the Project folder:

VisualStudio2010_LocateDLLGenerated

And copy it in your AX testing environment. Take care with the path in which you copy your .dll: it has to be located in the “bin” directory of your AX installation (in my case C:\Program Files (x86)\Microsoft Dynamics AX\50\Client\Bin) otherwise AX will show you the following message:

DynamicsAX2009_AddingReferenceWarning

And maybe you wont use the library:

DynamicsAX2009_UsingDLLError

5. Import the dll into AX. Open the AOT and do right click in the References node and click ‘Add reference’:

DynamicsAX2009_AOTAddReference

DynamicsAX2009_AddingReferenceBrowse

DynamicsAX_ReferenceAdded

Press OK.

If you selected the .NET Framework 4 when creating the project in step 1 you’ll get this error trying to import the reference:The selected file is not a valid .NET assembly, therefore the refence cannot be added.

VS2010_NETFramework_Error

6. Create a new job/class in AX:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static void testingNETCode(Args _args)
{
    MyDLL.TestingMyDLL          testingDll;
    InteropPermission           permission;
    ;
 
    try
    {
        permission = new InteropPermission(InteropKind::DllInterop);
        permission.assert();
 
        testingDll = new MyDLL.TestingMyDLL();
        testingDll.showMessage();
    }
    catch
    {
        error('Error executing DLL code');
    }
}

7. Run the job:

DynamicsAX_ExecutingNETCode_Job

No comments:

Post a Comment