Install windows service application

Develop Windows service apps

Using Visual Studio or the .NET Framework SDK, you can easily create services by creating an application that is installed as a service. This type of application is called a Windows service. With framework features, you can create services, install them, and start, stop, and otherwise control their behavior.

In Visual Studio you can create a service in managed code in Visual C# or Visual Basic, which can interoperate with existing C++ code if required. Or, you can create a Windows service in native C++ by using the ATL Project Wizard.

In this section

Provides an overview of Windows service applications, the lifetime of a service, and how service applications differ from other common project types.

Provides an example of creating a service in Visual Basic and Visual C#.

Explains the language elements used in service programming.

Describes the process of creating and configuring Windows services using the Windows service project template.

ServiceBase — Describes the major features of the ServiceBase class, which is used to create services.

ServiceProcessInstaller — Describes the features of the ServiceProcessInstaller class, which is used along with the ServiceInstaller class to install and uninstall your services.

ServiceInstaller — Describes the features of the ServiceInstaller class, which is used along with the ServiceProcessInstaller class to install and uninstall your service.

Create Projects from Templates — Describes the projects types used in this chapter and how to choose between them.

Introduction to Windows Service Applications

Microsoft Windows services, formerly known as NT 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 can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account. For more information about services and Windows sessions, see the Windows SDK documentation.

You can easily create services by creating an application that is installed as a service. For example, suppose you want to monitor performance counter data and react to threshold values. You could write a Windows Service application that listens to the performance counter data, deploy the application, and begin collecting and analyzing data.

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. You can then use the Services Control Manager to start, stop, pause, resume, and configure your service. You can also accomplish many of these same tasks in the Services node in Server Explorer or by using the ServiceController class.

Service Applications vs. Other Visual Studio Applications

Service applications function differently from many other project types in several ways:

The compiled executable file that a service application project creates must be installed on the server before the project can function in a meaningful way. You cannot debug or run a service application by pressing F5 or F11; you cannot immediately run a service or step into its code. Instead, you must install and start your service, and then attach a debugger to the service’s process. For more information, see How to: Debug Windows Service Applications.

Unlike some types of projects, you must create installation components for service applications. The installation components install and register the service on the server and create an entry for your service with the Windows Services Control Manager. For more information, see How to: Add Installers to Your Service Application.

The Main method for your service application must issue the Run command for the services your project contains. The Run method loads the services into the Services Control Manager on the appropriate server. If you use the Windows Services project template, this method is written for you automatically. Note that loading a service is not the same thing as starting the service. See «Service Lifetime» below for more information.

Windows Service applications run in a different window station than the interactive station of the logged-on user. A window station is a secure object that contains a Clipboard, a set of global atoms, and a group of desktop objects. Because the station of the Windows service is not an interactive station, dialog boxes raised from within a Windows service application will not be seen and may cause your program to stop responding. Similarly, error messages should be logged in the Windows event log rather than raised in the user interface.

The Windows service classes supported by the .NET Framework do not support interaction with interactive stations, that is, the logged-on user. The .NET Framework also does not include classes that represent stations and desktops. If your Windows service must interact with other stations, you will need to access the unmanaged Windows API. For more information, see the Windows SDK documentation.

The interaction of the Windows service with the user or other stations must be carefully designed to include scenarios such as there being no logged on user, or the user having an unexpected set of desktop objects. In some cases, it may be more appropriate to write a Windows application that runs under the control of the user.

Windows service applications run in their own security context and are started before the user logs into the Windows computer on which they are installed. You should plan carefully what user account to run the service within; a service running under the system account has more permissions and privileges than a user account.

Читайте также:  App installer windows 10 запуск

Service Lifetime

A service goes through several internal states in its lifetime. First, the service is installed onto the system on which it will run. This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. The Services Control Manager is the central utility provided by Windows to administer services.

After the service has been loaded, it must be started. Starting the service allows it to begin functioning. You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. The Start method passes processing to the application’s OnStart method and processes any code you have defined there.

A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. A service can exist in one of three basic states: Running, Paused, or Stopped. The service can also report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. These statuses indicate that a command has been issued, such as a command to pause a running service, but has not been carried out yet. You can query the Status to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. Each of these actions can call an associated procedure in the service (OnStop, OnPause, or OnContinue), in which you can define additional processing to be performed when the service changes state.

Types of Services

There are two types of services you can create in Visual Studio using the .NET Framework. Services that are the only service in a process are assigned the type Win32OwnProcess. Services that share a process with another service are assigned the type Win32ShareProcess. You can retrieve the service type by querying the ServiceType property.

You might occasionally see other service types if you query existing services that were not created in Visual Studio. For more information on these, see the ServiceType.

