ashx page opens in excel instead of document retrieved - javascript

I have links that call a javascript function "GetDocument" which passes the ID of the link that the user wants to retrieve to an ashx page which than retrieves the document from a database and writes it back to the users browser if it's a PDF or opens the appropriate program if it's something else. These could be PDF's, XLS, DOCX.... etc.. When the user clicks a link that is a PDF everything work just fine and the PDF is opened within the browser. When the user opens anything else though, lets say for example an xlsx excel opens a garbage file with the name of the .ashx page. No errors occur and everything works with PDF. I'm kind of at a loss.
Here is the javascript
function GetDocument(id) {
spl1.loadPage('RightContent', 'FrmDocHandler.ashx?ID=' + id);
}
Here is the .ashx page
Public Class FrmDocHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim sID As String = context.Request.QueryString("id")
Dim fileName As String = String.Empty
Dim fileType As String = String.Empty
Dim bytes() As Byte
bytes = Get_Blob(fileName, fileType, sSql_GetDocument(sID))
context.Response.Clear()
'clear the content of the browser
context.Response.ClearContent()
context.Response.ClearHeaders()
context.Response.Buffer = True
'I tried both of these add header and the same result
'context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
context.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName)
context.Response.ContentType = GetMIMEType(fileType)
context.Response.BinaryWrite(bytes)
End Sub
MIME Types returned by GetMIMEType
Public Const g_MIME_DOC As String = "application/msword"
Public Const g_MIME_DOCX As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Public Const g_MIME_DOT As String = "application/msword"
Public Const g_MIME_DOTX As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
Public Const g_MIME_HTM As String = "text/html"
Public Const g_MIME_HTML As String = "text/html"
Public Const g_MIME_JPEG As String = "image/jpeg"
Public Const g_MIME_PDF As String = "application/pdf"
Public Const g_MIME_PPSX As String = "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
Public Const g_MIME_PPT As String = "application/vnd.ms-powerpoint"
Public Const g_MIME_PPTX As String = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
Public Const g_MIME_XLS As String = "application/vnd.ms-excel"
Public Const g_MIME_XLSX As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Public Const g_MIME_XLTX As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"
Public Const g_MIME_XML As String = "application/rss+xml"

The line which is probably causing the file to be opened in Excel is the following:
context.Response.ContentType = GetMIMEType(fileType)
A couple of things you can do:
Check to see what MIME type is being returned by GetMIMEType, and ensure its a PDF related one (application/pdf) rather than an Excel related one (application/vnd.ms-excel)
Check on the browser end to see what application is set to handle the mime type and/or file extension that you are sending from the server

Related

How do i get RSACryptoServiceProvider to verify a message using public key and signature

