Compile the window service program

Source: Internet
Author: User

Compile the window serviceProgram 

1. Intuitive understanding of Windows Services.

Open Windows Control Panel, administrative tools, and services. The Windows Service list is displayed.

Double-click a service to display and change service properties. In this dialog box, you can control the start, pause, and stop of the service. You can also configure the Service Startup type to enable the service when the system starts. Therefore, Windows Services often run as servers. On the fault recovery attribute page, you can configure the system after the service fails. Some virus programs are done hereArticleTo activate the virus program.

Ii. Windows Service Development highlights

In the random document of Visual Studio, the development steps of Windows service programs are described in detail, and examples are provided. I will not repeat them here. Readers only need to pay attention to the following points:

1. Create an entry class derived from servicebase. This entry class manages the lifetime of this Windows service.

Public class myservice: system. serviceprocess. servicebase {...... }

2. In the main method of the entry class, register the service with the Service Control Manager (SCM) of windows,Code:...... System. serviceprocess. servicebase [] servicestorun;

Servicestorun = new system. serviceprocess. servicebase [] {New myservice ()};

System. serviceprocess. servicebase. Run (servicestorun );......

3. Rewrite the onstart, onstop, or onpause and oncontinue methods to respond to service status changes. Generally, you need to override the onstart method, release resources in the onstop method when the service is terminated, and rewrite the onpause and oncontinue methods as appropriate.

4. For Windows Services, a timer is usually started to periodically or poll for business processing.

5. Windows Services must be installed before they can be used. Install the Windows service in two ways: Run installutil.exe in the command line; Add the projectinstraller class instance to the code of the Windows Service Program, which contains the serviceprocessinstaller class and serviceinstaller class instances.

The above two methods are described in the framework's random document and will not be repeated here.

6. Windows Services run in Service Control Manager (SCM) of windows. Therefore, debugging is not as simple as other Visual Studio applications. For debugging Windows Services, we will introduce them in the random document of Visual Studio.

Iii. Windows Service Exception Handling

Windows Services have no user interface, so it is difficult to notify users of exceptions during running. Generally, an exception occurs during the running of a Windows Service, which may cause the service to be suspended, but there is no reminder.

We recommend that you capture exceptions in Windows Services and write the exception information in Windows event logs. Open "control panel, administrative tools, and Event Viewer" in windows, and the system displays Windows event logs.

In a practical application, the author not only records exceptions and prompts In the event log, but also automatically sends serious errors to relevant personnel by email. At the same time, all information recorded in the event log is also redirected to a self-developed console program to monitor the service at any time.

Iii. Key points and skills for developing Windows Event Logs

In the random document of Visual Studio, I will not go into details about how to add Event Logs to Windows Services while introducing the development steps of Windows service programs. Development points are as follows: 1. Create the EventLog instance EventLog in the class to write logs, and add the code to the constructor:

If (! System. Diagnostics. EventLog. sourceexists ("mysource ")){

System. Diagnostics. EventLog. createeventsource ("mysource", "myeventlog ");}

EventLog. Source = "mysource ";

EventLog. log = "myeventlog ";

2. Write logs where Event Logs need to be written, for example:

Protected override void onstop (){

EventLog. writeentry ("in onstop .");

}

You can try the following skills in practical applications.

1. encapsulate the code for writing Windows event logs into independent classes, so that Windows Event Logs can be used not only in Windows Services, but also in other business codes. See the attachment for the code.

2. To facilitate debugging and tracking, visual sdudio provides a trace class. In the debug compilation version of the application, you can use the trace class to write debugging and tracing information to the console. There is a trick to write the content written into the trace to the Windows event log at the same time. Key points are as follows:

First, declare an event listening class eventlogtracelistener instance,

Static private eventlogtracelistener ctracelistener = new eventlogtracelistener (m_eventlog );

Add the eventlogtracelistener instance to the trace listening list:

Trace. listeners. Add (ctracelistener );

After that, all debugging information written into the trace is written into the Windows event log. If you do not want to write the trace into the event log, run the following code:

Trace. listeners. Remove (ctracelistener );

3. Write Event Log information. You can also write display controls in other application forms.

First, open the design view of the form, select EventLog from the Toolbox/component, and add the form to configure the enableraisingevents attribute of EventLog to true.

Add the entrywritten event processing method of EventLog. The second parameter class behavior of this event is system. diagnostics. entrywritteneventargs, which contains the necessary content in the Windows event log entry, and displays the content in a display control in the form. The sample code is as follows:

/// <Summary> /// listen to Event Logs /// </Summary>

/// <Param name = "sender"> </param> ///

<Param name = "E"> </param>

Private void eventlog_entrywritten (Object sender, system. Diagnostics. entrywritteneventargs e ){

Try {

// Write the log content to the list control named listeventlog

Listeventlog. Items. insert (0, E. Entry. timewritten + "" + E. Entry. Message );

// The list control saves logs of no more than 500 rows

While (listeventlog. Items. Count> 500)

{

Listeventlog. Items. removeat (listeventlog. Items. Count-1 );

}

}

Catch (exception ex)

{

MessageBox. Show (ex. Message );

}}

