RPC error 1702 when calling a WinAPI method from a batch job

You probably already noticed that error messages are sometimes not really helpful when you are trying to understand a problem. The following code creates such misleading error message:

    1:  public void run()
    2:  {
    3:  ;
    4:  if(WinApi::folderExists(@"c:\temp\"))
    5:      info("Folder exists");
    6:  else
    7:      info("Folder does not exists");
    8:  }

If you do execute this code in a batch job, it will produce the following error message:

RPC error: RPC exception 1702 occurred in session xxx

1702 means:

The binding handle is invalid.

A complete list of RPC errors is available here.

But this error message has, of course, nothing to do with the real cause of the problem. The RPC 1702 is unfortunately in Ax 2009 (RTM and SP1) always thrown when you call a client method from a batch job. If you have a look at the code of the WinApi::folderExists(str filename):

    1:  client static boolean folderExists(Filename _filename)
    2:  {
    3:      boolean ret;
    4:      ;
    5:      ret = System.IO.Directory::Exists(_filename);
    6:      return ret;
    7:  }

you see that this method can’t be executed on the AOS because of the “client” keyword. It’s true that this should not work and create an error message (since batch jobs are executed on the AOS), but it should normally be a meaningful message.

Instead of calling this client method, you should change your code, so that this call can be executed on the server. For example like this:

    1:  public void run()
    2:  {
    3:      InteropPermission   interopPerm;
    4:      boolean isFolderExist;
    5:      ;
    6:   
    7:      interopPerm = new InteropPermission(InteropKind::ClrInterop);
    8:      interopPerm.assert();
    9:      isFolderExist = System.IO.Directory::Exists(@"c:\temp\");
   10:      
   11:      if(isFolderExist)
   12:      {
   13:          info("Folder exists");
   14:      }
   15:      else
   16:      {
   17:          info("Folder does not exists");
   18:      }
   19:   
   20:      CodeAccessPermission::revertAssert();
   21:  }
  
 Update (17/07/2009):
 You can find a blog entry from Klaas about this subject here:
 https://www.artofcreation.be/2009/04/08/winapi-rpc-1702-and-findfirstfilew/