C# – Execute SSRS Report from C# save as PDF

creporting-services

So, here's my delema.

The title says it all. I cannot seem to find any guidance on how to execute a SSRS report remotely and save it as a PDF.

I have tried to follow the below article.
Using Reporting Services (SSRS) as a reference in an ASP.NET Core site

However, when I add the Service Reference to my project some of the methods seem to have the wrong signatures.

For example.
rsExec.LoadReportAsync(report, null);

in my reference the first parameter is a TrustedUserHeader object.

Does anyone have a good starting point on how to execute an SSRS report from C#? I cannot find any simple example.

Best Answer

I do this by using Microsoft.Reporting.Webforms and the following method:

 using Microsoft.Reporting.WebForms;
 ...
 public byte[] ExportToExcel(string reportName, string[] paramNames, string[][] paramDic)
    {
        // Variables
        Warning[] warnings;
        string[] streamIds;
        string mimeType;
        string encoding;
        string extension;



        ReportViewer rv = new ReportViewer { ProcessingMode = ProcessingMode.Remote };
        rv.AsyncRendering = false;
        ServerReport sr = rv.ServerReport;
        sr.ReportServerUrl = new Uri("http://<server>/reportserver");
        sr.ReportPath = "/<report path>/" + reportName;

        if (paramNames.Length != 0)
        {
            List<ReportParameter> paramList = paramNames.Select((t, i) => new ReportParameter(t, paramDic[i])).ToList();
            rv.ServerReport.SetParameters(paramList);
        }

        return rv.ServerReport.Render("Excel", null, out mimeType, out encoding, out extension,
            out streamIds, out warnings);
    }

The byte array can then be sent to the client via Response or saved to a file to be emailed/transferred later.

The first parameter is the name of the report, the second is an array of parameter names, and the third is an array of arrays containing the parameter values. I wrote this method early in my career and I wouldn't write it this way now. If you use this, I would refactor the code to take two parameters: reportName and a Dictionary called parameters or something like that to manage the parameter values.