Create a Windows Server with Visual C #

xiaoxiao2021-03-06  39

One. Windows service introduction:

Windows services are previously referred to as NT services, which is a program that runs outside the user environment under operating systems such as Windows NT, Windows 2000, and Windows XP. In the past, writing a Windows service program requires a strong C or C context. However, under Visual Studio.net, you can use C or Visual C # or Visual Basic.Net to easily create a Windows service. Similarly, you can also use any other language compatible with the CLR to create a Windows service program. This article introduces you how to use Visual C # to create a Windows Server for file monitors step by step, then describe how to install, test, and debug the Windows service program.

Before describing how to create a Windows service, I will introduce some background knowledge about the Windows service. A Windows Server is an executable application that can complete a specific function under a Windows operating system. Although the Windows Server is executable, it is unlike a general executable file to start running, it must have a specific start-up mode. These startup methods include automatic startup and manual startup. For automatic Windows service programs, they start executing before Windows started or after the user logs in. As long as you register the corresponding Windows Server to the Service Control Manager, set it to the start category to start. And for manual start-up Windows service, you can use the NET Start for the command line tool

Command to start it, or start the corresponding Windows service program (see Figure 1) by controling the service in the control panel. Similarly, a Windows service program cannot be terminated as a general application. Because Windows Services are generally no user interface, you also need to stop it through the command line tool or the tool in the drawings below, or when the system is turned off, the Windows service is automatically stopped. Because the Windows Server does not have a user interface, the API function based on the user interface is not much. In order to make a Windows service program work properly and efficiently in the system environment, programmers must implement a series of methods to complete their service functions. The Windows service program is widely applicable. Typical Windows service programs contain features such as hardware control, application monitoring, system-level applications, diagnostics, reports, web, and file system services.

figure 1

two. Create a Windows Server:

Before how to create a Windows service program, I will introduce you to the .NET framework and the namespace related to the Windows service and the class libraries. The .NET framework greatly simplifies the creation and control of the Windows service program, which is due to the powerful class library in its namespace. The namespace related to the Windows service program involve the following two: System.ServiceProcess and System.Diagnostics.

To create a most basic Windows service, we only need to use the system.serviceProcess namespace under the .NET framework and four classes: ServiceBase, ServiceInstaller, ServiceProcessInstaller, and ServiceController, the architecture is shown in Figure 2.

figure 2

The ServiceBase class defines some functions that can be overloaded by their subclats, through these overloaded functions, the service control manager can control the Windows service program. These functions include: onStart (), onstop (), onpause (), and four onContinue (). Moreover, the subclass of the ServiceBase class can also overload the oncustommand () function to complete some specific operations. By overloading some of the above functions, we have completed the basic framework of a Windows service program, the overloaded methods of 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 us with some properties, and these attributes must be of any Widnows service. The serviceName property specifies the name of the Windows service. You can call Windows service through this name system, while other applications can also call it through this name. As the CanpauseAndContinue and Canstop attributes are to allow suspension and recovery and allowance to stop.

To make a Windows service program can run normally, we need to create a program's entry point for it like to create a general application. In the Windows service, we also completed this operation in the main () function. First we create an instance of a Windows service in the Main () function, which should be an object of a subclass of the ServiceBase class, and then we call a Run () method defined by the base class serviceBase class. However, the Run () method does not start the Windows service program, and we must call a specific control function to complete the startup of the Windows service program through the previously mentioned service control manager, that is, to wait until the ONSTART () method of the object is When the call is called, the service is really started. If you want to start multiple services in a Windows service program, just define instance objects of the subclass of multiple ServiceBae classes in the main () function, the method is to create an array object for a ServiceBase class, so that Each object corresponds to a service we have pre-defined in advance.

{

System.ServiceProcess.serviceBase [] myServices;

MyServices = new system.serviceProcess.serviceBase [] {new service1 (), new service2 ()};

System.ServiceProcess.serviceBase.run (MyServices);

}

Static void main ()

three. Add a file monitoring service:

After understanding the basic architecture of the Windows service and the creation method, we can try to add some actual features to the service. Below I will introduce you to a file monitoring service that monitors the local file system - FileMonitorService. This service can monitor any changes in the subfolder based on the pre-set local directory path: file creation, file deletion, file rename, file modification. At the same time, the service also created a corresponding counter for each change, the role of the counter reflects the frequency of the change.

First, we open the project of Visual Studio.net, new Visual C # Windows service, as shown in Figure 3:

image 3

Before you overStart () functions of the Windows service, we add some counter objects to the class, these counters correspond to changes in the creation, deletion, renumming, and modification of the file. Once the file in the specified directory has some changes above, the counter corresponding to it will be automatically added. All of these counters are variables defined as PerformanceCounter types, which are 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 individual counter objects defined above and determine their related properties in the class's initializecomponent () method. At the same time, we set the name of the Windows service to "FilemonitorService", which is set to be suspended and recovered is to stop.

Private vidinitiRizeComponent ()

{

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.counteaMe = "files change";

FileDeletecounter.countername = "files deleded";

FilerenameCounter.countername = "files renamed";

FilecreateCounter.counterName = "files created";

This.ServiceName = "FilemonitorService";

THIS.CANPAUSEANDCONTINUE = True;

THIS.CANSTOP = true; servicepaused = false;

}

