Well, I already tried a lot of stuff to solve this issue, but none did.
I developed a Reporting Service (2005) and deployed it.
This report will be used by everyone who access a website (it's a internet site, so, won't be accessed by intranet) developed on the framework 3.5 (but I think the framework's version is not the source of the problem).
I had other issues with authentication, and the workaround included the using of the FileStream class on my website.
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
For this code, I had to add a WebReference to the .asmx file mentioned in it.
Both Report and WebSite are deployed/published on the same server with a IIS 7.5 version.
Is there an way where user can choose where it wants to save the .pdf file?
Any help will be appreciated.
If you need more information to help me, just ask.
Thanks in advance.
You might want to combine the two try-catch blocks:
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
/*
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
*/
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=\"report.pdf\"");
Response.BinaryWrite(result);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
Related
I am trying to pass a PDF generated from a SQL ReportServer back to a UWP application as a PdfDocument. I keep getting an Exception when trying to create the StorageFile
[HttpGet]
[Route("invoicereport/{report}/{invoice}")]
public async Task<IHttpActionResult> GetInvoiceReport([FromUri] string report, [FromUri] string invoice)
{
try
{
Debug.WriteLine("Test");
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = CredentialCache.DefaultCredentials;
rs.Url = "http://localhost/reportserver/reportexecution2005.asmx";
rs.ExecutionHeaderValue = new ExecutionHeader();
var executionInfo = new ExecutionInfo();
executionInfo = rs.LoadReport($"{ReportsDir}/Invoice/{report}", null);
List<ParameterValue> parameters = new List<ParameterValue>();
parameters.Add(new ParameterValue { Name = "SOPNUMBER", Value = invoice });
parameters.Add(new ParameterValue { Name = "SOPTypeString", Value = "Invoice" });
rs.SetExecutionParameters(parameters.ToArray(), "en-US");
string deviceInfo = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string mimeType;
string encoding;
string[] streamId;
Warning[] warning;
var result = rs.Render("PDF", deviceInfo, out mimeType, out encoding, out encoding, out warning, out streamId);
FileStream stream = File.Create(System.Web.HttpRuntime.CodegenDir + $"/{invoice}.pdf", result.Length);
//write file with rendered result
stream.Write(result, 0, result.Length);
//close stream
stream.Close();
StorageFile file = StorageFile.GetFileFromPathAsync(System.Web.HttpRuntime.CodegenDir + $"/{invoice}.pdf").GetResults();
var pdf = PdfDocument.LoadFromFileAsync(file).GetResults();
return Ok(pdf);
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Reporting Error");
}
return Ok();
}
the Exception gets logged as:
System.IO.FileNotFoundException: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
at Windows.Foundation.IAsyncOperation`1.GetResults()
at Prism.Web.Queries.Controllers.ReportController.<GetInvoiceReport>d__6.MoveNext() in C:\Projects\PointOfSaleBeta\Prism.Web.Queries\Controllers\ReportController.cs:line 183
Line 183 corresponds to StorageFile file = StorageFile.GetFileFromPathAsync(System.Web.HttpRuntime.CodegenDir + $"/{invoice}.pdf").GetResults();
I have verified (many times) that the referenced PDF file actually got created. Am I not using the correct syntax for 'GetFileFromPathAsync`?
After I didn't get any answers or comments I tried a different approach. I installed the FreeSpire.PDF nuget package:
[HttpGet]
[Route("invoicereport/{report}/{invoice}")]
public async Task<IHttpActionResult> GetInvoiceReport([FromUri] string report, [FromUri] string invoice)
{
try
{
Debug.WriteLine("Test");
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = CredentialCache.DefaultCredentials;
rs.Url = "http://localhost/reportserver/reportexecution2005.asmx";
rs.ExecutionHeaderValue = new ExecutionHeader();
var executionInfo = new ExecutionInfo();
executionInfo = rs.LoadReport($"{ReportsDir}/Invoice/{report}", null);
List<ParameterValue> parameters = new List<ParameterValue>();
parameters.Add(new ParameterValue { Name = "SOPNUMBER", Value = invoice });
parameters.Add(new ParameterValue { Name = "SOPTypeString", Value = "Invoice" });
rs.SetExecutionParameters(parameters.ToArray(), "en-US");
string deviceInfo = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string mimeType;
string encoding;
string[] streamId;
Warning[] warning;
var result = rs.Render("PDF", deviceInfo, out mimeType, out encoding, out encoding, out warning, out streamId);
PdfDocument pdf = new PdfDocument();
pdf.LoadFromBytes(result);
return Ok(pdf);
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Reporting Error");
}
return Ok();
}
This solved (worked around) my problem.
So I have an issue I want display a View to indicate to the end user that their request to download/open an Excel spreadsheet is processing, and then I want to have the Excel spreadsheet open, and the View close.
Currently, I get a blank Screen and then the Excel opens
so 3 things:
Display View with a Preloader
Open/Download an Excel Spreadsheet
Close the View, after spreadsheet opens
Here is the View:
#{
ViewBag.Title = "CoursePriceHistory";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Course Price History</h2>
<img src="~/Images/loading.gif" />
Here is the ActionResult from the Controller:
public ActionResult CoursePriceHistory()
{
// Sql Statement to provide parameters for Quarter Year (MIN/MAX)
DAL.QuarterYear qy = new DAL.QuarterYear();
var min = qy.getMIN();
var max = qy.getMAX();
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Render arguments
byte[] result = null;
string fileName = #"\\department.chicagobooth.edu\Test\something.pdf";
string reportPath = #"/Sam - Faculty and Course Reports/Course Price History";
string format = "EXCEL";
string historyID = null;
string encoding;
string mimeType;
string extension;
ReportService.Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
ParameterValue[] parameters = new ParameterValue[3];
parameters[0] = new ParameterValue();
parameters[0].Name = "StartQuarterYear";
parameters[0].Value = min;
parameters[1] = new ParameterValue();
parameters[1].Name = "EndQuarterYear";
parameters[1].Value = max;
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
rs.SetExecutionParameters(parameters, "en-us");
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
MemoryStream ms = new MemoryStream(result);
// Write PDF
Response.Clear();
Response.AddHeader("Content-Disposition", "inline; filename=Course Price History");
Response.AddHeader("Content-Type", "application/Excel");
Response.ContentType = "application/vnd.ms-excel";
Response.OutputStream.Write(ms.ToArray(), 0, ms.ToArray().Length);
Response.Buffer = true;
Response.Flush();
Response.Close();
return View();
}
I just figured out how to render my RDL report to pdf file but it's currently in the temporary folder. The next step should be for it to open in a new window or tab for viewing. I tried many solutions but nothing seems to be working.
Here's my current code:
[HttpGet]
[Route("printDCF")]
public IHttpActionResult printDCF(int controlFormDetailID)
{
try
{
ApiResult apiResult = new ApiResult();
var reportData = ControllerLogic.GetReportData(controlFormDetailID);
generateReport(reportData);
return Ok(apiResult);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
public System.Web.Mvc.FileContentResult generateReport(List<DocumentControlFormPrintResult> reportData)
{
string RptPath = HttpContext.Current.Server.MapPath("~/AngularViews/forms/dcf/report/DCF_Report.rdl");
LocalReport rpt = new LocalReport();
rpt.DataSources.Add(new ReportDataSource("DataSet1", reportData));
rpt.ReportPath = RptPath;
string filePath = System.IO.Path.GetTempFileName();
Export(rpt, filePath);
rpt.Dispose();
System.Web.Mvc.FileContentResult result = new System.Web.Mvc.FileContentResult(System.IO.File.ReadAllBytes(filePath), "application/pdf")
{
FileDownloadName = "dcf_print.pdf",
};
return result;
}
public string Export(LocalReport rpt, string filePath)
{
string ack = "";
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = rpt.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
using (FileStream stream = File.OpenWrite(filePath))
{
stream.Write(bytes, 0, bytes.Length);
}
return ack;
}
catch (Exception ex)
{
ack = ex.InnerException.Message;
return ack;
}
}
I think, I tried myself this code working fine for me, it useful for you
[HttpGet]
[Route("api/Data/OpenPDF")]
public HttpResponseMessage OpenPDF()
{
var stream = new MemoryStream();
string filePath = #"D:\PDF\pdf-test.pdf";
using (FileStream fileStream = File.OpenRead(filePath))
{
stream = new MemoryStream();
stream.SetLength(fileStream.Length);
fileStream.Read(stream.GetBuffer(), 0, (int)fileStream.Length);
}
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(System.Net.Mime.DispositionTypeNames.Inline)
{
FileName = System.IO.Path.GetFileName(filePath)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
I am using ReportExecution2005.asmx service to execute report on report server and serve user with HTML of rendered report. I am setting the parameters programmatically but if i don't provider parameters, report crashes that parameter is not specified. What i want to do is to prompt the user for parameters if they are not provided. Prompt on parameters is on. Here is my source;
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://server/reportserver/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/Test reports/DemoReport";
string format = "HTML4.0";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[2];
parameters[0] = new ParameterValue();
parameters[0].Name = "CompanyName";
parameters[0].Value = "ASDA";
parameters[1] = new ParameterValue();
parameters[1].Name = "ProgramID";
parameters[1].Value = "6";
DataSourceCredentials[] credentials = null;
string showHideToggle = null;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
ParameterValue[] reportHistoryParameters = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
rs.SetExecutionParameters(parameters, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
Console.WriteLine("SessionID: {0}", rs.ExecutionHeaderValue.ExecutionID);
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
Console.WriteLine("Execution date and time: {0}", execInfo.ExecutionDateTime);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.OuterXml);
}
// Write the contents of the report to an MHTML file.
try
{
FileStream stream = File.Create("report.mht", result.Length);
Console.WriteLine("File created.");
stream.Write(result, 0, result.Length);
Console.WriteLine("Result written to the file.");
stream.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
I cannot open an SSRS report rendered as an xlsx file, produced by calling the Reporting Services Web Service ReportExecution2005.asmx?wsdl from an SSIS Script Task.
But I can open xls files produced by the same method.
Can someone please tell me what I need to do to render a usable xlsx file?
I am trying to run a Reporting Services report from SSIS using a script task.
I need the report to render as an Excel xlsx file.
The code I have works if I use an .xls extension, by works I mean it does result in an xls file that can be opened in Excel. But if I change the file extension to xlsx I get a file that can’t be opened, and produces the following error.
“Excel cannot open the file because the file format or file extension is not valid. Verify that the file ………..”
In my code I’m using
MimeType = “application/vnd.ms-excel” for the xls file
And
MimeType = “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
”
for the xlsx file
The web service I am using to run the report is ReportExecution2005.asmx?wsdl
(which I assume is the correct one to use?)
My code from the SSIS Script Task is below,
var rsClient = new RSExec.ReportExecutionServiceSoapClient();
rsClient.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password");
rsClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
byte[] result = null;
string reportPath = "filepath/filename";
string format = "EXCEL";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding = String.Empty; //"";
string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // Excel2010
//string mimeType = "application/vnd.ms-excel"; // EXCEL
string extension = "";
Warning[] warnings = null;
string[] streamIDs = null;
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "ReportDate";
parameters[0].Value = "12/11/2013";
RSExec.ExecutionInfo execInfo = new RSExec.ExecutionInfo();
RSExec.TrustedUserHeader trustedUH = new TrustedUserHeader();
RSExec.ExecutionHeader execHeader = new RSExec.ExecutionHeader();
RSExec.ServerInfoHeader serverInfo = new ServerInfoHeader();
execHeader = rsClient.LoadReport(trustedUH, reportPath, historyID, out serverInfo, out execInfo);
rsClient.SetExecutionParameters(execHeader, trustedUH, parameters, "en-us", out execInfo);
rsClient.Render(execHeader, trustedUH, format, devInfo, out result, out extension, out encoding, out mimeType, out warnings, out streamIDs);
string filename = #"filepath\filename.xlsx";
FileStream stream = File.OpenWrite(filename);
stream.Write(result, 0, result.Length);
stream.Close();
Dts.TaskResult = (int)ScriptResults.Success;
To get this to run as a deployed package the following amendments were made
As the deployed package was unable to reference the config file, the bindings for the web service have been coded in the Script Task
using System;
using System.IO;
using ST_ece9b5f6ee774a84a76c32da60affdef.RSExec;
namespace ST_ece9b5f6ee774a84a76c32da60affdef
{
//using System;
using System.Xml;
using System.Text;
using System.Data;
using System.Web;
using Microsoft.SqlServer.Dts.Tasks;
using Microsoft.SqlServer.Dts.Runtime;
//using System.IO;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Windows.Forms;
/// <summary>
/// ScriptMain is the entry point class of the script. Do not change the name, attributes,
/// or parent of this class.
/// </summary>
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
// set Report Name
string ReportName = "My Report";
// all other variables are set from Package Variables
string ReportDate = Dts.Variables["User::PreviousBusinessDate"].Value.ToString();
string reportPath = Dts.Variables["User::ReportServerFolder"].Value.ToString() + ReportName;
string filename = Dts.Variables["User::DestinationFolder"].Value.ToString() + ReportName + "_" + DateTime.Now.ToString("yyyy-MM-dd_hhmmss") + ".xlsx";
byte[] result = null;
string format = "EXCELOPENXML"; // "EXCEL"; //"PDF";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding = String.Empty; //"";
string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // Excel2010
string extension = "";
Warning[] warnings = null;
string[] streamIDs = null;
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "ReportDate";
parameters[0].Value = ReportDate; //"12/11/2013";
ExecutionInfo execInfo = new ExecutionInfo();
TrustedUserHeader trustedUH = new TrustedUserHeader();
ExecutionHeader execHeader = new ExecutionHeader();
ServerInfoHeader serverInfo = new ServerInfoHeader();
ReportExecutionServiceSoapClient serviceClient = this.GetServiceClient();
execHeader = serviceClient.LoadReport(trustedUH, reportPath, historyID, out serverInfo, out execInfo);
serviceClient.SetExecutionParameters(execHeader, trustedUH, parameters, "en-us", out execInfo);
serviceClient.Render(execHeader, trustedUH, format, devInfo, out result, out extension, out encoding, out mimeType, out warnings, out streamIDs);
FileStream stream = File.OpenWrite(filename);
stream.Write(result, 0, result.Length);
stream.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
private ReportExecutionServiceSoapClient GetServiceClient()
{
BasicHttpBinding binding = this.GetBinding();
var address = new EndpointAddress("http://myReportServer/ReportServer/ReportExecution2005.asmx");
var serviceClient = new ReportExecutionServiceSoapClient(binding, address);
serviceClient.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password");
serviceClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
return serviceClient;
}
private BasicHttpBinding GetBinding()
{
var readerQuotas = new XmlDictionaryReaderQuotas()
{
MaxDepth = 32,
MaxStringContentLength = 8192,
MaxArrayLength = 16384,
MaxBytesPerRead = 4096,
MaxNameTableCharCount = 16384
};
var transport = new HttpTransportSecurity()
{
ClientCredentialType = HttpClientCredentialType.Ntlm,
ProxyCredentialType = HttpProxyCredentialType.None,
Realm = string.Empty
};
var message = new BasicHttpMessageSecurity()
{
ClientCredentialType = BasicHttpMessageCredentialType.UserName,
AlgorithmSuite = SecurityAlgorithmSuite.Default
};
var security = new BasicHttpSecurity()
{
Mode = BasicHttpSecurityMode.TransportCredentialOnly,
Transport = transport,
Message = message
};
var binding = new BasicHttpBinding()
{
Name = "ReportExecutionServiceSoap",
CloseTimeout = TimeSpan.FromMinutes(1),
OpenTimeout = TimeSpan.FromMinutes(1),
ReceiveTimeout = TimeSpan.FromMinutes(10),
SendTimeout = TimeSpan.FromMinutes(1),
AllowCookies = false,
BypassProxyOnLocal = false,
HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
MaxBufferSize = 524288,
MaxBufferPoolSize = 524288,
MaxReceivedMessageSize = 524288,
MessageEncoding = WSMessageEncoding.Text,
TextEncoding = Encoding.UTF8,
TransferMode = TransferMode.Buffered,
UseDefaultWebProxy = true,
ReaderQuotas = readerQuotas,
Security = security
};
return binding;
}
}
}
You can't use XLS and XLSX interchangeably - they are completely different formats.
XLS is binary-based format and XLSX is an XML schema-based format - they will be totally different file types. You can test yourself - create an XLS file in Excel, rename it to XLSX and it will error when you try opening it.
The SSRS EXCEL format can be saved to XLS files only.
SSRS 2012 can export to XLSX, but you would need to use the EXCELOPENXML format, not EXCEL.
Using EXCELOPENXML worked for me. Thanks Ian.
Also as a contribution, even though you have specified :string filename = #"filepath\filename.xlsx does not mean SSRS will render report in .xlsx format. The final rendered format is specified in the third output parameter of the render method.(extension)
e.g Render("EXCEL",//Renderformat,
deviceInfo,
out extension,
out encoding,
out mimeType,
out warnings,
out streamIDs
);