Friday, September 3, 2010

Interruptable Background Processing in C#

I was looking for some Interruptable background processing utility in C#.

Background processing can be done with BackgroundWorker but making it interruptable
was the tricky one. Its not only the threading but handling the events too.

Tried to google it did not find the exact one but some good help.


On any activity (user stops the process or work completes ) signal shall be raised to process the main thread.

Doing the process of actual work can be started in the Thread or Worker Thread in the background asynchronously.
Starting Thread ( in InterruptableBGProcess.InitialiseServiceProcess(...))
in the background.

InterruptableBGProcessing.cs
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
isStopped = false;
            
/* initialise the background processing service */
var serviceControlEvents = InterruptableBGProcess.InitialiseServiceProcess((BackgroundWorker)sender);

/* now simulate a waitstate by waiting until the user click on stop orwork completed. */

while (true)
{
 if (isStopped || ProgressBar.Value == 100)
 {
  break;
 }
}
            
/* signal the event to tell the service to stop, then wait for the event
   to be set which indicates the service has stopped*/

 WaitHandle.SignalAndWait(serviceControlEvents[0], serviceControlEvents[1]);
        
}


Once thread started it will look for the event signals
SignalProcessToStop and ProcessHasCompleted of type AutoResetEvent

/*Initialises the processing controller, process events
 and starts the process.*/
public static WaitHandle[] InitialiseServiceProcess(
BackgroundWorker bg)
{
 var processSvc = new InterruptableBGProcess(bg);
 var thread = new Thread(processSvc.ProcessController);
 thread.Start();
 return new[] { 
    processSvc.SignalProcessToStop, processSvc.ProcessHasCompleted };
}


/* when thread runs... */
private void ProcessController()
{
/* wait on the threads SignalProcessToStop event*/
var wh = new WaitHandle[] { SignalProcessToStop };
while (true)
{
 /* SignalProcessToStop.Set(); 
 if above is done (i.e  set) than waitHandles will not 
receive the signal and loop will break;*/

var fTimedOut = !WaitHandle.WaitAll(wh, 100);
if (fTimedOut && counter != 100)
/* if we timed out, do the processing or 
   work not finished completely*/
  ExecuteWork(); 
else
{
  break; /* thread process was signalled to stop*/
}
}
/* indicate the processing service has stopped, allows 
waiting threads to proceed, if don't set this than main thread 
will not proceed.*/            
ProcessHasCompleted.Set();
}



Download complete example from here: Downlaod Demo InterruptableBackGroundProcessing.rar

Tuesday, July 6, 2010

C# LogViewer using FileSystemWatcher

I was facing a problem to get the new log message in the Message Log screen.
FileSystemWatcher which was introduced in .net 2.0 make it very easy to develop Message Log Viewer.

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;
                
            }



Refer the code for details.
You can download demo code from here here.
It may not be 100% bug free code.

Sunday, July 4, 2010

Learning art of Mocking by EasyMock

Continuing my earlier post about testing and mocking.
Here is the details about EasyMock.


Download presentation here (ppt)

Or

Here ( google docs)

The Art Of Mocking / Test using Mock Objects .

Quality assurance exists in many products, including software.
Software manufacturers perform software testing to ensure the correctness, completeness and quality of their products.

And the testing should also go with hand in hand along with development.
Find out more about testing and mocking in the provided link.

Click here to get the presentation from the link











Testing is an art. :-)

Heroku Custom Trust Store for SSL Handshake

  Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...