I generated a private and public key in javascript like this.
import crypto from "crypto";
/*export const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
});*/
const pair = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
export const privateKey = pair.privateKey.export({
type: "pkcs1",
format: "pem",
});
export const publicKey = pair.publicKey.export({
type: "pkcs1",
format: "pem",
});
Then i use the private key to create a signature for a jsonfile like this, and the public key to verify it before i return the signature.
//Lav signatur
const signate = crypto.createSign("SHA384");
signate.update(Buffer.from(licenseRelationship, "utf-8"));
const signature = signate.sign(privateKey, "hex");
const verifier = crypto.createVerify("SHA384");
// verificer signature, besked
verifier.update(Buffer.from(licenseRelationship, "utf-8"));
const verificationResult = verifier.verify(publicKey, signature, "hex");
This works perfectly, and then i return the json and the signature as a http response.
I recieve it in c# code and store the two components so im can use them later on request.
Upon request i fetch the two components and want to use the signature to check if the json has been tampered with.
I also has the public key in this code.
I do it like this.
string licenseRelationshipJson = licenseRelationshipDAO.getLicenseRelationshipWithoutSignatureAsJson(licenseRelationship);
byte[] signature = Encoding.UTF8.GetBytes(licenseRelationship.signature);
byte[] licenseRelationshipJsonAsArray = Encoding.UTF8.GetBytes(licenseRelationshipJson);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
result = rsa.VerifyData(licenseRelationshipJsonAsArray, signature,
HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
if (result)
{
log.write("Message verified ", null);
} else
{
log.write("Message not Verified ", null);
}
All debug code and exception handling removed.
I'm a crypto virgin, and am trying to understand this. But i must have misunderstood something serious.
I have the public key as a string (not base64 encoded)
Ive checked the json, and it is the exact same bytes when signed in Javascript as when being verified in c#
The public key is not used in this process. That has to be wrong i think ?
How do i get the public key into the RWACryptoServiceProvider ?
Im sure im using RWACryptoServiceProvider wrong.
EDIT....:
Ive tried this instead, but still to no avail.
string licenseRelationshipJson = licenseRelationshipDAO.getLicenseRelationshipWithoutSignatureAsJson(licenseRelationship);
byte[] signature = Encoding.UTF8.GetBytes(licenseRelationship.signature);
byte[] licenseRelationshipJsonAsArray = Encoding.UTF8.GetBytes(licenseRelationshipJson);
byte[] asBytes = Encoding.ASCII.GetBytes(DataStorage.Instance.PUBLIC_KEY);
char[] publicKeyAsArray = Encoding.ASCII.GetChars(asBytes);
ReadOnlySpan<char> publicKeyChars = publicKeyAsArray;
RSA rsa = RSA.Create();
try
{
rsa.ImportFromPem(publicKeyChars);
result = rsa.VerifyData(licenseRelationshipJsonAsArray, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
} catch (CryptographicException cex)
{
log.write("Something went wrong with the crypto verification process", cex);
}
.
.
.
Thankyou for your time.

ASP.NET MVC - Download PDF file in same window not working

I have download PDF file(not to open) generated from controller method. file is getting opened in new separate window. I am generating MemoryStream at server side. I have to return it to client in same window, here I don't have to open, just download in the same client window.
below code I have tried -
Server-
public async Task<ActionResult> DownloadReport(string id, string reportType="")
{
var fileData = await GetReport(id, reportType);
// here fileData is MemoryStream
return File(fileData, "application/pdf");
}
html code -
#Html.ActionLink("Download", "DownloadReport","Files", new { id = "abc" },null)
Use Content-Disposition header
public async Task<ActionResult> DownloadReport(string id, string reportType="")
{
var fileData = await GetReport(id, reportType);
// here fileData is MemoryStream
Response.AddHeader("Content-Disposition", "attachment;filename=file.pdf");
return File(fileData, "application/pdf");
}

How to call Export PDF with Reserved.ReportViewerWebControl.axd....URL from BackEnd C# Code

My Aim is to call ExportBaseUrl Link , that is given by Rdlc Exprot PDF button , on C# side, i want to do that because there are 285 reports and each one have diff parameters so this will take a lot time.
I have worked on one solution but that take 15 min to load 2 page RDLC to pdf.
Its taking time due to Response coming late or some deadlock is happening,
This is what i am doing.
JS file
var reportViewerName = ControlName; //Name attribute of report viewer control.
var src_url = $find(reportViewerName)._getInternalViewer().ExportUrlBase + 'PDF';
var contentDisposition = 'AlwaysInline'; //Content Disposition instructs the server to either return the PDF being requested as an attachment or a viewable report.
var src_new = src_url.replace(/(ContentDisposition=).*?(&)/, '$1' + contentDisposition + '$2');
window.open("/printPDF.asx?url=" + encodeURIComponent("http://localhost:5402"+src_new));
PrintPDF.aspx File is like this
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace WebApp.WebAPI
{
/// <summary>
/// Summary description for printPDF
/// </summary>
public class printPDF : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
string url = context.Request.QueryString["url"];
// Download data.
DownloadFile(url, context.Server.MapPath("~/pdf/pdffile.pdf"), context.Request).Wait();
PdfDocument pdfDoc = new PdfDocument(new PdfReader(context.Server.MapPath("~/pdf/pdffile.pdf")), new PdfWriter(context.Server.MapPath("~/pdf/pdffileAuto.pdf")));
// add content
PdfAction action = PdfAction.CreateJavaScript("this.print({bUI: true, bSilent: true, bShrinkToFit: true});");
pdfDoc.GetCatalog().SetOpenAction(action);
pdfDoc.Close();
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition",
"AlwaysInline;filename=\"FileName.pdf\"");
context.Response.BinaryWrite(File.ReadAllBytes(context.Server.MapPath("~/pdf/pdffileAuto.pdf")));
context.Response.Flush();
context.Response.End();
}
public async Task DownloadFile(string url, string destinationPath, HttpRequest req)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
var encoding = new UTF8Encoding();
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-IN");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Accept = "text/html, application/xhtml+xml, image/jxr, */*";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
request.KeepAlive = true;
request.Proxy = null;
request.CookieContainer = new CookieContainer();
Uri target = new Uri("http://localhost:5402/");
foreach (String item in req.Cookies)
{
request.CookieContainer.Add(new Cookie(item, req.Cookies[item].Value) { Domain = target.Host });
}
await request.GetResponseAsync().ContinueWith(t1 =>
{
using (var responseStream = t1.Result.GetResponseStream())
{
if (responseStream == null)
return;
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
using (FileStream fileStream = File.Create(destinationPath))
{
while ((bytesRead = responseStream.Read(buffer, 0, bufferSize)) != 0)
{
fileStream.Write(buffer, 0, bytesRead);
}
}
}
t1.Result.Close();
});
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
line
await request.GetResponseAsync().ContinueWith(t1 =>
with async and without async takes around 15 min time once, second time it go to deadlock/Freez
also i had to add cookie due to the url was throwing 500 internal server error.
And if i call url direct on browser it runs in 1 sec.
So if anyone know what is issue or can help then that would be really big help.
Thanks for Help in Advance.
Ok
I found what issue is,
Issue is tab request PrintPDF.aspx and that page request other URL on same site.
So untill PrintPDF.aspx response complete to tab that (HttpWebRequest) is not being called.
Any reason why? i set maxconnection in web.config though
I had to fix it by making 2 diff files, first ASPX file which show page and generate pdf in thread and on page load call Ashx file which checks if file is generated or not, if generated then return file.
there was not other way, so i fixed it by 2 links redirect call.
Thank Everyone who helped me.

How can I open a PDF file in new tab without saving this file using ASP.NET MVC 5? [duplicate]

I would like to view a PDF file directly in my browser. I know this question is already asked but I haven't found a solution that works for me.
Here is my action's controller code so far:
public ActionResult GetPdf(string fileName)
{
string filePath = "~/Content/files/" + fileName;
return File(filePath, "application/pdf", fileName);
}
Here is my view:
#{
doc = "Mode_d'emploi.pdf";
}
<p>#Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)</p>
When I mouse hover the link here is the link:
The problem with my code is that the pdf file is not viewed in the browser but I get a message asking me if I wand to open or save the file.
I know it is possible and my browser support it because I already test it with another website allowing me to view pdf directly in my browser.
For example, here is the link when I mouse hover a link (on another website):
As you can see there is a difference in the generated link. I don't know if this is useful.
Any idea how can I view my pdf directly in the browser?
The reason you're getting a message asking you to open or save the file is that you're specifying a filename. If you don't specify the filename the PDF file will be opened in your browser.
So, all you need to do is to change your action to this:
public ActionResult GetPdf(string fileName)
{
string filePath = "~/Content/files/" + fileName;
return File(filePath, "application/pdf");
}
Or, if you need to specify a filename you'll have to do it this way:
public ActionResult GetPdf(string fileName)
{
string filePath = "~/Content/files/" + fileName;
Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
return File(filePath, "application/pdf");
}
Instead of returning a File, try returning a FileStreamResult
public ActionResult GetPdf(string fileName)
{
var fileStream = new FileStream("~/Content/files/" + fileName,
FileMode.Open,
FileAccess.Read
);
var fsResult = new FileStreamResult(fileStream, "application/pdf");
return fsResult;
}
Change your code to this :
Response.AppendHeader("Content-Disposition","inline;filename=xxxx.pdf");
return File(filePath, "application/pdf");
If you read the file stored in database image column, you can use like this:
public ActionResult DownloadFile(int id)
{
using (var db = new DbContext())
{
var data =
db.Documents.FirstOrDefault(m => m.ID == id);
if (data == null) return HttpNotFound();
Response.AppendHeader("content-disposition", "inline; filename=filename.pdf");
return new FileStreamResult(new MemoryStream(data.Fisier.ToArray()), "application/pdf");
}
}
If you are using Rotativa package to generate PDF, Then don't put a name to file with FileName attribute like below example.
return new PartialViewAsPdf("_JcPdfGenerator", pdfModel);
Hope this is helpful to someone.
Although previous posts are often correct; I think most of them are not best practice!
I'd like to suggest to change action return types to FileContentResult and usereturn new FileContentResult(fileContent, "application/pdf"); at the end of action body.
Yes You Can do It Simply by redirecting . it ends extension like u need , .pdf ..
protected void OpenPdfPdf_Click(object sender, EventArgs e)
{
Response.Redirect("jun.pdf");
}
Or another Method ,its opens like .aspx page--
protected void OpenPdf_Click(object sender, EventArgs e)
{
string path = Server.MapPath("jun.pdf");
//or you want to load from url change path to
//string path="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}

parse file displays random alphanumeric text in textView Android

I am getting a parse file back from parse.com which is a string message and displaying it in textView.
ParseFile file = message.getParseFile(ParseConstants.KEY_FILE);
String filePath = file.getDataInBackground().toString();
if (messageType.equals("string")){
Intent intent = new Intent(getActivity(), StringActivity.class);
intent.putExtra("file", filePath);
string activity class i try to display file in textView:
protected TextView mDisplay;
mDisplay = (TextView)findViewById(R.id.stringDisplay);
String mess = getIntent().getStringExtra("file");
byte[] by = mess.getBytes();
String filePath =new String(by);
mDisplay.setText(filePath);
whats displayed in the textView is this bolts.Task#12af9f90 random numbers.
how can i get the string to display?
This will get you the content of the file:
String fileContent = "";
try {
fileContent = new String(file.getData());
} catch (ParseException e) {
e.printStackTrace();
}

Categories

Resources