A blog offering various X++ code snippets and tips for Microsoft Dynamics AX

Saturday, July 26, 2008

Compiling and running code at run time

Welcome to another lesson.

Here I will discuss how you can compile and run your code at run time. Similar to the scenario in the previous lesson, you might want to create certain code on the fly, when at compile time you do not know what should this code consist of. Therefore, you build the source code as a string based on certain conditions in your code.

Beware though, that this might pose a security risk and you must always call assert() on a valid (not null) SecurityPermission object before execute code which compiles and runs other code at run time. At the end of your dangerous code, you should then revert the permissions by using the following line of code:


  CodeAccessPermission::revertAssert();


Note: For the sake of clarity I will skip code relating to permissions in this lesson.

Let's get down to a simple example:


static void compileAtRunTime(Args _args)
{
  XppCompiler compiler;
  str sourceCode;
  ;
  sourceCode = @'
          static void runTimeMethod()
          {
            ;
            info("hello");
          }';

  compiler = new XppCompiler();

  // If some source code exists and it successfully compiled
  if (sourceCode && compiler.compile(sourceCode))
  {
    // Execute the source code
    // Displays an infolog with "hello"
    compiler.execute(sourceCode);
  }
}


Obviously, the above code is not very useful, because the source code is hardcoded. In practice you would build your source code based on different conditions that you want to cater for.

If you any questions or comments e-mail me on: mirko@mirkobonello.com

No comments: