Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Write Your Own Windows Services : Page 3

If you're using Windows, you're no stranger to Windows services, but do you know how to write one of your own? In this article, you'll learn not only how to build your own Windows service, but how to build a client with which to control it.


advertisement
Building Your Own Windows Service
The Windows service that you'll be developing will monitor for file activities on your hard disk—in particular, it will monitor Word documents. I often forget the filenames of Word documents that I have created, which I need to retrieve from time to time. This Windows service will allow you to monitor a specific path on your hard disk (or the entire drive) for Word documents.

Using Visual Studio 2005, create a new Windows Service project and name it as WordFilesMonitor. You should see the design view of the windows service: Service1.vb.

In the Properties window for Service1:

  • Set the CanPauseAndContinue property to True (see Figure 1) so that users can pause and continue the Windows service.


  • Set the ServiceName property to WordFilesMonitor.
  • Click on the Add Installer link located at the bottom of the Properties window to add two installers to aid in the installation of the Windows service.

Figure 1. Service1.vb: Setting the properties.
 
Figure 2. Configuration: The ServiceProcessInstaller and the ServiceInstaller classes.

The ServiceProcessInstaller and the ServiceInstaller classes (see Figure 2) help to configure the installation and un-installation of the Windows Service.

You need to configure the two installers as follows:

  • For the ServiceProcessInstaller1 control, set the Account property to LocalSystem (see Figure 3). This property uses an account that acts as a non-privileged user on the local computer, and presents anonymous credentials to any remote server. If you use the value User, the system will prompt for a valid user name and password when the service is installed.
  • For the ServiceInstaller1 control, set the StartType property with value Manual so that the service not to start until explicitly started by the user.
  • For the ServiceInstaller1 control, set the ServiceName property to WordFilesMonitor.
Remember to ensure that the ServiceName property in the Service1 application matches that of the ServiceName property in the ServiceInstaller1 control. Otherwise, the Windows service cannot be installed correctly.

Figure 3. Setting the Properties: The ServiceProcessInstaller1 and the ServiceInstaller1 controls.

Double-click on the design surface of Service1 to switch to its code-behind. Import the following namespace:

Imports System.IO

Declare the following constant and member variables:

Public Class Service1 '---name of the log file--- Const FILE_NAME = "c:\WordDocumentsHistory.txt" '---used for writing to log file--- Private SR As StreamWriter '---Create a new FileSystemWatcher--- Private WordFilesWatcher As New FileSystemWatcher()

The FileSystemWatcher class provides the capability to listen to the file system change notifications and raises events when a directory, or file in a directory, changes.

There are seven events in the ServiceBase class that you can service (the Windows Service inherits from the System.ServiceProcess.ServiceBase class):

  • OnStart: This specifies actions to take when a service starts.
  • OnStop: This specifies actions to take when a service stops.
  • OnContinue: This specifies actions to take when a service resumes normal functioning after being paused.
  • OnCustomCommand: This specifies actions to take when a command with the specified parameter value occurs.
  • OnPause: This specifies actions to take when a service pauses.
  • OnPowerEvent: This applies to laptop computers when they go into suspended mode, which is not the same as a system shutdown.
  • OnShutdown: This specifies what should happen immediately prior to the system shutting down.
Author's Note: For this article, I will not be discussing the last two events–OnPowerEvent and OnShutDown.

Code the OnStart event handler as shown in Listing 1.

First, create a log file to log the activities of the file system. If the log file does not exist, create one; otherwise, open the existing one for writing. You then create a FileSystemWatcher object and then set the required parameters for monitoring files activities. The Path property sets the directory to monitor (e.g. C:\); the IncludeSubdirectories property indicates whether the subdirectories of a specified path should be monitored as well; the NotifyFilter property sets the kinds of file activities to monitor (e.g. last access, last write, change in filename and change in directory name), and lastly the Filter property sets the type of files to monitor (through filename extension, e.g. *.doc). All these property values will be derived from the single input parameter of the OnStart() event handler. This allows maximum flexibility for the user to specify the degree of customization required.

Next, specify the events handlers for the different events, such as when files are modified, created, deleted, and renamed. Finally, set the EnableRaisingEvents property to true to enable the FileSystemWatcher object to start monitoring files.

Code the OnFileChanged event handler as follows:

Public Sub OnFileChanged( _ ByVal source As Object, _ ByVal e As FileSystemEventArgs) Dim str As String = Now.ToString & ": File " & _ e.ChangeType.ToString & " : " & e.FullPath '---log it to file--- SR.WriteLine(str) SR.Flush() End Sub

Code the OnFileRenamed event handler as follows:

Public Sub OnFileRenamed( _ ByVal source As Object, _ ByVal e As RenamedEventArgs) Dim str As String = Now.ToString & ": File : " & _ e.OldFullPath & " renamed to " & e.FullPath '---log it to file--- SR.WriteLine(str) SR.Flush() End Sub

Code the OnPause event handler as follows:

'---when the Windows Service is paused--- Protected Overrides Sub OnPause() WordFilesWatcher.EnableRaisingEvents = False SR.WriteLine(Now.ToString & ": WordFilesMonitor Paused.") SR.Flush() End Sub

Here, you will temporarily disable the FileSystemWatcher object (by setting its EnableRaisingEvents property to False) so that it will not raise any events when changes in the files activities in the hard disk are detected.

Code the OnContinue event handler as follows:

'---when the Windows Service is continued--- Protected Overrides Sub OnContinue() WordFilesWatcher.EnableRaisingEvents = True SR.WriteLine(Now.ToString & ": WordFilesMonitor Continued.") SR.Flush() End Sub

Here, you are doing the reverse of what you did in the OnPause event handler—you simply turn on the FileSystemWatcher object to enable it to monitor for file changes.

Finally, code the OnStop event handler as follows:

'---when the Windows Service is stopped--- Protected Overrides Sub OnStop() SR.WriteLine(Now.ToString & ": WordFilesMonitor Stopped.") SR.Flush() SR.Close() End Sub

This event handler simply closes the text file used for logging.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap