Render rdlc reports to PDF not working on azure websites - asp.net-mvc

I am having the following issue with my rdlc reports. I am creating an asp.net MVC application and need to use reports. All my reports work fine on my local machine, but on azure website I get the always this error:
Error.
An error occurred while processing your request.
On my azure bin folder I have the following dll's
Microsoft.ReportViewer.Common
Microsoft.ReportViewer.DataVisualization
Microsoft.ReportViewer.ProcessingObjectModel
Microsoft.ReportViewer.WebForms
Microsoft.ReportViewer.WinForms
and have a folder Reports with all my reports in it.
I also have change my reports properties Build Action to content and still nothing. Does any one know how can I resolve this issue.
The code that I am using and works fine on my localhost
LocalReport lr = new LocalReport();
string path = System.IO.Path.Combine(Server.MapPath("~/Reports"), "Model1.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View();
}
ReportDataSource rd = new ReportDataSource("Model1");
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.2in</MarginTop>" +
" <MarginLeft>0.1in</MarginLeft>" +
" <MarginRight>0.1in</MarginRight>" +
" <MarginBottom>0.3in</MarginBottom>" +
" <orientation>Landscape</orientation>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);

Azure App Service Apps run in a secure environment called a sandbox to isolate apps.
This sandbox is blocking various APIs calls, like GDI+ APIs.
The problem might come from this limitation.
Please see the following documentation page for more détails: https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox

Related

Authentication fail error on convert Html to Pdf

I try to convert Html to PDF use "HtmlToPdf" nuget , It was work fine on local test but when i upload site to host i get this error :
Conversion error: Authentication error.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Exception: Conversion error: Authentication error.
This is my Convert method Code
[AllowAnonymous]
public ActionResult Convert(int id)
{
HtmlToPdf converter = new HtmlToPdf();
var context = System.Web.HttpContext.Current;
string baseUrl = context.Request.Url.Host + ":"+context.Request.Url.Port + "/Doctor/DietTherapy/LineRegimePrint/";
PdfDocument doc = converter.ConvertUrl(baseUrl + id);
// save pdf document
byte[] pdf = doc.Save();
// close pdf document
doc.Close();
// return resulted pdf document
FileResult fileResult = new FileContentResult(pdf, "application/pdf");
fileResult.FileDownloadName = "Document.pdf";
return fileResult;
}
How can i authorize user for this convert ?
It sounds like you just need to authenticate the request being made by the PDF library. For example, if it's using Basic HTTP Authentication:
HtmlToPdf converter = new HtmlToPdf();
converter.Options.Authentication.Username = "some username";
converter.Options.Authentication.Password = "some password";
// the rest of your code...
The linked documentation also contains examples for other authentication methods.
Did you check to see if you're getting the proper value on this line of code (when running on host server)?
string baseUrl = context.Request.Url.Host + ":"+context.Request.Url.Port + "/Doctor/DietTherapy/LineRegimePrint/";
While your development machine's IIS Express uses Anonymous Authentication, your hosting server is probably using Windows Authentication or other kinds. Check the IIS Managers to see the difference.
SelectPDF's library somehow creates a separate process to perform the HtmlToPdf conversion, which is outside the IUser, and therefore, the server asks for authentication.
For Windows Authentication setting, you may just use a generic user login account for this purpose and populate the required properties as mentioned in above thread and all would be fine.
converter.Options.Authentication.Username = "WindowsUser";
converter.Options.Authentication.Password = "WindowsPassword";

Save file to path desktop for current user