4. Communication with Windows Services

Applications or other services can communicate with Windows Services, including:

Manage the life cycle of Windows Services, that is, enabling, stopping, suspending, and restarting services;

Obtain the properties and status of the Windows service;

Obtain the service list on a specific computer;

Send commands to a specific service.

These operations are completed through the servicecontroller class. Servicecontroller is a visual control that can be found in the toolbox.

What is interesting is the executecommand method in servicecontroller. by calling this method, you can send commands to the Windows service to command some operations of the Windows service. For example, there is an oncustomcommand () method in the entry class of the Windows Service:

/// <Summary> /// execute the custom message /// </Summary>

/// <Param name = "command"> message id </param>

Protected override void oncustomcommand (INT command)

{

Try

{

Switch (command)

{

Case 1: // business operations

Dobusiness1 ();

Break;

Case 2: // Business Operation

Dobusiness2 ();

Break;

Default:

...... Break;

}

}

Catch (exception ex)

{// Error message

String strerrormsg = string. Format ("exception: {0} \ n", Ex. Message );

// Write logs

Tlineeventlog. dowriteeventlog (strerrormsg, eventtype. Error );

// Send an email to the Administrator

CMail. Sendmail (propertymanager. strmailfromaddress, propertymanager. strmailadminaddress, "", "error message", strerrormsg );

// Write trace

Trace. writeline (strerrormsg );

}

}

In another application, use the executecommand () method of servicecontroller to send commands to this Windows Service:

Mycontroller.exe cutecommand (2 );

Windows Service will execute the business method: dobusiness2 ();

It should be admitted that the function of using servicecontroller to communicate with Windows Services is still very weak. Executecommand can only communicate with Windows Services in a simple and limited manner.

In practical applications, I use a command line program, a console program, and a WebService to communicate with a Windows Service, start or stop the service, or use executecommand to control the service behavior.

Attachment: common classes for manipulating Windows event logs: using system; using system. diagnostics; using system. configuration; namespace mycommon. EventLog {public Enum eventtype {error, information, warning}

/// <Summary> ///// </Summary>

Public class tlineeventlog {

// Task log

Static private EventLog m_eventlog = new EventLog (); // source name, read from the configuration file

Static private string m_streventsource = configurationsettings. deleettings ["f_eventlog.source"]. tostring (). Trim ();

// Log name, read from the configuration file

Static private string m_streventlog = configurationsettings. deleettings ["f_eventlog.log"]. tostring (). Trim ();

// Write debugging information into logs

Static private eventlogtracelistener ctracelistener = new eventlogtracelistener (m_eventlog );

// Default constructor. When the configuration file fails to be read, provide the default source name and log name

Public tlineeventlog (){

If (m_streventsource.length = 0)

M_streventsource = "mysource ";

If (m_streventlog.length = 0)

M_streventlog = "mylog ";

M_eventlog.source = m_streventsource;

M_eventlog.log = m_streventlog;

}

// Constructor. Provide the source name and log name.

Public tlineeventlog (string streventsource, string streventlog)

{

M_streventsource = streventsource;

M_streventlog = streventlog;

M_eventlog.source = m_streventsource;

M_eventlog.log = m_streventlog;

}

/// <Summary> /// write Event Logs /// </Summary>

/// <Param name = "strmessage"> event content </param>

/// <Param name = "eventtype"> event type, error, warning, or message </param>

Static public void dowriteeventlog (string strmessage, eventtype)

{

If (! System. Diagnostics. EventLog. sourceexists (m_streventsource ))

{

System. Diagnostics. EventLog. createeventsource (m_streventsource, m_streventlog );

}

Eventlogentrytype entrytype = new eventlogentrytype ();

Switch (eventtype)

{

Case eventtype. Error:

Entrytype = eventlogentrytype. error;

Break;

Case eventtype. Information:

Entrytype = eventlogentrytype. Information;

Break;

Case eventtype. Warning:

Entrytype = eventlogentrytype. Warning;

Break;

Default:

Entrytype = eventlogentrytype. Information;

Break;

}

M_eventlog.writeentry (strmessage, entrytype );

}

/// <Summary> /// write Event Logs. The default value is message /// </Summary>

/// <Param name = "strmessage"> event content </param>

Static public void dowriteeventlog (string strmessage)

{

If (! System. Diagnostics. EventLog. sourceexists (m_streventsource ))

{

System. Diagnostics. EventLog. createeventsource (m_streventsource, m_streventlog );

}

M_eventlog.writeentry (strmessage );

}

/// <Summary> /// write debugging information to the log /// </Summary>

Public static void opentrace ()

{

If (ctracelistener! = NULL)

{

If (! Trace. listeners. Contains (ctracelistener ))

{

Trace. listeners. Add (ctracelistener );

}

}

}

/// <Summary> /// the debugging information is not written into the log // </Summary>

Public static void closetrace (){

If (trace. listeners. indexof (ctracelistener)> = 0)

{

Trace. listeners. Remove (ctracelistener );

}

}

}}

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.