Services and the ServiceController Component

The ServiceController component is used to connect to an installed service and manipulate its state; using a ServiceController component, you can start and stop a service, pause and continue its functioning, and send custom commands to a service. However, you do not need to use a ServiceController component when you create a service application. In fact, in most cases your ServiceController component should exist in a separate application from the Windows service application that defines your service.

For more information, see ServiceController.

Requirements

Services must be created in a Windows Service application project or another .NET Framework–enabled project that creates an .exe file when built and inherits from the ServiceBase class.

Projects containing Windows services must have installation components for the project and its services. This can be easily accomplished from the Properties window. For more information, see How to: Add Installers to Your Service Application.

How to: Install and uninstall Windows services

If you’re developing a Windows service with the .NET Framework, you can quickly install your service app by using the InstallUtil.exe command-line utility or PowerShell. Developers who want to release a Windows service that users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer, InstallShield, or others. For more information, see Create an installer package (Windows desktop).

If you want to uninstall a service from your computer, don’t follow the steps in this article. Instead, find out which program or software package installed the service, and then choose Apps in Settings to uninstall that program. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.

To use the steps in this article, you first need to add a service installer to your Windows service. For more information, see Walkthrough: Creating a Windows service app.

You can’t run Windows service projects directly from the Visual Studio development environment by pressing F5. Before you can run the project, you must install the service in the project.

You can use Server Explorer to verify that you’ve installed or uninstalled your service.

Install using InstallUtil.exe utility

From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .

The Developer Command Prompt for Visual Studio appears.

Access the directory where your project’s compiled executable file is located.

Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:

If you’re using the Developer Command Prompt for Visual Studio, InstallUtil.exe should be on the system path. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .

  • For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
  • For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.

Uninstall using InstallUtil.exe utility

From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .

The Developer Command Prompt for Visual Studio appears.

Run InstallUtil.exe from the command prompt with your project’s output as a parameter:

After the executable for a service is deleted, the service might still be present in the registry. If that’s the case, use the command sc delete to remove the entry for the service from the registry.

Install using PowerShell

From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.

Access the directory where your project’s compiled executable file is located.

Run the New-Service cmdlet with the with your project’s output and a service name as parameters:

Uninstall using PowerShell

From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.

Run the Remove-Service cmdlet with the name of your service as parameter:

After the executable for a service is deleted, the service might still be present in the registry. If that’s the case, use the command sc delete to remove the entry for the service from the registry.

Tutorial: Create a Windows service app

This article demonstrates how to create a Windows service app in Visual Studio that writes messages to an event log.

Create a service

To begin, create the project and set the values that are required for the service to function correctly.

From the Visual Studio File menu, select New > Project (or press Ctrl+Shift+N) to open the New Project window.

Читайте также:  Последняя версия яндекс браузера для windows 10 64 bit

Navigate to and select the Windows Service (.NET Framework) project template. To find it, expand Installed and Visual C# or Visual Basic, then select Windows Desktop. Or, enter Windows Service in the search box on the upper right and press Enter.

If you don’t see the Windows Service template, you may need to install the .NET desktop development workload:

In the New Project dialog, select Open Visual Studio Installer on the lower left. Select the .NET desktop development workload, and then select Modify.

For Name, enter MyNewService, and then select OK.

The Design tab appears (Service1.cs [Design] or Service1.vb [Design]).

The project template includes a component class named Service1 that inherits from System.ServiceProcess.ServiceBase. It includes much of the basic service code, such as the code to start the service.

Rename the service

Rename the service from Service1 to MyNewService.

In Solution Explorer, select Service1.cs, or Service1.vb, and choose Rename from the shortcut menu. Rename the file to MyNewService.cs, or MyNewService.vb, and then press Enter

A pop-up window appears asking whether you would like to rename all references to the code element Service1.

In the pop-up window, select Yes.

In the Design tab, select Properties from the shortcut menu. From the Properties window, change the ServiceName value to MyNewService.

Select Save All from the File menu.

Add features to the service

In this section, you add a custom event log to the Windows service. The EventLog component is an example of the type of component you can add to a Windows service.

Add custom event log functionality

In Solution Explorer, from the shortcut menu for MyNewService.cs, or MyNewService.vb, choose View Designer.

In Toolbox, expand Components, and then drag the EventLog component to the Service1.cs [Design], or Service1.vb [Design] tab.

In Solution Explorer, from the shortcut menu for MyNewService.cs, or MyNewService.vb, choose View Code.

Define a custom event log. For C#, edit the existing MyNewService() constructor; for Visual Basic, add the New() constructor:

Add a using statement to MyNewService.cs (if it doesn’t already exist), or an Imports statement MyNewService.vb, for the System.Diagnostics namespace:

Select Save All from the File menu.

Define what occurs when the service starts

In the code editor for MyNewService.cs or MyNewService.vb, locate the OnStart method; Visual Studio automatically created an empty method definition when you created the project. Add code that writes an entry to the event log when the service starts:

Polling

Because a service application is designed to be long-running, it usually polls or monitors the system, which you set up in the OnStart method. The OnStart method must return to the operating system after the service’s operation has begun so that the system isn’t blocked.

To set up a simple polling mechanism, use the System.Timers.Timer component. The timer raises an Elapsed event at regular intervals, at which time your service can do its monitoring. You use the Timer component as follows:

  • Set the properties of the Timer component in the MyNewService.OnStart method.
  • Start the timer by calling the Start method.
Set up the polling mechanism.

Add the following code in the MyNewService.OnStart event to set up the polling mechanism:

Add a using statement to MyNewService.cs, or an Imports statement to MyNewService.vb, for the System.Timers namespace:

In the MyNewService class, add the OnTimer method to handle the Timer.Elapsed event:

In the MyNewService class, add a member variable. It contains the identifier of the next event to write into the event log:

Instead of running all your work on the main thread, you can run tasks by using background worker threads. For more information, see System.ComponentModel.BackgroundWorker.

Define what occurs when the service is stopped

Insert a line of code in the OnStop method that adds an entry to the event log when the service is stopped:

Define other actions for the service

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

The following code shows how you to override the OnContinue method in the MyNewService class:

Set service status

Services report their status to the Service Control Manager so that a user can tell whether a service is functioning correctly. By default, a service that inherits from ServiceBase reports a limited set of status settings, which include SERVICE_STOPPED, SERVICE_PAUSED, and SERVICE_RUNNING. If a service takes a while to start up, it’s useful to report a SERVICE_START_PENDING status.

You can implement the SERVICE_START_PENDING and SERVICE_STOP_PENDING status settings by adding code that calls the Windows SetServiceStatus function.

Implement service pending status

Add a using statement to MyNewService.cs, or an Imports statement to MyNewService.vb, for the System.Runtime.InteropServices namespace:

Add the following code to MyNewService.cs, or MyNewService.vb, to declare the ServiceState values and to add a structure for the status, which you’ll use in a platform invoke call:

The Service Control Manager uses the dwWaitHint and dwCheckpoint members of the SERVICE_STATUS structure to determine how much time to wait for a Windows service to start or shut down. If your OnStart and OnStop methods run long, your service can request more time by calling SetServiceStatus again with an incremented dwCheckPoint value.

In the MyNewService class, declare the SetServiceStatus function by using platform invoke:

To implement the SERVICE_START_PENDING status, add the following code to the beginning of the OnStart method:

Add code to the end of the OnStart method to set the status to SERVICE_RUNNING:

(Optional) If OnStop is a long-running method, repeat this procedure in the OnStop method. Implement the SERVICE_STOP_PENDING status and return the SERVICE_STOPPED status before the OnStop method exits.

Add installers to the service

Before you run a Windows service, you need to install it, which registers it with the Service Control Manager. Add installers to your project to handle the registration details.

In Solution Explorer, from the shortcut menu for MyNewService.cs, or MyNewService.vb, choose View Designer.

In the Design view, select the background area, then choose Add Installer from the shortcut menu.

By default, Visual Studio adds a component class named ProjectInstaller , which contains two installers, to your project. These installers are for your service and for the service’s associated process.

In the Design view for ProjectInstaller, select serviceInstaller1 for a Visual C# project, or ServiceInstaller1 for a Visual Basic project, then choose Properties from the shortcut menu.

In the Properties window, verify the ServiceName property is set to MyNewService.

Add text to the Description property, such as A sample service.

This text appears in the Description column of the Services window and describes the service to the user.

Add text to the DisplayName property. For example, MyNewService Display Name.

This text appears in the Display Name column of the Services window. This name can be different from the ServiceName property, which is the name the system uses (for example, the name you use for the net start command to start your service).

Читайте также:  Помню свой пароль от windows

Set the StartType property to Automatic from the drop-down list.

When you’re finished, the Properties windows should look like the following figure:

In the Design view for ProjectInstaller, choose serviceProcessInstaller1 for a Visual C# project, or ServiceProcessInstaller1 for a Visual Basic project, then choose Properties from the shortcut menu. Set the Account property to LocalSystem from the drop-down list.

This setting installs the service and runs it by using the local system account.

The LocalSystem account has broad permissions, including the ability to write to the event log. Use this account with caution, because it might increase your risk of attacks from malicious software. For other tasks, consider using the LocalService account, which acts as a non-privileged user on the local computer and presents anonymous credentials to any remote server. This example fails if you try to use the LocalService account, because it needs permission to write to the event log.

