Create a Windows Service Application

Source: Internet
Author: User
Tags command line continue current time execution implement reflection time interval visual studio
window| Program | Create a Windows service Application
--------------------------------------------------------------------------------


Download this article code
See Resources

It is the presence of the. NET framework that allows you to build an unattended (unattended) application that runs automatically when the system restarts.
by Stan Schultes
Technical Toolbox: vb.net, XML, ASP
Windows Service applications used to be a dedicated domain for C + + programmers, unless you use a Third-party tool in VB. Now they are a major part of the. NET Framework class Library under the System.ServiceProcess namespace, and you can use any of them at your own discretion. NET language to build it. Windows service is an automated, unattended program (existing only in Windows NT, 2000, and XP operating systems) that can start running when the system starts. You can access Windows service through the Service Control Manager (SCM) applet or some special Service-control applications (utility).

I'll explain how to build a Windows service that monitors file changes. The Filechangemonitor service is used to freely write transaction log (Event-log) entries and send e-mail when files have not changed over time. This file monitoring process is useful when it is used to make sure that backups are needed, a normal running report generator, or a schedule for transferring files to a remote system. Filechangemonitor service can also send a comprehensive report showing the program's normal operation.

The first step is to build a template for the Windows Service program that will serve as the starting point for future service projects. Open Visual Studio.NET, use the Windows service template to create a new project and name it Filechangemonitor (click here to download the sample code). Right-click the Service1.vb file in Solution Explorer (SE) and rename it to Changemonitor.vb. Click the ChangeMonitor design interface (you will see the "to add components to your class" message) and change the name and ServiceName properties in the Properties window (as shown by F4) to ChangeMonitor.

The CanPauseAndContinue and CanShutdown property values in the Properties window are also set to true. These properties control whether the service program can suspend/resume, and whether to respond when the system shuts down. You will use these events (and stop events) later to save the "state" of your service-that is, the execution text (execution context) for a given time.

Next, click the "click here to switch to Code View" link in the ChangeMonitor design window. In the Code window, click the plus sign on the left to open the area named "Component Designer generated code". In the Sub Main procedure (routine), change the Service1 in the ServicesToRun assignment statement to Changemonitor:servicestorun = New System. _
Serviceprocess.servicebase () _
{New changemonitor ()}





Right-click the filechangemonitor item in SE, select the property, and then select Sub Main from the StartupObject drop-down list. Now you're ready to start building your project (by using Build | Build Solution menu item).

Creating Event templates and procedures
Now, add a prototype of the event procedure (Event-routine) to the template. You wait a minute. You can add code to these service events to handle state changes in Windows service programs. Click the Class Name combo box (combo box on the left side of the code window) in the Code window and select the (Overrides) option. In Method Name combo box (combo box on the right-hand side of the Code window), select the items to add the process prototype (a null program) to the code window, such as OnContinue, OnPause, and OnShutdown. You must select the (Overrides) option in the Method Name combo box in each procedure.

Next you start building the process template. Create five child process prototypes in the Changemonitor.vb you need to add code: LoadSettings (), SaveSettings (), Runcheck (), Runsummary (), and StartService (). Under the topmost imports System.ServiceProcess statement for this class, add other namespaces that need to be used by using the Imports statement: Imports System.IO
Imports System.Timers
Imports System.Web.Mail
Imports System.Reflection
Imports System.Xml.Serialization





Since your service application is not a Web project, you may need to manually add a reference (reference) to the Web.mail namespace. Right-click the filechangemonitor item in SE and select Add Reference from the pop-up menu. In the Add Reference dialog box, select the System.Web.dll entry in the list, click the Select button, and then point to OK.

At the top of the ChangeMonitor class, before the Component designer area, add a declaration of the Timer object for the file check feature: Private WithEvents Controltimer as Timer



Then add the following three lines of code to the OnStart and OnContinue event programs: StartService ()
Runcheck ()
Runsummary ()





The OnStart event is triggered when your service is started, and the OnContinue event is triggered when you continue to run after the pause.

Select Controltimer in class Name combo box and select elapsed in the method Name combo box. This will add the Controltimer_elapsed event procedure prototype to the project. Simply add the two run statements to the Controltimer_elapsed event procedure, and then add code to interrupt the timer (timer) and save the settings in the OnPause, OnShutdown, and OnStop events: Controltimer.stop ()
SaveSettings ()





From this simple program outline you can see how the control process for the file checking feature of the Windows Service Application works. When one of these events is triggered, the StartService function loads the settings and then runs the file and a brief check. You can run the checker at timer time, you can break the timer with a stop or pause event, and save the settings.

Add code during the StartService to create the timer, set the time interval to 15 seconds (in milliseconds), and then start it: Controltimer = New timer ()
Controltimer.interval = 15000
Controltimer.autoreset = True
Controltimer.start ()





