Monday, June 9, 2014

How To Convert A Console Application To A Windows Service?

Problem

Today I want to share how to easily convert an existing console application to a windows service. There are a few reasons why we would want to do that:
  1. Console application must be running all time with an active user session in a server. A long running service application should be run by a non interactive (user logon) service account.
  2. When the console application is crashed due to unhandled exception, stack overflow or whatever reason, it will not be able to start back automatically unless someone manually go and restart the application.
  3. It is possible that someone login to the server with the same current active user session and accidentally close the console application.
  4. When the server is rebooted unintentionally such as power trip, the console application cannot start automatically. (Unless configured using startup link).

Solution

I came across a MSDN magazine, and found out that people are talking about Topshelf. It is quite an interesting small framework that allow us writing a console application and then easily convert it into a windows service. This framework is independent and not relying on any other framework or component. Fore more info, visit HERE for their official site. This framework is obtainable from NuGet.

Well, let's start coding. First, create a new console application project in your Visual Studio, or if you intend to convert an existing console application into a windows service, then open existing project.

At your console application project, download the Topshelf component from NuGet.


Then, create a new class that implement ServiceControl interface from Topshelf like below. For existing console application, move all your code from the Program class to this new class. The ServiceControl interface only has 2 methods that need to be implemented. One is Start() is for code execution when the windows service is started, then Stop() for the stop.

public class FileProcessorService : ServiceControl
{
    private static FileProcessorComponent _component;

    public bool Start(HostControl hostControl)
    {
        try
        {
            //Execute my existing console application code
            _component = new FileProcessorComponent();
            _component.Start();

            return true;
        }
        catch
        {
            return false;
        }
    }

    public bool Stop(HostControl hostControl)
    {
        try
        {
            _component.Stop();
            return true;
        }
        catch
        {
            return false;
        }
    }

}

Then, at your console Program.cs Main method, create the Topshelf host that run the above service which implement the ServiceHost class like the following:

class Program
{
    static void Main(string[] args)
    {
        HostFactory.Run(host =>
        {
            host.SetServiceName("PuttyCatFileProcessor"); //cannot contain spaces or / or \
            host.SetDisplayName("Putty Cat File Processor");
            host.SetDescription("A file processor service that uses Topshelf.");
            host.StartAutomatically();

            //host.RunAs("service account name", "the password");
            //Don't think you like to expose your password in the code. =P
            //We can set it manually for one time after installing the windows service in the services.msc
               
            host.Service<FileProcessorService>();
        });
    }
}


In my host configuration, I used 4 methods that I find commonly we would use.

SetServiceName() - To set the service name, not the one display in the services.msc
SetDisplayName() - The display name that will appear in the services.msc list.
SetDescription() - The service description that will appear in services.msc and Task Manager.
StartAutomatically() - To indicate the service shall start automatically after reboot.
RunAs() - We can set the username and password which to be used to run this windows service. Though, I think no one would want to do that to expose your credential information in the code.

Now, to test your application, you can simply press F5 to proceed for debug. Even with the above code, it is NOT automatically install and run as windows service yet. It is still a console application.

This is how it look like after pressing F5:


Pros

1. Debug

So, here is one advantage that I quickly can identify is, Topshelf creates the convenience in debugging a windows service. In conventional way, we have to install windows service first with installutil.exe and then start it then from Visual Studio attach process to the windows service to debug. Sometimes, we think of workaround such as writing code to change the windows service's ServiceBase behavior to temporary run the code in console mode, so that we can simply debug windows service by just pressing F5.

2. Deployment

Another advantage is Topshelf internally already support accepting pre-defined parameters that automate the windows service install or uninstall. For example, to install your console application as a windows service, just run your console application with install parameter in a command prompt.

<Console App Name>.exe install


Note that the above verbose log during the windows service installation. It also cater for the event log registration which I suppose any error occur in the event log will be automatically logged in the application event log.

Then, you can verify your windows service installation. The display name, description, account, start mode were as defined in the code.


Here is where you set the service account information instead of entering credential information in the code which I mentioned just now.


And, here is the auto recovery that I mentioned just now that a console application cannot support.



Alright now, in order to uninstall your windows service, just run the same console application with uninstall parameter.

<Console App Name>.exe uninstall


3. Migration

Last advantage that I discover is I can easily migrate my existing console application into a windows service with very minimal code change. I can simply move the code from the Program class to another new class, then add a windows service host class on top of the new class to convert it into a windows services.

Cons

1. Redundant

Well, if you have experience with windows service development, actually you may find that windows service project template from Visual Studio is quite complete and generated all the basic necessary code already. It can achieve the same result as this little framework do. Somehow, I feel it is redundant.

2. Maintenance

As per this document, Topshelf prerequisites .net framework is version 4.0. Well, console project that uses later .net framework library may not be supported and used with Topshelf. Also, the project .net framework upgrade become dependent on Topshelf .net framework usage.

Summary

A long running console application should be running as a windows service for those stated reasons at the problem section above. Topshelf makes developer life easier in developing windows service by simplifying and automating the debug and deployment work. If you are interested with my complete source code, feel free to download it from HERE.





