UploadBarDotNet tool



Description

The UploadBarDotNet library intercepts uploads initiated from ASP.NET pages, providing progress data, including the names of all files received in the current upload, the data transferred, and the total size of the upload. It is also capable of filtering out illegal characters found in uploaded file names. Operation is transparent, making integration with existing code simple.

Contents

Integrating UploadBarDotNet into a web site

This section will guide you through the steps required to incorporate UploadBarDotNet into a web site.

Prerequisites

Microsoft IIS

Microsoft .NET framework

UploadBarDotNet installed from the supplied MSI installer

A valid license key obtained from Leading IT

Note on uploading large files

For security purposes, the maximum upload limit for a machine is capped using a value in the machine.config file for the local .NET framework. The tag httpRuntime contains the attribute maxRequestLength, whice defines the maximum upload size (in kilobytes) permitted on the machine.

To increase the absolute limit for the machine, edit machine.config, found in {Windows directory}\Microsoft.NET\Framework\{.NET version}\CONFIG\machine.config, and update the httpRuntime tag.

For example, to limit the machine file upload size to 10 megabytes, edit the file "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\config\machine.config" and set the maxrequestlength attribute to 10000:

  <system.web>
    ...
    <httpruntime maxrequestlength="10000">
    ...
</system.web>

To limit the maximum upload size for an individual website, the same tag can be inserted into web.config. For example, in the file "C:\InetPub\wwwroot\UploadBar\Demo1\web.config", set the maxrequestlength attribute:

  <system.web>
    ...
    <httpruntime maxrequestlength="5000">
    ...
</system.web>

Integration steps

  1. Build an ASP.NET web application project on the target machine.
  2. Place UploadBar.dll into the bin directory of that project, or, if using Microsoft Visual Studio .NET, simply add a reference to the DLL.
  3. Edit the web.config file for the project, and insert the appropriate details specified in the Configuration section of this document. Note that you must include your registration key(s) in the registrationcodes section of web.config. You may use the default registration key for localhost: <add key="hosturl;localhost;" value="0560-F1F5-887D-3C51-8360" />. This will allow unrestricted testing when connecting to the test server via the local loopback connection, e.g. http://localhost/UploadBarDotNetDemos/Demo1/default.aspx.
  4. When an upload is to be monitored, the page which performs the upload must include in its query string a unique identifier for that upload. This can be any url encoded string, but it is recommended that a GUID be used. Including this value on the query string allows the data for an upload to be stored against this ID. The name of the query string element is defined in web.config under the key uploadidqueryfield. For example, the post back URL might be: http://website/Upload.aspx?UploadID=952d6ace-8dd1-4831-b9cb-0ab7ca9bdac5.
  5. Once the upload is started, no further data may be sent up the current stream until the upload completes. Therefore, another connection must be opened to the destination server, using another browser window or a different frame. This other stream must be initialised at the same time that the upload starts, so client side code is recommended to allow this. For an example of some server side code which generates the necessary client side code, see the section entitled 'generating an upload identifier'. The upload ID is passed to the progress bar page via the query string, so that the data for that upload can be obtained using that ID.
  6. The progress bar page can obtain the data for an upload using the GetStatus method in the UploadDetails class. An example of this is shown in the section 'Extracting the upload details for a batch'.
  7. Data for previous uploads will be destroyed when the expiry time is reached, but it is also possible to clean up after an upload by calling the ClearProgress method in the UploadDetails class. This causes the upload data for the specified upload to be destroyed.
  8. Once the data has been obtained by the progress bar panel, it needs to be presented to the user. The UploadHelperUtils class contains a method for the formatting of a raw value in bytes into a comma delimited string in appropriate units. This FormatBytes method is designed for use with the byte values returned for the bytes read, total bytes, and data rate values returned by the GetStatus method. This class also contains the BuildProgressBar method, which produces an html progress bar for the insertion into a web page. It is fully customisable through stylesheets.
  9. Since a progress bar is essentially a dynamic control, the page needs to be refreshed periodically. This can be performed using the <meta httpequiv="refresh"> tag in the page, or through client side code, such as the javascript setTimeout() function.
  10. When an upload is complete, the progress bar page should stop updating. Upload completion status is indicated by the complete variable returned by the GetStatus method in the UploadDetails class. For a popup upload bar, it is recommended that client side code is used to close the progress bar window, such as the javascript function window.close(). For inline progress bars, which can be placed into an <iframe> inside a <div> tag. To hide such a progress bar, simply change its visibility and display CSS style attributes accordingly.
  11. Should these instructions appear dauntingly complex, a number of sample web sites are supplied in the install package, ranging from a very basic upload status popup ( simple upload) to inline upload bars with upload history and data rate display ( inline upload bar and inline upload bar with background update).

