Wednesday, August 17, 2011

How to use backgroundworker control

Hi, Please note, The control Backgroundworker is available with Visual Studio 2008 and Visual Studio 2010.

Backgroundworker:
is used when you need to work with Threads parallely.
For Example

1. if you want to show the file names along with files being copied or
2. file content in label (line by line) with Progressbar etc.

I'm using the 2nd example here for demonstration but you can implement with any similar kind of task.

Steps:


1. Start-->Programs-->Microsoft visual Studio 2010-->Microsoft visual Studio 2010.

2. Create new window application by selecting File-->New-->Project-->Windows Form Application.

3. Goto ToolBox, if not visible Select View-->ToolBox from menubar or Press(Ctrl + Alt + X).


4. Scroll to Component, Select BackgroundWorker and drag to Windows application.


5. Now Drag Button, Label and Progressbar on windows form.


6. Inside button clcik event write this code:


With Me.BackgroundWorker1
.WorkerReportsProgress = True
.RunWorkerAsync("C:\crp.txt")
End With
ProgressBar1.Minimum = 1
ProgressBar1.Maximum = 2000
ProgressBar1.Visible = True
ProgressBar1.Value = 1

7. Note, BackgroundWorker control has three event,


1. BackgroundWorker1_DoWork
2. BackgroundWorker1_ProgressChanged
3. BackgroundWorker1_RunWorkerCompleted


Paste these code in your program:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim filename As String = e.Argument
Using reader As New System.IO.StreamReader(filename)
While Not reader.EndOfStream
Me.BackgroundWorker1.ReportProgress(0.0, reader.ReadLine())
System.Threading.Thread.Sleep(1000)
End While
End Using

End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.Label1.Text = e.UserState
ProgressBar1.PerformStep()
End Sub


Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("Done reading the file!")

End Sub

8. Run the application, You may see the screen as shown below:



Your comment will be appreciated.

Saturday, August 6, 2011

Create web page with download links

This article shows how to create web page with download links using ( VB.NET or C# ).

You just need to create two different page
1. Having all download links (e.g; link.aspx).
2. The url to redirect when the download link is clicked (e.g; downloading.aspx).

Steps:


1. Open visual studio with ur choiced version(2003,2005,2008 0r 2010)

Start->Programs->Microsoft Visual Studio 2005->Microsoft Visual Studio 2005.


2. Create new ASP.NET Web application or website

3. Rename the Default.aspx page as link.aspx and open the link.aspx.vb.
paste the below code. in page_load

You must import System.Io namespace
using VB.NET
Imports System.IO

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim di As New DirectoryInfo(Server.MapPath("NudiDownload"))
Dim i As Integer = 0
For Each fi As FileInfo In di.GetFiles()
Dim HL As New HyperLink()
HL.ID = "HyperLink" & System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
HL.Text = fi.Name
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name
Page.Controls.Add(HL)
Page.Controls.Add(New LiteralControl("
"))

Next
End Sub


The code looks similar as below

using C#
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("NudiDownload"));
int i = 0;
foreach (FileInfo fi in di.GetFiles())
{
HyperLink HL = new HyperLink();
HL.ID = "HyperLink" + i++;
HL.Text = fi.Name;
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;
Page.Controls.Add(HL);
Page.Controls.Add(new LiteralControl("
"));
}

}

4. Now right click on the solution and create new folder named(e.g; NudiDownload) and copy the softwares you want to provide for download. see the below picture.


5. Now create the another aspx page (e.g; downloading.aspx). click on downloding.aspx.vb
Imports the two namespaces: Syatem.Io and System.Threading
'-- VB.NET
Imports System.IO
Imports System.Threading


Paste the below code:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim filename As String = Request("file").ToString()
fileDownload(filename, Server.MapPath("NudiDownload/" & filename))

End Sub
Private Sub fileDownload(ByVal fileName As String, ByVal fileUrl As String)
Page.Response.Clear()
Dim success As Boolean = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000)
If Not success Then
Response.Write("Downloading Error!")
End If
Page.Response.[End]()

End Sub
Public Shared Function ResponseFile(ByVal _Request As HttpRequest, ByVal _Response As HttpResponse, ByVal _fileName As String, ByVal _fullPath As String, ByVal _speed As Long) As Boolean
Try
Dim myFile As New FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim br As New BinaryReader(myFile)
Try
_Response.AddHeader("Accept-Ranges", "bytes")
_Response.Buffer = False
Dim fileLength As Long = myFile.Length
Dim startBytes As Long = 0

Dim pack As Integer = 10240
'10K bytes
Dim sleep As Integer = CInt(Math.Floor(CDbl(1000 * pack \ _speed))) + 1
If _Request.Headers("Range") IsNot Nothing Then
_Response.StatusCode = 206
Dim range As String() = _Request.Headers("Range").Split(New Char() {"="c, "-"c})
startBytes = Convert.ToInt64(range(1))
End If
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString())
If startBytes <> 0 Then
_Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength))
End If
_Response.AddHeader("Connection", "Keep-Alive")
_Response.ContentType = "application/octet-stream"
_Response.AddHeader("Content-Disposition", "attachment;filename=" & HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8))

br.BaseStream.Seek(startBytes, SeekOrigin.Begin)
Dim maxCount As Integer = CInt(Math.Floor(CDbl((fileLength - startBytes) \ pack))) + 1

For i As Integer = 0 To maxCount - 1
If _Response.IsClientConnected Then
_Response.BinaryWrite(br.ReadBytes(pack))
Thread.Sleep(sleep)
Else
i = maxCount
End If
Next
Catch
Return False
Finally
br.Close()
myFile.Close()
End Try
Catch
Return False
End Try
Return True
End Function


'-- C#
Using System.IO;
Using System.Threading;

protected void Page_Load(object sender, EventArgs e)
{
string filename = Request["file"].ToString();
fileDownload(filename, Server.MapPath("NudiDownload/" + "Setup.exe"));

}
private void fileDownload(string fileName, string fileUrl)
{
Page.Response.Clear();
bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
if (!success)
Response.Write("Downloading Error!");
Page.Response.End();

}
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;

int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(pack)); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; } 6. Save the page and set link.aspx as default page.

7. Run the application.

You will see the below screen.


You are done. Now Click on any of the link. You will be promted to Run or Save the download.


If you liked this article please put your comment.