Share via


How to create a Windows Service in the Component Designer

Microsoft Windows services enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer.

You create your service as a Microsoft Visual Studio project, defining code within it that controls what commands can be sent to the service and what actions should be taken when those commands are received. Commands that can be sent to a service include starting, pausing, resuming, and stopping the service; you can also execute custom commands.

After you create and build the application, you can install it by running the command-line utility InstallUtil.exe and passing the path to the service's executable file, or by using Visual Studio's deployment features. You can then use the Services Control Manager to start, stop, pause, resume, and configure your service.

A Windows Service can either be created using the Visual Studio project template called Windows Service OR you can write your own services by setting up the inheritance and other infrastructure elements yourself. In this post we will focus on creating a service using the provided template and component designer. We will explore the advanced method of coding the service directly in a later post.

Creating a Windows Service using the Component Designer

When you create a service, you can use a Visual Studio project template called Windows Service. This template automatically does much of the work for you by referencing the appropriate classes and namespaces, setting up the inheritance from the base class for services, and overriding several of the methods you're likely to want to override. To create a service using the component designer, you need to follow 3 basic steps:

  • Create a project by using the Windows Service application template. This template creates a class for you that inherits from ServiceBase and writes much of the basic service code, such as the code to start the service.

  • Write the code for the OnStart and OnStop procedures, and override any other methods that you want to redefine.

  • Add the necessary installers for your service application. By default, a class that contains two or more installers is added to your application when you click the Add Installer link: one to install the process, and one for each associated service that your project contains.

 

Step 1: Service creation – basic plumbing

1. Start Visual Studio and on the File menu, click New Project.

2. Select Windows Service in the list of Visual Basic or Visual C# project templates, and name the project MyNewService. Click OK.

image

3. The project template automatically adds a component class named Service1 that inherits from System.ServiceProcess.ServiceBase.

image

4. Click the designer to select Service1. Then, in the Properties window, set the ServiceName and the (Name) property for Service1 to MyNewService.

image

Step 2: Service purpose – define what your service does

Now that we have the basic service creation taken care of, let’s add the code that executes the business logic of your application. At a minimum, you should setup the initialization and override the OnStart() and OnStop() methods.

1. In Solution Explorer, right-click Service1.cs and select View Code. The code created by the project template looks like this:

 using System.ServiceProcess;

namespace MyNewService
{
    public partial class MyNewService : ServiceBase
    {
        public MyNewService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}

2. You need to now add code to the 3 methods shown above. Note that a service application is designed to be long running. Therefore, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system after the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.

 using System.ServiceProcess;

namespace MyNewService
{
    public partial class MyNewService : ServiceBase
    {
        public MyNewService()
        {
            InitializeComponent();
            // do your service initialization here
            // setup the timer here
        }

        protected override void OnStart(string[] args)
        {
            // when the service starts, enable the timer
        }

        protected override void OnStop()
        {
            // clean up - stop the timer
        }
    }
}

You can also override the OnPause, OnContinue, and OnShutdown methods to define additional processing for your component.

 

Step 3: Create service installers (not setup project)

Now that you have your service ready, you will need to create installers to install your service. This enables you to control the services using Windows Services controller. Do not confuse this step with creation of the setup (vdproj) project that shows the windows installer.

1. In Solution Explorer, right-click Service1.cs and select View Designer.

2. Click the background of the designer to select the service itself, instead of any of its contents.

3. With the designer in focus, right-click, and then click Add Installer.

image

By default, a component class that contains two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.

image

4. In Design view for ProjectInstaller, click serviceInstaller1.

5. In the Properties window, make sure the ServiceName property is set to MyNewService.

6. Set the StartType property to Automatic.

image

7. As the final step in creating the installer for your service, click serviceProcessInstaller1. Set the Account property to LocalSystem. This will cause the service to be installed and to run on a local service account.

image 

 

The service wiring process has already created the main entry for your service in Program.cs as shown below:

 using System.ServiceProcess;

namespace MyNewService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new MyNewService() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

Now all that is remaining to complete your service creation is setting up the correct startup object. In Solution Explorer, right-click your project and then click Properties. The project's Property Designer appears. On the Application page, from the Startup object list, click MyNewService.

image

How to Install and Uninstall Services

Unlike most projects you create in Visual Studio, Windows Service projects cannot be run directly from the development environment by pressing F5. This is because the service in the project must be installed before the project can run.

You can quickly install your service application by using a command-line utility called InstallUtil.exe. You can also create a setup project that contains your project's output and create a custom action with it that will run the installers associated with the project and install your service.

To install your service manually
  1. Access the directory in which your project's compiled executable file is located.

  2. Run InstallUtil.exe from the command line with your project's output as a parameter. Enter the following code on the command line: 

    installutil yourproject.exe

image

Installing the service installs and then commits it to the service database as shown below:

image

To uninstall your service manually
  1. Run InstallUtil.exe from the command line with your project's output as a parameter. Enter the following code on the command line:

    installutil /u yourproject.exe

I know this has been a super long post, but hopefully it has given you a clear picture on how to create a windows service using the component designer.

Comments

  • Anonymous
    June 27, 2011
    to integrate install util into your service use the following main       static void Main(string[] args)        {            // Thread.Sleep(15000);            bool success;            if (args != null && args.Length == 1 && args[0].Length > 1            && (args[0][0] == '-' || args[0][0] == '/'))            {                switch (args[0].Substring(1).ToLower())                {                    case "install":                    case "i":                        success = ServiceInstaller.Install();                        if (success)                            Console.WriteLine("Installation was successful.");                        else                            Console.WriteLine("Installation failed.");                        break;                    case "uninstall":                    case "u":                        success = ServiceInstaller.Uninstall();                        if (success)                            Console.WriteLine("Uninstall was successful.");                        else                            Console.WriteLine("Uninstall failed.");                        break;                    case "console":                    case "c":                    default:                        MyService ms = new MyService ();                        ms.Start(null);                        Console.ReadLine();                        break;                }            }            else            {                ServiceBase[] ServicesToRun;                // More than one user Service may run within the same process. To add                // another service to this process, change the following line to                // create a second service object. For example,                //                //   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};                //                ServicesToRun = new ServiceBase[] { new MyService () };                ServiceBase.Run(ServicesToRun);            }        } with the following helper class    static class ServiceInstaller    {        static readonly string exe = Assembly.GetExecutingAssembly().Location;        public static bool Install()        {            try            {                ManagedInstallerClass.InstallHelper(                    new string[] { exe });            }            catch (Exception ex)            {                return false;            }            return true;        }        public static bool Uninstall()        {            try            {                ManagedInstallerClass.InstallHelper(                    new string[] { "/u", exe });            }            catch (Exception ex)            {                return false;            }            return true;        }    }