Emailing an SSRS Report using ReportViewer

Posted on May 26, 2009. Filed under: SSRS | Tags: , , , , |

Introduction

SQL Server Reporting Services (SSRS) is Microsoft’s offering in the reporting space, if you install SSRS as part of a SQL Server install you get a nice web front end through which users can navigate and view reports. But SSRS is not restricted to this online portal style access, reports can be embedded into you application using the ReportViewer component shipped with Visual Studio. 

 Through the ReportViewer component users can view, export and print reports in exactly the same manner as the web based version but we also get some nice hooks into the ReportViewer control, I’m going to demo how we can use these to extract the report to a pdf and attach it to a new outlook message ready for the user to view and send. I’m using the inbuilt Outlook interoperability to achieve this but you could just as easily apply the same principles to another method of email delivery. 

 I’m doing this demo using VS2008 but it will work in exactly the same manner in VS2005. 

Adding a ReportViewer 

For this demo I’m starting with a blank form, first we need to drag a ReportViewer control onto the design surface. I’m using the a report stored on an SSRS server in this demo but you can also include reports locally in your solution, whichever option you choose does not affect the following steps. 

 

Configure the report viewer to point to your report, I’m using a server based report so I have expanded the “ServerReport” property and specified a report server and a report path, I have also changed the “ProcessingMode” property to “Remote” to specify that I am using a remote report. 

 

Now when we run the application we are able to interact with the report. 

Exporting the Report 

To attach our report to an email the first step is to get the pdf file out to disk, I’m going to write a utility type function to achieve this which will return a filepath to the saved PDF file; 

//You will need to import these namespaces
using Microsoft.Reporting.WinForms;
using System.IO;

 

/// <summary>
/// Exports the current report out to a pdf file
/// </summary>
/// <returns>
/// Path to the file that was generated
/// </returns>
private string ExportReport()
{
    Warning[] warnings;
    string[] streamids;
    string mimeType;
    string encoding;
    string filenameExtension;
 
    //Render the report to a byte array
    byte[] bytes;
    if (reportViewer1.ProcessingMode == ProcessingMode.Local)
    {
       bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType,
           out encoding, out filenameExtension, out streamids, out warnings);
    }
    else
    {
       bytes = reportViewer1.ServerReport.Render("PDF", null, out mimeType,
          out encoding, out filenameExtension, out streamids, out warnings);
    }

    //Write report out to temporary PDF file
    string filename = Path.Combine(Path.GetTempPath(), "ReportToAttach.pdf");
    using (FileStream fs = new FileStream(filename, FileMode.Create))
    {
        fs.Write(bytes, 0, bytes.Length);
    }

    //return path to saved file
    return filename;
}

Sending the Email 

The last step is to attach the report to a new email and load it up for the user, I’m using the Outlook interoperability assemblies. If you want to use the same method you will need to add a reference to Microsoft.Office.Interop.Outlook to your project. 

Let’s add a button to our form to kick of the process and in the event handler we will create an email and attach our report. 

//You will need to import this namespaces
using Microsoft.Office.Interop.Outlook;

 

private void emailButton_Click(object sender, EventArgs e)
{
    //Write report out to temporary PDF file
    string reportFilename = ExportReport();

    // Create a new email using outlook
    ApplicationClass outlookApp = new ApplicationClass();
    MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
    mailItem.To = "mail@yourdomain.com";
    mailItem.Subject = "Your Report";
    mailItem.Body = "Please find your report attached";
    mailItem.Attachments.Add(reportFilename, (int)OlAttachmentType.olByValue, 1, reportFilename); 

    //Remove the temp file once attached
    File.Delete(reportFilename);
 
    // Display the window
    mailItem.Display(false);
}

Now when we click the button we should get a new outlook message with the PDF attached; 

Advertisement

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

3 Responses to “Emailing an SSRS Report using ReportViewer”

RSS Feed for RoMiller.com Comments RSS Feed

Hi Miller,

I tried convert your code to VB.net (at developerfusion.com site) After success convert I get following code on site:

Imports Microsoft.Office.Interop.Outlook
Imports System.IO
Imports Microsoft.Reporting.WinForms

Public Class Form1
”’
”’ Exports the current report out to a pdf file
”’
”’
”’ Path to the file that was generated
”’
Private Function ExportReport() As String
Dim warnings As Warning()
Dim streamids As String()
Dim mimeType As String
Dim encoding As String
Dim filenameExtension As String

‘Render the report to a byte array
Dim bytes As Byte() = reportViewer1.ServerReport.Render(“PDF”, Nothing, mimeType, encoding, filenameExtension, streamids, _
warnings)

‘Render the report to a byte array
Dim bytes As Byte()
If reportViewer1.ProcessingMode = ProcessingMode.Local Then
bytes = reportViewer1.LocalReport.Render(“PDF”, Nothing, mimeType, encoding, filenameExtension, streamids, _
warnings)
Else
bytes = reportViewer1.ServerReport.Render(“PDF”, Nothing, mimeType, encoding, filenameExtension, streamids, _
warnings)
End If

‘Write report out to temporary PDF file
Dim filename As String = Path.Combine(Path.GetTempPath(), “ReportToAttach.pdf”)
Using fs As New FileStream(filename, FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
End Using

‘return path to saved file
Return filename
End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

‘Write report out to temporary PDF file
Dim reportFilename As String = ExportReport()

‘ Create a new email using outlook
Dim outlookApp As New ApplicationClass()
Dim mailItem As MailItem = DirectCast(outlookApp.CreateItem(OlItemType.olMailItem), MailItem)
mailItem.[To] = “mail@yourdomain.com”
mailItem.Subject = “Your Report”
mailItem.Body = “Please find your report attached”
mailItem.Attachments.Add(reportFilename, CInt(OlAttachmentType.olByValue), 1, reportFilename)

‘Remove the temp file once attached
File.Delete(reportFilename)

‘ Display the window
mailItem.Display(False)
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Me.ReportViewer1.RefreshReport()
End Sub
End Class

I try to running a project but the project to stopped following error messages:
‘Render the report to a byte array
Dim bytes As Byte() << Local variables "bytes" is already declared in the current block..
Then I try disqualify this line, but after disqualify. First declaration program line get following error messages:
(Variable ' mimeType, encoding, filenameExtension, streamids, warnings' is passed by reference before is has been assigned a value, a null reference exception could result at runtime)

Please help Me :)

Regards
Robert

Hi Robert,

There was in fact a copy paste error in the code snippet in my post, which I have now rectified, thank you.

You are receiving the error message because VB.Net does not have the concept of out parameters, you should be able to solve the warning by setting the variables it mentions to Nothing before passing them in to the Render function.

Rowan

[...] Emailing an SSRS Report using ReportViewer « RoMiller.com [...]


Where's The Comment Form?

    About

    Rowan works as a Program Manager for the ADO.NET Entity Framework team at Microsoft. He speaks at technical conferences and blogs at http://romiller.com. Rowan lives in Seattle, Washington with his wife Athalie. Prior to moving to the US he resided in the small state of Tasmania in Australia. Outside of technology Rowan's passions include snowboarding, mountain biking, horse riding, rock climbing and pretty much anything else that involves being active. The primary focus of his life, however, is to follow Jesus.

    RSS

    Subscribe Via RSS

    • Subscribe with Bloglines
    • Add your feed to Newsburst from CNET News.com
    • Subscribe in Google Reader
    • Add to My Yahoo!
    • Subscribe in NewsGator Online
    • The latest comments to all posts in RSS

    Meta

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.