Configuration

Once installed, the DLL will be found in the bin directory under the installation path. To use the DLL, it must be placed under the bin directory of the web site in which it is to be used. The namespace of the DLL is LIT.UploadBar.

Each web site which uses the DLL must specify the configuration data via the web.config file for that web site. The following lines need to be included in that document under the configuration tag. Note that the <registrationcodes> section under <lit.uploadbar> should contain your registration code(s) (demo or licensed) obtained from Leading IT.

    <configsections>
	    <sectiongroup name="lit.uploadbar">
		    <section name="core" type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
   		    <section name="optional" type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
		    <section name="registrationCodes" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
	    </sectiongroup>
    </configsections>
    
    <!-- The uploader config data -->
    <lit.uploadbar>
	    <core uploadidqueryfield="UploadID" />
	    <optional 
	        chunksize="8192"
	        samplesize="32768"
	        statuslifehours="24"
	        safefilenames="True">
	    </optional>
        <registrationcodes>
        </registrationcodes>
    </lit.uploadbar>

Parameters
chunksize
The size of block (in kilobytes) used when reading data from the input stream. Controls the fineness of the progress bar steps.
statuslifehours
The time for which the status information for a batch can remain unchanged before it is deleted
uploadidqueryfield
The name of the field on the query string used to identify an upload
safefilenames
If true, the upload helper will filter any illegal path characters out of the filenames associated with the uploaded files
samplesize
The length of the sample (in kilobytes) to be used when estimating data transfer rates and time to completion
registrationcodes
The registration keys for the software. One is required for each domain or machine name under which the software is to be used
The central class of the package must be registered in web.config, in order for it to be able to intercept uploads as they commence. The following code should be inserted under <system.web> :
<httpmodules>
	<add name="UploadHelper" type="LIT.UploadBar.UploadHelper, UploadBar" />
</httpmodules>

Using the package

Once the web.config has been set up correctly, the central class will automatically monitor any uploads made to pages containing the query field defined by the key uploadidqueryfield in the <core> config section.

This package has two classes within in which expose methods for the acquisition, control, and formatting of data associated with uploads. These classes are described in the support classes section.

Support Classes

UploadDetails class

This class handles the details for all uploads within the web site. It exposes two methods:

GetStatus method

The GetStatus method obtains the current status for a batch given its unique ID.
public static bool GetStatus(string uniqueId, out string sourceFileName,
    out int bytesRead, out int bytesTotal, out int percentage,
    out bool completed, out string[] fileList, out int timeToCompletion,
    out double dataRate)
        
Parameters
uniqueId
[in]The unique identifier for the upload
sourceFileName
[out]The original name and path of the file currently being uploaded
bytesRead
[out]The number of bytes read from the upload
bytesTotal
[out]The size of the upload
percentage
[out]The percentage of the upload transferred
fileList
[out]A list of files found so far in the upload
complete
[out]Indicates if the upload is complete
timeToCompletion
[out]The estimated number of seconds before the upload is complete
dataRate
[out]The estimated data rate in bytes per second

ClearProgress method

The ClearProgress method removes the status data for an upload. Used when upload is complete
public static void ClearProgress(string uniqueId)
        
Parameters
uniqueId
[in]The unique identifier for the upload

UploadHelperUtils class

This class contains methods for the formatting of data prior to display. It exposes two methods:

FormatBytes method

The FormatBytes method formats a number of bytes into the appropriate units, with commas inserted if needed, eg. 3,102KB. Numbers below 4KB are displayed in bytes, numbers below 4MB will be displayed in kilobytes, numbers below 4GB are displayed in megabytes, and numbers below 4TB are displayed in gigabytes. All other numbers are displayed in terabytes.
public static string FormatBytes(long inputBytes)
        
