Windows Service Development Learning, windows Service Development

Source: Internet
Author: User

Windows Service Development Learning, windows Service Development

I. What is the window service?

 

When you click Start, Run the services. msc command. The following window is displayed. It displays the services that come with the system or third-party software installed in the current operating system. The service status includes the name, description, startup status, and Startup type. You can also manage related services in this form. Be careful when performing operations to prevent system errors or software faults.

Here, we want to give you an overall understanding of the Code projects used later. The entire project has the following items:

1. ServerForm: A WinForm program called for the MyService test of window service (only one is always displayed, unless the previous ServerForm is closed ).

2. CreateWSSetup: a Console program that serves MyService for window

Generate installation and uninstall scripts. It is also called in MyServiceSetup of the service installation package. The input parameter install identifies the installation and startup of the service. unstall indicates that the service is stopped and uninstalled.

3. MyService: the focus of today is a Window service program.

4. MyServiceSetup: A Window service installation package program. Supports the installation, start, stop, and uninstallation of Window service MyService.

 

 

Ii. How to develop the Window service

 

Here, we will briefly introduce the development of the Window service from the perspective of C #. NET development.

1. Create a Window service project.

 

2. Compile the main MyService code

The MyService class inherits the service base class ServiceBase encapsulated by Microsoft.

Public partial class MyService: ServiceBase

Service OnStart (string [] args), you can choose whether to include input parameters to execute the service.

 

// Start the service

Protected override void OnStart (string [] args)

{

// Add code here to start the service

Timer. Enabled = true;

}

 

Service stop OnStopt ()

// Stop the service

Protected override void OnStop ()

{

// Add code here to stop the service.

Timer. Enabled = false;

System. Diagnostics. Process [] myproc = System. Diagnostics. Process. GetProcessesByName ("ServerForm ");

If (myproc! = Null & myproc. Length> 0)

{

Int n = myproc. Length;

For (int I = 0; I <n; I ++)

{

Myproc [I]. Kill ();

}

}

}

 

This is a custom function. The third-party program page is displayed on a scheduled basis. ServerForm is another C #. NET WinForm program. We put it in

Under MyService \ Bin \ Debug.

 

// Scheduled execution

Private void timer_Elapsed (object sender, System. Timers. ElapsedEventArgs e)

{

System. Diagnostics. Process [] myproc = System. Diagnostics. Process. GetProcessesByName ("ServerForm ");

If (myproc = null | myproc. Length = 0)

{

// Control Program, executed in a single example

System. Diagnostics. Process. Start (AppDomain. CurrentDomain. BaseDirectory + "ServerForm.exe ");

}

}

 

Finally, let's take a look at the complete MyService code.

Public partial class MyService: ServiceBase

{

Private static System. Timers. Timer timer = null;

// Service structure

Public MyService ()

{

InitializeComponent ();

If (timer = null)

{

Timer = new System. Timers. Timer ();

Timer. Enabled = true;

Timer. Interval = 10000; // 10 seconds

Timer. Elapsed + = new System. Timers. ElapsedEventHandler (this. timer_Elapsed );

This. ServiceName = "MyService ";

}

}

// Start the service

Protected override void OnStart (string [] args)

{

// Add code here to start the service

Timer. Enabled = true;

}

// Stop the service

Protected override void OnStop ()

{

// Add code here to stop the service.

Timer. Enabled = false;

System. Diagnostics. Process [] myproc = System. Diagnostics. Process. GetProcessesByName ("ServerForm ");

If (myproc! = Null & myproc. Length> 0)

{

Int n = myproc. Length;

For (int I = 0; I <n; I ++)

{

Myproc [I]. Kill ();

}

}

}

// Scheduled execution

Private void timer_Elapsed (object sender, System. Timers. ElapsedEventArgs e)

{

System. Diagnostics. Process [] myproc = System. Diagnostics. Process. GetProcessesByName ("ServerForm ");

If (myproc = null | myproc. Length = 0)

{

// Control Program, executed in a single example

System. Diagnostics. Process. Start (AppDomain. CurrentDomain. BaseDirectory + "ServerForm.exe ");

}

}

}

Configure the Install Component of the service. After we write a MyService. cs service, it cannot be directly installed and registered. We also need to configure Install components for it. The procedure is as follows:

Step 1: select the service MyService. cs and double-click the mouse. On the left side of VS2008, The MyService. cs [design] * tab is displayed.

 

Step 2: On the "MyService. cs [design] * tab", right-click the option "add installer ".

After "add installer" is executed, the following files and components are added to the project.

 

Step 3: Set the properties of the installation service

1. Set the main attributes of serviceInstaller1.

StartType: AutoMatic and Manual. Disabled is Disabled.

ServiceName: service system identifier,

Run the sr start/stop/query command in the cmd command to uniquely identify a Window service.

 

2. Set the main attributes of serviceProcessInstaller1.

Accout: Account type. LocalService is a local running service, NetworkService is a network-based running service, LocalSystem is a local system service, and User is a User-Authenticated Service.

 

3. Set "allow interaction with the desktop" after the service is installed ",

