I have an ASP.NET Web Forms page with an image control bound to an animated gif. If I open it in Internet Explorer (as opposed to other browsers) and click a button on the page, which opens a file, the gif stops moving even after the file is opened and closed. It won't start up again until I refresh the browser. I'm trying to solve the problem with the following code:
protected void lnkStart_Click(object sender, EventArgs e) // Link Button Click Event
{
imgRefresher.Enabled = 1 == 1; // setting Timer Control Enabled to 1
Session["TimerEnabled"] = imgRefresher.Enabled; // storing 1 in Session
Session["FileName"] = "myFile.exe";
}
protected void imgRefresher_Tick(object sender, EventArgs e) // Timer Control Tick Event
{
if (((int)Session["TimerEnabled"]) == 1) // This line gives me an invalid cast error
{
Session["TimerEnabled"] = 0 == 1;
string fileName = Session["FileName"].ToString();
// This part I stole off the internet and will actually open the file.
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fileInfo.FullName);
Response.End();
}
}
imgRefresher.Enabled = 0 == 1;
}
The line if (((byte)Session["TimerEnabled"] ^ 1) == 0) gives me an invalid cast error. I've tried casting it into an integer, a byte, a char, a float, and a double. The goal is to toggle Session["TimerEnabled"] from 1 to 0 so the next pass turns off the Timer Control.
In your case it's better to use the type bool. (you cant cast bool to int like this (int)myBool -> invalid cast error
If you wanna us an integer you can cast like this:
int myInteger = (imgRefresher.Enabled) ? 1 : 0;
Change your Code to:
protected void lnkStart_Click(object sender, EventArgs e) // Link Button Click Event
{
imgRefresher.Enabled = true; // setting Timer Control Enabled to 1
Session["TimerEnabled"] = imgRefresher.Enabled; // storing 1 in Session
Session["FileName"] = "myFile.exe";
}
protected void imgRefresher_Tick(object sender, EventArgs e) // Timer Control Tick Event
{
if (Session["TimerEnabled"]) // This line gives me an invalid cast error
{
Session["TimerEnabled"] = false;
string fileName = Session["FileName"].ToString();
// This part I stole off the internet and will actually open the file.
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fileInfo.FullName);
Response.End();
}
}
imgRefresher.Enabled = false;
}
Related
I have a page with grid that generates PDF files using iTextSharp dll. The code is as following:
var document = new Document();
bool download = true;
if (download == true)
{
PdfWriter.GetInstance(document, Response.OutputStream);
BindGrid();
}
string fileName = "PDF" + DateTime.Now.Ticks + ".pdf";
try
{
document.Open();
// adding contents to the pdf file....
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
finally
{
document.Close();
BindGrid();
}
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
BindGrid();
}
I need to bind the grid once the download window pops up, or after user clicks to download it doesn't matters, I just need the grid to bind after the user generates the pdf file. I have tried binding the grid on numerous places as you can see, but none of them worked, the grid binds only after I refresh the page :(.
Is there any way I can do this ???
Response.End ends the page life cycle.
I suggest you to:
Generate the PDF file and save it on the server
Bind the grid
Flush the generated file
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindGrid(); // Bind the grid here
// After reloading the page you flush the file
if (Session["FILE"] != null)
FlushFile();
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Generate & Save PDF here
Session["FILE"] = fullFilePath; // The full path of the file you saved.
Response.Redirect(Request.RawUrl); // This reload the page
}
private void FlushFile()
{
string fullFilePath = Session["FILE"].ToString();
Session["FILE"] = null;
// Flush file here
}
Hope this helps.
Cheers
I want to dowlnload a PDF file on a button click. I've try like that:
protected void lbtnDownload_Click(object sender, EventArgs e)
{
if (lbtnDownload.Text != string.Empty)
{
else if (lbtnDownload.Text.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
string filePath = lbtnDownload.Text;
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(HttpContext.Current.Server.MapPath("~/") + "\\PDF\\" + filePath );
Response.End();
}
}
But nothing happens, I mean when I debug it there is no exception, but the file is not downloading.
Does anyone knows where my mistake is, and what I should do to download the PDF?
Try this
protected void btnUpload_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtName.Text)) return;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + txtName.Text);
string filePath = Server.MapPath(Path.Combine("~/SavedFolder/PDF", txtName.Text));
Response.TransmitFile(filePath);
Response.End();
}
I was wondering if anyone had a quick solution to have a button click to pass values from aspx web form to a word.dot. I have a button that opens my template but i would like it to pass textbox.text to book marks in the word template
e.g textbox1.text = bookmark.ID textbox2.text = bookmark.Fname
textbox3.text = bookmark.Lname textbox4.text = bookmark.Address ext...
protected void Button7_Click(object sender, EventArgs e)
{
string fPath = #"\\Server12\170912.dot";
FileInfo myDoc = new FileInfo(fPath);
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("content-disposition", "attachment;filename=" + myDoc.Name);
Response.AddHeader("Content-Length", myDoc.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(myDoc.FullName);
Response.End();
}
Thank you in advance as always
I want to give option to upload multiple files and then download it. I am creating link buttons Dynamically like:
private void AddLinkButtons()
{
string[] fileNames = (string[])Session["fileNames"];
string[] fileUrls = (string[])Session["fileUrls"];
if (fileNames != null)
{
for (int i = 0; i < fileUrls.Length - 1; i++)
{
LinkButton lb = new LinkButton();
phLinkButtons.Controls.Add(lb);
lb.Text = fileNames[i];
lb.CommandName = "url";
lb.CommandArgument = fileUrls[i];
lb.ID = "lbFile" + i;
//lb.Click +=this.DownloadFile;
lb.Attributes.Add("runat", "server");
lb.Click += new EventHandler(this.DownloadFile);
////lb.Command += new CommandEventHandler(DownloadFile);
phLinkButtons.Controls.Add(lb);
phLinkButtons.Controls.Add(new LiteralControl("<br>"));
}
}
And my DownloadFile event is:
protected void DownloadFile(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string url = lb.CommandArgument;
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
try
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
catch (Exception ex)
{
}
}
else
{
Response.Write("This file does not exist.");
}
}
I am getting link buttons on screen but DownloadFile event is never called after clicking. i tried all options that are commented, but its not working. What is wrong in code?
Where and when is AddLinkButtons() called ?
It should be called during init of your page, on each postback.
Depending on the logic of your page, your OnInit should look like this
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
AddLinkButtons();
}
code seems fine ..
dont understand what is lbTest in AddLinkButtons() method.
please remove this line from AddLinkButtons() method.
lb = (LinkButton)lbTest;
Hope that will works...
Add Link button after its properties have been set. Your Code is adding 2 lb buttons
phLinkButtons.Controls.Add(lb); //------1
lb.Text = fileNames[i];
lb.CommandName = "url";
lb.CommandArgument = fileUrls[i];
lb.ID = "lbFile" + i;
//lb.Click +=this.DownloadFile;
lb.Attributes.Add("runat", "server");
lb.Click += new EventHandler(this.DownloadFile);
////lb.Command += new CommandEventHandler(DownloadFile);
phLinkButtons.Controls.Add(lb); //-------------------2
Remove First line
I have dynamically added few link buttons inside a grid view with this code:
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.ID = str; // str is file URL
lb.Click += new EventHandler(lbStatus_click);
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void lbStatus_click(object sender, EventArgs e)
{
string fileName = ((Control)sender).ID;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
The link bottons appear in the webpage fine, but the problem is when I click on them, the page simply gets refreshed and nothing happens. The event handler code never gets executed.
Is this problem related to postback of the page? if yes then how can I solve it?
You need to suscribe to the command event of the grid view and add whatever information you need to the CommandArgs property.
EDIT: Added example
public void Page_Load(object sender, EventArgs e ){
gvTicketStatus.RowCommand += new EventHandler(RowCommand);
}
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.CommandName = "download"; //this is useful if you need to add more links with different commands.
lb.CommandArgument = str;// str is file URL
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void RowCommand(object sender, GridViewCommandEventArgs e)
{
string fileName = e.CommandArgument;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
For more information, please read http://msdn.microsoft.com/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.80).aspx
I've seen this behavior many times before when adding controls dynamically. Make sure that the code which binds your datagrid (which in turn executes your gvTicketStatus_RowDataBound event) runs after each and every page postback. This needs to occur in order for the linkbutton control to persist its click event after the postback.