Change File Ownership through X++ in Dynamics AX

This article shows a little trick that might be needed for testing AX AIF file adapter based integration. We all know that how frustrating it can be to setup input file ownership to current AX user while testing otherwise AX will complain about it.

Here is a small static function with filepath as a parameter. This function will set current AX user as the owner of the input file. This function can be called right before the call to fileSystem.ReadFile(filePath) in ClassesAifFileSystemReceiveAdapterreadFile.

   1:  static client protected void SetFileOwnership2CurUser(FilePath _filePath)
   2:  {
   3:      UserInfo                                            userInfo;
   4:      System.IO.FileInfo                                  fileInfo;
   5:      System.Security.AccessControl.FileSecurity          fileSecurity;
   6:      System.Security.Principal.SecurityIdentifier        sid;
   7:      System.Security.AccessControl.AccessControlSections acSections;
   8:      ;
  10:      //select current user
  11:      select userInfo
  12:          where userInfo.Id == curuserid();
  14:      try
  15:      {
  16:          new InteropPermission(InteropKind::ClrInterop).assert();
  17:          fileInfo           = new System.IO.FileInfo(_filePath);
  18:          acSections      = System.Security.AccessControl.AccessControlSections::Owner;
  19:          fileSecurity       = fileInfo.GetAccessControl(acSections);
  20:          sid = new System.Security.Principal.SecurityIdentifier(userInfo.sid);
  21:          //set ownership
  22:          fileSecurity.SetOwner(sid);
  23:          fileInfo.SetAccessControl(fileSecurity);
  24:          CodeAccessPermission::revertAssert();
  25:      }
  26:      catch
  27:      {
  28:          throw error(AifUtil::getClrErrorMessage());
  29:      }
  30:  }

Join me on facebook and feel free to post your comments / feedback / queries.

If you liked the story and want to see more of this kind of content, please follow our twitter handle @CursorRun or FB page @CursorRun
Default image
Rahul Sharma
Rahul is a technology enthusiast, solutions architect, trainer, and blogger, working on various Microsoft and open source solutions with more than 18 years of industry experience. He specially takes interest in designing enterprise applications, cloud integrations, IoT, and other architecture rich business solutions.

Leave a Reply

%d bloggers like this: