image Add release annotations to Application Insights from Azure DevOps image Check Azure CosmosDB “currency” from code and adapt the throughput

    Visual Studio Pre and Post build scripts for Windows Services development

    Development and testing of Windows Services is a bit cumbersome. You can not run them from Visual Studio as you can Windows Form or Web application, but there is a trick that can help to improve the development experience.

    Normally I have some scripts to install, uninstall, start and stop Windows service. There is also a delete script I use to delete any “stuck” Windows service. I create separate *.cmd files for each of them, but for sake of brevity I’ve put them in one code block here:

    Read more about taskkill here and sc_delete here.

    Anyway, those script are pretty handy themselves, but I want to give them some automation. For example, as soon as I build the executable in Visual Studio, I want to stop the service, copy the overwrite the service executable and start it again. We can do this with pre- and post- build scripts inside Visual Studio.

    Open Visual Studio as Administrator (we need this in order to operate with Windows services), open your project properties and navigate to Build Events. There you have 2 fields for your pre-build and post-build scripts. I’ve entered the scripts below.

    Pre- and post-build scripts in the Build Events tab in your project properties.
    Figure 1: Pre- and post-build scripts in the Build Events tab in your project properties.

    Scripts only run under Debug profile and run the bat scripts to start and stop services. It also sets exit command errorlevel as 0, which always complete successfully. For example, if MyService is not running and I want to stop it with pre-build script, the command will fail and the build will not continue. That’s why the exit /b 0 is there to ignore that and continue. It could be done differently, but in my case works like a charm.

    Every time I build a project in Visual Studio, the service is stopped files, project built and service started again.

    Additionally you need some sort of logging in your Windows Services, for example to a text file. What really speeds up my Windows Service development is also a tool like SnakeTail which can monitor the log file and you can instantly see the status of your service (no need to refresh/re-open your logs). Pretty neat! 🙂

    I hope you like these tips as much as I do! Please leave your comments down below.


    About Miha
    I've always been fascinated by computers. I am happy that I can work in this creative field of software development, where I can solve problems. I am also an avid cyclist :) and I love to learn...a lot!
    Related Posts
    • All
    • By Author
    • By Category
    • By Tag

    Leave a Reply