web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Suggested answer

To attach the file on form attachment

(3) ShareShare
ReportReport
Posted on by 1,836
hi everyone
I was trying to attach the file to the from attachment in my form to header table , but it is not getting attach it is going to the view history ,
in sql is is showing  but on front end it is not visible in attachment , and when i click view history it is there , can anyone help me on this to how can i get this done .
 
Below is my code 
 public void generateAndAttachSalaryRegisterExcel(ISPAccountingPeriod accountingPeriod, RefRecId headerRecId)
    {
        SrsReportRunController controller = new SrsReportRunController();
        SalaryRegisterByEmpContract contract = new SalaryRegisterByEmpContract();
        SRSPrintDestinationSettings  settings;
        SrsReportDataContract        reportDataContract;
        SRSReportRunService          srsReportRunService = new SrsReportRunService();
        DocuRef                      docuRef;
        DocuActionArchive            archive;
        SRSProxy                     srsProxy;
        Map                          reportParamMap;
        Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[] parameterValueArray;
        str reportPath = ssrsReportStr(PayRegisterByEmp, Report);
        str                          baseFolder,folderName,folderPath,tempFilePath,fileName;
        TransDate                    currentDate;
        System.DateTime              sysDateTime;

        baseFolder = @'C:\Temp';
        folderName = 'Emp Salary Register';
        folderPath = baseFolder + '\\' + folderName;

        // Create folder if it doesn't exist
        System.IO.Directory::CreateDirectory(folderPath);

        currentDate = DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());
        sysDateTime =  DateTimeUtil::newDateTime(currentDate, DateTimeUtil::getTimeNow(DateTimeUtil::getUserPreferredTimeZone()));
        fileName = strFmt("SalaryRegister_%1.xlsx", sysDateTime.ToString("ddMMyyyyHHmmss"));

        tempFilePath = folderPath + '\\' + fileName;

        // Create print settings
        settings = new SRSPrintDestinationSettings();
        settings.printMediumType(SRSPrintMediumType::File);
        settings.fileFormat(SRSReportFileFormat::Excel);
        settings.fileName(tempFilePath);

        // Setup controller
        controller = new SrsReportRunController();
        controller.parmReportName(reportPath);
        controller.parmShowDialog(false);
        controller.parmLoadFromSysLastValue(false);
    
        // Set contract
        contract = new ARPayrollRunSalaryRegisterByEmpContract();
        contract.parmAccountingPeriod(accountingPeriod);

        // Assign contracts
        reportDataContract = controller.parmReportContract();
        reportDataContract.parmRdpContract(contract);
        reportDataContract.parmPrintSettings(settings);
        reportDataContract.parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());
        reportDataContract.parmReportExecutionInfo(new SRSReportExecutionInfo());

        // Required step: Get data contract from SSRS runtime
        srsReportRunService.getReportDataContract(reportPath);

        // REQUIRED: preRunReport – run validation / setup
        srsReportRunService.preRunReport(reportDataContract);

        reportParamMap = srsReportRunService.createParamMapFromContract(reportDataContract);
        parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParamMap);

        // Render report to byte[]
        srsProxy = SRSProxy::constructWithConfiguration(SRSConfiguration::getDefaultServerConfiguration());
        System.Byte[] reportBytes = srsProxy.renderReportToByteArray(
        controller.parmReportContract().parmReportPath(),
        parameterValueArray,
        settings.fileFormat(),
        settings.deviceinfo());

        // Save reportBytes to file manually
        System.IO.File::WriteAllBytes(tempFilePath, reportBytes);

        System.IO.Stream stream = new System.IO.MemoryStream(reportBytes);

        this.attachDocumentToHeaderFromStream(
                                             stream,
                                             headerRecId,
                                             tableNum(EmpSalaryRegister),
                                             fileName
                                             );



    }
 public void attachDocumentToHeaderFromStream(
    System.IO.Stream stream,
    RefRecId headerRecId,
    TableId headerTableId,
    str fileName,
    str docuTypeId = 'File', // Optional: Specific docuType ID, must exist
    str mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') // Excel MIME type
    {
        DocuRef docuRef;
        DocuType docuType;

        if (!stream || headerRecId == 0 || headerTableId == 0)
        {
            throw error("Invalid parameters for document attachment.");
        }

        // Validate document type
        docuType = DocuType::find(docuTypeId);
        if (!docuType.RecId)
        {
            throw error(strFmt("Document type '%1' not found.", docuTypeId));
        }

        // Attach the file using standard API
        docuRef = DocumentManagement::attachFile(
        headerTableId,                         // TableId of the record
        headerRecId,                           // RecId of the record
        'dat',                              // DataAreaId (current company)
        enum2Symbol(enumNum(SRSPrintMediumType), SRSPrintMediumType::File), // Print medium type
        stream,                                // File stream
        fileName,                              // File name
        mimeType,                              // MIME type
        fileName);                             // Description (optional)

        if (docuRef.RecId)
        {
            info(strFmt("Document '%1' successfully attached to record %2.", fileName, headerRecId));
        }
        else
        {
            warning(strFmt("Failed to attach document '%1' to record %2.", fileName, headerRecId));
        }
    }
thanks,
Regards,
 
Dinesh
I have the same question (0)
  • Martin Dráb Profile Picture
    236,570 Most Valuable Professional on at
    To attach the file on form attachment
    What forms are you talking about in "i click view history"? Does it mean that you attached the file to a different record than intended?
     
    Do you use the file for anything? You get the data in the byte array and that's what you stored as an attachement. You also write it to a file, but never read the data from there.
     
    By the way, the fourth parameter of attachFile(). has nothing to do with SRSPrintMediumType. The type is DocuTypeId and it's used to identify the type of attachment, configured in document management. You have that in docuTypeId variable; use it.
     
     
  • Dineshkarlekar Profile Picture
    1,836 on at
    To attach the file on form attachment
    this is my form , i want to flow the file from this code to its attachment , but attachment are empty as you can see in second from , but when i click view history button on attachnment form , thery are available here , but i want it to be shown on attachment form.please guide me on this 
  • Dineshkarlekar Profile Picture
    1,836 on at
    To attach the file on form attachment
    I it possible to remove the file part ,  like i am creating the  folder and saving the excel there , but to directly render th report in excel and flow it into attachment without saving it , is that possible if yes i will remove the file saving saving to folder in my environment .
     
    thanks,
    Regards,
  • Martin Dráb Profile Picture
    236,570 Most Valuable Professional on at
    To attach the file on form attachment
    You first screenshot shows that you have no record in the form. If you want to see attachements of a record, you need to use a form where the record is displayed and select the record before looking at its attachmments.
     
    Saving a report to memory instead of a file is possible and you're already doing it in your code. You're using renderReportToByteArray() for that.
  • Dineshkarlekar Profile Picture
    1,836 on at
    To attach the file on form attachment
    thanks for reply martin ,
     
    I just put the screen shot of empty form for reference, so that it gives you more clarity , i am having records in my header table and are showing on form too, i am passing the recid and table id of that .can you tell me, do i need to do any changes in my attachment  code.please
     
    thanks,
    regards,
     
    Dinesh 
  • Martin Dráb Profile Picture
    236,570 Most Valuable Professional on at
    To attach the file on form attachment
    You can't fix the code before identifying the problem. 
     
    Instead of staring at source code, check out why the record isn't shown in the form. Compare  the data in database with the query used by the form.

    I see you attached the file in dat company. Are you in the same company in GUI?
        
    When you use View history without any record to work  with, the correct behavior would be showing  nothing. You're now either seeing history of all attachements, or you have corrupt data in the history table  and you see those that refers to RecId = 0. Again, check the query and the data. In either case, it's a different problem than why you don't see the attachment, 
  • Suggested answer
    DAnny3211 Profile Picture
    11,389 on at
    To attach the file on form attachment

    Hi Dinesh 👋

    Thanks for sharing your code and question!

    From your description, it seems the file is being successfully generated and stored, and it appears in the document history, but not in the visible attachments section of the form. This usually indicates a mismatch in how the document is being linked or displayed.

    ✅ Here are a few things to check and try:

    1. Check the DocuType configuration

      • Ensure the DocuType used (File) is configured to show in the Attachments section of the form.
      • Go to Document Management > Document Types, open the File type, and verify that:
        • Active is set to Yes
        • Group is set to File or Attachment
        • Default File Type is appropriate
        • Visible in Document Handling is enabled
    2. Verify the DataAreaId

      • In your attachDocumentToHeaderFromStream method, you're hardcoding 'dat' as the DataAreaId.
      • This should be dynamically set to CompanyInfo::currentDataAreaId() or curExt() to match the current company context.
     
    'dat' → CompanyInfo::currentDataAreaId()
    1. Ensure the form is configured to show attachments

      • The form displaying the header record must have the Document Handling control properly configured.
      • Check if the form has a Document Handler or DocuView control bound to the correct table and record.
    2. Confirm the record context

      • Make sure the headerRecId and headerTableId passed to the attachment method match the record currently open in the form.
    3. Debug with DocuRef viewer

      • Try opening the Document Handling form manually for the record to see if the attachment appears there.
      • If it does, the issue is likely with the form UI, not the attachment logic.

    ✅ Please mark this reply as helpful if it answered your question.
    Best regards! 👋

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
CA Neeraj Kumar Profile Picture

CA Neeraj Kumar 1,922

#1
CA Neeraj Kumar Profile Picture

CA Neeraj Kumar 1,922

#3
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 835 Super User 2025 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans