Save and send SSRS report as attachment through email using X++ code in Ax2012

 Hello Techies,

    Welcome to code trekking journey with me!

    I had a requirement where they wanted a functionality which will automate emailing the salary slip report to all the selected employees on a click of button. Here's the roadmap to implement the same.


Step 1 : Firstly created a form with required payroll data of all the employees.

    To allow them to send particular month's salary slip to employees, I have give two lookup fields for       selecting Year and Month and On clicking OK button the data on form will get filtered based on the      selected value from the lookup. 
    
    After filtering the data and selecting the employees, on click of 'Send Email' button the salary slip report will be downloaded to a given file path and same will be sent as an attachment to all the selected employees.

Step 2: Override the clicked() method of 'Send Email' button and write the below code in it.

           void clicked()

{

    HRMPayEmpPayDetails payDetails;

    SalaryslipController  SalaryslipController;

    SalaryslipContract    SalaryslipContract;

    SrsReportRunImpl            srsReportRun;

    ReportName                  reportName = "salaryslip.Report";

    // To get the user selected values, created the buffer of EDTs

    HRMYearSelect               yyyy;

    MonthsOfYear                mm;

    SrsReportRunController ssrsController;

    SalaryslipContract Contract;

    HRMYearSelect hrmYearsel;

    MonthsOfYear monthsOfYear;

    // to get user selected value from form controls

    startYear  = YearSelected.valueStr(); // formControlName.valueStr()

    month = MonthsSelected.valueStr();

 

    super();

     // for loop to get the value/data of selected records from grid

    for(payDetails = getFirstSelection(HRMPayDetails_ds):payDetails:payDetails=HRMPaydetails_ds.getnext())                                   

    {

 

        select hcmWorker where hcmWorker.PersonnelNumber == payDetails.EmpCode;

        

            SalaryslipController = new SalaryslipController();

            SalaryslipController.parmReportName(reportName);

            SalaryslipContract = SalaryslipController.parmReportContract().parmRdpContract();

        // call the contract class parm methods and pass the current selected records to run the report

            SalaryslipContract.parmempID(payDetails.EmpCode);

            SalaryslipContract.parmEmplName(hcmWorker.name());

            SalaryslipContract.parmHRMBranchCode(payDetails.BranchCode);

                 SalaryslipContract.parmHRMEmploymentContractCode(payDetails.EmploymentContractCode);

            SalaryslipContract.parmHRMEmplStatus(hcmWorker.EmployeeStatus);

            SalaryslipContract.parmHRMPayType(payDetails.PayType);

            SalaryslipContract.parmHRMYearSelect(str2enum(hrmYearsel,startYear));

            SalaryslipContract.parmMonthsOfYear(str2enum(monthsOfYear,month));

  // To distinguish the report files, give a unique name to every pdf while downloading                       

            PDFName = strFmt("%1",payDetails.EmpCode + "_" +startYear +month + ".pdf");

            filepath = "F:\\SalarySlip"; // filepath to save the PDF files

            srsReportRun = SalaryslipController.parmReportRun() as SrsReportRunImpl;

            SalaryslipController.parmReportRun(srsReportRun);

            SalaryslipController.parmReportContract().parmPrintSettings().printMediumType(SRSPrintMediumType::File);

                    SalaryslipController.parmReportContract().parmPrintSettings().overwriteFile(true);

            SalaryslipController.parmReportContract().parmPrintSettings().fileFormat(SRSReportFileFormat::PDF);

 

            SalaryslipController.parmReportContract().parmPrintSettings().fileName(strFmt("%1//%2",filepath,PDFName));

            SalaryslipController.runReport();

  // Filepath will be the name of PDF file + the path of the folder where all the PDFs are saved     

           filepath = strFmt("%1\\%2",filepath,PDFName); 

            this.email(filepath); 

// call this method to send the report from mentioned filepath through email.                                       

      }

  }


Step 3: Create a method to email the report from filepath.

  public void email(str filepath)

