Use Visual C # To create a Windows Service Program

Source: Internet
Author: User
Tags building windows

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.
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. receivettings

["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>

/// Required designer variables.

/// </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: add any initialization after the InitComponent call

}

# Region Component Designer generated code

/// <Summary>

/// The designer supports the required methods-do not use the code editor to modify

/// Content of this method.

/// </Summary>

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:

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)

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.