Tuesday, May 19, 2009

Sql Server Reporting Service : Rendering Report From C# Code & Save The Report

One of the requirement for our last project was after generating the report the report link would be emailed to client. The client will follow the link and download the report in PDF format. So we decided that after generating the report we will save the report in the file system in PDF format.To achieve the goal we have gone through the following steps.

1.Add web reference to the url http://MyServer/ReportServer/ReportExecution2005.asmx
2.Generate a report snapshot which I described here.
3.Call the following function to get stream in your preferred format.

public byte[] GetRenderStream(string historyID, string format)
{
ReportExecutionService reportExecutionService = new ReportExecutionService();
CredentialCache credentials = new CredentialCache();
NetworkCredential serviceCredential = new
NetworkCredential(Settings.Default.ReportUserName, Settings.Default.ReportPassword);
credentials.Add(new Uri(reportExecutionService.Url), "Basic", serviceCredential);

reportExecutionService.Credentials = serviceCredential;

byte[] resultStream = null;
string reportPath = Settings.Default.ReportPath;
string format = format; // PDF,Excel etc;

string encoding;
string mimeType;
string extension;
ReportExecutionService.Warning[] warnings = null;
string[] streamIDs = null;

ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();

try
{
reportExecutionService.ExecutionHeaderValue = execHeader;
execInfo = reportExecutionService.LoadReport(reportPath, historyID);
String SessionId = reportExecutionService.ExecutionHeaderValue.ExecutionID;
resultStream = reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

return resultStream;
}
catch (Exception ex)
{
throw ex;
}
}


4. Save the returned stream as a file.

string snapshotID = CreateAndGetNewSnapShotID(int year); // this method is described
//here
string format = "PDF";
string fullFileName = @"C:\Reports\Report.pdf";
byte[] responseStream = _reportServiceProxy.GetRenderStream();

try{
FileStream stream = File.OpenWrite(fullFileName);
stream.Write(responseStream, 0, responseStream.Length);
stream.Close();
}
catch(Exception ex)
{
//catch and log exception;
}

No comments:

Post a Comment