20 comments:

  1. So what is the difference if I port the Console App into Windows Service solution that is not Topshelf? It doesn't seems to be better than the old one....

    ReplyDelete
    Replies
    1. Well...
      1. Write less code?
      2. Reuse existing console application project, download the Topshelf, then your console application can become a windows service without creating another new windows service project?
      3. Easy to debug during development?

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Sylvester'S Knowledge Base: How To Convert A Console Application To A Windows Service? >>>>> Download Now

      >>>>> Download Full

      Sylvester'S Knowledge Base: How To Convert A Console Application To A Windows Service? >>>>> Download LINK

      >>>>> Download Now

      Sylvester'S Knowledge Base: How To Convert A Console Application To A Windows Service? >>>>> Download Full

      >>>>> Download LINK cV

      Delete
  2. Hi everybody, I cant understand what's the FileProcessorComponent class?
    Thk u

    ReplyDelete
    Replies
    1. Hi Leonardo,
      The FileProcessorComponent is just my custom class that process file. You can download my complete source code and look for the FileProcessorComponent class then you will understand. The download link is available in the Summary section.
      Thanks.

      Delete
  3. If you are unable to install/uninstall your newly compiled exe (throws errors), then please close MMC and other service management related app , then try again.

    ReplyDelete
  4. Very helpful thank you! One suggestion though, somehow designate that the "FileProcessorComponent" related code is what your code is. It seems that a few people have been tripped up (myself included) thinking it was part of Topshelf.

    ReplyDelete
  5. Genuinely interested by all these articles on your blog Lee, learned a bunch of things I didn't even know of. Thanks a lot, do keep them coming!

    ReplyDelete
  6. thanks, this helped me

    ReplyDelete
  7. Sir, I really appreciate your help. but I'm really beginner until I dont know how to put & call my program.cs in the FileProcessorService class. Can you help further?Thank you.

    ReplyDelete
  8. Hi there,
    Thank you so much for the post you do and also I like your post, Are you looking for bitcoin halving countdown in the whole USA? We are providing Free Bitcoin QR Codes, BTC QR Code, BTC QR, BTC Address To QRCode, Bitcoin QR Maker, bitcoin qr generator with amount, bitcoin qr code generator blockchain, Bitcoin QR CodeGenerator and our services are very fast.
    Click here for Contact: +1 626 245 8049 Email: disujarock2312@gmail.com

    ReplyDelete
  9. Hi there,
    Thank you so much for the post you do and also I like your post, Are you looking for Most secure cryptocurrency in the whole USA? We are providing Augment Trade, most secure cryptocurrency, digital trading, Blockchain Technology, buy bitcoins online, Bitcoin users, The Cryptocurrency, bitcoin/Forex broker, bitcoin address , Bitcoin investment, with the well price and our services are very fast.
    Click here for MORE DETAILS......
    Email us at: info@augment-trade1.com

    ReplyDelete
  10. Hi there,
    Thank you so much for the post you do and also I like your post, Are you looking for Bitcoin Investment in the whole USA? We are providing Augment Trade, most secure cryptocurrency, digital trading, Blockchain Technology, buy bitcoins online, Bitcoin users, The Cryptocurrency, bitcoin/Forex broker, bitcoin address , Bitcoin investment, with the well price and our services are very fast.
    Click here for MORE DETAILS......
    Email us at: info@augment-trade1.com

    ReplyDelete
  11. Hi there,
    Thank you so much for the post you do and also I like your post, Are you looking for The cryptocurrency in the whole USA? We are providing Augment Trade, most secure cryptocurrency, digital trading, Blockchain Technology, buy bitcoins online, Bitcoin users, The Cryptocurrency, bitcoin/Forex broker, bitcoin address , Bitcoin investment, with the well price and our services are very fast.
    Click here for MORE DETAILS......
    Email us at: info@augment-trade1.com

    ReplyDelete
  12. Hi there,
    Thank you so much for the post you do and also I like your post, Are you looking for The bitcoin investment in the whole USA? We are providing Augment Trade, most secure cryptocurrency, digital trading, Blockchain Technology, buy bitcoins online, Bitcoin users, The Cryptocurrency, bitcoin/Forex broker, bitcoin address , Bitcoin investment, with the well price and our services are very fast.
    Click here for MORE DETAILS......
    Email us at: info@augment-trade1.com

    ReplyDelete
  13. Hi there,
    Thank you so much for the post you do and also I like your post, Are you looking for forex broker in the whole USA? We are providing Augment Trade, most secure cryptocurrency, Bitcoin users, The Cryptocurrency, bitcoin/Forex broker,digital trading, Blockchain Technology, buy bitcoins online, bitcoin address , Bitcoin investment, with the well price and our services are very fast.
    Click here for MORE DETAILS......
    Email us at: info@augment-trade1.com

    ReplyDelete
  14. PineSucceed offers blockchain-powered solutions to build innovative products that augment digital currency (cryptocoin, bitcoin, etc). Our blockchain experts use their expertise in Blockchain Development services to build incorruptible digital and distributed ledger for economic transactions that can be programmed as per your transaction needs

    ReplyDelete
  15. Your blog is excellent, and you have provided very important information through this blog. I was looking for a similar blog for a long time that can clear my doubts. That's why I want to thank you, and I wish you to keep writing similar blogs in the future. JPLoft is an App Development Company in India Known for creating innovative mobile applications, JPloft has been helping companies convey their brand message through easy-to-use applications.

    ReplyDelete

Send Transactional SMS with API

This post cover how to send transactional SMS using the Alibaba Cloud Short Message Service API. Transactional SMS usually come with One Tim...