214 Online Sessions Search :
HomePublish TutorialsAdd ResourcesSponsored ResourcesNewslettersRSS NewsSiteMapJoin UsLoginForumsBlogs

ASP.NET
C#
VB.NET
ASP.NET Hosting
Web Applications
RSS News
Link To Us
Advertise With Us
Join Us
About Us
Contact Us

Newsletter Updates
Unsubscribe Here

Your Email :
Frequency


Email Fornat








Tutorial : RiverASP.NET >> AJAX and ATLAS >> File Upload with AJAX.NET Progress Bar

File Upload with AJAX.NET Progress Bar
File Upload with AJAX.NET Progress Bar using ScriptManager and UpdatePanel
Date Published : Thursday, February 28, 2008

Author : Majid MalikArticleLevel : Advanced
Platform : .NETTechnology : ASP.NET
Language : C#Views : 445
Ratings : No Rating
| |

Introduction

In this short article I will try to explain how to show, during a File Upload,

a Progress Bar using AJAX.NET Web Server Contrls ScriptManager and UpdatePanel.

Background

This demo/sample involves an HTTPModule which is used to
intercept the uploaded file. This interception operation off-loads the file
data chunck by chunck and enables a Progress Bar as well as enables virtually
unlimited file sizes in the upload.

Using the code

1) Download the file Upfilesbe.zip
2) Unzip to any directory
3) Copy the Upfilebe folder to wwwroot directory.
4) View the aspx page samples\CS\uploadsamples\Advanced\UploadWithAjaxProgress
\uploadwithAjaxNETprogress.aspx in the browser.
5) Everything is all setup and ready to go.

The aspx source can be viewed in the file uploadwithAjaxNETprogress.aspx.

 The following code snippet is from the codefile
uploadwithAjaxNETprogress.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using expandata.net;