{

     List                                  toList;

    List                                  ccList;

    ListEnumerator                        le;

    System.Exception                      exception;

 

    Set                                   permissionSet;

    System.Exception                      e;

 

    Filename                                ReportPath = filepath;

    System.Net.Mail.MailMessage             mailMessage;

    System.Net.Mail.SmtpClient              mailClient;

    System.Net.Mail.MailAddressCollection   mailcoll;

    System.Net.Mail.MailAddress             mailFrom;

    System.Net.Mail.MailAddress             mailTo;

    System.Net.Mail.MailAddressCollection   mailToCollection;

    System.Net.Mail.MailAddressCollection   mailCCCollection;

    System.Net.Mail.AttachmentCollection    mailAttachementCollection;

    System.Net.Mail.Attachment              mailAttachment;

 

    str                                     receiverMailAddress;

    str                                     mailBody;

    str                                     mailServer;

    str                                     mailSubject;

    int                                     mailServerPort;

 

 

    #File

    str                 mail;

    userinfo            userInfo;

    str pwd;

    str  recipient = hcmWorker.email();

    str  cc = 'Test@gmail.com';

    SysEmailParameters parameters = SysEmailParameters::find();

    ;

    new InteropPermission(InteropKind::ClrInterop).assert();

    if(recipient != "") // check if email id exists for employee then send a mail

    {

        mailSubject         = "SALARY SLIP";

        mailFrom            = new  System.Net.Mail.MailAddress(parameters.SMTPUserName ,"urSMTPUserName");

        mailTo              = new  System.Net.Mail.MailAddress(recipient);

        mailcoll            = new  System.Net.Mail.MailAddressCollection();

        mailBody            = strFmt("Dear Sir/Madam\n\nPlease find attached here with your Salary Slip for the month of %1-%2,\n\n\nThanks,", month, startYear);

        try

        {

            toList = strSplit(recipient, ';');

            ccList = strSplit(cc, ';');

 

            permissionSet = new Set(Types::Class);

            permissionSet.add(new InteropPermission(InteropKind::ClrInterop));

            

            mailServer = SysEmaiLParameters::find(false).SMTPRelayServerName;

            mailServerPort = SysEmaiLParameters::find(false).SMTPPortNumber;

            mailClient = new System.Net.Mail.SmtpClient(mailServer, mailServerPort);

 

            le = toList.getEnumerator();

            le.moveNext();

 

            mailTo  = new System.Net.Mail.MailAddress(strLTrim(strRTrim(le.current())));

            mailMessage = new System.Net.Mail.MailMessage(mailFrom, mailTo);

 

            mailToCollection = mailMessage.get_To();

            while (le.moveNext())

            {

                mailToCollection.Add(strLTrim(strRTrim(le.current())));

            }

 

            le = ccList.getEnumerator();

            mailCCCollection = mailMessage.get_CC();

            while (le.moveNext())

            {

                mailCCCollection.Add(strLTrim(strRTrim(le.current())));

            }

 

            mailMessage.set_Priority(System.Net.Mail.MailPriority::High);

            mailMessage.set_Subject(mailSubject);

            mailMessage.set_Body(mailBody);

            //mailMessage.set_IsBodyHtml(true);

            mailClient.set_EnableSsl(true);

            mailAttachementCollection = mailMessage.get_Attachments();

            mailAttachment = new System.Net.Mail.Attachment(ReportPath);

            mailAttachementCollection.Add(mailAttachment);

            pwd = SysEmailParameters::password();

            mailClient.set_Credentials(New System.Net.NetworkCredential(parameters.SMTPUserName,pwd));

            System.Net.ServicePointManager::set_SecurityProtocol(System.Net.SecurityProtocolType::Tls12);

            mailClient.Send(mailMessage);

            //ret = true;

            INFO("EMAIL SENT");

 

        }

        catch (Exception::CLRError)

        {

            //ret = false;

            exception = ClrInterop::getLastException();

            while (exception)

            {

                info(exception.get_Message());

                exception = exception.get_InnerException();

            }

            CodeAccessPermission::revertAssert();

        }

}


In all the above code, we first fetched the user entered values for month and year.We fetched the records selected from grid by user and passed the values through contract class parm methods to process the report.

After execution it will save the report as PDF on mentioned file folder with mentioned file name and we are using the file name + file path to fetch report file and send it through email as attachment to multiple employees at once.

Below is the format of email received.



Thank you for reading.
Hope this finds you helpful.

 














Comments

  1. Thank you for a initiative, finally found a solution a i am searching for🙏

    ReplyDelete
  2. Very helpful and detailed informative blog. You have explained everything in detailed thanks. you did a great work here.

    ReplyDelete

Post a Comment