Window Service

(Run by OS)

Create Window Service.
1. Visual Studio .NET > File > New > project > Visual C# > Windows > Windows Service (Template) ( This creates Service1.cs and Program.cs )
2. Window Service must inherits from System.ServiceProcess.ServiceBase.
3. Click on designer of Service1, Set Servicename & Name = MyFirstWinService
4. Set AutoLog =true
5. In program.cs (calling program) , ensure instance of MyFirstWinService is created .

static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// Change the following line to match.
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new MyFirstWinService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

 

To Add Custom Event Log Functionality To Window Service ( Application , Security , System)
1. From component tab (toolbox) > drag Eventlog to designer (Eventlog1)
2. In Service1.cs , put the following code to create eventlog source and log if NOT exist


public MyFirstWinService()
{
InitializeComponent();
if (!EventLog.SourceExists("MySource"))
{
EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog"; // Event viewer log name
}

protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
eventLog1.WriteEntry("In OnStop");
}

Create Installer For Window Wervice.
1. Go to designer of Service.cs.
2. Right click on background > Add Installer.
3. ProjectInstaller.cs is added , 2 installers are embraced.
- ServiceInstaller1 = Installer for window service.
- ServiceProcessInstaller = Installer for service's associated process.
4. ServiceInstaller1 > properties > ServiceName = MyFirstWinService > StartType=Automatic .
5. ServiceProcessInstaller >properties > Account = LocalService (make service run on local service account)

Buid window service project
1. Project > right click > properties
2. Application > StartUp Object = MyFirstWinService
3. right click on solution > Build it.

Back

To Create Setup Project For Window Service (installutil servicename.exe)
1. Right click Solution > Add > New project.
2. Other project type > Setup and Deployment > Setup Project > Name it : ServiceSetup

To Add MyFirstWinService.exe to Setup Project
1. Right click serviceSetup > Add > Project Output
2. Select MyFirstWinService.exe in Project box.
3. Select primary Output > OK > This will add primary output to setup project.

To Add Custom Action To The Setup Project
1. Right click ServiceSetup> View > Custom Action.
2. Right click Custom Action > Add custom action.
3. Double click Application folder > OK >
This will add primary output to all 4 nodes(install, commit, rollback, uninstall)
4. Right click ServiceSetup > Build


To Install the Windows Service
1. Right click ServiceSetup > Install
2. Follow setup wizard and save solution.

Back

 

@Copy right of Soon Lim 2006. All Right Reserved