Getting Error when using response.write() - asp.net

I need to save a file as .csv in client machine. I am using the code below.
protected void btnGen_Click(object sender, EventArgs e)
{
try
{
string fileName = "test";
string attachment = "attachment; filename=" + fileName + ".csv";
List<string> lst1 = new List<string> { "wert", "fds", "hjgfh", "hgfhg" };
List<string> lst2 = new List<string> { "hgfds", "hdfg", "yretg", "treter" };
List<string> lst3 = new List<string> { "hgfdgf", "gfdg", "gfdgf", "ghfdg" };
List<List<string>> lst = new List<List<string>> { lst1, lst2, lst3 };
StringBuilder sb = new ExportFacade().GenerateStringBuilder(lst);
Response.ContentType = "text/csv" ;
lblProgress.ForeColor = System.Drawing.Color.Green;
lblProgress.Text = "File created and write successfully!";
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
Response.Write(sb.ToString());
lblProgress.ForeColor = System.Drawing.Color.Green;
lblProgress.Text = "File created and write successfully!";
Response.Flush();
Response.End();
}
catch (Exception ex)
{
lblProgress.ForeColor = System.Drawing.Color.Red;
lblProgress.Text = "File Saving Failed!";
}
}
I am not using update panels.
When I click on the button I get the following error
Sys.WebForms.PageRequestManagerParserErrorException: The message
received from the server could not be parsed. Common causes for this
error are when the response is modified by calls to Response.Write(),
response filters, HttpModules, or server trace is enabled.
It will be a great help to me if you can help me to get rid of this problem.
thank you.

I solved it. Ajax script manager in the master page has created the problem. After removing it, the function worked properly. But labels are not being updated as response is not for the page.

Related

I can't open .pdf, .doc etc. file from other servers via SFTP using rebex

I have Two different servers as like below.
1. WebServer - Where is my application is locate
2. FileServer - where is my all uploaded files are locate in perticular location / Folder
Now in my web application I have created one page which display all uploaded files from FileServer (which i have uploaded).
But the issue is, when I try to open/read that file then I am not able. I have all rights of SFTP. and I am getting below issue in Try-catch block.
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
I have used REBEX for upload and download files.
Note : I can able to open simple text file (.txt) but not other formated files like (.PDF, .docx, .jpg etc.)
My file read code is like below.
protected void LinkButton1_Click(object sender, EventArgs e)
{
try
{
LinkButton lbtn = (LinkButton)sender;
using (Sftp _sftp = new Sftp())
{
_sftp.Connect(serverNm, 22);
_sftp.Login(username, password);
_sftp.ChangeDirectory(currentDirectory);
Stream stream = _sftp.GetStream(lbtn.ToolTip.ToString(), FileMode.Open, FileAccess.Read);
StreamReader sourceStream = new StreamReader(stream);
Byte[] buffer = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
Response.Buffer = true;
if (lbtn.ToolTip.IndexOf(".pdf") > 0)
{
Response.ContentType = "application/pdf";
}
else if (lbtn.ToolTip.IndexOf(".txt") > 0)
{
Response.ContentType = "text/plain";
}
else if (lbtn.ToolTip.IndexOf(".xls") > 0)
{
Response.ContentType = "application/ms-excel";
}
else if (lbtn.ToolTip.IndexOf(".doc") > 0)
{
Response.ContentType = "application/msword";
}
else if (lbtn.ToolTip.IndexOf(".jpeg") > 0)// || lbtn.ToolTip.IndexOf(".jpg") > 0)
{
Response.ContentType = "image/jpeg";
}
else if (lbtn.ToolTip.IndexOf(".jpg") > 0)
{
Response.ContentType = "image/jpg";
}
else if (lbtn.ToolTip.IndexOf(".bmp") > 0)
{
Response.ContentType = "image/png";
}
Response.AddHeader("Content-Length", "attachment;filename=" + buffer.Length.ToString());
Response.BinaryWrite(buffer);
Response.End();
}
}
catch (Exception ex)
{
}
}
So any one can help to fixe this issue.
I am using latest Mozila browser.
Thank you.
Would it be possible to post the complete stack trace of the exception here? You can get the stack trace by modifying the catch block like this:
try
{
//... your code
}
catch (Exception ex)
{
Response.ContentType = "text/plain";
Response.Write(ex.ToString());
Response.End();
}

"server cannot append header after http headers have been sent"

