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, ...
Answered

Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO

(0) ShareShare
ReportReport
Posted on by 17

Hello everyone,

 

I’m facing an issue when trying to automatically attach an XML file to a Batch Job in Dynamics 365 Finance & Operations.

 

I am generating an XML file inside a class that extends RunBaseBatch.

After generating the file, I want to attach it to the Batch Job.

 

What works


  • The batch job executes successfully.

  • The XML file is generated correctly.

  • The DocuRef + DocuValue records are created in SQL with the correct:

  • RefRecId = BatchJob RecId

    • RefTableId = 12070 (BatchJob)

    • RefCompanyId = correct company

    • File is saved through IDocumentStorageProvider.SaveFile  

What does NOT work

 

The attachment does not appear in the Batch Job form.

 

I have checked SQL and the DocuRef/DocuValue entries are created correctly, but the UI does not show the attachment.

 

I also tried using the class DocuManagement (method attachFileForReference), but I still get the same result.

 

public void run()
{
    XmlSAFTGenerator xmlSAFTGenerator;
    str result;
    result = xmlSAFTGenerator.GerarArquivoXML(
        _nameFile,
        _auditFileVersion,
        _taxAccountingBasis,
        _startDate,
        _endDate,
        _fiscalYear
    );
    // XML file path
    str xmlFileName = _nameFile + ".xml";
    str xmlFilePath = System.IO.Path::GetTempPath() + xmlFileName;
    // Attach XML to Batch Job
    this.attachFileToBatchJob(_batchJobId, xmlFileName, xmlFilePath);
}

private void attachFileToBatchJob(RefRecId _batchJob, str _xmlFileName, str _filePath)
{
    DocuRef docuRef;
    DocuValue docuValue;
    DocumentLocation location;
    IDocumentStorageProvider storageProvider;
    System.IO.MemoryStream fileStream =
        new System.IO.MemoryStream(System.IO.File::ReadAllBytes(_filePath));
    DocuType docType = DocuType::find("File");
    storageProvider = Docu::GetStorageProvider(docType, true, curUserId());
    ttsBegin;
    docuValue.clear();
    docuValue.FileId            = newGuid();
    docuValue.OriginalFileName  = _xmlFileName;
    docuValue.FileName          = _xmlFileName;
    docuValue.Name              = _xmlFileName;
    docuValue.FileType          = "xml";
    docuValue.StorageProviderId = storageProvider.ProviderId;
    location = storageProvider.SaveFile(
        docuValue.FileId,
        storageProvider.GenerateUniqueName(_xmlFileName),
        "application/xml",
        fileStream
    );
    if (location)
    {
        if (location.get_NavigationUri())
            docuValue.Path = location.get_NavigationUri().ToString();
        if (location.get_AccessUri())
            docuValue.AccessInformation = location.get_AccessUri().ToString();
    }
    docuValue.insert();
    ttsCommit;
    ttsBegin;
    docuRef.clear();
    docuRef.RefTableId   = tableNum(BatchJob);
    docuRef.RefRecId     = _batchJob;
    docuRef.RefCompanyId = curext();
    docuRef.TypeId       = "File";
    docuRef.Name         = _xmlFileName;
    docuRef.ValueRecId   = docuValue.RecId;
    docuRef.insert();
    ttsCommit;
    info(strFmt("SAF-T XML attached to Batch Job %1", _batchJob));
}



Has anyone successfully attached documents to a Batch Job?

Any help, guidance, or working example would be greatly appreciated.

Thank you!


 

