Response.Redirect is not working - asp.net

i am writing a code where after clicking one button one page will be redirected to another nd after opening 2nd page one pdf file will be download just like this website http://www.findwhitepapers.com/content22881 .But instead of opening the 2nd page and downloading the pdf file only pdf file is downloaded but 2nd page is not opening.1st page code is
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("2nd.aspx");
}
2nd page's code is written below.
protected void Page_Load(object sender, EventArgs e)
{
string filepath = "guar-gum/Guar-gum-export-report.pdf";
// The file name used to save the file to the client's system..
string filename = Path.GetFileName(filepath);
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(Server.MapPath("Guar-gum-export-report.pdf"), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes from the stream in small portions.
while (bytesToRead > 0)
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
Response.Flush();
}
catch (Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if (stream != null)
{
stream.Close();
//
}
}
}

What do you expect to see on the 2nd page? All you have there is a pdf file. Do you expect an empty page?
Your redirect works fine. When you click the button a PDF file will be sent back to the browser and it will see it as a file that should be downloaded. No page will be sent to the browser so there is no page to see.

Here is the solution:
Don't code what you have done in page2.aspx for file downloading instead put an iframe in the page2.aspx and set the src to the file Url.
I guess it is guar-gum/Guar-gum-export-report.pdf in your case. May be you should change this to start from root of the site by prefix / to the file url.
Put this in page2.aspx
<iframe width="1" height="1" frameborder="0" src="[File location]"></iframe>
It is very simple way and No redirects or JavaScript and your Page2.aspx will also open.
UPDATE
Based on the comments below this answer
I think there is no better solution but here is another mindbending one (psst! hope you and other like..) move the page2.aspx code one for file download ONLY to the third page page3.aspx and set iframe.src to page3.aspx
Reference
SO - How to start automatic download of a file in Internet Explorer

Related

ASP.Net image become unable to open after Upload with AJAX HTMLEditor

I implemented a functions in AJAXControlToolkit to allow upload of image, but once I uploaded the image, it become not able to open (originally it open without problem in my PC). Note that however, some of the files uploaded without problem.
Below is the upload code
protected void tbxContent_HtmlEditorExtender_ImageUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string storage = #"/storage/";
string filename = DateTime.Now.Ticks.ToString() + e.FileName.Substring(e.FileName.IndexOf('.'));
if (!Directory.Exists(Server.MapPath(storage)))
{
Directory.CreateDirectory(Server.MapPath(storage));
}
// Save your File
(sender as AjaxControlToolkit.AjaxFileUpload).SaveAs(Server.MapPath(storage + filename));
// Tells the HtmlEditorExtender where the file is otherwise it will render as: <img src="" />
e.PostedUrl = storage + filename;
}
catch (Exception ex)
{
}
}
When I click on the image file at the server, I got the error as below.
Updated 1:
Seems like all the image details gone after uploaded to server, previously it exists my local PC.

How to Display byte image on the asp.net page dynamically?

I have loaded an byte array image from a web service to my asp.net website.
I need to display it on the web page as soon as execute the web service.
I have tried using generic handler, but i could not do it since there wasn't way to pass byte[] image into the generic handler
void Button2_Click1(object sender, EventArgs e)
{
this.verifyTemplates();
byte[] userImg;
try
{
matchTemp.templateService hs = new matchTemp.templateService();
bool s1 = hs.matchTemplates(template, out userID, out userName, out userImg);
// userImg is the byte image i need to display
}
catch(Exception exc)
{
// vLabel.Text = exc.Message;
}
}
What you're looking for is a Data URL. You can get the base64 of a byte array like this (change the image type as required)
string imageBase64 = Convert.ToBase64String(userImg);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
In the view:
<img src='"<%=imageSrc%>"' />
This won't work in IE 7 or earlier, if you need to support those then you'll want to look at MHTML.

How to get image directly?

Follwing webpage includes light adult contents. Please do not click link if you don't want it.
go to : http://www.hqasians.com/tgp/bigasiantits/MaiNishida/at.htm
you can see several thumb images.
click one of them. you can see large image.
Check current page url. It will be like ~~~~~~~~~~~~~~~~/tgp/bigasiantits/MaiNishida/images/01.jpg
you can know how to access another image by changing last .jpg name of whole url
change 01.jpg to 02.jpg and enter.
But, you will encounter website's main page not 02.jpg.
Is this security way to block direct access by that site ?
Is there any work-around way to get image directly?
Following is my codes.
InputStream bmis;
bmis = new URL(params[0]).openStream();
final Drawable image =
new BitmapDrawable(BitmapFactory.decodeStream(new FlushedInputStream(bmis)));
if(image != null)
{
activity.setContentView(imageSwitcher);
imageSwitcher.setImageDrawable(image);
}
I'm only guessing here, but I think what this site does is to check the "Referer" field from the HTTP request header to check whether the request came from within the site, or from outside.
It isn't a secure way of blocking direct access. In fact, there's an workaround, but I don't think the site rules allow me to write it here, so, you'll have to figure out yourself.
It's because of the Referrer. You have to be referred by that main page to open the picture.
Sorry I'm not sure how to use Android, but C# code should look like this:
static void Main(string[] args)
{
for (int i = 1; i <= 15; i++)
{
HttpWebRequest request =
WebRequest.Create(
string.Format("http://www.hqasians.com/tgp/bigasiantits/MaiNishida/images/{0:00}.jpg", i)
) as HttpWebRequest;
request.Credentials = CredentialCache.DefaultCredentials;
request.Referer = "http://www.hqasians.com/tgp/bigasiantits/MaiNishida/at.htm";
request.Method = "POST";
WebResponse response = request.GetResponse();
string inputFile = string.Format("{0}.jpg", i);
Console.WriteLine(response.ResponseUri.AbsoluteUri);
using (Stream file = File.OpenWrite(inputFile))
{
CopyStream(response.GetResponseStream(), file);
}
}
}
/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
The CopyStream method is got from here: How do I save a stream to a file in C#?

