Windows service and service operations in. net

Source: Internet
Author: User
Open vs2008, "File> New> Project", select "Windows Service" in "Windows", and set the path and name as "writetextservice" according to your own situation ", after confirmation, a "if you want to add components to the class, drag them out of the toolbox, and then set their properties in the" properties "window. To create methods and events for a class, click here to switch to the Code view ." To process the business logic, click "switch to Code view" to switch to the code page. Code writetextservice. CS 1 using system;
2 using system. serviceprocess;
3 using system. IO;
4 using system. Threading;
5
6 namespace writetextservicens
7 {
8 public partial class writetextservice: servicebase
9 {
10 public writetextservice ()
11 {
12 InitializeComponent ();
13}
14 protected override void OnStart (string [] args)
15 {
16 Thread t = new Thread (new ThreadStart (DY ));
17 t. Start ();
18}
19 private void DY ()
20 {
21 while (true)
22 {
23 File. WriteAllText (@ "F:/gsw.txt", DateTime. Now. ToString ());
24 Thread. Sleep (2000 );
25}
26}
27 protected override void onstop ()
28 {
29}
30}
31}
32 now, we also need to create a service installation class in the service to complete service initialization and installation. We create a class serviceinstallserviceinstall. CS 1 using system. collections;
2 using system. configuration. Install;
3 using system. serviceprocess;
4 using system. componentmodel;
5 using Microsoft. Win32;
6
7 namespace writetextservicens
8 {
9 [runinstaller (true)]
10 public class ServiceInstall: Installer
11 {
12 private ServiceInstaller WTSerInst; // It is used by the installation utility to write the registry value associated with the service into the subitem In the HKEY_LOCAL_MACHINE \ System \ CurrentControlSet \ Services registry key.
13 private ServiceProcessInstaller WTProInst; // use the installation utility to write the registry value associated with the service to be installed.
14 public ServiceInstall ()
15 {
16 WTProInst = new ServiceProcessInstaller ();
17 WTProInst. Account = ServiceAccount. LocalSystem; // The Account used to install the service
18
19 WTSerInst = new ServiceInstaller ();
20 WTSerInst. StartType = ServiceStartMode. Automatic; // The Post-service startup mode (Automatic, Manual, and Disabled)
21 WTSerInst. ServiceName = "WriteTextService"; // The name of the service to be installed is the same as that of the service class
22
23 Installers. Add (WTSerInst); // Add the service installation class to the installation set
24 installers. Add (wtproinst );
25}
26/** // <summary>
27 // rewrite the parent class installation and write the service description after installing the service
28 /// </Summary>
29 /// <Param name = "statesaver"> </param>
30 public override void Install (IDictionary stateSaver)
31 {
32 RegistryKey system, service, config;
33 try
34 {
35 base. Install (stateSaver );
36 system = Registry. LocalMachine. OpenSubKey ("System"). OpenSubKey ("CurrentControlSet"). OpenSubKey ("Services ");
37 service = system. OpenSubKey (this. WTSerInst. ServiceName, true );
38 service. SetValue ("Description ","...... This is a service that writes Text once per second ...... ");
39 config = service. CreateSubKey ("AdditionalInformation ");
40}
41 catch
42 {}
43}
44/*** // <summary>
45 // rewrite the parent class uninstallation and delete the description after the service is uninstalled.
46 /// </summary>
47 // <param name = "stateServer"> </param>
48 public override void Uninstall (IDictionary stateServer)
49 {
50 RegistryKey system, currentControlSet, services, service;
51 try
52 {
53 system = Microsoft. Win32.Registry. LocalMachine. OpenSubKey ("System ");
54 currentControlSet = system. OpenSubKey ("CurrentControlSet ");
55 services = currentControlSet. OpenSubKey ("Services ");
56 service = services. OpenSubKey (this. WTSerInst. ServiceName, true );
57 service. DeleteSubKeyTree ("AdditionalInformation ");
58}
59 catch
60 {}
61 finally
62 {
63 base. Uninstall (stateServer );
64}
65}
66}
67}
68 in this way, a service is completed with a service description, which is added by rewriting the parent class install and uninstall. Because the service has a description under HKEY_LOCAL_MACHINE/system/CurrentControlSet/services/writetextservice, the description of the service should be added to this item, therefore, the install and uninstall methods are essentially the addition and deletion of registry English. Next, let's take a look at the service operations, that is, load, unload, start, and stop. We create a new web site with only one default. on the ASPX page, the Code is as follows: default. aspx 1 <% @ page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. CS "inherits =" _ default "%>
2
3 <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <HTML xmlns = "http://www.w3.org/1999/xhtml">
6 7 <title> No title page </title>
8 9 <body>
10 <form id = "form1" runat = "server">
11 <div>
12
13 <asp: Button ID = "Button1" runat = "server" Text = "loading service"/>
14 <asp: Button ID = "Button2" runat = "server" Text = "uninstall service"/>
15 <asp: Button ID = "Button3" runat = "server" Text = "Start Service"/>
16 <asp: Button ID = "Button4" runat = "server" Text = "Stop Service"/>
17
18 </div>
19 </form>
20 </body>
21 22 Default. aspx. cs 1 using System;
2 using System. Configuration;
3 using System. Web;
4 using System. Web. Security;
5 using System. Web. UI;
6 using System. Web. UI. HtmlControls;
7 using System. Web. UI. WebControls;
8 using System. Web. UI. WebControls. WebParts;
9 using System. Xml. Linq;
10 using System. Configuration. Install;
11 using System. Collections;
12 using System. ServiceProcess;
13
14
15 public partial class _ Default: System. Web. UI. Page
16 {
17 protected void Page_Load (object sender, EventArgs e)
18 {
19
20}
21 protected void button#click (object sender, EventArgs e)
22 {
23 AssemblyInstaller myassemblyinstaller = new AssemblyInstaller (); // load an assembly and run all the installation programs.
24 myassemblyinstaller. usenewcontext = true;
25 myassemblyinstaller. Path = @ "F:/gsw.exe"; // path of the service
26 hashtable mysavedstate = new hashtable ();
27 myassemblyinstaller. Install (mysavedstate );
28 myassemblyinstaller. Commit (mysavedstate );
29 myassemblyinstaller. Dispose ();
30 Response. Write ("service installation successful ");
31
32}
33 protected void Button2_Click (object sender, EventArgs e)
34 {
35 AssemblyInstaller myassemblyinstaller = new AssemblyInstaller ();
36 myassemblyinstaller. UseNewContext = true;
37 myassemblyinstaller. Path = @ "f:/gsw.exe"; // Path of the service
38 myassemblyinstaller. CommandLine = new string [1] {"/u"}; // uninstall by running the/u command.
39 myassemblyinstaller. Uninstall (null );
40 myassemblyinstaller. Dispose ();
41 Response. Write ("service uninstalled successfully ");
42}
43 protected void Button3_Click (object sender, EventArgs e)
44 {
45 ServiceController SC = new ServiceController (); // indicates a Windows Service and allows you to connect to a running or stopped service, operate on it, or obtain information about it.
46 SC. DisplayName = "Gui suwei ";
47 SC. ServiceName = "WriteTextService ";
48 SC. Start (); // Start the service with this name
49 System. Threading. Thread. Sleep (1000 );
50 SC. Refresh (); // Refresh the service status
51 if (SC. Status = ServiceControllerStatus. Running) // judge whether the service is Running
52 {
53 Response. Write ("service started successfully! ");
54}
55}
56 protected void Button4_Click (object sender, EventArgs e)
57 {
58 ServiceController SC = new ServiceController ();
59 SC. servicename = "writetextservice ";
60 SC. Stop ();
61
62 system. Threading. thread. Sleep (1000 );
63 SC. Refresh (); // refresh the service status
64 if (SC. Status = servicecontrollerstatus. Stopped) // determine whether the service is running
65 {
66 Response. Write ("Service stopped successfully! ");
67}
68}
69}
70 we load and unload services through the AssemblyInstaller class, and start and stop services through the ServiceController class. In this way, we will complete the services and control services. (My code is implemented under vista and vs2008 .)
Related Article

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.