Friday, January 7, 2011

Creating Windows Service

Create Simple Windows Service

-- Open Studio 2010 >> File >> New >> Project >>
-- Select Visual C# >> Windows >> Windows Service
-- Gave Name to "TestWinService"
-- In .cs file there is two functions where service start/stop
protected override void OnStart()
{
}
protected override void OnStop()
{
}

-- we can use two approch to implement service to run

1) Using System.Timers

// initialize timer object
System.Timers.Timer timertest;

protected override void OnStart()
{
EventLog.WriteEntry("Timer Started at " + DateTime.Now, System.Diagnostics.EventLogEntryType.SuccessAudit);
timertest = new System.Timers.Timer();

this.timertest.Interval = Convert.ToDouble("12000");
this.timertest.Enabled = true;
this.timertest.Elapsed += new System.Timers.ElapsedEventHandler(timertest_Tick);
}


void timertest_Tick(object sender, EventArgs e)
{
try
{
// Service Logic

}
catch (Exception ex)
{
EventLog.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
}
}

protected override void OnStop()
{
timertest.Enabled = false;
}

2) Using Thread

System.Threading.Thread workerThread1;

protected override void OnStart(string[] args)
{

System.Threading.ThreadStart st1 = new System.Threading.ThreadStart(FunctionServicelogic);
workerThread1 = new Thread(st1);
// set flag to indicate worker thread is active
service1Started = true;
// start the thread
workerThread1.Start();
}

protected override void OnStop()
{
service1Started = false;
}

private void FunctionServicelogic()
{
while (service1Started)
{
// Service logic
if (service1Started)
{
Thread.Sleep(new TimeSpan(0, 10, 0));
}
}
// time to end the thread
Thread.CurrentThread.Abort();
}

--- You can Build service. Service build sucessfully

--- In the Properties dialog box, click Add Installer.
--- In the Properties dialog box for ServiceInstaller1, change the ServiceName property to LogWriterService.
--- In Design view, click ServiceProcessInstaller1 in the Code Editor.
--- In the Properties dialog box, change the Account property to LocalSystem. The LocalService value and the NetworkService value are only available in Microsoft Windows XP and later operating systems.

-------- Install Windows Service -----------
1) Command Prompt C:\Windows\Microsoft.Net\Framework\v2.0.50727\installutil -i "Service.exe path"
-- -i is for install
-- -u is for uninstall

-------- Varify Windows Service ------------

--- Click Start, point to Control Panel, point to Administrative Tools, and then click Services.
--- Right-click LogWriterService, and then click Start.
--- To verify that an event is logged in the event log, use one of the following methods:
Click Start, point to Control Panel, point to Administrative Tools, and then click Event Viewer. In the left pane, click Application Log. In the right pane, locate the event log for your service.