Parameters
inputBytes
[in]The number to be formatted
Return values
The formatted string

BuildProgressBar method

The BuildProgressBar method builds a progress bar as an html table. It can be customised via css stylesheets
public static HtmlTable BuildProgressBar(int percentage, string emptyClass,
    string filledClass, string tableClass)
        
Parameters
percentage
[in]The percentage completion of the upload
emptyClass
[in]The CSS class to which the empty part of the bar should belong
filledClass
[in]The CSS class to which the coloured part of the bar should belong
tableClass
[in]The CSS class to which the outer table of the progress bar belongs
Return values
The completed progress bar control

Generating an upload identifier

Each upload requires an ID in order to distinguish between simultaneous uploads running on the system. This ID needs to be generated before the upload starts, and must be passed both to the page generating the upload, and the upload progress bar. This is performed via the query string. The name of the variable in the query string is defined in the web.config, under the key uploadidqueryfield, as describer earlier in this document.

The following segment of code shows the registration of a block of javascript against the onclick event of a server side html button control. It is written for a page called 'Upload.aspx'.

// Generate a GUID for any uploads to be performed.
string uploadGUID = HttpUtility.UrlEncode(Guid.NewGuid().ToString());

// Build up the client side script (javascript)
string script = "";
script += "<script type=\"text/javascript\"><!--\r\n";
script += "function StartUpload()\r\n";
script += "{\r\n";
// The progress bar window opener
script += "window.open('UploadProgressBar.aspx?UploadID=" + uploadGUID
    + "', 'UploadProgressBar', 'width=500, height=140, left=150, top=100, location=no,
    menubar=no, status=no, resizable=no, titlebar=no, toolbar=no, scrollbars=no');\r\n";
// The self reload code
script += "document.Form1.action = 'Upload.aspx?UploadID=" + uploadGUID + "';";
script += "document.Form1.submit();\r\n";
script += "}\r\n";
script += "// -->\r\n";
script += "</script>\r\n";

// Place the script into the page
RegisterClientScriptBlock("uploadStart", script);

// Set the onclick event for the submit button
// to execute the above script
btnUpload.Attributes.Add("onclick", "StartUpload();");

Extracting the upload details for a batch

Upon loading, a progress bar page must obtain the details for the batch which it is monitoring. The following sample shows how the data can be extracted from the UploadDetails class.
private void Page_Load(object sender, System.EventArgs e)
{
	// Obtain the unique ID from the query string.
	string uniqueId;
	if (Request.QueryString["UploadID"] != null)
		uniqueId = Request.QueryString["UploadID"];
	else
		return;

	// Variables which will be used to read/display the results
	string sourceFileName;
	int
		percentage,
		bytesRead,
		bytesTotal,
		timeToCompletion;
	
	double dataRate;

	bool completed;

	string[] fileNames;
	// Obtain the status for this upload
	UploadDetails.GetStatus(uniqueId, out sourceFileName, out bytesRead,
	    out bytesTotal, out percentage, out completed, out fileNames,
	    out timeRemaining, out dataRate);

    /*****************
    Continue page load code here
    *****************/
}
 

Sample code

Three sample projects are included in the 'sample' directory under the installation path. These contain commented sample web sites which demonstrate use of the upload control. To use these samples, simply mount the samples on the local web server, each in their own directory under UploadBarDotNetDemos, using the same name as the zip, e.g. Demo1.zip should be mounted at http://localhost/UploadBarDotNetDemos/Demo1.

Simple upload - Demo1

A very basic single file upload page offering a single popup window containing details about the current upload.

Upload bar - Demo2

An upload page containing a popup progress bar which displays a formatted html progress bar. It also demonstrates the multiple file upload capabilities of UploadBarDotNet.

Inline upload bar - Demo3

Displays upload information inside the same page as the submission page, using a combination of stylesheets and client side code to display the progress bar information. It also displays a progress list of the files received from the current upload. Only appropriate for multiple file uploads.

Inline upload bar with background update - Demo4

A special upload bar page for use over slow links. Instead of directly displaying a progress bar iframe, it communicates with a progress information page which updates the contents in the main page. This eliminates the 'flicker' experienced as the progress bar page reloads. Like the previous inline demo, this page displays a list of files received during the upload.