I have the same question (0)
  • Martin Dráb Profile Picture
    237,077 Most Valuable Professional on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    Which form are you using?
     
    Is document management enabled for BatchJob table?
  • JR-26060826-0 Profile Picture
    17 on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    Hi @Martin Dráb, thanks for your reply,

    To call the The batch job Im using a form that I created, 
    [Form]
    public class FormExport extends FormRun
    {
       
        [Control("Button")]
        class RunBatch
        {
            /// <summary>
            ///
            /// </summary>
            public void clicked()
            {
                super();
                // Create an instance of the batch class
                MyClass batchJob = new MyClass ();

                str strNameFile;
                str strAuditFileVersion;
                str strTaxAccountingBasis;
                str strStartDate;
                str strEndDate;
                str strFiscalYear;
                
     
                FormControl control1 = FormRun.design().controlName('FiscalYear');
                FormControl control2 = FormRun.design().controlName('StringNameFile');
                FormControl control3 = FormRun.design().controlName('AuditFileVersion');
                FormControl control4 = FormRun.design().controlName('TaxAccountingBasis');
                FormControl control5 = FormRun.design().controlName('StartDate');
                FormControl control6 = FormRun.design().controlName('EndDate');

                strFiscalYear = control1.valueStr();
                strNameFile = control2.valueStr();
                strAuditFileVersion = control3.valueStr();
                strTaxAccountingBasis = control4.valuestr();
                strStartDate = control5.valueStr();
                strEndDate = control6.valueStr();

                MyClass ::submitBatchJob(strNameFile,strAuditFileVersion,strTaxAccountingBasis,strStartDate,strEndDate,strFiscalYear);
              
                formRun.close();
            }
        }
    public static void submitBatchJob(Filename nameFile, str auditFileVersion, str taxAccountingBasis, str startDate, str endDate, str fiscalYear)
    {
        MyClass batchJob = new MyClass();

        batchJob._nameFile = nameFile;
        batchJob._auditFileVersion = auditFileVersion;
        batchJob._taxAccountingBasis = taxAccountingBasis;
        batchJob._startDate = startDate;
        batchJob._endDate = endDate;
        batchJob._fiscalYear = fiscalYear;

        BatchHeader batchHeader = BatchHeader::construct();

        batchHeader.AddTask(batchJob);

        batchHeader.save();

    }

    How can I check this? Is document management enabled for BatchJob table?
     
  • Martin Dráb Profile Picture
    237,077 Most Valuable Professional on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    Is FormExport the form where you're unable to see the attachment? What about the standard BatchJob form? Can you see them there?
     
    Tables for document management are configured at Organization administration > Document management > Active document tables.
     
    It's off topic, but note that you don't need code like formRun.design().controlName('FiscalYear'). If they're unbound controls (I suppose so), simply set Auto Declaration property of the controls to Yes and then refer to them in code by name, such as FiscalYear.text(). If they were bound to a data source, you'd use them throw the data source buffer (myTable.FiscalYear).
  • Vigneshvaran Profile Picture
    350 on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    Without batch job, normally if you are running means, is this working as expected?
  • JR-26060826-0 Profile Picture
    17 on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    Hello @Martin Dráb

    The form where I can´t see the attachment is the  standard BatchJob form, I open my batch job and theres nothing in the attachmens






    I checked this on Common > Inquiries > Batch jobs > My Batch jobs and 

    System administration > Inquiries > Batch jobs.


    Tables for document management are configured at Organization administration > Document management > Active document tables.

    It was not.

    I set it up like this now.




    Is it correct? 

    Also thanks for the advices 
  • Verified answer
    Martin Dráb Profile Picture
    237,077 Most Valuable Professional on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    Okay, now try to add an attachment (of File type) through GUI. Did it succeed and do you see now a single attachment while you expect two? If so, it must mean that the one created by your code isn't correct; it doesn't meet the criteria of the query looking for attachments of the given job. You can compare the DocuRef and DocuValue records to see the differences. You can also check the query compare its conditions with your data.
     
    By the way, I see no reason for avoiding the DocumentManagement class and rather then trying to write the code on your own. It means an extra and a risk of bugs. Simply using the tested standard code is both easier and safer.
  • JR-26060826-0 Profile Picture
    17 on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    Hi @Martin Dráb

    I used again the DocumentManagement class and at first it didn´t work no attachments, so as you sugested I created one manually.



    My problem was that I was using curext()

     DocumentManagement::attachFileForReference(
           tableNum(BatchJob),             
           currentBatchNow.BatchJobId,                 
           'dat',                       // curExt() before now it works thanks
           docuType.TypeId,                     
           memoryStream,                   
           xmlFileName,                    
           _nameFile,                      
           "SAF-T gerado automaticamente." 
           );

    But my question is why? aahha Why does it need to be dat? Can I change this to be my Company? 



    By the Way 2 more things:

    The Batch job finishes But in the Logs I have this error: 



    Any idea?


    2 - Currently Im saving the generated xml file on the a local file
     
    xmlDoc.save(xmlFilePath);
            
    System.IO.MemoryStream memoryStream;
    memoryStream = new System.IO.MemoryStream(System.IO.File::ReadAllBytes(xmlFilePath));
    File::SendFileToUser(memoryStream, xmlFilename);

    But in the future I will generate big files is there another solution for saving this file so it doesnt store local memory?

    Thanks again for all youre help!

     
  • Martin Dráb Profile Picture
    237,077 Most Valuable Professional on at
    Unable to Attach generated XML File to a Batch Job in Dynamics 365 FO
    The reason is that BatchJob table is shared across companies. It doesn't even have DataAreaId field; when the company reference is needed, it's considered to be in the default company ('dat').
     
    Regarding the error, use the debugger to find where it was thrown.
     
    Please create a new thread for your new question about the local file and explain your problem in detail there. Don't forget to mention the type of your xmlDoc variable.

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…

Pallavi Phade – Community Spotlight

We are honored to recognize Pallavi Phade as our Community Spotlight honoree for…

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

#1
Martin Dráb Profile Picture

Martin Dráb 628 Most Valuable Professional

#2
CU05031448-0 Profile Picture

CU05031448-0 578

#3
André Arnaud de Calavon Profile Picture

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

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans