Wednesday, March 21, 2012

Need help downloading a file to clients computer

I really hope one of you guys can help me with this becauseI have been trying to fix this for a week and I am no further down the roadthan when I started. The task I amtrying to accomplish is this:

User clicks a button which starts an asynchronous processwhich creates an Excel spreadsheet. Thisprocess takes about 5 or 10 minutes. Screenupdates are sent as process runs. At theconclusion of the process I want to download the excel file to the userscomputer and therein lies the problem.

The way I have it rigged now is that a timer control insidean update panel ticks which allows screen updates to happen. This works fine.

When the async process is done, it enables a timer which isoutside the update panel. The synchronoustimer downloads the file however there is no way to disable the timer. I know this wrong however I have no idea howto fix it. The code below illustratesthe general architecture of what I have now. Any help is much appreciated.

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Security.Principal;using System.IO;public partialclass Worker : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e) {if (IsPostBack) { Label2.Text = (string)Session["jobStatus"]; }else { Session["jobCompleted"] =false; Session["userCanceledJob"] =false; Session["jobStatus"] =null; Session["jobObject"] =null; } }private void Notify(string msg) { Label2.Text = msg +" - Current time is " + DateTime.Now.ToLongTimeString(); Session["jobStatus"] = Label2.Text; }private void ProcessCompleteCallBack(IAsyncResult result) {// This is is called when the asycronous process is completed. workerDelegate worker = (workerDelegate)result.AsyncState; worker.EndInvoke(result); Session["jobCompleted"] =true; }protected void Timer1_Tick(object sender, EventArgs e) {//This timer causes an asycronous postback. Label3.Text ="Timer ticked at " + Environment.NewLine + DateTime.Now.ToLongTimeString();if ((bool)Session["jobCompleted"]) { Timer1.Enabled =false; Sync_Timer.Enabled =true; StartButton.Enabled =true; CancelButton.Enabled =false; Label1.Text ="No processes are running."; Label3.Text =""; } }protected void StartButton_Click(object sender, EventArgs e) { StartButton.Enabled =false; CancelButton.Enabled =true; WindowsIdentity winIdentity = WindowsIdentity.GetCurrent(); WorkingClass me =new WorkingClass(); messangerDelegate notify =new messangerDelegate(Notify); workerDelegate worker =new workerDelegate(me.VeryLongProcess); worker.BeginInvoke(notify, winIdentity,new AsyncCallback(ProcessCompleteCallBack), worker); Timer1.Interval = 2000; Timer1.Enabled =true; Label1.Text ="Process started at " + DateTime.Now.ToLongTimeString(); Session["jobCompleted"] =false; Session["userCanceledJob"] =false; Session["jobStatus"] =""; Session["jobObject"] = me; }protected void CancelButton_Click(object sender, EventArgs e) { Session["userCanceledJob"] =true; WorkingClass me = (WorkingClass)Session["jobObject"]; me.CancelJob =true; }protected void Sync_Timer_Tick(object sender, EventArgs e) {// This timer causes a synchronis postback (?) // The timer never gets disabled Sync_Timer.Enabled =false; DownloadThis("import.txt",true); }private void DownloadThis(string fname,bool forceDownload) {// Download Excel file to clientstring path = MapPath(fname);string name = Path.GetFileName(path);string ext = Path.GetExtension(path);string type ="";// set known types based on file extensionif (ext !=null) {switch (ext.ToLower()) {case".htm":case".html": type ="text/HTML";break;case".txt": type ="text/plain";break;case".doc":case".rtf": type ="Application/msword";break; } }if (forceDownload) { Response.AppendHeader("content-disposition","attachment; filename=" + name); }if (type !="") Response.ContentType = type; Response.WriteFile(path); Response.End(); }}public class WorkingClass{public bool CancelJob;public void VeryLongProcess(messangerDelegate notify, System.Security.Principal.WindowsIdentity identity) {// Create Excel file here WindowsImpersonationContext impContext = identity.Impersonate();int recordCount = 10;string msg ="";this.CancelJob =false;for (int i = 1; i <= recordCount; i++) { msg ="Now processing record " + i.ToString() +" of " + recordCount.ToString(); notify(msg);if (!this.CancelJob) System.Threading.Thread.Sleep(500);else { msg ="Job canceled.";break; } }if (msg !="Job canceled.") msg ="Job completed."; notify(msg); }}public delegate void messangerDelegate(string msg);public delegate void workerDelegate(messangerDelegate notify, System.Security.Principal.WindowsIdentity winIdentity);
 
 <%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="DownLoadWorker.aspx.cs" Inherits="Worker" debug="true"%
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript" language ="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

function EndRequestHandler(sender, args)
{
//alert('hello there');
//window.open('http://www.ibm.com',target='new');
}
</script>
<br />
<br />
<asp:Label ID="Label4" runat="server" Font-Bold="True" Font-Size="16pt" Text="DownLoad Worker"
Width="192px"></asp:Label><br />
<br />

<br />

<br />

<br />
<asp:Panel ID="MainPanel1" runat="server" Height="256px" Width="472px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<br />
<asp:Label ID="Label1" runat="server" Height="64px" Text="No processes are running." Width="344px"></asp:Label><br />
<br />
<asp:Label ID="Label2" runat="server" Height="64px" Width="344px"></asp:Label><br />
<br />
<asp:Label ID="Label3" runat="server" Height="64px" Width="344px"></asp:Label><br />
<br />
<br />
<br />
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Enabled="False" Interval="2000">
</asp:Timer><asp:Button ID="StartButton" runat="server" OnClick="StartButton_Click" Text="Run a long Process"/> <br />
<asp:Button ID="CancelButton" runat="server" Text="Cancel Process" Enabled="False" OnClick="CancelButton_Click" /><br />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<br />
<br />
<br />
<br />
<br />
<asp:Timer ID="Sync_Timer" runat="server" OnTick="Sync_Timer_Tick" Interval="5000" Enabled="False">
</asp:Timer>
</div>
</form>
</body>
</html

So is the file downloading? or is it not downloading? What is the actual problem? Above you say that it works, but you can't disable the timer... is that your only issue? (a timer not being disabled... so I'm guessing it promts to download the file over and over again)?

Please explain.

Thanks,


Working...??

Solve the issue ot not yet?

No comments:

Post a Comment