Why can't StorageFile.GetFileFromPathAsync load from an exsisting PDF file - c#

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.

Related

How to open a rendered RDL report in a new tab in MVC Web API?

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;
}

Upload an image to Google Drive with OCR and convert to Doc

I want to upload an image to Google Drive with OCR function and convert it to Google Doc. I am using this method
public static File UploadFile(DriveService Service, string UploadFile, string Parent)
{
if (System.IO.File.Exists(UploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(UploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(UploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = Parent } };
// File’s content.
byte[] byteArray = System.IO.File.ReadAllBytes(UploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = Service.Files.Insert(body, stream, GetMimeType(UploadFile));
request.Ocr = true;
request.OcrLanguage = "he";
request.Convert = true;
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else
{
Console.WriteLine("File does not exist: " + UploadFile);
return null;
}
}
and I call it via this line
Google.Apis.Drive.v2.Data.File newFile = DriveHelper.UploadFile(service, #"E:\myImage.png", myFolderId);
My problem is: request.ResponseBody returns null but when I remove this lines
request.Ocr = true;
request.OcrLanguage = "he";
request.Convert = true;
My file uploaded successfully
and request.ResponseBody returns File Object
This is missing the Upload function.
request.Upload();
return request.ResponseBody;
Reference link: http://anthonygiretti.com/category/google-api/

Prompt user for parameters in Reporting Service 2005

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);
}

Google Drive Parse error when uploading file with special unicode characters

A problem has occurred recently when trying to upload files with the Google API dotnet client sdk. When the file name has any special Unicode characters, it throws an error.
Here is my code
public static Google.Apis.Drive.v2.Data.File InsertResource(Google.Apis.Drive.v2.DriveService service, string filePath, string parentId, string fileName, string mimeType)
{
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
try
{
// File's metadata.
body.Title = fileName;
body.MimeType = mimeType;
// Set the parent folder.
if (!String.IsNullOrEmpty(parentId))
{
var response = DriveUtils.GetFileInfo(service, parentId);
if (response.Error != null)
{
body.Error = response.Error;
return body;
}
body.Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } };
}
byte[] byteArray = System.IO.File.ReadAllBytes(filePath);
MemoryStream stream = new MemoryStream(byteArray);
Google.Apis.Drive.v2.FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
return request.ResponseBody;
}
catch (GoogleApiRequestException e)
{
body.Error = e.RequestError;
return body;
}
}
It was working fine up until this week. Any files that have chinese characters or turkish characters in the name will throw an error.
at Google.Apis.Json.JsonReader.ParseExpression(JsonToken token, TokenStream ts)
at Google.Apis.Json.JsonReader.Parse(String jsonAsText)
at Google.Apis.Upload.ResumableUpload`1.Upload()
Try to download the latest version of the API (from https://code.google.com/p/google-api-dotnet-client/wiki/APIs#Drive_API).
I changed line 122 in the Drive sample (instructions to download this sample are here), to
Title = "字/漢字" and Title = "title with ç", and both of them worked for me.

Downloading FileStream object doesn't open Download Dialog Box

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);
}

Categories