Thursday 9 August 2018

Email SSRS Report As an Attachment D365FO/ AX 7.0

As everyone knows that this task is too simple in AX 2012, Where we save the file in client or server file systems and then send as Email attachment.

Things are a bit more complicated when it comes to D365 in cloud. You are no longer able to save the file locally as storage now move to Azure.

Following is the code to convert the SSRS report in Binaries 



public class ConvertReportPDF
{

    public static void main(Args _args)
    {
       
  
        Filename                        fileName = "P000173_AbcTest.pdf";
        SrsReportRunController    controller = new SrsReportRunController();
        SLD_TaxProfileContract   contract = new SLD_TaxProfileContract();
        SRSPrintDestinationSettings     settings;
        Array                           arrayFiles;
        System.Byte[]                   reportBytes = new System.Byte[0]();
        SRSProxy                        srsProxy;
        SRSReportRunService             srsReportRunService = newSrsReportRunService();
       Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[]  parameterValueArray;
        Map reportParametersMap;
        SRSReportExecutionInfo executionInfo = new SRSReportExecutionInfo();
        ;

  
        contract.parmAccountNum('K-VDR-000001');
        contract.parmAccountType(SLD_AccountType::Vendor);
        // Provide details to controller and add contract
        controller.parmArgs(_args);
        controller.parmReportName(ssrsReportStr(SLD_TaxProfile, Report));
        controller.parmShowDialog(false);
        controller.parmLoadFromSysLastValue(false);
        controller.parmReportContract().parmRdpContract(contract);
        // Provide printer settings
        settings = controller.parmReportContract().parmPrintSettings();
        settings.printMediumType(SRSPrintMediumType::File);
        settings.fileName(fileName);
        settings.fileFormat(SRSReportFileFormat::PDF);

        // Below is a part of code responsible for rendering the report
       controller.parmReportContract().parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());
        controller.parmReportContract().parmReportExecutionInfo(executionInfo);

       srsReportRunService.getReportDataContract(controller.parmreportcontract().parmReportName());
        srsReportRunService.preRunReport(controller.parmreportcontract());
        reportParametersMap = srsReportRunService.createParamMapFromContract(controller.parmReportContract());
        parameterValueArray =SrsReportRunUtil::getParameterValueArray(reportParametersMap);

        srsProxy =SRSProxy::constructWithConfiguration(controller.parmReportContract().parmReportServerConfig());
        // Actual rendering to byte array
        reportBytes = srsproxy.renderReportToByteArray(controller.parmreportcontract().parmreportpath(),
                                              parameterValueArray,
                                              settings.fileFormat(),
                                              settings.deviceinfo());
    



        // You can also convert the report Bytes into an xpp BinData object if needed
        container binData;
        Binary binaryData;
        System.IO.MemoryStream mstream = new System.IO.MemoryStream(reportBytes);
        binaryData = Binary::constructFromMemoryStream(mstream);
       // System.IO.File::WriteAllBytes("C:\\backup\\"+fileName,reportBytes); // You can save the file on your local instance for verification
       

        if(binaryData)
        {
            binData = binaryData.getContainer();
        }
        Map map=new Map (Types::String,Types::String);
        map.insert("message","Its working fine for me");
        SLD_EmailAttachment::sendPDFEamilAttachment("EmailRecpt","en-us","Sheikh.Sohail@systemsltd.com",map,binData,"P000173_AbcTest");
    }

}


USE following code to send as Email Attachment 


class SLD_EmailAttachment

{


  

    public static void sendPDFEamilAttachment( SysEmailId      _emailId,
        LanguageId      _language,
        SysEmailAddress             _emailAddr,
        Map             _mappings,container _binData,str _fileName)
    {
        SysEmailItemId                   nextEmailItemId;
        SysEmailTable                    sysEmailTable;
        SysEmailMessageTable             sysEmailMessageTable;
        SysEmailContents                 sysEmailContents;
        SysOutgoingEmailTable            outgoingEmailTable;
        SysOutgoingEmailData             outgoingEmailData;
        Filename filename, FileExtension;
      
        FileExtension=".pdf";
       
        select sysEmailTable
               join    sysEmailMessageTable
                where sysEmailMessageTable.EmailId==sysEmailTable.EmailId
                    && sysEmailMessageTable.EmailId== _emailId
                    && sysEmailMessageTable.LanguageId==_language;
       
        if(sysEmailTable.RecId>0)
        {
            sysEmailContents=SysEmailMessage::stringExpand(sysEmailMessageTable.Mail, _mappings);
            nextEmailItemId = EventInbox::nextEventId();
      
            filename =strFmt("%1_%2.pdf",nextEmailItemId,_fileName);
    
    
            outgoingEmailTable.clear();
            outgoingEmailTable.Origin=sysEmailTable.Description;
            outgoingEmailTable.EmailItemId = nextEmailItemId;
            outgoingEmailTable.IsSystemEmail = NoYes::Yes;
            outgoingEmailTable.Sender = sysEmailTable.SenderAddr;
            outgoingEmailTable.SenderName = sysEmailTable.SenderName;
            outgoingEmailTable.Recipient = _emailAddr;
            outgoingEmailTable.Subject =SysEmailMessage::stringExpand(sysEmailMessageTable.Subject, _mappings);
            outgoingEmailTable.Priority = eMailPriority::High;
            outgoingEmailTable.WithRetries = NoYes::NO;
            outgoingEmailTable.RetryNum = 0;
            outgoingEmailTable.UserId = curUserId();
            outgoingEmailTable.Status = SysEmailStatus::Unsent;
            outgoingEmailTable.Message =  sysEmailContents;
            outgoingEmailTable.LatestStatusChangeDateTime =DateTimeUtil::getSystemDateTime();
            outgoingEmailTable.TemplateId= _emailId;
            outgoingEmailTable.insert();


            if(conLen(_binData)>0)
            {
                outgoingEmailData.clear();

                outgoingEmailData.EmailItemId = nextEmailItemId;
                outgoingEmailData.DataId = 1;
                outgoingEmailData.EmailDataType = SysEmailDataType::Attachment;
                outgoingEmailData.Data = _binData;
                outgoingEmailData.FileName = filename;
                outgoingEmailData.FileExtension =FileExtension;

                outgoingEmailData.insert();
            }
        }
    }

}

7 comments:

  1. Can you please help me How can i use above code to send Product Safety sheet along with Sales Invoice report as PDF in the mail .
    Actually , I created one job in D365 and used the above code , It is working fine for Sales Invoice Report and attching it in the mail as PDF but how to add the Safety sheet which is associate with each item in the sales invoice line in the same mail .
    Any suggestion.


    ReplyDelete
  2. I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. email extractor mobile

    ReplyDelete
  3. What is an outstanding post! “I’ll be back” (to read more of your content). Thanks for the nudge! bulk email subscription

    ReplyDelete
  4. Saved my day, thanks for sharing this masterpiece.

    ReplyDelete
  5. You bear through a awesome vacancy. I sanity definitely quarry it moreover personally suggest to my buddys. I am self-possessed they determination be benefited from this scene. LinkedIn Profile Scraper

    ReplyDelete
  6. It's possible to send multiple attachment through this code or is there any changes we have do to.

    ReplyDelete

Adding a newline into a string in C# and X++

Below is the sample code we can use for  adding a newline after every occurrence of "@" symbol in the string in C#   using System...