Showing posts with label Attachment. Show all posts
Showing posts with label Attachment. Show all posts

Wednesday, December 3, 2025

Code to attach multiple files from a folder X++

My requirement is to attach multiple files from a folder to a specific record. This code selects only the files that are allowed by D365 Finance & Operations.

  public static void main(Args _args)

  {

      FilePath filePath = @"C:\Temp\saitesting"; //Folder path

      PurchId  purchId  = "000030";

      int attachedCount = 0;

      int skippedCount  = 0;

      PurchTable purchTable = PurchTable::find(purchId, true);

      if (!purchTable)

      {

          throw error(strFmt("PO %1 not found", purchId));

      }

      DocuType docType = DocuType::find("File");

      if (!docType)

      {

          throw error("@SYS19389");

      }

      System.String[] files = System.IO.Directory::GetFiles(filePath, "*.*");

      System.Collections.IEnumerator enumerator = files.GetEnumerator();

      while (enumerator.MoveNext())

      {

          try

          {

              Filename fileFullPath = enumerator.get_Current();

              Filename fileNameOnly = System.IO.Path::GetFileName(fileFullPath);

              str fileExtension = Docu::GetFileExtension(fileNameOnly);

              if (fileExtension && !Docu::validateExtension(fileExtension))

              {

                  skippedCount++;

                  warning(strFmt("Skipped %1 due to invalid extension", fileNameOnly));

                  continue;

              }

              System.IO.FileStream fileStream =

          new System.IO.FileStream(fileFullPath, System.IO.FileMode::Open, System.IO.FileAccess::Read);

              System.IO.MemoryStream memStream = new System.IO.MemoryStream();

              fileStream.CopyTo(memStream);

              fileStream.Close();

              memStream.Position = 0;

              ttsBegin;

              DocumentManagement::attachFileForReference(

          purchTable.TableId,

          purchTable.RecId,

          curext(),

          docType.TypeId,

          memStream,

          fileNameOnly,

          fileNameOnly,

          ''

      );

              ttsCommit;

              attachedCount++;

              info(strFmt("Attached %1 to PO %2", fileNameOnly, purchId));

          }

          catch (Exception::Error)

          {

              skippedCount++;

              warning(strFmt("Error attaching %1: %2", enumerator.get_Current(), exceptionTextFallThrough()));

          }

      }

      info(strFmt("Attachment job completed. %1 files attached, %2 files skipped.", attachedCount, skippedCount));

  }

Reference blog :

https://daxture.blogspot.com/2017/04/ax-2012-reading-files-from-directory.html

Friday, May 31, 2024

X++ code to attach a file in D365F&O

 using Microsoft.Dynamics.ApplicationPlatform.Services.Instrumentation;

using Microsoft.DynamicsOnline.Infrastructure.Components.SharedServiceUnitStorage;

using Microsoft.Dynamics.AX.Framework.FileManagement;

internal final class RunnableClass1

{

    /// <summary>

    /// Class entry point. The system will call this method when a designated menu 

    /// is selected or when execution starts and this class is set as the startup class.

    /// </summary>

    /// <param name = "_args">The specified arguments.</param>

   

    public static void main(Args _args)

    {

        boolean                     ret = false;

        str docfiletype;

        Microsoft.Dynamics.AX.Framework.FileManagement.IDocumentStorageProvider storageProvider;

        DocuRef     docuref;

        str downloadUrl;

        Filename    _Filename = 'GeneralLedger-General journal custom.xlsx';

        FilePath    _filePath = @'C:\Users\Admin41df0ec1e1\Downloads\GeneralLedger-General journal.xlsx';

        System.IO.Stream    _stream;

        _stream = File::UseFileFromURL(_filePath);

        str _contentType = System.Web.MimeMapping::GetMimeMapping(_filePath);

        DocuType fileType = DocuType::find(DocuType::typeFile());

        storageProvider = Docu::GetStorageProvider(fileType, true, curUserId());


        if(storageProvider)

        {

            str uniqueFileName = storageProvider.GenerateUniqueName(_Filename);

            str fileNameWithoutExtension = System.IO.Path::GetFileNameWithoutExtension(_filePath);

            str fileExtension = Docu::GetFileExtension(uniqueFileName);

  

            if(Docu::validateExtension(fileExtension))

            {

                guid FileId = newGuid();

                DocuValue docValue;

                docValue.Name = fileNameWithoutExtension;

                docValue.FileId = FileId;

                docValue.FileName = uniqueFileName;

                docValue.FileType = "xlsx";//fileExtension;

                docValue.OriginalFileName = _Filename;

                docValue.Type = DocuValueType::Others;

                docValue.StorageProviderId = storageProvider.ProviderId;

                DocumentLocation location = storageProvider.SaveFile(docValue.FileId, uniqueFileName, contentType, stream);

                

                if (location != null)

                {

                    if(location.NavigationUri)

                    {

                        docValue.Path = location.get_NavigationUri().ToString();

                    }


                    if(location.AccessUri)

                    {

                        docValue.AccessInformation = location.get_AccessUri().ToString();

                        //info(docValue.AccessInformation);

                    }


                    if (docValue.validateWrite())

                    {

                       

                        docValue.insert();

                        DocuUploadResult DocuUploadResult =  new DocuUploadResult(_fileName, _contentType, false, "", newGuid());

                        DocuUploadResult.fileId(FileId);

                         docuref = DocuUploadResult.createDocuRef(9615,68719508511,DocuType::typeFile());

                        if(docuref)

                        {

                            ret =  true;

                        }

                        else

                        {

                            ret =  false;

                        }

                    }        

                }

             }

        }

    }


}