Working with Windows Service using Visual Studio


This article explains the purpose of Windows Service. It also shows how to create Windows Service using Visual Studio 2008, Add installer and install it. It also tells how to install it using Command line. It also explains you to manage Windows Service using Computer Management like start, stop and pause the service.

WINDOWS SERVCIE




Introduction



Windows Service is a long running executable application that runs 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. Windows services can be configured to start when the operating system is booted and run in the background as long as Windows is running, or they can be started manually when required

Create a Windows Service


Follow the below steps to a create Windows Service

  1. Create a Windows Service project by picking Windows Service option from your Visual C# Windows projects.

  2. Enter your service name(Eg: WindowsService1) and click OK.

  3. This will create a Windows Service project and add Service1.cs class to the project.

  4. Switch to code view to start developing.

  5. Write the functionality that the service needs to do. In the above screen Service1.cs has two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service.

  6. In this example, it writes a message into the event log when the service starts and stops. Code snippet is as below:


  7. Protected override void OnStart(string[] args)
    {
    EventLog.WriteEntry("Service", "WindowsService1 Started",
    EventLogEntryType.Information);
    }

    Protected override void OnStop(string[] args)
    {
    EventLog.WriteEntry("Service", "WindowsService1 Stopped",
    EventLogEntryType.Information);
    }

  8. Build the solution (Ctrl + Shift + B) and make sure that all the code doesn't have any bugs.


Create an Installer for your Windows Service



  1. From menu select File --> Add -->New project

  2. From Add New project, select Other Project Types and choose Setup Project

  3. Add our service to the installer. Right click the Application folder, Select Add --> Project output

  4. In Add Project Output Group widow, Select the project as our Windows service and select Primary Output and click OK.

  5. Add a project installer configuration code into your project. Right click from service class in your windows service project within design mode, and choose "Add Installer" from the menu, then ProjectInstaller class will create for you.

  6. Modify the service installer. Switch to code mode to start configure the behavior of your windows service application by selecting ProjectInstaller.Designer.cs

  7. Modify the account service will run as, the service startup type, the service name, etc.,.


  8. Private void InitializeComponent()
    {

    this.serviceProcessInstaller1 = new
    System.ServiceProcess.ServiceProcessInstaller();

    this.serviceInstaller1 = new
    System.ServiceProcess.ServiceInstaller();

    this.serviceProcessInstaller1.Account =
    System.ServiceProcess.ServiceAccount.LocalSystem;

    this.serviceProcessInstaller1.AfterInstall += new
    System.Configuration.Install.InstallEventHandler
    (this.serviceProcessInstaller1_AfterInstall);

    this.serviceInstaller1.ServiceName = "Service1";

    this.serviceInstaller1.StartType =
    System.ServiceProcess.ServiceStartMode.Automatic;

    this.Installers.AddRange(new System.Configuration.Install.Installer[]
    {this.serviceProcessInstaller1,

    this.serviceInstaller1});
    }

  9. Build the solution

  10. Build the installer from the setup project by right-click on the setup project , and choose build the project.

  11. Right click the setup project and choose Install

  12. Installing our windows service, as setup wizard will show up


Install and run the Service from Command Line


Windows service can be installed from command line without creating the installer. Follow the below steps to install windows service from command line.

  1. Build the windows service as it is bug free.

  2. Run the below command to register the windows service.


  3. Installutil d:\documents\Visual Studio 2008\Projects\WindowsService1\bin\debug\WindowsService1.exe

  4. Run the below command to uninstall the windows service.


  5. Installutil \u d:\documents\Visual Studio 2008\Projects\WindowsService1\bin\debug\WindowsService1.exe


Start and Stop the service


Go to Computer Management to start and stop the service. Follow the below steps:

  1. Right click on My Computer and choose Manage from the menu item.

  2. Under Services and Applications, you will see our service created.

  3. Right click our service and select Start or Stop.


Managing Services


The installed service can be managed by launching "Services" from the windows Control Panel --> Administrative Tools or by typing "Services.msc" in the run command. In Windows Vista and later, the services can be managed from the Services tab in Task Manager. The "Services" management console provides a brief description of the service functions and displays the path to the service executable, its current status, startup type, dependencies and the account under which the service is running. It enables users to

  • Start, stop, pause or restart services.

  • Specify service parameters.

  • Change the startup type which includes Automatic, Manual and Disabled.

  • Change the account under which the service logs on.

  • Configure recovery options upon service failure.

  • Export the list of services as a text file or a CSV file.


Allow Service to Interact with Desktop


The Windows Service does not have a user interface. But the developers can add the Form and other UI Components to the service. Follow the below steps to add user interface to the Windows Service:

  1. Open Service properties dialog box.

  2. Go to the Logon tab.

  3. Select the "Allow Service to Interact with Desktop" checkbox.


When the User Interface is added to the Windows Service, then it can be interacted by any logged in user. So it may lead to some security risk.

Security Context for Services


Services run in the context of the default system account, called LocalSystem, which gives them different access privileges to system resources than the user. You can change this behavior to specify a different user account under which your service should run. The account property for the process allows you to set the service to one of four Account types:

  • User

  • LocalService

  • LocalSystem

  • NetworkService


Follow the below steps to set the Account Types:

  1. After creating your service, add the necessary installers for it.

  2. In the designer, access the ProjectInstaller class and click the service process installer for the service you are working with.

  3. In the Properties window, set the Account to the appropriate value.


Debug Windows Service Applications


Debugging a service is not as straightforward as debugging other visual studio application types. To debug a service, we must start the service and then attach a debugger to the process in which it is running. You can then debug your application using all of the standard debugging functionality of Visual Studio.
Follow the below steps to debug a service:

  1. Install your service.

  2. Start your service, either from Services Control Manager, Server Explorer, or from code.

  3. In Visual Studio, choose Processes from the Debug menu.

  4. The Processes dialog box appears.

  5. Click Show system processes.

  6. In the Available Processes section, click the process for your service, and then click Attach.

  7. The Attach to Process dialog box appears.

  8. Choose any appropriate options, and then click OK to close the dialog box.

  9. Set any breakpoints you want to use in your code.

  10. Access the Services Control Manager and manipulate your service, sending stop, pause, and continue commands to hit your breakpoints.


Drawbacks of attaching a debugger



  1. Cannot debug the OnStart() or Main() method. Because the debugger can be attached to the service only after it has started running. By that time OnStart() method completes its execution and returned the control to the operating system.

  2. The debugger must be attached each time the project is started.

  3. This feature is not available for Visual Studio .Net Express Edition.


Log Information about Services


All Windows Service projects have the ability to interact with the Application event log and write information and exceptions to it. AutoLog property is used to enable this functionality in your application. By default, logging is turned on for any service that is created with the Windows Service project template


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: