Monday, May 12, 2008

Working with Timer Control in C#

The Timer control allows you to set a time interval to execute an event after that interval continuously. It is useful when you want to execute certain applications after a certain interval. Say you want to create a backup of your data processing in every hour. You can make a routine which will take the backup and call that routine on Timer's event and set timer interval for an hour.

Using timer control is pretty simple. To test the control, I'm going to create a Windows Application. I also add two button controls to the form and change their text to Start and Stop as you can see from the following Figure.



In this application, I'm going to create a text file mcb.txt in your C:\temp directory and start writing the time after 5 seconds interval. Stop button stops the timer and Start again start the timer.

Now you can drag a timer control from the toolbox to the form. You can set timer properties from the IDE as well as programmatically. To set the timer properties, right click on the timer control and change Interval property. As you can see from the Figure,

I put 5000 milliseconds (5 seconds).

I sec = 1000 milliseconds (In case your mathematics is poor as mine ;).



Now click on the Events button and write event for the timer click as you can see from the following figure.



Now I add a FileStream and a StreamWriter object in the beginning of the class. As you can see from the following code, FileStream class creates a mcb.txt file and StreamWriter will be used to write to the file.

private static FileStream fs = new
FileStream(@"c:\temp\mcb.txt", FileMode.OpenOrCreate, FileAccess.Write);
private static StreamWriter m_streamWriter = new
StreamWriter(fs);

Now write the following code on the Form Load event:

private void Form1_Load(object sender, System.EventArgs e)
{
// Write to the file using StreamWriter class
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(" File Write Operation Starts : ");
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.WriteLine(" ===================================== \n");
m_streamWriter.Flush();
}

As you can see from the above code, this code writes some lines to the file.

Now write code on the start and stop button click handlers. As you can see from the following code, the Start button click sets timer's Enabled property as true. Setting timer's Enabled property starts timer to execute the timer event. I set Enabled property as false on the Stop button click event handler, which stops executing the timer tick event.

private void button1_Click(object sender, System.EventArgs e)
{
timer1.Enabled =
true
;
}
private void button2_Click(object
sender, System.EventArgs e)
{
timer1.Enabled =
false
;
}

Now last step
is
to write timer's tick event to write current time to the text file. Write the following code on your timer event.

private void timer1_Tick(object
sender, System.EventArgs e)
{
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.Flush();
}

Now use Start and Stop buttons to start and stop the timer. The output mcb.txt file looks like the following figure.



Using Timer control Programmatically

If you don't have Visual Studio .NET, you can also write the same sample. Just following these steps.

Creating an instance of Timer

The Timer class's constructor is used to create a timer object. The constructor is overloaded.

Public Timer()
Public Timer(
double
) Sets the interval property to the specified.

Here is
how to create a Timer with 5 seconds interval.

Timer myTimer =
new
Timer(500);

Here are some useful members of the Timer class:

Tick This event occurs when the Interval has elapsed.
Start Starts raising the Tick event by setting Enabled to true.
Stop Stops raising the Tick event by setting Enabled to false.
Close Releases the resources used by the Timer.
AutoReset Indicates whether the Timer raises the Tick event each time the specified Interval has elapsed or whether the Tick event is raised only once after the first interval has elapsed.
Interval Indicates the interval on which to raise the Tick event.
Enabled Indicates whether the Timer raises the Tick event.
How to use Timer class to raise an event after certain interval?

timer1.Interval = 5000;
timer1.Enabled =
true
;
timer1.Tick +=
new
System.EventHandler (OnTimerEvent);

Write the event handler

This event will be executed after every 5 secs.

public static void OnTimerEvent(object
source, EventArgs e)
{
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.Flush();
}


This is originally posted by
Mahesh Chand I used this for one of my projects.Hope this will help you all!!!!!

Creating a Windows Service in C#

NOTE: The project name in this sample code is mcWebService which is a spelling mistake. I meant to put mcWinService. And now I don't want to change all the screen shots and code all over again. I hope it won't confuse you :).

Ok, its time for one more tutorial. This times pick is Windows Services. Creating Windows Services is not a big deal using C# and Visual Studio. Just follow few simple steps and you are all set to run and test your first Windows Service.

Windows Services is new name for NT Services you used to develop in previous versions of Visual Studio. This tutorial walks you through how to create and use your Windows Services. This Service writes some text to a text file when stop and start the service. The base idea is taken from MSDN but its more elaborated. You can modify it according to your needs.

Step 1. Create Skeleton of the Service

To create a new Window Service, pick Windows Service option from your Visual C# Projects, give your service a name, and click OK.

The result look like this. The Wizard adds WebService1.cs class to your project.

Set your ServiceName to your own name so it would be easier to recognize your service during testing OR you can set this property programmatically using this line this.ServiceName = "mcWinService";

This is the name you will be looking for later :).

The default code of WebService1.cs added by the Wizard looks like here

namespace mcWebService
{
using
System;
using
System.Collections;
using
System.Core;
using
System.ComponentModel;
using
System.Configuration;
using
System.Data;
using
System.Web.Services;
using
System.Diagnostics;
using
System.ServiceProcess;
public class
WinService1 : System.ServiceProcess.ServiceBase
{
///


///
Required designer variable.
///

private
System.ComponentModel.Container components;
public
WinService1()
{
// This call is required by the WinForms Component Designer. InitializeComponent();

// TODO: Add any initialization after the InitComponent call
}
// The main entry point for the process
static void
Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
/ create a second service object. For example,
//
// ServicesToRun = New System.ServiceProcess.ServiceBase[] {new WinService1(), new
ySecondUserService()};
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
WinService1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
///
///
Required method for Designer support - do not modify
///
the contents of this method with the code editor.
///

private void
InitializeComponent()
{
components =
new
System.ComponentModel.Container();
this
.ServiceName = "WinService1";
}
///
///
Set things in motion so your service can do its work.
///

protected override void OnStart(string
[] args)
{
// TODO: Add code here to start your service.
}
///
///
Stop this service.
///

protected override void
OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}

Step 2. Add functionality to your service

As you saw WebService1.cs, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service. I write some text to a text file when you start and stop the service.

protected override void OnStart(string[] args)
{
FileStream fs =
new
FileStream(@"c:\temp\mcWindowsService.txt" ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter =
new
StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" mcWindowsService: Service Started \n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
///


///
Stop this service.
///

protected override void
OnStop()
{
FileStream fs =
new
FileStream(@"c:\temp\mcWindowsService.txt" ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter =
new
StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" mcWindowsService: Service Stopped \n"); m_streamWriter.Flush();
m_streamWriter.Close();
}

Step 3: Install and Run the Service

Build of this application makes one exe, mcWinService.exe. You need to call installutil to
egister this service from command line.
installutil C:\mcWebService\bin\Debug\mcWebService.exe
You use /u option to uninstall the service.
installutil /u C:\mcWebService\bin\Debug\mcWebService.exe
Run the application

Step 4: Start and Stop the Service

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer.

Under Services and Applications, you will see the service mcWinService. Start and Stop menu item starts and stops the service.

Step 5: Test the Service

Go to your temp directory and see if text file is there with contents or not.

That's it.


This is originally posted by