Creating a File Watcher


Now let’s step through another example to illustrate what a Windows Service can do and how to construct one. We will build a service that monitors a particular directory and reacts when a new or changed file is placed in the directory. The example Windows Service application waits for those files, extracts information from them, and then logs an event to a system log to record the file change.

As before, create a Windows Service from the built-in template named Windows Service in the New Project screen. Name the new project FileWatcherService and click OK. This creates a new service class called Service1.vb. Rename this to FileWatcherService.vb. Right-click the design surface, select Properties, and set the ServiceName property to FileWatcherService.

As in the first example, set the application type to Windows Service and reset the project’s start object to FileWatcherService. All of this is illustrated earlier in this chapter.

Writing Events Using an Eventlog

The way to ensure that the service is doing its job is by having it write events to a system Event Log. Event Logs are available under the Windows operating system. As with many other system-level features, the use of Event Logs is simplified in .NET because a .NET Framework base class does most of the work for you.

There are three Event Logs on the system: Application, Security, and System. Normally, your applications should only write to the Application log. A property of a log entry called Source identifies the application writing the message. This property does not have to be the same as the executable name of the application, but is often given that name to make it easy to identify the source of the message.

You can look at the events in the Event Log by using the Event Viewer. Select Control Panel image from book Administrative Tools image from book Event Viewer on Windows 2000, and Start image from book All Programs image from book Administrative Tools image from book Event Viewer on Windows XP. The following example uses the Event Viewer to ensure that the service is generating events.

It was mentioned earlier in the chapter that the AutoLog property of the ServiceBase class determines whether the service automatically writes events to the Application log. The AutoLog property instructs the service to use the Application Event Log to report command failures, as well as information for OnStart, OnStop, OnPause, and OnContinue events on the service. What is actually logged to the Event Log is an entry indicating whether the service started successfully and stopped successfully, and any errors that might have occurred. If you look in the Application Event Log now, these events are logged for the CounterMonitor Windows Service that you created and ran earlier in the chapter.

You can turn off the Event Log reporting by setting the AutoLog property to False in the Properties window for the service, but we will leave it set to True for our example. That means some events will be logged automatically (without us including any code for them). Then, we add some code to our service to log additional events not covered by the AutoLog property. First, though, we need to implement a file monitoring control into the project.

Creating a FileSystemWatcher

For performance reasons, you should do all of your work on a separate thread to your main application thread. You want to leave your main application free to accept any requests from the user or the operating system. You can do this by using some of the different components that create their own threads when they are launched. The Timer component and the FileSystemWatcher component are two examples. When the Timer component fires its Elapsed event, a thread is spawned and any code placed within that event will work on that newly created thread. The same thing happens when the events for the FileSystemWatcher component fire.

Tip 

You can learn more about threading in .NET in Chapter 24.

The FileSystemWatcher Component

The FileSystemWatcher component is used to monitor a particular directory. The component implements Created, Changed, Deleted, and Renamed events, which are fired when files are placed in the directory, changed, deleted, or renamed, respectively.

The operation that takes place when one of these events is fired is up to the application developer. Most often, logic is included to read and process the new or changed files. However, we are just going to write a message to a log file.

To implement the component in the project, drag and drop a FileSystemWatcher control from the Components tab of the Toolbox onto the designer surface of FileWatcherService.vb. This control is automatically called FileSystemWatcher1.

The EnableRaisingEvents Property

The FileSystemWatcher control should not generate any events until the service is initialized and ready to handle them. To prevent this, set the EnableRaisingEvents property to False. This prevents the control from firing any events. We will enable it during the OnStart event in the service. These events fired by the FileSystemWatcher are controlled using the NotifyFilter property, discussed later.

The Path Property

Next, the path that we want to monitor is the TEMP directory on the C: drive, so set the Path property to C:\TEMP (be sure to confirm that there is a TEMP directory on your C: drive). Of course, this path can be changed to monitor any directory depending on your system, including any network or removable drives.

