Windows Service Flashcards
(6 cards)
Why use a console application instead of the windows service project type?
Because we can run it at a console application and debug it locally and then install it as a service (instead of attaching the debugger to the running application)
What open source tool can you use?
Topshelf (right click reference, manage nuget packages)
What to add in the service class?
In the class (heartbeat) Define a timer from system.timer Private readonly Timer _timer; Constructor: Public heartbeat() _timer=new Timer(1000){AutoReset=true}; Create event: (shortcut:+=tab) _timer.elapsed+=Timerelapsed; ... Public void Start() {_timer.Start();}...
TimerElapsed function that add the time to a text file
Private void TimerElapsed(object sender, elapsedeventargs e)
{
String[] lines=new string[]{DateTime.Now.ToString};
file.AppendAllLines(@“c:/temp/myFile.txt”, lines)
}
Code in main (using topshelf)
Var exitCode= HostFactory.run(x=>
{
x.Service(s=>
{
s.ConstructUsing(heartbeat=new HeartBeat());
s.WhenStarted(heartbeat=>heartbeat.start());
s.WhenStopped(heartbeat=>heartbeat.stop());
});
x.RunAsLocalSystem();
x.SetServiceName=…displayname,description
});
Int exitCodeValue= (int)convert.ChangeType(exitCode,exitCode.getTypeCode());
Environment.ExitCode=exitCode.value;
How to install the windows service (from the console app)
Right click on the project-> openfolder in file explorer-> bin->debug, copy all file and put them in the folder you want. Copy the path, open admin command prompt, type:
Cd mypath
Myservice.exe install start
(Put uninstall instead to uninstall)