Eclipsed4utoo's Blog
Not Your Ordinary Programmer

Posts Tagged ‘progressbar’

C# – Windows Form with ProgressBar

Wed ,09/09/2009

This post will deal with showing a ProgressBar with a Windows Forms application to show progress of a long process running in the background.  If you have code that will take an abnormal amount of time(more than a few seconds), you don’t want your UI to “hang” because of the long processing.  To get around this is to run the long process in a background thread, and update the main UI with progress of where the process is at.

We will be doing this using the BackgroundWorker class.  This is probably the easiest way to get background threads up and running quickly.

So first we will have these using statements at the top.

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

Next, we define our BackgroundWorker object.

BackgroundWorker bgw;

public Form1()
{
    InitializeComponent();
}

On my form, I have a button to start the process.  Here is the Click Event for it…

private void btnStart_Click(object sender, EventArgs e)
{
     bgw = new BackgroundWorker();
     bgw.WorkerReportsProgress = true;
     bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
     bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
     bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
     bgw.RunWorkerAsync();
}

In the preceding code, we created a new BackgroundWorker object.  We also set the object to allow it to report it’s progress.  We then create 3 event handlers for the ProgressChanged, RunWorkerCompleted, and DoWork events.  The ProgressChanged event is fired when the progress is changed(like you didn’t see that one coming).  The RunWorkerCompleted event is fired when the process has been completed.  The DoWork event is the event where your long processing code will go.

The RunWorkerAsync method fires the DoWork event.

void bgw_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        bgw.ReportProgress((i + 1) * 10);
        Thread.Sleep(1000);
    }
}

In the preceding code, I am basically just running a loop that will report the progress of the thread.  It will also stop the thread temporarily so that we can see the progress bar move.

Now I will set the progress bar’s value to the percentage that I reported.  The progress bar was dragged onto the form from the Toolbox.

void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

And last, the code that runs when the task has been completed..

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     MessageBox.Show("Finished");
}

And it’s as simple as that.

ASP.Net – AJAX with Continuous Progress Bar

Fri ,07/08/2009

I was recently asked about getting a Progress Bar to work in ASP.Net.  It didn’t need to be a progress bar that had a percentage, just something that would alert a user that something is happening behind the scenes.

So I did some Google searching, and found tons of resources where people had created their own Progress Bar controls.  While that was all fine and good, I wasn’t looking to download somebody else’s custom control, and I wasn’t going to make my own.  So I wanted to figure out how I could use existing ASP.Net and AJAX controls to accomplish this task.

It turned out to be easier than I thought it would be.

I knew that I needed the progress bar to show modally, so that the user would not be able to interact with the form during the postback.  So I decided to use the ModalPopupExtender AJAX control.

So first, I have my Button, the ModalPopupExtender, the Panel that the extender will display, the Script Manager, and a hidden control.

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <div>
            <asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="StartProgressBar()"
                     runat="server" Text="Submit Time" Width="170px" />

            <ajaxToolkit:ModalPopupExtender ID="ProgressBarModalPopupExtender" runat="server"
                     BackgroundCssClass="ModalBackground" BehaviorID="ProgressBarModalPopupExtender"
                     TargetControlID="hiddenField" PopupControlID="Panel1" />

            <asp:Panel ID="Panel1" runat="server" Style="display: none; background-color: #C0C0C0;">
                 <img src="progressbar.gif" alt="" />
            </asp:Panel>

            <asp:HiddenField ID="hiddenField" runat="server" />
       </div>
   </ContentTemplate>
</asp:UpdatePanel>

If you notice, the TargetControlID attribute of the extender is NOT the button.  The reason for this is that the default functionality of the ModalPopupExtender is to require a button click from the Panel to close it.  Since I want the Panel to stay visible while the server does it’s processing, I set the TargetControlID to the hidden control.

Another thing to notice is the BackgroundCssClass attribute of the ModalPopupExtender.  This is REQUIRED for the extender to actual be modal.  Without it, the extender is a non-modal popup.(more on this later)

Also notice that the Button has both of the click events populated.  The OnClick event will be the server-side event handler.

protected void btnSubmit_Click(object sender, EventArgs e)
{
     Thread.Sleep(7000);
     ProgressBarModalPopupExtender.Hide();
}

This event simply pauses server processing for 7 seconds to simulate a long running process.

The OnClientClick event will be calling a javascript function…

<script language="javascript" type="text/javascript">
    function StartProgressBar() {
        var myExtender = $find('ProgressBarModalPopupExtender');
        myExtender.show();
        return true;
    }
</script>

And last, the CSS entry for the background of the ModalPopupExtender.

If you do not already have a CSS class added to your project, you will need to add one, and link it to the page in the HEAD tag.

<link href="main.css" rel="stylesheet" type="text/css" />

Then add this entry to the CSS file.

.ModalBackground
{
    background-color:Gray;

    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
}

If using Visual Studio 2008, you will get warnings saying that “filter” and “opacity” are not known CSS properties.  This is an issue with Visual Studio.  They are valid properties and they do work.  The 4 properties that are listed in the CSS entry should handle the opacity for all major browsers.  I have tested with IE7, Firefox 3.5, and Chrome.

And that is all you have to do.  The ModalPopupExtender will show when the button is clicked, and the server will start processing the code.  When the server has completed and sends the response back to the browser, it will hide the ModalPopupExtender.

C# – Download File Asynchronously with ProgressBar

Fri ,31/07/2009

If you’ve ever wanted to create your own Download Manager, where you download a file, keep track of the amount of the file that has been downloaded, and use a ProgressBar, this is the tutorial for you.

So first, drag a ProgressBar and a Button from the Toolbox onto the form.

Create a Click_Event for the button by double clicking it.

Add this using statement to the top of the form.

using System.Net;

In the Click_Event, we are going to create a WebClient object to download the file.

private void btnStartDownload_Click(object sender, EventArgs e)
{
     WebClient client = new WebClient();
     client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
     client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

     // Starts the download
     client.DownloadFileAsync(new Uri("SomeURLToFile"), "SomePlaceOnLocalHardDrive");

     btnStartDownload.Text = "Download In Process";
     btnStartDownload.Enabled = false;
}

In the previous code, we are creating two event handlers to handle when the Progress of the file download changes, and when the download completes.

We also use the DownloadFileAsync method so that the download(which could be lengthy) does not freeze the main GUI.

Next, we need to do the code to calculate the percentage of the download complete so that we can assign it to the ProgressBar.

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
     double bytesIn = double.Parse(e.BytesReceived.ToString());
     double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
     double percentage = bytesIn / totalBytes * 100;

     progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}

In this code, we use the BytesReceived and TotalBytesToReceive properties of the DownloadProgressChangedEventArgs object.

Next, we need to do the code for the event when the download completes.

void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
     MessageBox.Show("Download Completed");

     btnStartDownload.Text = "Start Download";
     btnStartDownload.Enabled = true;
}

That is all the code you need.

If you would like to have the percentage “embedded” into the ProgressBar, check out JacobJordan’s tutorial.