In an earlier post, I had described a customer scenario, where they would want to execute and render a report from a .Net application, and then send the rendered report as an email attachment.
In the previous post, I had talked about how to generate a Tree View of the Report Server Items. In this post, I would be talking mainly about the how to execute a report and render it in a required format. And then send the Report as an email attachment.
The Post, assumes the following
- The report which needs to be executed is selected on the Tree View and the report path is passed to the function.
- The Report runs with default parameters.
- The SMTP mail server is preconfigured.
In order to execute a Report, we need to use the ReportExecutionService() Class, defined in the ReportExecution2005 endpoint for Reporting Services.
I created a new class ExecuteAndRender for this functionality.
The ExecuteAndRender Class, defines and object for the ReportExecutionService() class, in order to execute the methods exposed by Reporting Services.
Next I created a function RenderReport(string ReportName), this function performance the following tasks
- Define the Report Rendering and execution settings.
- Calls the ReportExecutionService.LoadReport() to load the report definition.
- Defines the report parameters. In this case, since all default values would be used, we do not explicitly define the parameters.
- Calls the ReportExecutionService.Render() method to render the report in the desired format.
- One the report have been rendered, we create a PDF file for the report.
- Then call the AttachAndSendEmail() to send the email.
Next, we have the AttachAndSendEmail() function to connect to the SMPT server and send the email. This function achieves the following tasks
- Create an SMTP client to connect to the SMTP server.
- Create the From and To Addresses for the email.
- Creates the MailMessage with the attachment.
- And Sends the email.
This code sends the messages in an synchronous manner. In case if required, SMTPClient.SendAsync method can also be used.