I have a project ASP.NET Core 2.0 MVC running on IIS.
Want to Export some information from data grid to Excel and save it from web page to the desktop of current user.
string fileName = "SN-export-" + DateTime.Now + ".xlsx";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
fileName = rgx.Replace(fileName, ".");
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName2 = Path.Combine(path, fileName);
FileInfo excelFile = new FileInfo(fileName2);
excel.SaveAs(excelFile);
This works perfect local at Visual Studio, but not after publishing at IIS.
Using simple path string path = #"C:\WINDOWS\TEMP"; It will save this export file at the server temp folder, but not current web page user.
How to get this?
ASP.NET MVC is framework for a web application. So you have fronted and backend parts. This code will executed on the server side of your application. Even if you use Razor pages, they also generated at the backend. So there are several ways to save data on the computer:
use js to iterate data and save it, but I'm not sure that saving to excel with js is easy;
send desired data to backend, save it to excel and then return to the client.
For a second way you can use next code:
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(YourData data) {
Stream stream = await {{__get_stream_based_on_your_data__}}
if(stream == null)
return NotFound();
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
And because of security reasons you can save data only to downloads directory.

IE name of download file and its extension are wrong when Web site run on server

I create name file for download file:
string fileName = Resources.Resource.VacationLimits + year + ".xlsx";
When aplication run on localhost - I can normal download file.
After build as Release and publish Web on server,
when I download file I have wrong file name without the file extension .xlsx in IE. In other browser I can download file with correct name and the file extension .xlsx.
all method:
MemoryStream stream;
var result = vacationService.GetVacationFile(out stream);
string fileName = Resources.Resource.VacationLimits + year + ".xlsx";
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(stream, contentType, fileName);

call birt report from action class

I am developing a project in Java EE Struts 2 and Hibernate for airline reservations. Now my all work is done and I have to generate a ticket. Instead of generating a simple JSP or HTML ticket, I want to generate a downloadable report (like Crystal Reports in Java). I have my entire ticket info in a session that (as on internet) I can get on BIRT report using script.
I am totally new to BIRT and wanted to know how I can generate a BIRT report or maybe call its execution engine from one of my action classes. Any ready example will be a great help.
I guess you're trying to send PDF ticket to customers. Please create your template and pass parameters using these lines:
ReportAdminServiceRemote birtAdmService = (ReportAdminServiceRemote)MXServer.getMXServer().lookup(“BIRTREPORT”);
byte[] abyte0 = birtAdmService .runReport(userInfo, reportName, appName, parameterData, filename, “pdf”);
Once you have the bytes generated you can do this way:
public String actionDownload() throws Exception{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Disposition","attachment; filename=\"" + example.pdf+ "\"");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bis = new ByteArrayInputStream(abyte0);
inputStream = bis;
return SUCCESS;
}
All the credits goes to authors on these pages:
http://www.maximonews.com/?p=65
http://www.coderanch.com/t/432713/Struts/Struts-Files-DownLoad-Streaming-as

Why doesn't my PDF document render/download in ASP.NET MVC2?

I have an ASP.NET MVC2 application in development and I am having problems rendering a .pdf file from our production server.
On my Visual Studio 2010 integrated development server everything works fine, but after I publish the application to the production server, it breaks. It does not throw any exceptions or errors of any kind, it simply does not show the file.
Here's my function for displaying the PDF document:
public static void PrintExt(byte[] FileToShow, String TempFileName,
String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter =
new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = ReportPath;
p.StartInfo.UseShellExecute = true;
p.Start();
}
My production server is running Windows Server 2008 and IIS 7.
You cannot expect opening the default program associated with PDF file browsing on the server. Try returning the file into the response stream which will effectively open it on the client machine:
public ActionResult ShowPdf()
{
byte[] fileToShow = FetchPdfFile();
return File(fileToShow, "application/pdf", "report.pdf");
}
And now navigate to /somecontroller/showPdf. If you want the PDF opening inside the browser instead of showing the download dialog you may try adding the following to the controller action before returning:
Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf");
i suggest you use ASP.NET MVC FileResult Class to display the PDF.
see http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx
your code open`s the PDF on the webserver.
Here's how I did it.
public ActionResult PrintPDF(byte[] FileToShow, String TempFileName, String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter = new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
return base.File(FileToShow, "application/pdf");
}
Thank you all for your efforts. Solution I used is the most similar to the Darin's one (almost the same, but his is prettier :D), so I will accept his solution.
Vote up for all of you folks (both for answers and comments)
Thanks

Resources