473,420 Members | 2,907 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,420 software developers and data experts.

ASP.NET Progress

What if your event handler has to be nonstatic?
Dec 17 '09 #1
18 3904
Frinavale
9,735 Expert Mod 8TB
Navyjax2, could you please provide more information about the problem you are facing?

There is the INotifyPropertyChanged.PropertyChanged Event. When this event is raised it indicates that the property has been changed.



-Frinny
Dec 17 '09 #2
Bare with me, I'm fairly new to delegates, interfaces, and events, even though I've been doing C# for almost 2 yrs and VB/VB .NET since VB6.

Basically I wanted to do an event whenever a variable's value changed. A public variable value (essentially a counter) is increased as a DataTable is parsed through a foreach loop. The variable's value changing would trigger an event that would change the innerHTML of a span tag on the page (which has to happen within a nonstatic function), to give an indication of what row we were on out of the total - creating a progress counter.

Something like:
Expand|Select|Wrap|Line Numbers
  1.     private long _rowCount = CSV.rowCount;
  2.     public delegate void PrivateVariableChanged(object sender, EventArgs e);
  3.     public event PrivateVariableChanged SelectedChanged
  4.     {
  5.         add { fileLinkArea.InnerHtml = "Processed " + CSV.rowCount + " of " + CSV.rowTotal; }
  6.         remove { }
  7.    };  
  8.  
  9.     private void NotifyPrivateVariableChanged(String info)
  10.     {
  11.         if (SelectedChanged != null)
  12.         {
  13.             SelectedChanged(this, new PrivateVariableChangedEventArgs(info));
  14.         }
  15.     }
  16.     public long RowCount
  17.     {
  18.         get
  19.         {
  20.             return this._rowCount;
  21.         }
  22.  
  23.         set
  24.         {
  25.             if (value != this._rowCount)
  26.             {
  27.                 this._rowCount = value;
  28.                 NotifyPrivateVariableChanged("RowCount");
  29.             }
  30.         }
  31.     }
But this is totally hosed and does not work. I checked MSDN and there is no PrivateVariableChangedEventArgs even though there is a PrivateVariableChanged. Any help?

