Thursday 4 July 2013

C# - How to Fetch a Report from SQL Server Reporting Services (SSRS)

Tested with SSRS 2008, may well work with 2005 too. You'll need to add a Service Reference in your project to the SSRS API, which will generate the ReportExecutionServiceSoapClient proxy seen here. You can request the report in various formats: "PDF", "WORD", or "EXCEL".
 class ReportFetcher  
   {  
     public enum ReportFileFormat  
     { PDF }  
     /// <summary>  
     /// Makes a call to a a SSRS server to load and render a report in a certain file format  
     /// </summary>  
     /// <param name="pathToReport">Path to the report on the server (including name)</param>  
     /// <param name="execParams">Execution parameters</param>  
     /// <param name="fileFormat">Rendering file format</param>  
     /// <returns></returns>  
     public byte[] ToFile(string pathToReport, List<ParameterValue> execParams, string format = "PDF")  
     {  
       ExecutionInfo execInfo;  
       var trusteduserHeader = new TrustedUserHeader();  
       var execHeader = new ExecutionHeader();  
       ServerInfoHeader serviceInfo;  
      
       var client = new ReportExecutionServiceSoapClient();  
       if (client.ClientCredentials == null)  
       {  
         throw new NullReferenceException("Client Credentials are null");  
       }  
       client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;  
       client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;  
       // Load the report  
       client.LoadReport(trusteduserHeader, pathToReport, null, out serviceInfo, out execInfo);  
       execHeader.ExecutionID = execInfo.ExecutionID;  
       client.SetExecutionParameters(execHeader, trusteduserHeader, execParams.ToArray(), "en-us", out execInfo);  
       // Render the report  
       string extension;  
       string encoding;  
       string mimeType;  
       string[] streamIds;  
       var warnings = new Warning[1];  
       warnings[0] = new Warning();  
       Byte[] result;  
       client.Render(execHeader, trusteduserHeader, format, null, out result, out extension, out mimeType, out encoding, out warnings, out streamIds);  
       ConnectionHelper.SafelyCloseConnection(client);  
       return result;  
     }  
   }  

If you want to save the returned byte array to a file, it's easily done like this:
using (var stream = File.OpenWrite("myReport.pdf"))
{ stream.Write(result, 0, result.Length);
}

No comments:

Post a Comment