Like a BATch out of hell
LIKE A BATCH OUT OF HELL
Today’s Blog, Like a BATch Out of Hell, has been written based on some experience I’ve recently had with building and debugging a Windows Service.
Recently we have been tasked with building a windows service for a client that would use multi-threading to continuously poll between two databases. We chose to create a windows service for this solution as we felt it would be the most efficient approach. However, having never built a windows service before, debugging and creating the service was a little more tricky than simply clicking start and running with breakpoints … This is where the magic batch file came into play.
To test a windows service first you need to make your necessary changes, build the project and then install it onto your computer. Making sure you are logged in as an administrator else you won’t get anything done! We added a “nice to have feature” whereby the service will write to the windows Event Log – something we made sure to get setup properly before deploying the service.
Key batch file commands to stream line your windows service developing:
wevtutil cl logName – this command clears the log for the windows service, replace logName with that of your log.
call “C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\Tools\VsDevCmd.bat” – this command opens the visual studio command prompt that is necessary to begin the installation.
cd C:\YourFileLocation\YourSolutionFolder\bin\Debug – change the directory into the bin – debug folder where you have built your windows service to.
installutil.exe /u YourWindowsService.exe – This will uninstall the windows service that you are working with (always good to start a fresh right?).
cd C:\YourFileLocation\YourSolutionFolder\bin\Debug – double check that you are back in the same directory as your windows service again
installutil.exe YourWindowsService.exe – final command to reinstall the windows service to your machine
Just for ease of reading a code snippet is here.
wevtutil cl logName
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\Tools\VsDevCmd.bat"
installutil.exe /u YourWindowsService.exe
Just to clarify a batch file is saved ‘.bat’, to clear up the title. Right-click on the file and click run as administrator else your batch commands won’t work.
To begin running your service, search for services in your start-up and then start your service. To attach your debugger to your installed service, select debug in visual studio, and then attach to process. Search for your process in the list of running processes and attach to the process you have installed (note: it HAS to be running to show up in this list) it should then hit any set breakpoints that you have set, fingers crossed.