Add the following code to ProjectInstaller. cs.

Namespace MyService

{

[RunInstaller (true)]

Public partial class ProjectInstaller: Installer

{

Public ProjectInstaller ()

{

InitializeComponent ();

}

Protected override void OnAfterInstall (IDictionary savedState)

{

Try

{

Base. OnAfterInstall (savedState );

// Allows service desktop Interaction

System. Management. ManagementObject myService = new System. Management. ManagementObject (string. Format ("Win32_Service.Name = '{0}'", this. serviceInstaller1.ServiceName ));

System. Management. ManagementBaseObject changeMethod = myService. GetMethodParameters ("Change ");

ChangeMethod ["Publish topinteract"] = true;

System. Management. ManagementBaseObject OutParam = myService. InvokeMethod ("Change", changeMethod, null );

}

Catch (Exception ex)

{

}

}

}

}

 

3. Install and uninstall Windows Services

 

Note: before you install or uninstall the service, copy the files required by the Service to C: \ MyService \ or another path. Once the installation is complete, the directory cannot be changed; otherwise, an error is returned when the service and service cannot be uninstalled.

Method 1: cmd command

Click Start and run the cmd command. In the displayed cmd window, install or uninstall the service.

1. Install the service: sr start is the startup service.

The basic commands are as follows:

% Systemroot % \ microsoft.net \ framework \ v2.0.50727 \ installUtil.exe C: \ MyService \ MyService.exe

SC start "TaskWS"

Step 1: Install the MyServie service, for example:

Run the installation command to display the result message of installing and registering the Service, as shown in.

 

Step 2: for example, if the result shows that the service is successfully installed, go to the Service Management page and check whether the service appears. As shown in.

Step 3: start MyService: run the SC start "MyService" command.

 

2. Uninstall the service

SC stop "MyService"

% Systemroot % \ microsoft.net \ framework \ v2.0.50727 \ installUtil.exe/u C: \ MyService \ MyService.exe

The procedure is similar to the procedure for installing the service.

 

Method 2: bat file mode:

The principle is method 1. Just put the commands for installing and uninstalling the service in installWS. bat and unstallWS. bat. The createwssetup.exe tool can be used to generate a bat file for installation and uninstallation of the Window service.

 

Method 3: Package the service program into an installation package

Note: The supervisor generates the service installation script and uninstall script, and runs the installation and start service according to the input parameter intall. The unstall command stops and uninstalls the service.

Implementation principle: select the installation project, add the project to output the MyService, and add the behavior in the View:

Install: The createwssetup.exe output from the Export Project, and the parameter is install.

Uninstall: The createwssetup.exe output from the export project. The parameter is unstall.

Step 1: add the project output, and add the MyServie and CreateWSSetup project output.

Step 2: add operation behavior: Add installation and uninstall Operation Behavior

Add a custom Installation Behavior: select the project output CreateWSSetup and set the parameter install.

Next, set the "install" attribute: Arguments (install, which is defined by yourself, depending on the program you write) and InstallClass (optional, because CreateWSSetup. cs is not an InstallClass ).

Add and unmount a custom behavior: select the project output CreateWSSetup and set the parameter unstall. The operation screen is the same as the custom behavior of the installation.

Step 3: select the installation project MyServiceSetup and execute "regenerate" to obtain the package for installing and uninstalling Window service MyService under Bin \ Debug.

 

4. How to debug the Window service

 

First install the service, and then the rest will be the same as debugging for common programs.

Note that the installation path should be the service program exe file under Bin \ Debug \ where the program is located.

 

V. Use Value of the Window service

 

1. Create scheduled tasks.

2. Create a server monitoring program.

3. Public Application access interfaces.

4. other purposes.

 

Vi. Window service use drills

 

When myserviceservice is released, you can also write a form1.exe program into the service. For example, query existing services on the server. Or restart the database or IIS.

 

Others:

1. Install the service:
Method 1: (Multiple service instances can be installed)
SC create "MyService_PRD" binPath = "H: \ Program Files \ MyServiceSetup \ MyService"
SC start "MyService_PRD"
---- Generate Service 1: MyService_PRD
--
SC create "MyService_DEV" binPath = "H: \ Program Files \ MyServiceSetup \ MyService"
SC start "MyService_DEV"
---- Generate Service 2: MyService_DEV
 
Method 2: (you cannot install multiple service instances)
% Systemroot % \ microsoft.net \ framework \ v2.0.50727 \ installUtil.exe "H: \ Program Files \ MyServiceSetup \ MyService.exe"
SC start "MyService"

2. Uninstall the service
Method 1:
SC delete "MyService_PRD"

Method 2:
SC stop "MyService"
% Systemroot % \ microsoft.net \ framework \ v2.0.50727 \ installUtil.exe/u "H: \ Program Files \ MyServiceSetup \ MyService.exe"

 

Postscript:

The modified project is already in Window XP \ Window Server 2003, and the installation package runs correctly. However, in Window Server 2008, a system warning Window is displayed, "services support desktop interaction, but the system is not configured to allow: services allow interaction with desktops ", if you know the solution, tell me. Thank you.

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.