C # create a Windows Service Program

Source: Internet
Author: User
Tags building windows

The Windows service is called the NT Service. It is a program running in a Windows NT, Windows 2000, Windows XP, and other operating systems outside the user environment ......

 

  1. Introduction to Windows Services:

A Windows service, known as an NT Service, is a program running in a Windows NT, Windows 2000, Windows XP, and other operating systems outside the user environment. In the past, writing Windows service programs required strong C or C ++ skills from programmers. However, in Visual Studio. NET, you can use C ++, Visual C #, or Visual Basic. Net to easily create a Windows service program. Similarly, you can use any other CLR-compatible language to create a Windows service program. This article introduces how to use Visual C # To create a Windows Service Program for file monitoring step by step, and then describes how to install, test and debug the Windows service program.

Before introducing how to create a Windows service program, I would like to introduce some background knowledge about Windows Services. A Windows Service Program is an executable application that can complete specific functions in a Windows operating system. Although a Windows service program is executable, it does not run as a normal executable file by double-clicking it. It must have a specific startup method. These methods include automatic start and Manual start. For automatically started Windows service programs, they are executed before the user logs on after Windows is started or restarted. You only need to register the corresponding Windows Service Program in Service Control Manager and set the startup category to Automatic startup. For a Windows service program that is manually started, you can use the net start command of the command line tool to start it, or start the corresponding Windows service program through the service item under the management tool in the control panel (see figure 1 ). Similarly, a Windows service program cannot be terminated as a normal application. Because Windows service programs generally do not have a user interface, you need to stop them using the command line tool or the tool shown in the figure below, or make the Windows Service Program stop automatically when the system is disabled. Because Windows service programs do not have a user interface, the user interface-based API functions have little significance for them. To enable a Windows service program to work normally and effectively in a system environment, programmers must implement a series of methods to complete its service functions. Windows service programs have a wide range of applications. Typical Windows service programs include hardware control, application monitoring, system-level applications, diagnostics, reporting, web and file system services.

Figure 1

  2. Create a Windows Service Program:

Before introducing how to create a Windows service program, I would like to introduce the namespaces related to Windows Services and the class libraries in the. NET Framework .. The. NET Framework greatly simplifies the process of creating and controlling Windows service programs, thanks to the powerful class libraries in its namespace. The namespaces related to Windows service programs involve system. serviceprocess and system. diagnostics.

To create a basic Windows service program, we only need to use it.. NET Framework. serviceprocess namespace and its four classes: servicebase, serviceinstaller, serviceprocessinstaller, and servicecontroller. The architecture of serviceprocess is shown in figure 2.

 

The servicebase class defines some functions that can be overloaded by its subclass. With these overloaded functions, the Service Control Manager can control the Windows service program. These functions include onstart (), onstop (), onpause (), and oncontinue. In addition, the subclass of the servicebase class can also overload the oncustomcommand () function to complete some specific operations. By reloading the above functions, we have completed the basic framework of a Windows service program. The methods for reloading these functions are as follows:

The servicebase class also provides some attributes that are required by any Widnows service program. The servicename attribute specifies the name of the Windows Service. The system can call the Windows service by using this name. Other applications can also call its service by using this name. The canpauseandcontinue and canstop attributes, as the name suggests, allow pause, recovery, and allow stop.

To make a Windows service program run properly, we need to create a program entry point for it just like creating a general application. In the Windows service program, we also completed this operation in the main () function. First, create a Windows service instance in the main () function. The instance should be a subclass object of the servicebase class, then we call a run () method defined by the base class servicebase class. However, the run () method does not start the Windows service program. We must use the service control manager mentioned earlier to call specific control functions to start the Windows service program, that is, the service will not really start running until the onstart () method of the object is called. If you want to start multiple services in a Windows Service Program at the same time, you only need to define the Instance Object of multiple servicebae class subclasses in the main () function, the method is to create an array object of the servicebase class so that each object corresponds to a pre-defined service.

Static coId main ()

  3. Add the file Monitoring Service:

After learning about the basic architecture and creation method of the Windows service, we can try to add some practical functions to the service. Next I will introduce filemonitorservice, a file monitoring service that monitors local file systems. This service monitors any changes in files including subfolders Based on preset local directory paths: File Creation, file deletion, file rename, and file modification. At the same time, the service also creates a counter for each change. The counter is used to reflect the frequency of this change.

First, open Visual Studio. NET and create a Windows Service Project of Visual C #, as shown in 3:

Figure 3

Before the onstart () function of Windows service is reloaded, we add some counter objects to its class. These counters correspond to file creation, deletion, renaming, modification, and other changes. Once the files in the specified directory change, the corresponding counter will automatically add 1. All these counters are defined as variable of the performancecounter type, which is included in the system. Diagnostics namespace.

Then, we create the counter objects defined above in the class initializecomponent () method and determine their related attributes. At the same time, we set the name of the Windows service to "filemonitorservice" to allow pause and recovery and stop.

 

The following is a code snippet:
Private void initializecomponent ()
{
This. components = new system. componentmodel. Container ();
This. filechangecounter = new system. Diagnostics. performancecounter ();
This. filedeletecounter = new system. Diagnostics. performancecounter ();
This. filerenamecounter = new system. Diagnostics. performancecounter ();
This. filecreatecounter = new system. Diagnostics. performancecounter ();
Filechangecounter. categoryname = "File Monitor Service ";
Filedeletecounter. categoryname = "File Monitor Service ";
Filerenamecounter. categoryname = "File Monitor Service ";
Filecreatecounter. categoryname = "File Monitor Service ";
Filechangecounter. countername = "files changed ";
Filedeletecounter. countername = "files deleted ";
Filerenamecounter. countername = "files renamed ";
Filecreatecounter. countername = "files created ";
This. servicename = "filemonitorservice ";
This. canpauseandcontinue = true;
This. canstop = true;
Servicepaused = false;
}

 

