Use Visual C # To create a Windows Service Program from CCID)

Source: Internet
Author: User
Tags building windows

Use Visual C # To create a Windows ServiceProgram
Author: Wang Kaiming published at: 10:04:39

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 Windows service programs that are manually started, you can use the net start command line tool. Command to start it, or start the corresponding Windows service program through a 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.

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:


     
      
Protected override void onstart (string [] ARGs) {} protected override void onstop () {} protected override void onpause () {} protected override void oncontinue (){}

     

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.


     
      
{System. serviceprocess. servicebase [] myservices; myservices = new system. serviceprocess. servicebase [] {New service1 (), new service2 ()}; system. serviceprocess. servicebase. run (myservices );}

     

Static void 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.


     
      
Private system. Diagnostics. performancecounter filecreatecounter; private system. Diagnostics. performancecounter filedeletecounter; private system. Diagnostics. performancecounter filerenamecounter; private system. Diagnostics. performancecounter filechangecounter;

     

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.


     
      
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.


     
      
Protected override void onstart (string [] ARGs) {filesystemwatcher curwatcher = new filesystemwatcher (); curwatcher. begininit (); curwatcher. includesubdirectories = true; curwatcher. path = system. configuration. configurationsettings. appsettings ["filemonitordirectory"]; curwatcher. changed + = new filesystemeventhandler (onfilechanged); curwatcher. created + = new filesystemeventhandler (onfilecreated); curwatcher. deleted + = new filesystemeventhandler (onfiledeleted); curwatcher. renamed + = new renamedeventhandler (onfilerenamed); curwatcher. enableraisingevents = true; curwatcher. endinit ();}

     

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.


     
      
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.


     
      
Protected override void onstop () {If (filechangecounter. rawvalue! = 0) {filechangecounter. incrementby (-filechangecounter. rawvalue);} If (filedeletecounter. rawvalue! = 0) {filedeletecounter. incrementby (-filedeletecounter. rawvalue);} If (filerenamecounter. rawvalue! = 0) {filerenamecounter. incrementby (-filerenamecounter. rawvalue);} If (filecreatecounter. rawvalue! = 0) {filecreatecounter. incrementby (-filecreatecounter. rawvalue );}}

     

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.


     
      
Protected override void onpause () {servicepaused = true;} protected override void oncontinue () {servicepaused = false ;}

     

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.


     
      
[Runinstaller (true)] public class installer1: system. configuration. Install. installer {// <summary> // The required designer variable. /// </Summary> 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: After the initcomponent call, add any initialization} # region component designer generated code // <summary> // The method required by the designer-do not use
       Code Modify the content of this method in the editor. /// </Summary> private void initializecomponent () {components = new system. componentmodel. container (); // create 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"; // sets 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 space limitations, no code is provided here. If you are interested, refer toSource codeFile.

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:


     
      
Installutil filemonitorservice.exe

     

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


     
      
Installutil/u filemonitorservice.exe

     

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.

(Note: the source code file is source.rar)

Related Article

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.