i have application like email messaging system. here i adjust one solution to download all file that are in table from particular post.
this is my code:
protected void lbu_download_all_Click(object sender, EventArgs e)
{
if (rpt_file_list.Items.Count > 0)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = from f in db.Files
where f.Post_History_id == int.Parse(post_id.Value.ToString())
select new
{
FileName = f.File_name,
File_ext= f.File_ext
};
foreach (var item in query)
{
System.IO.FileInfo objFile = new FileInfo(Server.MapPath("~/PostFiles/" + item.FileName.ToString() + item.File_ext.ToString()));
if (objFile.Exists)
{
Response.Clear();
string strFileName = item.FileName.ToString() + item.File_ext.ToString();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
Response.AddHeader("Content-Length", objFile.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(objFile.FullName);
Response.BufferOutput = true;
Response.Flush();
}
}
}
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append(" No files found to download');");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "script", sb.ToString());
}
}
i don't know what is problm please help me..
You won't be able to download multiple files like that, I imagine what is happening is that the loop goes through once and on the second iteration it then throws the exception.
What you really should be doing is zipping all the files into one file to download, this question should give you an idea of what I mean.
By zipping the file you'll also get the benefit of compression (less bandwidth, faster transfer) and the user (in your current scenario) won't be presented with multiple 'Save As' dialog windows (much more professional!).
This link may also help you with some other potential ideas (like having a 'Download' page with URL parameters to identify the file). I'm more a fan of a zipped single file option though!
Do you have Response.BufferOutput = true; set properly? If not, the page will be sent as it is generated, which means the Response.Clear() won't do what you want :)

Path issue with wkhtmltopdf.exe to convert HTML file to PDF

