Tuesday, March 22, 2011

Background Worker


Why use the BackgroundWorker?

You can use it to shift some heavy calculations, for example database access or file searching, to another thread and make the user interface more responsive. If both UI and the heavy calculations are ran within the same thread the UI appears to hang, making the average pc user think the program has crashed. So let's do it the decent way and use BackgroundWorker! 

How to use the BackgroundWorker?

The BackgroundWorker may sound quite intimidating, but actually it's very easy and intuitive to do use once you've done the first time. So let's get going and make a simple application showing you the usage of the BackgroundWorker. In case you want to look up the BackgroundWorker class on MSDN, it's in the System.ComponentModel namespace.

The first thing you need to do is to add the BackgroundWorker to the application and the easiest way to do so is to drag it from the toolbox onto your form. It's under the components tab. You'll see the BackgroundWorker showing up as BackgroundWorker1 in the gray box under your form.
Attached Image

The BackgroundWorker is event-driven, so what you need to do to get the basics working is this:
-Invoke the BackgroundWorker's DoWork class from your application.
-Give DoWork some work to do by adding the code in the BackgroundWorker1.DoWork method.
-After the code in the DoWork method is done, the event RunWorkerCompleted is invoked.
-Through the RunWorkerCompleted method, we'll retrieve our return values from the 2nd thread

Ok, lets get coding! Double click on the DoWork event and add:


Find below the simple and easy code how to use background worker



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;


namespace Backgroundworker

{
public partial class MainPage : UserControl
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();

public MainPage()

{

InitializeComponent();


backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);

backgroundWorker.WorkerReportsProgress = true;

backgroundWorker.WorkerSupportsCancellation = true;

backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);


backgroundWorker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);


}


void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{

if (e.Error != null)

{
txtPercentComplete.Text = e.Error.Message;
}

else if (e.Cancelled)
{
txtPercentComplete.Text = "Task Cancelled";
}

else

{
txtPercentComplete.Text = "Task Completed";
}

}


void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
txtPercentComplete.Text = e.ProgressPercentage.ToString() + " %";
}


void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
const int SECOND = 1000;

BackgroundWorker backgroundWorker = (BackgroundWorker)sender;


for (int i = 0; i < 20; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}

backgroundWorker.ReportProgress((i + 1) * 5);

System.Threading.Thread.Sleep(SECOND / 4);

}

}



private void btnStartTask_Click(object sender, RoutedEventArgs e)

{
backgroundWorker.RunWorkerAsync();
}


private void btnCancelTask_Click(object sender, RoutedEventArgs e)
{
backgroundWorker.CancelAsync();
}

}
}

Saturday, March 19, 2011

Display Log in Logviewer

1) Create the FileSystemWatcher and set its properties.



FileSystemWatcher_Log_1.Path = Directory.GetParent("C:\\temp").FullName;

FileSystemWatcher_Log_1.Filter = "MyLogFile.log";

NotifyFilters notifyFileters = new NotifyFilters();

notifyFileters = notifyFileters
NotifyFilters.LastWrite;

// You can choose other notification filters


FileSystemWatcher_Log_1.NotifyFilter = notifyFileters;

FileSystemWatcher_Log_1.EnableRaisingEvents = true;




2) Set the event handler.



this.FileSystemWatcher_Log_1.Changed += new

System.IO.FileSystemEventHandler(this.FileSystemWatcher_Changed);



3) Update GUI when event occours



// create stream writer only once so that whenever new log is appended in the log file,

// only that text will be shown in the list view (or which ever the gui component you are using).

if (null == sr_Log_1)

{

sr_Log_1 = new StreamReader(new FileStream(SelectedFileName_Log1_textbox.Text,

FileMode.Open, FileAccess.Read, FileShare.ReadWrite), true);

}

string line;

while (sr_Log_1.EndOfStream != true)

{

line = sr_Log_1.ReadLine();

if (line.Trim().Length == 0)

{

continue;

}

Log_1_listBox.Items.Add(line);

Log_1_listBox.TopIndex = Log_1_listBox.Items.Count - 26 + 1;



}






WIndows Communication Foundation


Now learn windows communication foundation in few easy steps.





Please find the power point presentation  and example of windows communication foundation