Autoreset = True property setting causes the timer to continue to run when time is up. Next, you can add code to write the Windows application transaction log while the check function is running, so you can see that the service is running: Private Sub Runcheck ()
EventLog.WriteEntry (ServiceName & _
"-Check", "Checking Files."
End Sub





You can view the messages in the event log by using an Event Viewer (EV) application in Windows.

Add a Setup program (Installer)
The last thing you should do to create a service application template is to add a setup program to your project. Before it runs you need to register this Windows service program first. Switch to the ChangeMonitor design interface and open the Properties window (you can press F4 if you don't see it), and you can see that there is a link under the Properties window named Add installer, When you click on the link, a wizard appears to guide you through adding a component named ProjectInstaller to the current project. The wizard placed two service controls in the ProjectInstaller design interface: ServiceProcessInstaller and ServiceInstaller.


Figure 1. Set service Properties
Click the ServiceProcessInstaller control and set the Account property. You may want to choose LocalSystem (most service is run in LocalSystem), but if you like, you can also set it as a user account. Click ServiceInstaller to set its properties to DisplayName = filechangemonitor, ServiceName = ChangeMonitor, and StartType = Automatic (if you want to start the service manually, you can also set it to manual).

Through Build | Build solution your own project to make sure there are no errors. Now you can use a framework application called InstallUtil to install your service. Open the command line prompt (command-prompt) window and execute the CorVars.bat file to set the environment variable (you can download the Readme file to learn more). Use the CD (change directory) command to navigate to the \ Bin directory in your project. Execute the following command to install your service:> installutil Filechangemonitor.exe




You can now start, stop, pause, and continue to run your filechangemonitor using the SCM applet in the Control Panel's Administrative Tools menu (Win2K and WinXP operating systems) Service (see Figure 1). When you start this service, you can use the EV to view the events generated by the service in the application transaction log. Click F5 to refresh the display of the EV, and you will see "Check messages every seconds". You can uninstall the service using the following command (SCM is the first to terminate the service): > InstallUtil filechangemonitor.exe/u




Now you can save the project and use it as a template for future service programs.

Service runs in some state (this may be a set of settings saved when it is not running). When the service restarts, you can load the state of the last time it was run. An easy way to do this is to use the serialization Class (serialization Class) in the. NET framework, such as XML serialization under the System.Xml.Serialization namespace (you can also choose binary and SOAP serialization).

Save settings with XML serialization
XML serialization is used in conjunction with classes marked with the <serializable () > attribute. Right-click the filechangemonitor item in SE and choose Add | from the pop-up menu Add class, Name the Class Cmonitor and click OK. Add two classes ――monitorheader and Monitorfile to Cmonitor: <serializable () > public class Monitorheader
Public Monitorintsecs as Integer
' <other header properties>
Public Files () as Monitorfile
End Class
<serializable () > Public Class monitorfile
Public Path as String
' <other file properties>
End Class




Monitorheader contains settings that control the service, including a set of Monitorfile objects. The Monitorfile object contains the monitoring settings for each file you want to check for progress. You can implement the properties of most classes as public variables because they are only used in your service project. Review the sample code to understand the complete definition of the class. You can implement the LoadSettings and SaveSettings serialization process in the modules of the ChangeMonitor class (see Listing 1).

Add the private variable for the class at the top of the ChangeMonitor class used to declare the settings object and store the path to the settings file: Private M_monitorcontrol as New _
Monitorheader ()
Private M_ssettingspath as String




Add code to the OnStart process before calling StartService () to complete the test of the settings file name before the service starts. Use reflection to locate the application's runtime. exe path, and substitute. xml as the file's extension (these two files are in the same directory): M_ssettingspath = [Assembly]. _
Getentryassembly.location. _
Replace (". exe", ". xml")





Assembly is a keyword in vb.net, so you have to enclose it in a square bracket in your code. You need to organize the startservice () process to load the timer interval from the settings file: If M_monitorcontrol _
. Monitorintervalsecs > 0 Then
Controltimer.interval = _
Ctype (M_monitorcontrol _
. Monitorintervalsecs * 1000, Double)
Controltimer.autoreset = True
Controltimer.start ()
End If




Now you can implement the main check function ――runcheck (see Listing 2). Runcheck is responsible for calling runalarmaction and calculating the number of occurrences of each file in the files array, whose Nextcheck represents the time before the current time and has not changed since the last check. Runalarmaction is responsible for checking alarmaction tags, writing transaction logs, and then sending e-mail through the SendEmail process (see Listing 3).

You can use a similar approach to implement Runsummary and Runsummaryaction methods based on the MONITORHEADER structure Rollup settings (summary setting) to build and test your Windows service application. A Service-control application named Filechgctl is also included in the sample code. It is used primarily for debugging purposes and can be sent to the Filechangemonitor service by the custom command. Custom commands are integers ranging from 128 to 255. When the Oncustomcommand event in a Windows service application is triggered, you get a notification that the custom command appears.

You will find that service applications are useful in many situations, such as system maintenance, monitoring, and other automated, unattended operations. Windows service usually records its activity through the transaction log, but as I've described, your service can also easily track its progress by sending e-mail. The ability to build Windows Service applications allows you to easily scale up with Windows to build effective business solutions.


About the Author:
Stan Schultes is the architect and developer of a Web and enterprise application in the Sarasota area of Florida State, and an MCP in the VB Development area. Stan is a special editor at VSM, who regularly writes articles for the magazine. You can visit Stan's website www.vbnetexpert.com to view online code demos, updates, and other information. His e-mail address is stan@vbnetexpert.com.


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.