The next step is to reload the onstart () and onstop () functions. The onstart () functions complete some necessary initialization work. In the. NET Framework, the file monitoring function can be completed by the filesystemwatcher class, which is included in the system. Io namespace. The functions required by the Windows Service include creating, deleting, renaming, and modifying monitored files. The filesystemwatcher class contains all the processing functions corresponding to these changes.

Note that the monitored directory is stored in an application configuration file, which is an XML file. The advantage of this approach is that we do not have to re-compile and release the Windows service, but simply modify its configuration file to achieve the function of changing the directory to be monitored.

After the Windows service is started, once the files in the monitored Directory change, the corresponding counter value will increase accordingly. The method is very simple, you only need to call the incrementby () of the counter object.

 

The following is a code snippet:
Private void onfilechanged (Object source, filesystemeventargs E)
{
If (servicepaused = false)
{
Filechangecounter. incrementby (1 );
}
}
Private void onfilerenamed (Object source, renamedeventargs E)
{
If (servicepaused = false)
{
Filerenamecounter. incrementby (1 );
}
}
Private void onfilecreated (Object source, filesystemeventargs E)
{
If (servicepaused = false)
{
Filecreatecounter. incrementby (1 );
}
}
Private void onfiledeleted (Object source, filesystemeventargs E)
{
If (servicepaused = false)
{
Filedeletecounter. incrementby (1 );
}
}

 

The onstop () function stops the Windows service. In this Windows Service, once the service is stopped, all the counter values should be set to zero, but the counter does not provide a reset () method, therefore, we have to subtract the current value from the value in the counter to achieve this goal.

At the same time, because our windows service allows pause and recovery, we have to reload the onpause () and oncontinue () functions, the method is very simple, you only need to set the previously defined Boolean value servicepaused.

In this way, the main part of the Windows service has been completed, but it is not useful. We must add an installation file for it. The Installation File is properly installed for the Windows Service. It includes an installation class for the Windows Service, which is inherited by system. configuration. Install. installer. The installation class includes the account information, user name, password information, Windows Service name, and startup method required for running the Windows service.

 

The following is a code snippet:
[Runinstaller (true)]
Public class installer1: system. configuration. Install. Installer
{
///
/// Required designer variables.
///
Private system. componentmodel. Container components = NULL;
Private system. serviceprocess. serviceprocessinstaller spinstaller;
Private system. serviceprocess. serviceinstaller sinstaller;
Public installer1 ()
{
// This call is required by the designer.
Initializecomponent ();
// Todo: add any initialization after the initcomponent call
}
# Region component designer generated code
///
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
///
Private void initializecomponent ()
{
Components = new system. componentmodel. Container ();
// Create the serviceprocessinstaller object and serviceinstaller object
This. spinstaller =
New system. serviceprocess. serviceprocessinstaller ();
This. sinstaller = new system. serviceprocess. serviceinstaller ();
// Set the account, user name, and password of the serviceprocessinstaller object
This. spinstaller. Account =
System. serviceprocess. serviceaccount. LocalSystem;
This. spinstaller. Username = NULL;
This. spinstaller. Password = NULL;
// Set the service name
This. sinstaller. servicename = "filemonitorservice ";
// Set the Service Startup Mode
This. sinstaller. starttype =
System. serviceprocess. servicestartmode. Automatic;
This. installers. addrange (
New system. configuration. Install. installer []
{This. spinstaller, this. sinstaller });
}
# Endregion
}

 

Similarly, because the counter object is used in the Windows service, we also need to add the corresponding installation file for it. The content and function of the installation file are similar to the previous one. Due to the limited length, no corresponding code is provided here. If you are interested, you can refer to the source code file attached to the article.

So far, the entire Windows service has been built, but the Windows service program is different from the general application, it cannot be directly debugged and run. If you try to debug and run the SDK directly under IDE, the following message is displayed: 4.

Figure 4

When prompted, we know that the installation of Windows Service is used as a command line tool named installutil.exe. Using this tool to install a Windows service is very simple. The command to install the Windows service is as follows:

To uninstall the Windows service, you just need to enter the following command:

After the Windows service is successfully installed, it appears in Service Control Manager, as shown in Figure 5.

Figure 5

In this way, the Windows service monitored by this file is complete. Once we operate on the files in the monitored directory, the corresponding counters will operate to monitor file changes. However, this feature does not make much sense for general users. However, you can add new features on this basis, such as building a background file processing system, once the files in the monitored Directory change, the Windows Service performs specific operations on them, and the end user does not have to worry about how the background processing program is implemented.

  Iv. Summary:

This article introduces some basic concepts of Windows Services and the methods required to build general Windows Services. It also shows you a Windows service program with file monitoring function. Through this article, readers should be able to understand that building Windows Services is not as complicated as they think, thanks mainly to the. NET Framework's great efforts. At the same time, we hope that you can build a more comprehensive and powerful Windows service program based on the examples provided in this Article. Finally, I hope this article will help you a lot.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.