Wednesday, April 16, 2014

Windows service gotchas...

I'm working on a new Windows service, and it's been a while since I've had to create a Windows service from scratch (they are more work, but they taste the best when created from scratch - har har). Here are some of the gotchas I've run into, and have a vague recollection of dealing with these issues before:

 1. You go to install your service (installutil <path to your service executable>), and then start it (net start <your service name>) but get an "System error 5 has occurred. Access is denied." message. 

 The issue is that you need to make sure that the directory where the executable lives has the correct privileges for whatever user you are using to run the Windows service. In my case, I was trying to run the Windows service as "Local Service". That meant that I needed to set security permissions for the parent directory to include "LOCAL SERVICE" and let "LOCAL SERVICE" have full control.

You can see which user will be executing the service by right clicking on the service from withing the "Services" application, and selecting the "Properties" menu item.  Here is the view of my service properties:

Local Service has minimal privileges, and therefore is more secure to use than Network Service or Local System.  There is no password for Local Service despite what it looks like in the image to the left.



I granted access for Local Service to the bin\Debug folder for my Windows service while testing.  


















2. You go to debug your Windows service, but it errors and quits before you can get to Visual Studio and attach to your Windows service process. I ended up adding a Thread.Sleep(10000) in the Main() method right before the ServiceBase.Run() method is called. That seems to be enough time on my machine to open the Attach to Process dialog and then navigate to my Windows service.

Also, it is important that you are running your Visual Studio instance as administrator, or you won't have privileges to attach to your Windows service.

3. You uninstall your service and then attempt to re-install the service, but you get a message stating that the service has been marked for deletion. Once that happens, then you need to reboot your machine in order to install the service. I ran into that problem before, and wrote about it here, but the short version is that you should avoid having the "Services" application running while uninstalling/installing the service.

I'll add onto this post if I hit other generic issues while working on the Windows service.