Reference: Create a Windows Server with Visual C #
http://www.vchome.net/dotnet/dotnetdocs/dotnet38.htm
Note that the user selected in the installation class is Localsystem
-------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------
Create a Windows Server with Visual C #
One. Windows service introduction: Windows service is previously referred to as NT service, which is some programs running 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. For manual start-up Windows service, you can launch it through the NET Start command of the command line, or start the corresponding Windows service program (see Figure 1) by the service one of the management tools 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. Create a Windows Server: Before you introduce how to create a Windows service, I will introduce you to the namespace related to the Windows service under the .NET framework 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 Where the ServiceBase class defines a function that can be overloaded by its subclass, 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 Visual Studio.NET, newly built a Visual C # Windows service project, as shown in Figure 3: Figure 3 Before we overrunning the onstart () function of the Windows service, we add some counter objects to the class first, these The 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 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" FILECREATECUNTER.CATEGORYNAME = "File Monitor Service"; filechangecounter.counteaMe = "files change"; fileDeletecounter.couname = "files deleted"; filerenamecounter.couname = "Files Renamed"; fileCreateCounter.CounterName = "Files Created"; this.ServiceName = "FileMonitorService"; this.CanPauseAndContinue = true; this.CanStop = true; servicePaused = false;} is then reload the OnStart () function and OnStop () Functions, the onstart () function has completed some necessary initialization work. 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.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 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 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) {filedele TECUNTER.INCREMENTBY (1);}} OnStop () function is to stop Windows service, in which service is stopped, all counter values should be zero, but the counter does not provide a reset () method So we have to reduce the values in the counter to this purpose.
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 service is Windows Allow pause and recovery, so we have to overload the onpause () function and the onContinue () function, the method is simple, just set the Boolean servicePaused of the previously defined.
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] public class installer1: system.configuration.install.installer {///
/// summary> private void InitializeComponent () {components = new System.ComponentModel.Container (); // Create ServiceProcessInstaller ServiceInstaller objects and objects this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller (); this.sInstaller = new System.ServiceProcess.ServiceInstaller (); // set ServiceProcessInstaller target account information, user name and password this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.spInstaller.Username = null; this.spInstaller.Password = NULL; // Setting the service name this.sinstaller.ServiceName = "filemonitorservice"; // Setting the service startup method this.sinstaller.StartType = system.serviceProcess.ServiceStartMode.automatic; this.installers .Addrange (new system.configuration.install.installer [] {this.spinstaller, this.sinstaller});} #ENDREGON} is also because the counter object is used in the Windows service, we also have to add a corresponding installation file for it. The content and role of the installation file are similar to the previous. 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 According to the prompt, we know that the Windows service needs to be used to use 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, the Windows service monitored by the file is completed, once we operate on the files in the monitored directory, the corresponding counter will work to monitor 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: Source code file is source.rar)