XMLFileWatcher Windows Service

Introduction

When I was reading the MSDN.Net, I found an interesting topic on Windows services and FileSystemWatcher. So, I tried to write a Windows service that monitors the directory changes, writes an entry in the event log about the change, notifies the changes to the users by sending mail, and also converts the input XML file into a Dataset.

This service is useful in scenarios where the clients upload the files (say XML files) on the server and server will take care of processing the uploaded files and updating them in the database if they are valid.

Building the Application

Start by creating a new Windows service project:

Change the service1.cs name to XMLWatcher.cs by editing the service1.cs properties in the solution explorer and also change service1 to XMLWatcher in the generated view code window.

This application uses FileSystemWatcher to observe the directory changes and SmtpMail to send the mails. To access FileSystemWatcher and MailMessage (in SmtpMail), you need add the reference to System.IO and System.Web.dll to this project using Project->Add Reference. You should also add the reference to System.Data.dll to access ADO.NET objects.

Include System.IO, System.Web.Mail, and System.Data.SqlClient name spaces to this project.

using System.IO;
using System.Web.Mail;
using System.Data.SqlClient;

Now, write the code to initialize the Event Log, FileSystemWatcher, and MailServer in InitializEventLog (), IntializeFileSystemWatcher (), and InitializeMailServer () respectively and call them from the OnStart();.

/// <summary>
/// Initialize the Event Log
/// </summary>

private void InitializEventLog()
{
   //Check whether " XMLWatcherSource " exists or not
   if(!System.Diagnostics.EventLog.SourceExists("XMLWatcherSource"))
   {
      //Create "XMLWatcherSource" and "XMLWatcherLog"
      System.Diagnostics.EventLog.CreateEventSource
         ("XMLWatcherSource","XMLWatcherLog");
   }

   //Create Event Log
   el=new EventLog();
   //Assign Event Log Name
   el.Log="XMLWatcherLog";
   //Assign Event Source Name
   el.Source="XMLWatcherSource";
}

/// <summary>
/// Initialize File System Watcher
///
/// </summary>

private void IntializeFileSystemWatcher()
{
   //Create File System Watcher for XML files
   fsWatcher=new System.IO.FileSystemWatcher("c:\\temp","*.xml");
   // Add event handlers for new XML files and change of existing
   // XML files.
   fsWatcher.Changed += new FileSystemEventHandler(OnXMLFileChanged);
   fsWatcher.Created += new FileSystemEventHandler(OnXMLFileCreated);
   // Begin watching.
   fsWatcher.EnableRaisingEvents = true;

}


/// <summary>
/// Initalize Mail Server
///
/// </summary>

private void InitializeMailServer()
{
    mailMsg=new System.Web.Mail.MailMessage();
}


/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>

protected override void OnStart(string[] args)
{
   // TODO: Add code here to start your service.

   //Initialize Event Log
   InitializEventLog();
   //Initialize File System Watcher
   IntializeFileSystemWatcher();
   //Initliaze Mail Server
   InitializeMailServer();

}

Now, provide event handlers for FileSystemWatcher. These event handlers are called when a file is changed or created.

XMLFileWatcher Windows Service

Event handlers will write the entry into the event log and notify the required people by sending the mail and also converts the XML data into a Dataset. This Dataset can be used to update the database.

/// <summary>
/// Event Handler for File Changed
///
/// </summary>

private void OnXMLFileChanged(object source, FileSystemEventArgs e)
{
   //Write entry into the Event Log
   el.WriteEntry("XML File :" + e.FullPath + " changed");

   //Send mail
   SendMail(e.FullPath);

//Get the Dataset from XML
   GetDataSetFromXML(e.FullPath);

}


/// <summary>
/// Event Handler for File Created
///
/// </summary>

private void OnXMLFileCreated(object source, FileSystemEventArgs e)
{
   //Write entry into the Event Log
   el.WriteEntry("XML File :" + e.FullPath + " created");

   //Send mail
   SendMail(e.FullPath);

   //Get the Dataset from XML
   GetDataSetFromXML(e.FullPath);

}


/// <summary>
/// Notify the users by sending mail
///
/// </summary>

private void SendMail(string XMLFileName)
{
   string fileName=XMLFileName;
   //Message From
   mailMsg.From="admin@xxx.com";
   //Message To
   mailMsg.To="dev@xxx.com";
   //Message Subject
   mailMsg.Subject="New File Uploaded to the server ";
   //Message Body
   mailMsg.Body="XML File :" + fileName + " is uploaded ";
   //Everything set..now send the mail
   SmtpMail.Send(mailMsg);

}


/// <summary>
/// Get Dataset from XML
///
/// </summary>

private DataSet GetDataSetFromXML(string XMLFileName)
{
   string uploadedXMLfile = XMLFileName;
   //Create the Dataset
   DataSet ds = new DataSet();
   // Create new FileStream with which to read the schema.
   System.IO.FileStream fsReadXml = new System.IO.FileStream
      (uploadedXMLfile, System.IO.FileMode.Open);
   try
   {
      ds.ReadXml(fsReadXml);
   }

   catch (Exception ex)
   {
      //Write entry into the Event Log
      fsReadXml.Close();
      el.WriteEntry("Error in readig XML File : " + uploadedXMLfile );
   }

   return ds;

}

You are done with the coding. Now, this service needs to be installed under the services. To install this service, you need to add installers to this project.

To add installers to the project, open XMLWatcher.cs in design mode and right-click on the form and click Add Installer. Studio will add ServiceProcessInsatller1 and ServiceInsatller1 to the project.

Right-click on the ServiceProcessInsatller1 properties and change the Account to Local System to avoid user name and password entry while installing the service.

[AddInstaller1.JPG]

Now, build the project. After build has succeeded, open the Visual Studio.NET 2003 Command Prompt. Using the installutil command, install the service.

[cmdprompt.JPG]

Now, the service is installed under the Services. To start the service, goto Administrative Tools->Services, look for the XMLWatcherservice, and start the service.

Now, the service is up and running.

It's time to test the service. To test the service, create an XML file in c:\temp. The service will monitor the directory change and write an entry in the Event Log under XMLWatcherLog. It will also send a mail to the required users about the directory change.

This application can be further extended to insert the Dataset (which is retrieved from GetDataSetFromXML) into the database.



Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds