From Visual Studio
File->New Project
Select Window Service Project from the template.
Give the project name and location.
Click “Ok” will create a project as shown in the following screen shot.
Open the Service1.cs by right clicking and selecting View Code
OnStart - control the service startup
OnStart - control the service stoppage
Note:- Never put an infinite loop inside the OnStart method. If you are looking for something like Remoting or Socket programming that needs to keep listening; Start a thread on OnStart that will handle it.Here the point to be noted is that OnStart must return.
Here am going to demonstrate an Event Logging Ser
vice using Timer elapsed event
.
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
System.Timers.Timer myTimer;
string Source;
string Log;
string Event;
protected override void OnStart(string[] args)
{
Source = "Timer Service";
Log = "Application";
Event = "Timer Event";
myTimer = new System.Timers.Timer();
myTimer.Interval = 10000;
myTimer.Enabled = true;
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
if (!EventLog.SourceExists(Source))
EventLog.CreateEventSource(Source, Log);
}
private void myTimer_Elapsed(object sender, EventArgs e)
{
if (EventLog.SourceExists(Source))
{
EventLog.WriteEntry(Source, Event);
EventLog.WriteEntry(Source, Event, EventLogEntryType.Warning, 1234);
}
}
protected override void OnStop()
{
}
}
Now right click Service1.cs and select View Designer.
In the designer right click and select Add Installer.
This will create two components
Now select the components and change their properties accordingly.
Using these components you can configure the authentication, name of service, service startup, etc.
Select the property page of the Project and set the Startup Object.
Compile the project.
Window service is ready.
Creating a setup for deploying windows service
Next, I will explain how you can package the service into one installer that will automate the installation process.
From Visual Studio
File->Add->New Project
From Other Project Types select Setup Project.
Give name and click OK.
It will create a project as shown in the following screen shot.
Right click TimerServiceSetup Select Add->Project Output
Which will brings the following window.
From this window select TimerService from Project and Select Primary Output and click OK.
Now right click and select View->Custom Actions.
The custom action window will be visible in the designer area.
Right Click Custom Actions and select Add Custom Actions.
This will bring a new window. Double click the Application Folder and click Ok.
Build the project.
Setup is ready.
:-)