The NotifyFilter Property

We only want to monitor when a file is freshly created or the last modified value of a file has changed. To do this, set the NotifyFilter property to FileName, LastWrite. We could also watch for other changes such as attributes, security, size, and directory name changes as well, just by changing the NotifyFilter property. Note that you specify multiple changes to monitor by including a list of changes separated by commas.

The Filter Property

The types of files that we will look for are text files, so set the Filter property to .txt. Note that if you were going to watch for all file types, then the value of the Filter property would be set to *.*.

The IncludeSubdirectories Property

If you wanted to watch subdirectories, you would set the IncludeSubdirectories property to True. This example leaves it as False, which is the default value. Figure 31-9 shows how you should have the properties set.

image from book
Figure 31-9

Adding FileSystemWatcher Code to OnStart and OnStop

Now that some properties are set, let’s add some code to the OnStart event. You want to start the FileSystemWatcher1 component so it will start triggering events when files are created or copied into the directory you’re monitoring, so set the EnableRaisingEvents property to True:

 Protected Overrides Sub OnStart(ByVal args() As String)     ' Start monitoring for files     FileSystemWatcher1.EnableRaisingEvents = True End Sub

Once the file monitoring properties are initialized, you are ready to start the monitoring. When the service stops, you need to stop the file monitoring process. Add this code to the OnStop event:

 Protected Overrides Sub OnStop()     ' Stop monitoring for files      FileSystemWatcher1.EnableRaisingEvents = False End Sub

The EventLog Component

Now you are ready to place an EventLog component in the service to facilitate logging of events. Drag and drop an EventLog control from the Components tab of the Toolbox onto the designer surface of FileWatcherService.vb. This control is automatically called EventLog1.

Set the Log property for Eventlog1 to Application, and set the Source property to FileWatcherService.

The Created Event

Next, we will place some logic in the Created event of the FileSystemWatcher component to log when a file has been created. This event fires when a file has been placed or created in the directory that we are monitoring. It fires because the last modified information on the file has changed.

Select FileSystemWatcher1 from the Class Name drop-down list and select Created from the Method Name drop-down list. The Created event will be added to your code. Add code to the Created event as follows:

 Public Sub FileSystemWatcher1_Created(ByVal sender As Object, _            ByVal e As System.IO.FileSystemEventArgs) _            Handles FileSystemWatcher1.Created      Dim sMessage As String      sMessage = "File created in directory - file name is " + e.Name       EventLog1.WriteEntry(sMessage) End Sub

Notice that the event argument’s object (the object named “e” in the event parameters) includes a property called Name. This property holds the name of the file that generated the event.

At this point, you could add the other events for FileSystemWatcher (Changed, Deleted, Renamed) in a similar way and create corresponding log messages for those events. To keep the example simple, we’ll just do the Created event in this service.

You need to add an Installer class to this project to install the application. This is done as it was in the CounterMonitor example, by right-clicking the design surface for the service and selecting Add Installer or by clicking the Add Installer link in the Properties window of Visual Studio 2005. Don’t forget to change the Account property to LocalSystem, or set it to User and fill in the Username and Password properties.

As before, you must install the service using InstallUtil.exe. Then, start it with the Server Explorer or the Service Manager. Upon successful compilation of these steps, you will get a message logged for any file with a .txt extension that you copy or create in the monitored directory. After dropping some sample text files into the monitored directory, you can use the Event Viewer to ensure that the events are present.

Figure 31-10 shows the Event Viewer with several example messages created by the service. If you right-click one of the events for FileWatcherService, you’ll see a detail screen. Notice that the message corresponds to the Event Log message we constructed in the Created event of the FileSystemWatcher control in the service, as shown in Figure 31-11.

image from book
Figure 31-10

image from book
Figure 31-11




Professional VB 2005 with. NET 3. 0
Professional VB 2005 with .NET 3.0 (Programmer to Programmer)
ISBN: 0470124709
EAN: 2147483647
Year: 2004
Pages: 267

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net