How to handle errors when using ASP.NET to create a zipfile for download?

I'm working on a functionality in my asp.net web site that enables the user to download some files as a zip file. I'm using the DotNetZip library to generate the zip file.
My code looks like this:
protected void OkbtnZipExport_OnClickEvent(object sender, EventArgs e)
{
var selectedDocumentIds = GetSelectedDocIds();
string archiveName = String.Format("archive-{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
AddResponseDataForZipFile(Response, archiveName);
try
{
string errorMessage = Utils.ExportToZip(selectedDocumentIds, arkivdelSearchControl.GetbraArkivConnection(), Response.OutputStream);
if (!string.IsNullOrEmpty(errorMessage))
{
LiteralExportStatus.Text = errorMessage;
}
else
LiteralExportStatus.Text = "Success";
}
catch (Exception ex)
{
LiteralExportStatus.Text = "Failure " + ex.Message;
}
Response.Flush();
Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
private void AddResponseDataForZipFile(HttpResponse response, string zipName)
{
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
Response.AddHeader("Expires", "0");
Response.AddHeader("Content-Description", "Zip Arcive");
}
Now, if anything goes wrong, say the Utils.ExportToZip method fails, I want to present an error message to the user and not the download dialog. Do I have to remove some data from the Response object in order to cancel the download operation?
Best regards
OKB
first, Don't call HttpContext.Current.ApplicationInstance.CompleteRequest();
Reference.
At one point, there was some example code that showed CompleteRequest(), but it's wrong.
Second - to do what you describe,
you'll need to insure that the zip file can be created correctly and in its entirety, before sending anything. That means you should do the AddResponseDataForZipFile() only after the zipfile is completely created. That means you need to create an actual zip file on the server, and not simply save out to Response.OutputStream. Once the file is successfully created, then call AddResponseDataForZipFile(), stream the bytes for the temp zip file, call Response.Close(), then delete the temporary zip file.
I can't comment at the moment, so take this answer as one.
How does Utils.ExportToZip work?
If the reason it takes the Response.OutputStream for the constructor is to write the zip-file directly into it, then you need to set Buffering in order to "undo" that in your AddResponseDataForZipFile Method:
Response.BufferOutput = true;

Asp.net Webform Display Alert and redirect

I'm currently stuck. I have a webform with a button that registers or saves a record.
What i'd like to is have it display a javascript alert and then redirect to a page.
Here is the code i am using
protected void Save(..)
{
// Do save stuff
DisplayAlert("The changes were saved Successfully");
Response.Redirect("Default.aspx");
}
This code just redirects without giving the prompt Saved Successfully.
Here is my DisplayAlert Code
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');", message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true
);
}
Can anyone help me find a solution to this?
Thanks
You can't do a Response.Redirect because your javascript alert will never get displayed. Better to have your javascript code actually do a windows.location.href='default.aspx' to do the redirection after the alert is displayed. Something like this:
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');window.location.href = 'default.aspx'",
message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true);
}
The DisplayAlert method adds the client script to the currently executing page request. When you call Response.Redirect, ASP.NET issues a HTTP 301 redirect to the browser, therefore starting a new page request where the registered client script no longer exists.
Since your code is executing on the server-side, there is no way to display the alert client-side and perform the redirect.
Also, displaying a JavaScript alert box can be confusing to a user's mental workflow, an inline message would be much more preferable. Perhaps you could add the message to the Session and display this on the Default.aspx page request.
protected void Save(..)
{
// Do save stuff
Session["StatusMessage"] = "The changes were saved Successfully";
Response.Redirect("Default.aspx");
}
Then in Default.aspx.cs code behind (or a common base page class so this can happen on any page, or even the master page):
protected void Page_Load(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty((string)Session["StatusMessage"]))
{
string message = (string)Session["StatusMessage"];
// Clear the session variable
Session["StatusMessage"] = null;
// Enable some control to display the message (control is likely on the master page)
Label messageLabel = (Label)FindControl("MessageLabel");
messageLabel.Visible = true;
messageLabel.Text = message;
}
}
The code isn't tested but should point you in the right direction
This works perfect:
string url = "home.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Saved Sucessfully.');window.location.href = '" + url + "';",true);
protected void Save(..)
{
// Do save stuff
ShowMessageBox();
}
private void ShowMessageBox()
{
string sJavaScript = "<script language=javascript>\n";
sJavaScript += "var agree;\n";
sJavaScript += "agree = confirm('Do you want to continue?.');\n";
sJavaScript += "if(agree)\n";
sJavaScript += "window.location = \"http://google.com\";\n";
sJavaScript += "</script>";
Response.Write(sJavaScript);
}

Resources