I am using wkhtmltopdf to convert HTML file into PDF document on a link Button
http://code.google.com/p/wkhtmltopdf/
When User Click on a link Button it runs the following code as shown below code in pass file path as an argument ProcessStartInfo. THis code works fine in Following Scenarios only
Taking Into consideration that website is hosted on Domain http://www.xyz.net/
When i mention path as http://demo.XYZ.net/ It works fine
When i mention path as http://www.XYZ.net/ It doesn't work
In-case of local-host it works fine if path is http://localhost:51005/XYZ/or http://web:8080/
For this to work properly we need to give the website full trust level & i am not sure why code doesn't run i give it the same domain path if i create put PrintArticle.aspx if i create a sub domain then it will work fine. I am nost sure if this is a security problem or what
Code Below
protected void lnkbtnDownload_Click(object sender, EventArgs e)
{
//ConvertURLToPDF();
try
{
string url = "PrintArticle.aspx?articleID=" + Request["articleID"] + "&download=yes&Language=" + Request["Language"];
//string args = string.Format("\"{0}\" - ", "http://demo.XYZ.net/" + url); //Works
//string args = string.Format("\"{0}\" - ", "http://www.xyz.net/" + url); Doesnt work
//string args = string.Format("\"{0}\" - ", url);
string args = string.Format("\"{0}\" - ", "http://localhost:51005/XYZ/" + url); //Works
var startInfo = new ProcessStartInfo(Server.MapPath("bin\\wkhtmltopdf.exe"), args)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
var proc = new Process { StartInfo = startInfo };
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
byte[] buffer = proc.StandardOutput.CurrentEncoding.GetBytes(output);
proc.WaitForExit();
proc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=download.pdf");
Response.BinaryWrite(buffer);
Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
Error Message in case file is on same domain
Server Error in '/' Application. The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make sure
that it is spelled correctly.
Requested URL: /PrintArticle.aspx
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.272
I resolved this issue by using the following statement
var url = Request.Url.GetLeftPart(UriPartial.Authority) + "/PrintArticle.aspx?articleID=" + Request["articleID"] + "&download=yes&Language=" + Request["Language"];
Now it is working fine i am not sure what it doesn't work when i specify the file path.
output variable contains empty string
my code as follows:
try
{
string url=Request.Url.GetLeftPart(UriPartial.Authority) +"/PrintQuickPrescription.aspx?DoctorId=" + DoctorID + "&DispnID=" + DispnID + "&ApptID=" + ApptID + "&PatientID=" + PatientID;
System.Diagnostics.Process process = new System.Diagnostics.Process();
string args = string.Format("\"{0}\" - ", "http://localhost:50013/DPMNewWeb/"+url);
//string args="http://localhost:50013/DPMNewWeb/PrintQuickPrescription.aspx";
var startInfo = new ProcessStartInfo(Server.MapPath("~\\Bin\\wkhtmltopdf.exe"), args)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
var proc = new Process { StartInfo = startInfo };
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
byte[] buffer = proc.StandardOutput.CurrentEncoding.GetBytes(output);
proc.WaitForExit();
proc.Close();
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
Response.End();
//byte[] fileContent = GeneratePDFFile();
//GeneratePDFFile();
//if (fileContent != null)
//{
// Response.Clear();
// Response.ContentType = "application/pdf";
// Response.AddHeader("content-length", fileContent.Length.ToString());
// Response.BinaryWrite(fileContent);
// Response.End();
//}
}
catch
{
}

Silverlight OOB WebBrowser Exception

I've got an oob app with a webbrowser on it.
The webbrowser source is databound with a URI defined by me. The URI has a path to a webpage from my server that displays a PDF file from its hardrive.
Note that all this is done on a local network.
URI example: uri = new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
Page code-behind:
protected void Page_Load(object sender, EventArgs e)
{
string myURL = Request.Url.ToString();
string[] ParamArray = Regex.Split(myURL, "pdf=");
string Params = ParamArray[ParamArray.Length - 1];
if (Params.Length > 0)
{
Filename = Regex.Replace(Params, #"//", #"\\"); ;
if (File.Exists(Filename))
{
Response.ContentType = "Application/pdf";
Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream.
Response.End();
}
else
this.Title = "PDF Not Found";
}
}
protected void Page_Load(object sender, EventArgs e) { string myURL = Request.Url.ToString(); string[] ParamArray = Regex.Split(myURL, "pdf="); //If the URL has parameters, then get them. If not, return a blank string string Params = ParamArray[ParamArray.Length - 1]; if (Params.Length > 0) { //to the called (src) web page Filename = Regex.Replace(Params, #"//", #"\\"); ; if (File.Exists(Filename)) { Response.ContentType = "Application/pdf"; Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream. Response.End(); } else this.Title = "PDF Not Found"; } }
The first time I set the WebBrowser source everything it displays the PDF. But when I set the URI one second time the app throws an exception: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100).
I've done a few tests and here are the results:
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://www.google.com"); ->error
1º new Uri(#"http://www.google.com");
2º new Uri(#"http://www.microsoft.com");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
3º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
I also forgot to say that when running the app from my browser (using a HTMLHost) the pages display just fine. Opening the pages using a browser will also work well.
It must be some problem with my aspx page. Any ideas?
Pedro
I've managed to resolve this by creating a new browser for each page. If you know of a more elegant solution please share.
I am not sure if I'm following the question/problem correctly but maybe loading the pages async and then assigning to webbrowser? Forgive me if I am off-base here.
public void ShowLink(string linkUrl)
{
if (App.Current.IsRunningOutOfBrowser)
{
var pageRequest = new WebClient();
pageRequest.DownloadStringCompleted += pageRequest_DownloadStringCompleted;
pageRequest.DownloadStringAsync(new Uri(linkUrl, UriKind.Absolute));
}
}
void pageRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
webBrowserLink.NavigateToString(e.Result.ToString());
}

Problem downloading a 25MB file - the 8MB file downloads without problem (ASP.NET)

I have two files at the same location but the big one, when is about to finish download, gives an error (both in IE and Firefox).
I use the following code:
public static void DownloadZipFile (string filename, bool notifyMe)
{
HttpContext context = HttpContext.Current;
HttpServerUtility server = context.Server;
bool ok = false;
try
{
string file = string.Format ("~/contents/licensing/members/downloads/{0}", filename);
string server_file = server.MapPath (file);
HttpResponse response = context.Response;
//response.BufferOutput = false;
response.ContentType = "application/zip";
string value = string.Format ("attachment; filename={0}", filename);
response.AppendHeader ("Content-Disposition", value);
FileInfo f = new FileInfo (server_file);
long size = f.Length;
response.TransmitFile (server_file, 0, size);
response.Flush ();
ok = true;
response.End ();
}
catch (Exception ex)
{
Utilities.Log (ex);
}
finally
{
if (ok && notifyMe)
NotifyDownload (filename);
}
}
Any ideas?
Response.End() calls Response.Flush(). Try removing the Flush call.
The solution to this problem is to add the line:
response.AddHeader("Content-Length",size.ToString());
before the call to TransmitFile ().
The credits go to Jim Schubert (see his comment above).

Resources