Create a Windows Service App
Thanks to the .NET Framework, you can build applications that start at system boot time and run unattended.
by Stan Schultes
March 2003 Issue
Technology Toolbox: VB.NET, XML, ASP
Windows service apps were once the exclusive domain of C++ programmers, unless you used third-party tools with VB. Now they're an integral part of the .NET Framework's class library in the System.ServiceProcess namespace, and you can build them in the .NET language of your choice. Windows services are unattended apps—available only on Windows NT, 2000, and XP OSs—that can start at system boot time. You access Windows services through the Service Control Manager (SCM) applet, or through special service-control utilities.
I'll show you how to build a Windows service that monitors files for changes. The FileChangeMonitor service optionally writes event-log entries and sends e-mail if the files don't change within certain intervals. This kind of file monitoring is useful for ensuring that your backups occur when they should, that report generators are operating, or that remote systems are delivering files on schedule. The FileChangeMonitor service can also send out summary reports to provide reassurance that it's operating properly.
The first step is building a Windows service app template you can use as a starting point for future service projects. Start Visual Studio .NET, use the Windows Service template to create a new project, and name it FileChangeMonitor (download the sample code). Right-click on the Service1.vb file in Solution Explorer (SE) and rename it to ChangeMonitor.vb. Click on the ChangeMonitor design surface (where you see the "To add components to your class …" message), and change both the (name) and ServiceName properties to ChangeMonitor in the Properties window (which you show by pressing F4).
Set the CanPauseAndContinue and CanShutdown properties to True, also in the Properties window. These control whether the service app can be paused/resumed and whether it responds when the system is shut down. You'll use these service events later, along with the Stop event, to save your service's state—its execution context at a given time.
Next, click on the "click here to switch to code view" link on the ChangeMonitor designer. In code view, click on the plus sign in the left margin to open the region named "Component Designer generated code." Change the ServicesToRun assignment statement reference from Service1 to ChangeMonitor in the Sub Main routine:
ServicesToRun = New System. _
ServiceProcess.ServiceBase() _
{New ChangeMonitor()}
Right-click on the FileChangeMonitor project in SE, choose Properties, then select Sub Main from the StartupObject dropdown list. You should be able to build your project now without any errors (using the Build | Build Solution menu item).
Back to top
|