Then, the overstart () function and the onstop () function are overstart () functions completed some necessary initialization. Under the .NET framework, the monitoring function of the file can be done by the FileSystemWatcher class, which is included under System.io namespace. The features to be completed by the Windows service include changes in the creation, deletion, renovation, and modification of the monitoring file, and the FileSystemWatcher class contains all handlers corresponding to these changes.

protected override void onstart (String [] ARGS)

{

FileSystemWatcher Curwatcher = New FileSystemWatcher ();

Curwatcher.beginit ();

Curwatcher.includesubdirectories = true;

Curwatcher.path =

System.configuration.configurationSettings.AppSettings

["FileMonitorDirectory];

Curwatcher.changed = new filesystemEventHandler (onfilechanged);

Curwatcher.created = New FileSystemEventHandler (onfilecreated);

Curwatcher.deleted = New FileSystemEventHandler (onfileeted);

Curwatcher.renamed = new renamedendhandler (onfileres);

Curwatcher.enableraisingevents = true;

Curwatcher.endinit ();

}

Note that the catalog in which the monitored directory is stored in an application configuration file, which is an XML type file. The advantage of this approach is that we don't have to recompile and publish the Windows service and you can achieve the functionality of the directory you want to monitor directly.

When the Windows service is started, once the file in the monitored directory occurs some changes, the value of the counter corresponding to the counter is correspondingly increased, and the method is simple, as long as the INCREMENTBY () of the counter object is invoked.

Private void OnfileChanged (Object Source, FileSystemEventArgs E)

{

IF (servicepaused == false)

{

FileChangeCounter.Incrementby (1);

}

}

Private void ONFileres (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 ONFILETED (Object Source, FileSystemEventArgs E)

{

IF (servicePaused == false) {

FileDeetecounter.Incrementby (1);

}

}

The onStop () function is to stop Windows service. In the Windows service, once the service is stopped, all the values ​​of all counters should be zero, but the counter does not provide a reset () method, so we have to set the value in the counter. Leave the current value to achieve this.

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 (-filerescounter.rawvalue);

}

IF (filecreateCounter.RawValue! = 0)

{

FilecreateCounter.IncrementBy (-filecreatecounter.rawvalue);

}

}

At the same time, because our Windows service is allowed to be suspended and recovered, we have to overload the onpause () function and the onContinue () function, the method is simple, as long as the front defined Boolean servicePaused can be set.

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 also add installation files. The installation file is installed for the correct installation of the Windows service, which includes a installation class for a Windows service, which is the weight of system.configuration.install.installer inherited. The installation class includes the account information, user name, password information, and Windows service name, start mode, and other information.

[Runinstaller (TRUE)]

Public Class Installer1: System.Configuration.install.installer

{

///

/// The required designer variable.

///

Private system.componentmodel.Container Components = NULL;

Private system.serviceProcess.serviceProcessInstaller Spinstaller;

Private system.serviceProcess.serviceInstaller sinstaller;

Public installer1 ()

{

// This call is necessary for the designer.

InitializationComponent ();

// Todo: Add any initialization after INitComponent call

}

#Region Component Designer Generated Code ///

/// Designer supports the required method - do not use the code editor to modify

/// This method is content.

///

Private vidinitiRizeComponent ()

{

Components = new system.componentmodel.container ();

// Create a ServiceProcessInstaller object and ServiceInstaller object

this.spinstaller =

New system.serviceProcess.ServiceProcessInstaller ();

This.sinstaller = new system.serviceProcess.serviceInstaller ();

// Set the account, username 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 of the service

this.sinstaller.startType =

System.ServiceProcess.ServiceStartMode.Automatic;

this.installers.Addrange (

New system.configuration.install.installer []

{this.spinstaller, this.sinstaller});

}

#ndregion

}

Similarly, because the counter object is used in the Windows service, we also have to add the corresponding installation file, the contents and functions of the installation file and the front. It is limited to the space, where the corresponding code is not given, interested readers can refer to the source code file included after the text.

To this end, the entire Windows service has been built, but the Windows service procedure is different from the general application, it cannot be directly commissioned. If you try to debug the run directly under the IDE, the prompt shown in Figure 4 will be reported.

Figure 4

Based on the prompt, we know that the installation of Windows services requires a command line tool called InstallUtil.exe. The way to install the Windows service using this tool is very simple, the command to install the Windows service is as follows:

Installutil FilemonitorService.exe

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

InstallUTIL / U FilemonitorService.exe

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

Figure 5

Thus, the Windows service monitored by the file is complete, once we operate on the files in the monitored directory, the corresponding counter will work, and play a function of monitoring file changes. However, this feature does not make much sense for a general user, but you can add new features on this, such as building a background file processing system. Once a file in the monitored directory, Windows service For specific operations, end users do not have to care about how the background handler is implemented.

four. Summary: This article introduces some of the basic concepts of Windows services and to build a general Windows service, and show you a Windows service program with file monitoring features. Through this article, the reader should experience that the building of Windows services is not as complex, this is mainly due to a large number of efforts to our .NET framework. At the same time, I hope that everyone can build more improved and more powerful Windows service programs on the basis of the instances given here. Finally, I hope this article will have a lot of help to everyone.

(Note: The source code file is

Source.rar)

转载请注明原文地址:https://www.9cbs.com/read-66307.html

New Post(0)