Windows Service Development log (reproduced in csdn)

Source: Internet
Author: User
Windows Service Development log 1 (Windows Service tips and error handling)

Recently, I want to add a QQ robot-like function to the company's system. The chatbot can send related commands (special characters) to the database and return relevant information to the chatbot, because the function is single and requires long-term execution, I think of using the Windows Service for processing, and I can also learn about it. I have recorded all the problems and solutions encountered during development, hoping to help friends who have the same difficulties to deal.

I. Clock problems in Windows Services.

There are two methods to implement scheduled inquiry in the service. One is to use the clock for scheduled execution, and the other is to use the thread. If the clock is used for processing, you should pay attention to it, the controls retrieved from the toolbox are inherited from the class system by default. windows. forms. timer, but such controls will not be executed in the service. If you want to use them in the service, you must inherit from the class system. timers. timer controls,

If you want to keep development in a visual way, you can open the design file corresponding to the service (for example, the service file name is alarmservice, then open alarmservice. desinger. CS. windows. forms. change timer to system. timers. timer (note, there are two changes). After you save the changes, double-click the timer control in the service and you will find that the created events are different, but the events are roughly the same elsewhere.

You can also create with code homomorphic, define a method, and then bind the method to the elapsed event of the object. The Code is as follows:

Timer timer1 = new timer ()

Protected override void onstart (string [] ARGs)
{
Timer1.elapsed + = This. timer1_elapsed; // dynamically binds events.
}

Private void timerincluelapsed (Object sender, system. Timers. elapsedeventargs E)
{
// Omitted in the middle
}

You can.

2. An error occurred while creating the service and starting the service. Tip #1083

Because I have created two services in the same project, but C # is stupid, when I change the name of the service, he will not create a new object for the new service. For example: when I create a Windows service project, the system automatically creates a service named service1. If I rename other files to alarmservice, open program. CS finds that the service object created in it is still service1, which must be manually modified. Otherwise, 1083 will be reported when the service is registered and running. If two or more services are created for the same project, the newly created service system does not create objects for it, but also needs to be manually created in program. added to the CS file. Otherwise, 1083 error will be reported when the service is started.

Syntax:

Servicebase [] servicestorun;
Servicestorun = new servicebase []
{
New amiservice (), new alarmservice () // assume that the two services are named amiservice and alarmservice respectively.
};
Servicebase. Run (servicestorun );

Windows Service Development log 2 (installation and debugging)

To run this service, we need to perform the following steps:

1. add installer for our service, right-click design view, and select add installer. Vs will add projectinstaller for us. CS, and add components serviceinstaller1 and serviceprocessinstaller1 to projectinstaller. Now let's modify their attributes to control service installation and startup options. In the project installer design view, select serviceprocessinstaller1 and select the account attribute as LocalSystem to start the account service. If you want the service to be automatically started when the system starts, select the starttype attribute of serviceinstaller1 as automatic. If it is manually started, select manaul.

 

2. Install the serviceprogram intallutil.exe, which is located in c: \ windows \ Microsoft. NET \ framework \ v2.0.50727. Click the Start menu and select "run". In the run dialog box, Enter cmd to enter the command line window, and enter CD: \ windows \ Microsoft. net \ framework \ v2.0.50727, enter this directory, and then enter installutil F: \ Programs \ C # \ testservice \ bin \ debug \ testserveice.exe, the content behind installutil is the path of the executable program generated by our project, which can be modified as needed.

If you set starttype of serviceinstaller1 to automatic, the service is running after the service is installed. If starttype is manual, you need to start it manually. Now, go to "service". To open "service", click "start", point to "Settings", and click "Control Panel ". Click "performance and maintenance" and "Management Tools", and then double-click "service ". You should be able to see our service myfirstservice. Here, we can start, shut down the service, and set the Service Startup type. Then, let's see if the service has correctly written logs. We need to go to the Event Viewer. To open the Event Viewer, click Start and point to settings ", click control panel ". Click performance and maintenance, click management tools, and double-click event viewer ". As shown in, our message has been successfully written to the system log.

 

3. if you do not need this service, you still use the installutil program to uninstall it. However, after installutil, it is followed by the parameter-u, such as installutil-u F: \ Programs \ C # \ testservice \ bin \ debug \ testserveice.exe.

 

The service debugging method is different from the common program debugging method. Let me introduce it.
1. Build your project

 

2. Set breakpoints because our service is very simple and there is no execution logic. Therefore, it makes no sense to set breakpoints. You can write some code for practice. In general, we need another thread to execute the task in our service. You need to set the breakpoint in the thread's Execution Code.

 

3. Install the service. We will introduce how to install the service.

 

4. If your service start type is manual, you need to start your service in "service. In general, if your service is in the development stage, I recommend that you set the Service Startup type to manual to facilitate debugging, because if the service is running, you will not be able to build the project.

 

5. In vs, select debug-> attach process... from the menu ...., :

 

The running processes are listed in. If you cannot find your service, select Show processes from all users. In the available processes list, select the process testservice where our service is located, and click attach. If the breakpoint you set is reasonable, the program stops at the breakpoint, next you can perform debugging. ,

Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. diagnostics;
Using system. serviceprocess;
Using system. text;

Namespace testservice
{
Public partial class myfirstservice: servicebase
{
Public myfirstservice ()
{
Initializecomponent ();
}

Protected override void onstart (string [] ARGs)
{
// Todo: Add code here to start your service.
Eventlog1.writeentry ("service start ");
}

Protected override void onstop ()
{
// Todo: Add code here to perform any tear-down necessary to stop your service.
Eventlog1.writeentry ("service stop ");
}
}
}

Windows Service Development log 3 (create an installation package)

Windows service cannot be run by double-clicking it. It requires an installation class to assist. Next we need to add an installation helper class for this service.
Right-click the project name and add a new project. Selecting installer class. Vs will automatically create an installation class for us.
In fact, you can also add a new class and make it inherit from system. configuration. install. installer. therefore, in fact, using C # To write an installation class is to write a step

Class from installer.
Speaking of this, you can try to create a Windows service class and an install class on your own, but we recommend that you create a visual Studio for you, because in addition to a clear hierarchy, you will also get a lot

The automatically generated code segment, for example, the rewritten dispose method.
To install the Windows service class, you first need a service installation process and then install services in the process. Therefore, we need to create these two classes in this installation class.
This. serviceprocessinstaller1 = new system. serviceprocess. serviceprocessinstaller ();
This. serviceinstaller1 = new system. serviceprocess. serviceinstaller ();
You can think like this: serviceinstaller is responsible for installing Windows service, while serviceprocessinstaller is a layer wrapped outside.
This. serviceprocessinstaller1.account = system. serviceprocess. serviceaccount. LocalSystem;
This. serviceprocessinstaller1.password = NULL;
This. serviceprocessinstaller1.username = NULL;
This is used to set the permissions for installation. Generally, if you select a local system account, you do not need the user name and password.
This. serviceinstaller1.servicename = "notus ";
This. serviceinstaller1.description = "a sample ";

Serviceinstaller1.starttype = servicestartmode. Automatic;
Serviceinstaller sets parameters related to the service, such as the startup method, name, and description.
The servicename here must be the same as the name of the Windows service you wrote earlier. Otherwise, the problem may occur.
If you want to do something before and after installation, you need to enter the event operation. serviceinstaller provides some events for you to use during installation, such as the following:
Serviceinstaller1.beforeuninstall + = new system. configuration. Install. installeventhandler (serviceinstaller=beforeuninstall );
We can add code to this event to ensure that the service is stopped when you delete the service. (If the service is running and you want to delete it, a problem will occur)
Void serviceinstallerpolicbeforeuninstall (Object sender, system. configuration. Install. installeventargs E)
{
Servicecontroller con = new servicecontroller (serviceinstaller1.servicename );
If (con. Status = servicecontrollerstatus. Running | con. Status = servicecontrollerstatus. startpending)
{
Con. Stop ();
}
}
Note that if you want to use those environment variables, You need to obtain them using the following method:
This. serviceprocessinstaller1.context. Parameters ["Surl"];
This installation class is a little troublesome, because three classes with install appear, and it should look like this at last:
[Runinstaller (true)]

Public partial class projectinstaller: Installer

{
This. serviceprocessinstaller1 = new system. serviceprocess. serviceprocessinstaller ();
This. serviceinstaller1 = new system. serviceprocess. serviceinstaller ();
//......
}
In this way, complete your installation class.

In this way, the work is basically completed. if you use vs to automatically add these two classes, it may be a little confusing, because clicking View code and clicking in it will show many classes with the same name, and then

Some inherit the base class, some do not inherit, and some reference something... in fact, let's take a look at it quietly. These classes are all partial, that is, local classes. Do not get dizzy by.

2. Install Widnows Service

Vs Command Prompt

One is to use commands at the vs command prompt (note that it is not the one typed by CMD, but the one in the vs installation directory of the Start Menu ).
Use this to install installutil myservice1.exe
Delete installutil/u myservice1.exe
Of course, you must first locate the folder where myservice1.exe is located before running.

Windows Installation Project

You can also use the installation program creation function provided by Vs to add your project to the main output for installation.
Create a new peject and select setup project in other categories. Vs will create an installation project for you.
Right-click the project name, add, peojet output (output), and add your service project. right-click the project name, view, and m action, and you will see four categories:

Is install, commit, rollback, uninstall, right-click on the top, add custom action, and then find your service project in application folder and add it.
So (...), complete.
Compile, run, and check the effect. If no exception occurs, you can find your service in the "service" Window of the control panel.

Windows Service Development log 4 (use a program to set the service running status and startup mode)

When a service is developed, you always need to develop a setting interface to enable or stop the service.

There are two ways to start a service:

1. Manual run: manual run. You must start the service manually every time. After the service is enabled, the service will be stopped once the computer is restarted.

2. automatic Running: when the service is set to be installed automatically, the service will not be automatically started after installation (whether automatic or manual, the status will be stopped after the service is installed ), however, after the service is restarted, the service is automatically started. Even if the service is stopped, the service will run automatically after the computer is restarted.

Due to development needs, my setup program needs to implement several functions:

1. You can enable or stop the service.

2. If you select enable, set the Startup Type to automatic.

3. if you select stop, set the start type to manual to avoid automatic execution after restart.

This is why I wrote this chapter.

1. In fact, it is not difficult to implement these functions, but it is difficult to provide less relevant information.

First, let's talk about setting the service running status:

You can use serviceprocess. servicecontroller of C #. The following is the implementation code.

View plaincopy to clipboardprint?
Using system. serviceprocess;
Servicecontroller alarmcon = new servicecontroller ("alarmservice ");
// Obtain the service object to be controlled

If (alarmcon. Status = servicecontrollerstatus. Running)
{
Butalstart. Enabled = false;
Butalstop. Enabled = true;
}
Else
{
Butalstart. Enabled = true;
Butalstop. Enabled = false;
}
Using system. serviceprocess;
Servicecontroller alarmcon = new servicecontroller ("alarmservice ");
// Obtain the service object to be controlled

If (alarmcon. Status = servicecontrollerstatus. Running)
{
Butalstart. Enabled = false;
Butalstop. Enabled = true;
}
Else
{
Butalstart. Enabled = true;
Butalstop. Enabled = false;
}
 

You only need to set the running status as follows:

View plaincopy to clipboardprint?
Alarmcon. Start ();
Alarmcon. waitforstatus (servicecontrollerstatus. Running );
// Wait until the service status becomes effective before executing
Getalarmservicestate ();
Alarmcon. Start ();
Alarmcon. waitforstatus (servicecontrollerstatus. Running );
// Wait until the service status becomes effective before executing
Getalarmservicestate ();

2. How to change the Service Startup Mode? It was originally implemented by modifying the registry.

View plaincopy to clipboardprint?
Using Microsoft. Win32;
String keypath = @ "SYSTEM \ CurrentControlSet \ Services \ alarmservice ";
Registrykey key = registry. localmachine. opensubkey (keypath, true );
Key. setvalue ("START", 2 );
// 2: automatic start; 3: Manual start; 4: Disabled

 

 

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.