public partial class samples_CS_uploadsamples_Advanced_UploadWithAjaxProgress_uploadwithAjaxNETprogress 
    : System.Web.UI.Page
{
    // This field is visible in the javascript code being used in the aspx file. It is required by the HTTPModule
    protected string ProgID = "";



    // On Page_Load event we create a new ProgresID by calling the GenerateProgressID() method.
    // After that we store this value in the session object for later use.
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!this.IsPostBack)
        {
            // GenerateProgressID
            GenerateProgressID();

            //store ProgID in Session["PROGRESSID"]
            Session["PROGRESSID"] = ProgID;

            //Remove "CANCELLED" object from Session
            Session.Remove("CANCELLED");
        }
    }
    
    
    //// <SUMMARY>
    /// ////////////////////////////////////////
    /// </SUMMARY>
    private void GenerateProgressID()
    {
        // create NextProgressID and assign it to global variable ProgID
        // DNUpFilesBE class is in the expandata.net assembly
        ProgID = (new DNUpFilesBE()).NextProgressID();
    }


    protected void ButtonUpload_Click(object sender, System.EventArgs e)
    {
        // disable ButtonUpload
        this.ButtonUpload.Enabled = false;

        //ProcessUpLoad();
        ProcessUpLoad();
    }


    /// <SUMMARY>
    /// /////////////////////////////////
    /// </SUMMARY>
    void ProcessUpLoad()
    {
        // create DNUpFilesBE object
        expandata.net.DNUpFilesBE dnUpFilesBE = new expandata.net.DNUpFilesBE();

        // DNFileBE object
        expandata.net.DNFileBE dnFileBE;

        try
        {
            // set CacheFolder
            dnUpFilesBE.CacheFolder = Server.MapPath((string)Application["vroot"]) + "/Cache";

            //set DestinationFolder
            dnUpFilesBE.DestinationFolder = Server.MapPath((string)Application["vroot"]) + "/Dest";

            // ProcessRequest
            dnUpFilesBE.ProcessRequest(this.Request);

            // Display Results
            if (dnUpFilesBE.Files.Count > 0)
                LabelTitle.Text = "&lt;DT><B>All files have been successfully processed by UpFilesBE!!</B>";
            else
                LabelTitle.Text = "&lt;DT><B>No files have been submitted to UpFilesBE!!</B>";

            LabelSaveInfo.Text = "";

            System.Text.StringBuilder saveInfo = new System.Text.StringBuilder();

            //walk through the files collection
            for (int i = 0; i < dnUpFilesBE.Files.Count; i++)
            {
                dnFileBE = dnUpFilesBE.Files[i];

                if (i != 0)
                {
                    saveInfo.Append("&lt;DD> ");
                    saveInfo.Append("&lt;DT>----------------------------------------");
                }

                saveInfo.Append("&lt;DT><B>File Number (" + ((i + 1).ToString()) + ")" + "&lt;/B>");
                saveInfo.Append("&lt;DD> ");

                if (dnFileBE.Size == 0)
                {
                    LabelTitle.Text = "&lt;DT><B>Some files could not be processed by UpFilesBE!!</B>";
                    saveInfo.Append("&lt;DT>Please enter a valid filename to upload;");
                }
                else if (dnFileBE.Size > 0)
                {
                    //set Overwrite to true;
                    dnFileBE.Overwrite = true;

                    // call Save();
                    dnFileBE.Save();

                    // check savedresults
                    switch (dnFileBE.Processed)
                    {
                        //case dnSaved:
                        case dnSaveResultsEnum.dnSaved:
                            //--- File Name
                            saveInfo.Append("&lt;DT>File name::<DD> " + dnFileBE.Name + "");
                            //--- Form File Field Name
                            saveInfo.Append("&lt;DT>Form File Field name::<DD> " + dnFileBE.FormName + "");
                            //--- dnSaveResultsEnum, file save status code
                            saveInfo.Append("&lt;DT>File Save result of type dnSaveResultsEnum::<DD> " + dnFileBE.Processed + "");
                            //--- Full path of the file as it appears on the client
                            saveInfo.Append("&lt;DT>Full path of the file as it appears on the client::<DD> " + dnFileBE.ClientPath + "");
                            //--- Full path of the file as saved in thge destination folder on the server
                            saveInfo.Append("&lt;DT>Full path of the file as saved in the destination folder on the server::<DD> " + dnFileBE.DestinationPath + "");
                            //--- Size of the file  in Bytes 
                            saveInfo.Append("&lt;DT>Size of the file  in Bytes ::<DD> " + dnFileBE.Size + " bytes");
                            //--- Mime category of the file type
                            saveInfo.Append("&lt;DT>File Mime Type::<DD> " + dnFileBE.ContentType + "");
                            break;

                        //case dnError:
                        case dnSaveResultsEnum.dnError:
                            //--- The Error
                            LabelTitle.Text = "Files could not be saved by UpFilesBE!!";
                            saveInfo.Append("&lt;DD>" + dnFileBE.Error + "");
                            break;

                        default:
                            //--- The  unknown Error
                            LabelTitle.Text = "Files could not be saved by UpFilesBE!!";
                            saveInfo.Append("An unknown error has occurred. dnSaveResultsEnum: " + dnFileBE.Processed +
                                ". " + dnFileBE.Error);
                            break;
                    }
                }
            }

            LabelSaveInfo.Text = saveInfo.ToString();
        }
        catch (Exception ex)
        {
            ///--- display any errors that may have accured during processing 
            Page.Response.Write("&lt;B>WebServer exception:</B><BR>" +
                ex.Message);
        }
        finally
        {
            ///--- Call Dispose in finally to cleanup
            if (dnUpFilesBE != null)
            {
                dnUpFilesBE.Dispose();
                dnUpFilesBE = null;
            }
        }
    }
    
    
    
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        // if (Session["PROGRESSID"] == null)
        if (Session["PROGRESSID"] == null)
            return;


        // if (Session["PROGRESSID"] is not null
        // Get the ProgID from session object
        ProgID = Session["PROGRESSID"].ToString();

        //call the GetProgress(ProgID) methode which returns string[] collection object;
        //All the values aof the progress are in this  collection object;
        string[] Progressparams = GetProgress(ProgID);

        //Percentage to set the inner table width
        string temp = Progressparams[0];
        if (temp == "0%")
        {
            this.LabelStatus.Text = "Waiting...";

            if (Session["CANCELLED"] != null)
            {
                this.LabelStatus.Text = "Cancelling...";
            }
            
            ButtonCancel.Enabled = false;
            return;
        }

        // Set Status
        this.LabelStatus.Text = "Transfering...";

        // Enable Cancel Button
        ButtonCancel.Enabled = true;

        temp = temp.Substring(0,  temp.Length -1);
        int width = System.Convert.ToInt32(temp);
        TablePercentage.Width = Unit.Percentage(width);

        //write Uploaded Data information to
        //LabelDataUploaded
        this.LabelDataUploaded.Text = temp + "%" + " (" + Progressparams[9] + ")/";
        this.LabelDataUploaded.Text += "(" + Progressparams[8] + ") Uploaded at ";
        this.LabelDataUploaded.Text += Progressparams[2];

        //write CurrentFile to the Table cell
        this.LabelCurrentFile.Text = Progressparams[1];

        //write Elapsed Time to 
        //write LabelTimeElapsed
        this.LabelTimeElapsed.Text = Progressparams[5];

        //write Remaining Time to 
        //write LabelTimeRemaining
        this.LabelTimeRemaining.Text = Progressparams[6];
    }


    public string[] GetProgress(string pID)
    {
        // declare string[] array with ten varaibles
        string[] Progressparams = new string[10];

        //create DNUpFilesProgressBE object
        DNUpFilesProgressBE dNUpFilesProgressBE = new DNUpFilesProgressBE();

        // set ProgressId to pid from the QueryString
        dNUpFilesProgressBE.ProgressId = pID;

        // start Monitor
        dNUpFilesProgressBE.Monitor = true;

        int per = dNUpFilesProgressBE.Percentage;

        //write Percentage to set the inner table width
        string temp = (System.Web.UI.WebControls.Unit.Percentage(per)).ToString();
        Progressparams[0] = temp;

        //write CurrentFile to the Table cell
        temp = dNUpFilesProgressBE.CurrentFile;
        Progressparams[1] = temp;

        //write BytesPerSecondAverage to the Table cell
        temp = (dNUpFilesProgressBE.BytesPerSecondAverage / 1024).ToString() + " KB/sec";
        Progressparams[2] = temp;

        //write Finished status to the Table cell
        temp = dNUpFilesProgressBE.Finished.ToString();
        Progressparams[3] = temp;

        //write Percentage to the Table cell
        temp = dNUpFilesProgressBE.Percentage.ToString() + "%";
        Progressparams[4] = temp;

        //write SecondsElapsed to the Table cell
        temp = dNUpFilesProgressBE.TimeElapsed;
        Progressparams[5] = temp;

        //write SecondsRemaining to the Table cell
        temp = dNUpFilesProgressBE.TimeRemaining;
        Progressparams[6] = temp;

        //write Started status  to the Table cell
        temp = dNUpFilesProgressBE.Started.ToString();
        Progressparams[7] = temp;

        //write TotalBytes to the Table cell
        temp = ((float)dNUpFilesProgressBE.TotalBytes / 1024).ToString() + " KB";
        Progressparams[8] = temp;

        //write TransferredBytes to the Table cell
        temp = ((float)dNUpFilesProgressBE.TransferredBytes / 1024).ToString() + " KB";
        Progressparams[9] = temp;

        return Progressparams;
    }
    
    protected void ButtonCancel_Click(object sender, EventArgs e)
    {
        if (Session["PROGRESSID"] == null)
            return;

        //get ProgID from Session["PROGRESSID"] key object
        ProgID = Session["PROGRESSID"].ToString();


        // call CancelUpload(ProgID);
        CancelUpload(ProgID);

        // set Status to "Canceling...";
        this.LabelStatus.Text = "Canceling...";

        // set Session["CANCELLED"] key to "True";
        Session["CANCELLED"] = "True";
    }


    public int CancelUpload(string pID)
    {
        //create DNUpFilesProgressBE object
        DNUpFilesProgressBE dNUpFilesProgressBE = new DNUpFilesProgressBE();

        // set ProgressId to pid from the QueryString
        dNUpFilesProgressBE.ProgressId = pID;

        // call Cancel operation of the  dNUpFilesProgressBE object
        dNUpFilesProgressBE.Cancel();

        return 0;
    }
}


Conclusion

There are many other samples in the zip file and they use Ajax library
released prior to AJAX.NET libraries.

You can download fully functional file upload components packages application
from http://www.expandata.net/downloads.htm

References

Download Source Code


Other Related and Popular Articles :

Author Profile : mu2hm
Click to View Author Profile

How would you rate the quality of this content?
Excellent
Poor

Comments

Add A New Comment


WAPT is a load and stress testing tool for websites and web-based applications.




PURCHASE WAPT from here.




Downlaod a trial version of WAPT from here.

WAPT is a load and stress testing tool for websites and web-based applications.
PURCHASE WAPT from here.
Downlaod a trial version of WAPT from here.


Legend: - Within 4 Days - Within 8 Days - Within 12 Days

Home|Publish Tutorials|Add Resources|Sponsored Resources|Advertise With Us|SiteMap|Join Us|Link To Us|About Us|Contact Us
© 2007 RiverASP.NET ASP.NET Tutorials and Directory | All rights reserved