Develop Windows Services on the. Net platform

Source: Internet
Author: User

Windows service is another form of C/S program. The windows Service developed in. NET is the same as other services in the system.

First, we will introduce two important Windows Service classes (Class A) and install program classes (Class B ). There are two components in Class B: serviceInstaller1 and serviceProcessInstaller1. They are the objects of System. ServiceProcess. ServiceInstaller and System. ServiceProcess. ServiceProcessInstaller respectively. So what are the differences between them? MSDN provides the following explanations:

ServiceProcessInstaller: installs an executable file that contains the class that extends ServiceBase. This class is called by the installation utility (such as InstallUtil.exe) when installing the service application. ServiceProcessInstaller performs public operations on all services in the executable file. The installation utility uses it to write the registry value associated with the service to be installed.

To install the service, create a project Installer class inherited from the Installer, and set RunInstallerAttribute on the class to true. In a project, instantiate a ServiceProcessInstaller instance for each service application and instantiate a ServiceInstaller instance for each service in the application. Finally, add the ServiceProcessInstaller instance and ServiceInstaller instance to the project installer class.

When InstallUtil.exe is running, the utility searches for classes in the service assembly that RunInstallerAttribute is set to true. Add a class to the service assembly by adding the class to the Installers collection associated with the project installer. If RunInstallerAttribute is false, the installation utility ignores the project installer.

For ServiceProcessInstaller instances, attributes that can be modified include that the specified service application runs under an account other than the logged-on user. You can specify the specific UserName and Password pair used to run the service, or use an Account to specify whether the service runs under the system Account, local or network service Account, or user Account of the computer. (Note: The "system" Account of the computer is different from the "Administrator" account .)

ServiceInstaller: Installs a class that extends ServiceBase to implement services. This class is called by the installation utility when the service application is installed. ServiceInstaller performs operations specific to the services it is associated. It is used by the installation utility to write the registry value associated with the service to the subitem In the HKEY_LOCAL_MACHINE \ System \ CurrentControlSet \ Services registry key. The service is identified by the service name (ServiceName) in the subkey. The sub-key also contains the name of the executable file or. dll to which the service belongs.

For more information, see MSDN.

The following describes the implementation process of the service.

1. windows service projects cannot be directly created on the. NET 2.0 platform. To develop a windows Service on the. NET 2.0 platform, you need to build your own project, and then add the Installer. cs and window Service. cs ). Then, write the code in the installer file and the window service file respectively.

Environment Description:. NET2.0 SP2. (I cannot directly create it on my computer, but my colleague can directly create Windows Services on my computer. I don't know what the difference between the two SP2 instances is. But his version should be higher than mine)

The process is as follows:

1. create a project (the Winfrom project that I created directly during development), right-click the project, and select add Installer. cs) and window Service (Service. cs) are added to the project respectively. For example:

  

2. using System. ServiceProcess namespace in Service. cs.

ServiceInstaller installer = new ServiceInstaller ();
// Set the service name
Installer. ServiceName = "TestDemo ";

// Set the Service Startup type. The startup method set below is Automatic startup.
Installer. StartType = ServiceStartMode. Automatic;

// Set the service description
Installer. Description = "Test Service ";

 

// Declare the service installation object (when the Installation tool is used, it will be called by the tool to complete service installation)

ServiceProcessInstaller processer = new ServiceProcessInstaller ();

// Set the service account. The following is the local system
Processer. Account = ServiceAccount. LocalSystem;

// Add the installation service instance and the installation processing object to the set of installation programs.
Installers. Add (installer );
Installers. Add (processer );

3. Compile the code when the service is started and the service is stopped in the following methods:

 

Protected override void OnStart (string [] args)
{

}

 

Protected override void OnStop ()
{
}

4. Change the entry function (main function) in program. cs to ServiceBase. Run (new Service1 ())

5.generate the. exe file

2. In. to develop windows Services on the NET3.5 platform, you can directly create a project and press a window Service project, which has a Service. cs file. You can add an installer for it to complete the development of windows Services.

Environment:. NET3.5SP2.

1. Right-click Service1.cs to view the designer. Then, right-click the designer and choose add installer from the menu. The system will add the installer file ProjectInstall. cs for this service (default name, you can also modify it ).

2. In the same way, right-click ProjectInstall. cs and select View designer. By default, his design involves two files: ServiceProcessInstaller1 and ServiceInstaller1.cs.

3. Set the attributes of ServiceProcessInstaller1 and ServiceInstaller1.cs. Set the Account of ServiceProcessInstaller1 to LocalSystem. You can also set it to another one. If you set it to User, you need to set service LOGIN during service installation. In my example, the ServiceProcessInstaller1 attribute is set as follows:

    

The attribute settings of ServiceInstaller1.cs are as follows:

The property settings are the same as those of the installer property settings in the preceding example on the 2.0 platform. It is only set through attributes and through code.

3. Compile the functions implemented by the Service. The following is a service test function: Write the current time to the specified text every second.

 

System. Timers. Timer timer;
Public Service1 ()
{
InitializeComponent ();
This. ServiceName = "TestDemo ";
}

 

Protected override void OnStart (string [] args)
{
Timer = new System. Timers. Timer (1000 );
Timer. Elapsed + = new System. Timers. ElapsedEventHandler (timer_Elapsed );
Timer. AutoReset = true;
Try
{
Timer. Start ();
}
Catch (ArgumentOutOfRangeException Ex)
{
Throw Ex;
}
}

Protected override void OnStop ()
{
Timer. Stop ();
Timer = null;
}

Private void timer_Elapsed (object obj, EventArgs args)
{
Using (FileStream fs = new FileStream (@ "D: \ test.txt", FileMode. Append, FileAccess. Write ))
{
Using (StreamWriter sw = new StreamWriter (fs ))
{
Sw. WriteLine (DateTime. Now. ToString ());
}
}

}

4. compile the project and generate the Installation File

3. Install the service.

The installation of windows Services on platform 2.0 and platform 3.5 is completed through the installutil tool. The usage is as follows:

1. Open the command prompt under VS2008.

2. Enter installutil D: \ Visual2008 \ WindowsService \ WindowsService1 \ WindowsService1 \ bin \ Release \ WindowsService1.exe to install the service. After the installation is successful, the command interface is too large. Successfully installed services

It can be found in computer services. As follows:

 

3. Uninstall the service: Enter installutil/u D: \ Visual2008 \ WindowsService \ WindowsService1 \ WindowsService1 \ bin \ Release \ WindowsService1.exe to uninstall the service. If the service is running at this time, it can also be uninstalled (it will first try to close the service and then uninstall ). For example:

After doing this, you can see the time record of each second in D: \ test.txt.

I wrote it here, hoping to help the developers!

Note: When you use the installutil tool to install the service, if there is a space in the path, the installation will report an error.

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.