Thanks,
Tom
Dec 17 '09 #3
Frinavale
9,735 Expert Mod 8TB
I think that the easiest way to handle this is to make the public variable private and provide a public Property instead. That way your property could either raise an event that notifies all other classes of the change...or it could change the innerHTML (not sure why you're doing this but ok) of the element.

It's nice when encapsulation works for you :)

-Frinny
Dec 17 '09 #4
So what changed property would it be firing on? And is that the right syntax for the event?

I was trying this another way, too - as the foreach loop processes and increments the counter I have, couldn't I just set the innerHTML updating to occur there? But the thing is, _Default defaultClass = new _Default() won't instantiate the _Default class where my page is, so that it could run a function there that would take care of the innerHTML updating. Is there a way around this? If so, I might not even need events at all...

Thanks,
Tom
Dec 18 '09 #5
Frinavale
9,735 Expert Mod 8TB
What is really confusing me is the that you're setting the innerHTML.
First of all this isn't typically done in ASP.NET any more. Instead the Text property is usually used (for example: myLabel.Text = "1 of 5")

The other thing that is confusing me is that your C# code is executed on the server...this means that the user will not see the change to the innerHTML (or even the Text property) until the response to the request is sent to the browser....in which case, why don't you just do your loop and when you're finished, set the innerHTML (or Text property) of the control?

-Frinny
Dec 18 '09 #6
Well, what I was doing was setting a span on the page equal to this text. I wanted the span to be able to show the progress to a user ("Row 1 of 14298 processed", etc.) as the DataTable is being looped through. I found that, even if I put the code into the _Default class (to prevent instantiation issues) and had it try and update the field "updateText" as the counter increased, it doesn't show on the page, at least while debugging it and letting it run a couple of loops - probably for the very reason you are saying - me not waiting til the end probably prevented it from displaying, but I want it to do it as it's going, not wait til the end.

So I thought about how you might be able to do this with JavaScript, since I know that JavaScript can do this, but adding an attribute to the button click that initiates this whole thing in Page_Load():
Expand|Select|Wrap|Line Numbers
  1. btnDBExport.Attributes.Add("onclick", "sendIt(" + data + ")");
  2.  
where
Expand|Select|Wrap|Line Numbers
  1. function sendIt(data) {
  2.    document.getElementById('updateText').innerHTML = data;
  3. }
and
Expand|Select|Wrap|Line Numbers
  1. data = "Row " + rowCount + " of " + dt.Rows.Count + " processed.";
would only update the field once, and before my counter even exists - not throughout the loop. Is there a way to write on the fly to the page from C# to JavaScript in this way? Thanks for the replies.

-Tom
Dec 18 '09 #7
Frinavale
9,735 Expert Mod 8TB
This is actually a little more complicated than you would think.
I'm sure that there may be another way to do this but this is the first thing that comes to my mind....

When you click the button that starts the processing, also start a Ajax Timer control that posts back to the server after a given amount of time has passed.

Have the loop set a Session variable so that when the Ajax Timer posts back to the server the method that handles the tick event can retrieve the value and display it in the web page.

I suggest using an ASP.Net Label control instead of your typical HTML <span> because this control renders as a <span> and lets you manipulate the Text and style aspects (along with a bunch of other properties) in your VB.NET/C# server code.

Place the Label that is going to display the text inside an UpdatePanel so that only that section of the page is updated....likewise place the GridView and the Button in an UpdatePanel so only that section of the page is being processed when you click the button.

-Frinny
Dec 21 '09 #8
Frinavale
9,735 Expert Mod 8TB
I've moved your question into a thread of it's own because this question is straying off topic from the original question.

New questions should not be posted onto the end of old questions.

This thread has been split off of:
http://bytes.com/topic/net/answers/6...changes-vb-net

-Frinny
Dec 21 '09 #9
jumbojs
20
This sounds like it would work but I'm trying to add the Timer control in code behind after the button is clicked and it isn't really working

Expand|Select|Wrap|Line Numbers
  1.  protected void btnRunUpdateNow_Click(object sender, EventArgs e)
  2.     {
  3.  
  4.  
  5.         Timer timerControl = new Timer();
  6.         timerControl.Tick += new EventHandler<EventArgs>(timerControl_Tick);
  7.         timerControl.Interval = 3000;
  8.  
  9.        .......
  10.    }
What am I missing. Nothings happening as I run this code
Dec 22 '09 #10
Frinavale
9,735 Expert Mod 8TB
Instead of adding the event handler in this code try moving it to your declaration.
For example:
Expand|Select|Wrap|Line Numbers
  1. <asp:Timer ID="timerControl" runat="server" OnTick="timerControl_Tick" Interval="3000" ></asp:Timer>
Set your timer to be disabled at first....you will need to enable it when you need it to start ticking back to the server.

The thing is that I was a little mistaken earlier....you can't really enable the timer in your button click event because you need to send the request back to the client before you start the looping. You're probably going to have to send 2 requests: the first one starts the timer, the second starts the looping.

Or you need to figure out a way to send the request back to the client while the server continues to loop.

-Frinny
Dec 22 '09 #11
jumbojs
20
Thanks for the reply. I actually tried setting up the Timer control this way (disabling it and enabling it on button click) Didn't really work. I was trying to do something like this.

Expand|Select|Wrap|Line Numbers
  1. <asp:Timer ID="Timer1" runat="server" Interval="3000" Enabled="false" OnTick="Timer1_Tick">
  2.     </asp:Timer>
  3.  
  4.     <asp:UpdatePanel ID="upProgress" runat="server" >
  5.         <ContentTemplate>
  6.             <div>
  7.                 <asp:Label ID="Progress" runat="server" Text="Sample"></asp:Label>
  8.             </div>
  9.         </ContentTemplate>
  10.     </asp:UpdatePanel>
Then in my Timer Click Event

Expand|Select|Wrap|Line Numbers
  1. protected void Timer1_Tick(object sender, EventArgs e)
  2.     {
  3.  
  4.         Session["Progress"] = "Started processing...";
  5.  
  6.         Progress.Text = (string)Session["Progress"];
  7.     }
Then what I want to do here is on click, I start the import process by passing the control of to a class housed in an assembly.

Expand|Select|Wrap|Line Numbers
  1. protected void btnRunUpdateNow_Click(object sender, EventArgs e)
  2.     {
  3.                  Timer1.Enabled = true;
  4.                  myClass.RunUpdate();
  5.     }

Inside myClass housed in an assembly, I was trying to update progress using the Session variable.

Expand|Select|Wrap|Line Numbers
  1. public void RunUpdate()
  2.    {
  3.             .....
  4.             HttpContext.Current.Session["Progress"] = _Orders.Count.ToString();
  5.    }
I'm not sure how else to get this to work. If I need to move this to another thread, let me know.
Dec 22 '09 #12
Frinavale
9,735 Expert Mod 8TB
I just tried to implement what I was suggesting and it doesn't work.
This comes back to a problem that I got stuck on about a year ago (or so) that I had forgotten about...

Apparently (I'm not sure if this is a Cassini thing or not) the server code will not process more than one request from the same webpage at the same time.

For example:
  • Button posts back to server and a long process is started
  • TimerControl posts back to server

The TimerControl postback won't be processed until the button click event is finished processing. This defeats the whole purpose of Asynchronous. I was very annoyed when I discovered this and never did find out why this was happening, nor did I find out how to get around this.

-Frinny
Dec 22 '09 #13
Frinavale
9,735 Expert Mod 8TB
I think I'm getting closer to finding an answer.
Apparently you have to specify your page is Async in the @Page directive. Then you have to implement Begin and End methods for the things are going to take a long time so that they are executed asynchronously...

I'm reading Wicked Code:Asynchronous Pages in ASP.NET 2.0 in an attempt to solve this problem.

-Frinny
Dec 22 '09 #14
Frinavale
9,735 Expert Mod 8TB
Upon further reading of the article I discovered the asynchronous page was simply for processing more than one thing in different threads before the response is sent to the browser. It was an interesting read but doesn't help with the problem.

So, I have something that sort of works....it works the very first time the page is loaded but after that it doesn't.

This is what I have in my ASPX page:
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestingProgress.aspx.cs" Inherits="WebApplication1.TestingProgress" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" >
  5. <head runat="server">
  6.     <title>Testing</title>
  7. </head>
  8. <body>
  9.     <form id="form1" runat="server">
  10.     <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
  11.     <div>
  12.         <asp:UpdatePanel ID="upnl" runat="server">
  13.         <ContentTemplate>
  14.           <asp:Timer ID="timerControl" runat="server" Enabled="false" Interval="500" OnTick="timerControl_Tick"></asp:Timer>
  15.  
  16.           <asp:LinkButton ID="startTimer" runat="server" OnClick="startTimer_Click" Text="Start Timer" style="display:none;"></asp:LinkButton>
  17.           <asp:Label ID="processingMessage" runat="server"></asp:Label>
  18.           <asp:Button runat="server" ID="btnLongProcess" Text="start processing" OnClientClick="return startTimerBeforePosting();" OnClick="btnLongProcess_Click" />
  19.           <script type="text/javascript">
  20.               function startTimerBeforePosting() {
  21.                   setTimeout(waitBeforeStartingTimer, 1000);
  22.                   return true;
  23.               }
  24.               function waitBeforeStartingTimer() {
  25.                   __doPostBack('<%=startTimer.ClientID %>', '');
  26.               }
  27.           </script>
  28.         </ContentTemplate>
  29.         </asp:UpdatePanel>
  30.  
  31.      </div>
  32.     </form>
  33. </body>
  34. </html>
And this is what I have in my C# code:
Expand|Select|Wrap|Line Numbers
  1. namespace WebApplication1
  2. {
  3.     public partial class TestingProgress: System.Web.UI.Page
  4.     {
  5.         private static int loopIteration = 0;
  6.         private int max = 10;
  7.         protected void Page_Load(object sender, EventArgs e)
  8.         {   if (!IsPostBack) {
  9.             loopIteration = 0;
  10.             }
  11.         }
  12.         protected void timerControl_Tick(object sender, EventArgs e)
  13.         {  /*int iteration = 0;
  14.             if (Session["loopIteration"] != null) {
  15.                 iteration = (int)Session["loopIteration"];
  16.             }
  17.             processingMessage.Text = iteration.ToString() +"/"+ max.ToString();
  18.             if (loopIteration >= max-1)
  19.             {
  20.                 timerControl.Enabled = false;
  21.                 processingMessage.Text = "Done. Timer stopped in tick.";
  22.             }*/
  23.  
  24.             processingMessage.Text = loopIteration.ToString() + "/" + max.ToString();
  25.             if (loopIteration >= max)
  26.             {
  27.                 timerControl.Enabled = false;
  28.                 processingMessage.Text += " Done. Timer stopped in tick.";
  29.             }
  30.         }
  31.         protected void startTimer_Click(object sender, EventArgs e)
  32.         {
  33.             timerControl.Enabled = true;
  34.             processingMessage.Text = "Timer started...";
  35.         }
  36.         protected void btnLongProcess_Click(object sender, EventArgs e)
  37.         {
  38.             Session["loopIteration"] = 0;
  39.             loopIteration = 0;
  40.             for (loopIteration = 0; loopIteration < max; loopIteration++)
  41.             {
  42.                 //Session["loopIteration"] = loopIteration;
  43.                 System.Threading.Thread.Sleep(1000);
  44.             }
  45.             timerControl.Enabled = false;
  46.             processingMessage.Text = "Done. Timer stopped in button click.";
  47.         }
  48.     }
  49. }
Now, like I said this works the first time.

The JavaScript in the ASPX page calls a function that preforms a postback for a hidden LinkButton on the page a second after the button is clicked. The code that handles the LinkButton click event enables the timer. So the Timer is started after button click the process begins.

The button click process sets a static integer to 0 and then increments the static integer by one in a loop that puts the main thread to sleep for a second each loop.

In the timer tick event, the static integer is displayed on the page along indicating how much more it has to go before the process is done.

This works the first time the page is ever loaded.
Once the button has been clicked and the processing stuff has been displayed it stops working.

What do I mean by that?
Well, if you click the button again the JavaScript waits for one second and fires the postback for the hidden LinkButton...the thing is that the click event for the link button is not fired until after the button click event is complete. This means that the timer is started after the looping process is done which is not really useful.

I don't know why this is the case...

Aside from that, another thing that I found is that you can't use Session in this solution. I never realized how slow accessing Session was until this experiment. I tried locking session every time I accessed it thinking that the timer tick event implementation couldn't access Session since the button click event was using it...but this didn't help. You can see the Session attempt commented out in my above posted code.

And, I don't think that using a static variable is going to really be feasible in your real-world application, but Session wasn't working...so I tried something else....which "kind of" worked.

I'm not sure what to suggest...

-Frinny
Dec 22 '09 #15
***************
This is actually a little more complicated than you would think.
I'm sure that there may be another way to do this but this is the first thing
that comes to my mind....

When you click the button that starts the processing, also start a Ajax Timer
control that posts back to the server after a given amount of time has passed.

Have the loop set a Session variable so that when the Ajax Timer posts back to
the server the method that handles the tick event can retrieve the value and
display it in the web page.

I suggest using an ASP.Net Label control instead of your typical HTML <span>
because this control renders as a <span> but lets you manipulate the Text and
style aspects (along with a bunch of other properties) in your VB.NET/C# server
code.

Place the Label that is going to display the text inside an UpdatePanel so that
only that section of the page is updated....likewise place the GridView and the
Button in an UpdatePanel so only that section of the page is being processed
when you click the button.

-Frinny
Thank you very much for your help. This is everything I did, for the benefit of someone in the future. I'm fairly new to AJAX, but I installed it from http://www.microsoft.com/downloads/e...displayLang=en, updated the web.config file using http://www.asp.net/AJAX/documentatio...SPNETAJAX.aspx, created an UpdatePanel, but I found that I needed to just start from scratch to create an AJAX-enabled site because of all of the misguided web.config references (see [<link snipped>] .... seems Microsoft didn't tell us you can't just put some stuff in your web.config and throw some non-existant DLLs into your Bin folder to make this work....anyway...) ....

Followed the first half of <link snipped> to get me going once I created my AJAX-enabled ASP .NET site.

So once I had that (and corrected a "Sys.WebForms.PageRequestManagerTimeoutExcepti on" by setting AsyncPostBackTimeout really high), I tried invoking the .Tick() method on the timer to make it update the panel manually during my database "foreach" loop, but this doesn't work to make the content update; allowing it to load something "onload" did execute correctly, however. So the best I could do was to disable the timer at Page_Load, enable it right before the "foreach" loop, try to set the interval fast/low enough that I can see the number of records change to something other than the last number, and disable it right after the loop. And for some reason it only runs after the 2nd time I click my button - not sure why that is. In trying to find out/find a better way, I ran across a site (<link snipped>) where they say not to run a server-side timer, so I'm a little confused if I'm doing things right and if this is the best I can achieve. At any rate, here's my code... note that this is a stripped down version of my real program, but I want it to work here in this "tester" program, because if it works here, it will work in my main program.

Default.aspx:

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head runat="server">
  4.     <title>Search Monitoring:  Message Validation</title>
  5.     <script type="text/javascript">
  6.  
  7.     function activateClock() {
  8.         document.getElementById('formatText').innerHTML = "<img src='https://<% =ConfigurationManager.AppSettings["FQDN"] %>/SearchMonitoringSite/images/animated-clock.gif' />";
  9.     }
  10.  
  11.     </script>    
  12. </head>
  13. <body>
  14.  
  15.     <form id="form1" runat="server">
  16.  
  17.     <asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="360000" />
  18.     <asp:Button ID="btnDBExport" runat="server" Text="Export DB" OnClick="btnDBExport_Click" />
  19.      <asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load" UpdateMode="conditional">
  20.         <ContentTemplate>
  21.     <asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick="Timer1_Tick">
  22.     </asp:Timer>   
  23. <asp:Label ID="lblDBExport" runat="server"></asp:Label>
  24.         </ContentTemplate>
  25.         <Triggers >
  26.             <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
  27.         </Triggers>
  28.     </asp:UpdatePanel>  
  29.         <table>      
  30.         <tr><td><span id="formatText" style="color:red;font-size:13px;font-family:Arial" runat="server"></span></td></tr>
  31.         </table>
  32.     </form>
  33. </body>
  34. </html>
  35.  
Default.aspx.cs:

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Configuration;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. using System.Web.Configuration;
  12. using System.Windows.Forms;
  13. using System.Threading;
  14.  
  15. public partial class _Default : System.Web.UI.Page 
  16. {
  17.     protected void Page_Load(string data, object sender, EventArgs e)
  18.     {
  19.         btnDBExport.Attributes.Add("onclick", "activateClock();");
  20.         ScriptManager1.RegisterAsyncPostBackControl(btnDBExport);
  21.         Timer1.Enabled = false;
  22.     }
  23.  
  24.     private static long rowCount = 0;
  25.     private static long rowTotal = 0;
  26.  
  27.     protected void btnDBExport_Click(object sender, EventArgs e)
  28.     {
  29.         rowCount = 0;
  30.  
  31.         try
  32.         {
  33.             Configuration rootWebConfig =
  34.                 WebConfigurationManager.OpenWebConfiguration("/ShowDBProgress");
  35.             if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
  36.             {
  37.                 string connString = (string)WebConfigurationManager.ConnectionStrings["RemoteSqlServer"].ConnectionString;
  38.  
  39.                 SqlConnection sqlConn = new SqlConnection(connString);
  40.                 if (sqlConn.State == ConnectionState.Open)
  41.                 {
  42.                     sqlConn.Close();
  43.                 }
  44.                 sqlConn.Open();
  45.  
  46.                 string sqlCmd = "SELECT * FROM SearchMon.dbo.MsgStatus";
  47.                 SqlDataAdapter myDataAdapter = new SqlDataAdapter(sqlCmd, sqlConn);
  48.                 DataTable dt = new DataTable();
  49.                 myDataAdapter.Fill(dt);
  50.                 string name = "";
  51.                 Timer1.Enabled = true;
  52.                 Timer1.Interval = 1;
  53.                 rowTotal = dt.Rows.Count;
  54.                 foreach (DataRow r in dt.Rows)
  55.                 {
  56.                     name = r["MessageId"].ToString();
  57.                     rowCount++;
  58.                 }
  59.                 Timer1.Enabled = false;
  60.                 sqlConn.Close();
  61.             }
  62.         }
  63.         catch (Exception ex)
  64.         {
  65.             MessageBox.Show(ex.ToString(), "Error");            
  66.         }
  67.     }
  68.  
  69.     protected void UpdatePanel1_Load(object sender, EventArgs e)
  70.     {
  71.         lblDBExport.Text = "Processed " + rowCount + " of " + rowTotal;
  72.     }
  73.  
  74.     protected void Timer1_Tick(object sender, EventArgs e)
  75.     {
  76.         UpdatePanel1.Update();
  77.     }
  78.  
Dec 25 '09 #16
Frinavale
9,735 Expert Mod 8TB
Navyjax2, I don't know how I missed your last post.
This is very interesting. I'm going to check out that last egghead article that you posted to see if I can make sense of it.

-Frinny
Jan 26 '10 #17
Frinavale
9,735 Expert Mod 8TB
I didn't realize that the link you had posted was to a competing forum (not an article). I had to remove the link but it didn't have anything helpful on it anyways. The advise you were trying to follow was posted in 2006....it's 2010 now and technology has changed a lot.

-Frinny
Jan 26 '10 #18
I figured out a way to make what I was trying to do work. It's funny - I was doing the exact same thing using ASP that I did with Atlas, but the Atlas stuff worked and the ASP stuff didn't. I still don't get it, because you can literally swap out the ASP timer for an Atlas one and the Atlas one will tick, the ASP one won't until all of the other server side code has been run, even if you put it in a new Thread like I used from an Atlas-enabled site I found the code for and modified to my particular project from http://www.codeproject.com/KB/aspnet...or_ASPNET.aspx. You have to register there to download the code, but I'll paste what I did with it here:

Default.aspx
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml">
  5. <head runat="server">
  6.     <title>UpdatePanel Site</title> 
  7.  
  8. </head>
  9. <body>
  10.     <form id="form1" runat="server">
  11.  
  12.   <atlas:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True" />
  13. <div>
  14.             &nbsp;<atlas:TimerControl ID="Timer1" runat="server" OnTick="Timer1_Tick" Enabled="false" Interval="10">
  15.             </atlas:TimerControl>
  16.         </div>
  17.  
  18.               <atlas:UpdatePanel ID="UpdatePanel1" runat="server" Mode="Conditional">
  19.   <Triggers>
  20.             <atlas:ControlEventTrigger ControlID="Timer1" EventName="Tick" /></Triggers>
  21.         <ContentTemplate><div style="background-color:Black; height:10px; width:300px">
  22.                 <div id="bar" runat="server" style="height:10px; width:0px; background-color:#006699">
  23.                 </div>
  24.             </div>
  25.              <asp:Label ID="Label1" runat="server" Text="0 %"></asp:Label><br />
  26. <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default.aspx" Visible="False">Refresh Page</asp:HyperLink><br />          <br />
  27.         </ContentTemplate>
  28.     </atlas:UpdatePanel>
  29.             <br />    
  30.       <asp:Button ID="btnDBExport" Text="Export DB" OnClick="btnDBExport_Click" runat="server" />&nbsp;<br />
  31.             <br />                      
  32.             <br />
  33.      <br />       
  34.  
  35.     </form>
  36. </body>
  37. </html>
  38.  
Default.aspx.cs
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Configuration;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. using System.Security.Principal;
  12. using System.Web.Services;
  13. using System.Web.Services.Protocols;
  14. using System.Threading;
  15.  
  16. public partial class _Default : System.Web.UI.Page 
  17. {
  18.     // Progress Bar controls
  19.     private static long rowCount = 0;
  20.     private static long rowTotal = 0;
  21.     private static string msgUrl = "";
  22.  
  23.     protected void Page_Load(object sender, EventArgs e)
  24.     {
  25.         ScriptManager1.RegisterAsyncPostBackControl(Timer1);
  26.         Timer1.Enabled = false;
  27.     }
  28.     protected void btnDBExport_Click(object sender, EventArgs e)
  29.     {
  30.         Timer1.Interval = 10;
  31.         Timer1.Enabled = true;
  32.         Session["status"] = 0;
  33.         Thread objThread = new Thread(new ThreadStart(DoTheWork));
  34.         objThread.IsBackground = true;
  35.         objThread.Start();
  36.         Session["Thread"] = objThread;
  37.         btnDBExport.Enabled = false;
  38.     }
  39.  
  40.     protected void DoTheWork()
  41.     {
  42.         string verified = "";
  43.         string sqlCmdText = "";
  44.         DataTable dtDbList = new DataTable();
  45.         SqlDataAdapter sdaDbList = new SqlDataAdapter();
  46.         rowTotal = 0;
  47.         rowCount = 0;
  48.  
  49.         try
  50.         {
  51.             ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["RemoteSqlServer"];
  52.             string connString = cs.ConnectionString;
  53.  
  54.                 // Open the DB
  55.                 SqlConnection sqlConn = new SqlConnection(connString);
  56.                 if (sqlConn.State == ConnectionState.Open)
  57.                 {
  58.                     sqlConn.Close();
  59.                 }
  60.                 sqlConn.Open();
  61.  
  62.                 // Set the database query and fill the DataTable
  63.                 sqlCmdText = "SELECT * FROM SearchMon.dbo.MsgStatus";
  64.                 sdaDbList = new SqlDataAdapter(sqlCmdText, sqlConn);
  65.                 sdaDbList.Fill(dtDbList);
  66.                 rowTotal = dtDbList.Rows.Count;
  67.  
  68.                 // Cycle through the database
  69.                 foreach (DataRow dr in dtDbList.Rows)
  70.                 {
  71.                     verified = dr["Verified"].ToString();
  72.                     msgUrl = dr["MsgUrl"].ToString();
  73.                     rowCount++;
  74.                 }
  75.  
  76.                 // Dispose of our loose ends
  77.                 Timer1.Enabled = false;
  78.                 dtDbList.Clear();
  79.                 sdaDbList.Dispose();
  80.  
  81.                 // Close the connection
  82.                 sqlConn.Close();
  83.  
  84.         }
  85.         catch (Exception ex)
  86.         {
  87.             MsgBox("Error in DB or DB Connection String: " + ex.ToString());
  88.         }
  89.  
  90.         Timer1.Enabled = false;
  91.         Thread objThread = (Thread)Session["Thread"];
  92.         objThread.Abort();
  93.     }
  94.  
  95.     protected void Timer1_Tick(object sender, EventArgs e)
  96.     {
  97.         decimal complete = 0;
  98.         if (rowTotal != 0)
  99.             complete = (rowCount * 100) / rowTotal;
  100.         else
  101.             complete = 0;
  102.  
  103.         if (complete == 100)
  104.         {
  105.             Timer1.Enabled = false;
  106.             HyperLink1.Visible = true;
  107.             btnDBExport.Enabled = true;
  108.         }
  109.         Label1.Text = complete.ToString() + "% complete, MsgUrl = " + msgUrl + ", Row: " + rowCount + " of " + rowTotal + " complete.";
  110.         HtmlGenericControl div = (HtmlGenericControl)this.FindControl("bar");
  111.         complete = complete * 3;
  112.         div.Style["width"] = complete.ToString() + "px";
  113.  
  114.     }
  115.  
  116.     private void MsgBox(string sMessage)
  117.     {
  118.         string msg = "<script language=\"javascript\">";
  119.         msg += "alert('" + sMessage + "');";
  120.         msg += "</script>";
  121.         Response.Write(msg);
  122.     }
  123.  
  124. }
  125.  
I'm obviously going to do more in that database "foreach" loop above, just wanted to prove I could show a progress bar while I was doing it.

-Tom
Jan 27 '10 #19

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: SpamProof | last post by:
I got an animated gif that is a barber pole spinning that I want to use as a progress bar. The problem is that is stops spinning (shows 1 frame) when my browser is processing a submited request...
7
by: Pepi Tonas | last post by:
I have a form that takes some time to load because it has to populate some Data. I was trying to display a form on top of it with an activity bar so that user can see that something's going on. ...
1
by: scorpion53061 | last post by:
this code came from cor and I think Armin authored it. I am trying to download an access database and track its progress. It is reading the size fo the file but I am unsure of how to get the...
8
by: Brian Henry | last post by:
I created a smooth progress bar with this code.. but if you update the values in a row quickly of it and watch it on screen it flickers... how would i change this to reduce the flickering?...
8
by: WhiteWizard | last post by:
I guess it's my turn to ASK a question ;) Briefly my problem: I am developing a Windows app that has several User Controls. On one of these controls, I am copying/processing some rather large...
1
by: daniel_xi | last post by:
Hi all, I am running a VS 2003 .NET project on my client machine (Win 2000 SP4, ..NET framework 1.1), running an ASP.NET application on a remote web server (Win 2000 Server, IIS 6.0, .NET...
15
by: eladla | last post by:
Hi! I am creating a composite control the does some of it`s own data access. I want to display a progress bar between the time the page is loaded and the control place holder is displayed and...
5
by: Aggelos | last post by:
Hello I am doing sevreral scripts like sending a newsletter that might take a while to finish first to prevent the browser from timing out and to keep the user informed of the process progress I...
1
by: Bob | last post by:
Hi, I am having trouble seeing how this bolts together. The UI starts a process which involves a long running database update. All Database activity is handled by a class called DT. DT has a...
0
by: jags_32 | last post by:
Hello We use MFG-PRO as our ERP system which in turn uses Progress databases. In the old version of SQL 2000, using DTS packages, we used to set the code page via command prompts and execute DTS...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.