(Optional) Set startup parameters

Before you decide to add startup parameters, consider whether it’s the best way to pass information to your service. Although they’re easy to use and parse, and a user can easily override them, they might be harder for a user to discover and use without documentation. Generally, if your service requires more than just a few startup parameters, you should use the registry or a configuration file instead.

A Windows service can accept command-line arguments, or startup parameters. When you add code to process startup parameters, a user can start your service with their own custom startup parameters in the service properties window. However, these startup parameters aren’t persisted the next time the service starts. To set startup parameters permanently, set them in the registry.

Each Windows service has a registry entry under the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services subkey. Under each service’s subkey, use the Parameters subkey to store information that your service can access. You can use application configuration files for a Windows service the same way you do for other types of programs. For sample code, see ConfigurationManager.AppSettings.

To add startup parameters

Select Program.cs, or MyNewService.Designer.vb, then choose View Code from the shortcut menu. In the Main method, change the code to add an input parameter and pass it to the service constructor:

In MyNewService.cs, or MyNewService.vb, change the MyNewService constructor to process the input parameter as follows:

This code sets the event source and log name according to the startup parameters that the user supplies. If no arguments are supplied, it uses default values.

To specify the command-line arguments, add the following code to the ProjectInstaller class in ProjectInstaller.cs, or ProjectInstaller.vb:

Typically, this value contains the full path to the executable for the Windows service. For the service to start up correctly, the user must supply quotation marks for the path and each individual parameter. A user can change the parameters in the ImagePath registry entry to change the startup parameters for the Windows service. However, a better way is to change the value programmatically and expose the functionality in a user-friendly way, such as by using a management or configuration utility.

Build the service

In Solution Explorer, choose Properties from the shortcut menu for the MyNewService project.

The property pages for your project appear.

On the Application tab, in the Startup object list, choose MyNewService.Program, or Sub Main for Visual Basic projects.

To build the project, in Solution Explorer, choose Build from the shortcut menu for your project (or press Ctrl+Shift+B).

Install the service

Now that you’ve built the Windows service, you can install it. To install a Windows service, you must have administrator credentials on the computer where it’s installed.

In Developer Command Prompt for Visual Studio, navigate to the folder that contains your project’s output (by default, the \bin\Debug subdirectory of your project).

Enter the following command:

If the service installs successfully, the command reports success.

If the system can’t find installutil.exe, make sure that it exists on your computer. This tool is installed with the .NET Framework to the folder %windir%\Microsoft.NET\Framework[64]\ . For example, the default path for the 64-bit version is %windir%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.

If the installutil.exe process fails, check the install log to find out why. By default, the log is in the same folder as the service executable. The installation can fail if:

  • The RunInstallerAttribute class isn’t present on the ProjectInstaller class.
  • The attribute isn’t set to true .
  • The ProjectInstaller class isn’t defined as public .

Start and run the service

In Windows, open the Services desktop app. Press Windows+R to open the Run box, enter services.msc, and then press Enter or select OK.

You should see your service listed in Services, displayed alphabetically by the display name that you set for it.

To start the service, choose Start from the service’s shortcut menu.

To stop the service, choose Stop from the service’s shortcut menu.

(Optional) From the command line, use the commands net start and net stop to start and stop your service.

Verify the event log output of your service

In Windows, open the Event Viewer desktop app. Enter Event Viewer in the Windows search bar, and then select Event Viewer from the search results.

In Visual Studio, you can access event logs by opening Server Explorer from the View menu (or press Ctrl+Alt+S) and expanding the Event Logs node for the local computer.

In Event Viewer, expand Applications and Services Logs.

Locate the listing for MyNewLog (or MyLogFile1 if you followed the procedure to add command-line arguments) and expand it. You should see the entries for the two actions (start and stop) that your service performed.

Clean up resources

If you no longer need the Windows service app, you can remove it.

Open Developer Command Prompt for Visual Studio with administrative credentials.

In the Developer Command Prompt for Visual Studio window, navigate to the folder that contains your project’s output.

Enter the following command:

If the service uninstalls successfully, the command reports that your service was successfully removed. For more information, see How to: Install and uninstall services.

Next steps

Now that you’ve created the service, you can:

Create a standalone setup program for others to use to install your Windows service. Use the WiX Toolset to create an installer for a Windows service. For other ideas, see Create an installer package.

Explore the ServiceController component, which enables you to send commands to the service you’ve installed.

Instead of creating the event log when the application runs, use an installer to create an event log when you install the application. The event log is deleted by the installer when you uninstall the application. For more information, see EventLogInstaller.

Оцените статью