Posts

....
Technical Blog for .NET Developers ©

Sunday, January 24, 2016

Windows Services

Windows Services are applications that run in the background, performing diverse tasks and designed not to require user intervention

In this example, we are going to deploy a Windows Service which detects changes on a .txt file and will take its data to a database

The first step is begin a Windows Service Project



The code template of the Windows Service is as follows


namespace WSWatcher
{
    public partial class Service1 : ServiceBase
    {
        public SWatcher()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}
    


Now we add a .config file with the path of the archive to watch, and the connection string to the database

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="file_path" value="C:\ExampleData" />
  </appSettings>
  <connectionStrings>
    <add name="conSet" providerName="System.Data.SqlClient" 
         connectionString="Data Source=***; Initial Catalog=PRODUCTS; User=***; Pwd=***"/>
  </connectionStrings>
</configuration>


We add the FileSystemWatcher class to our code, and implement handlers for Created and Changed Events


protected override void OnStart(string[] args)
{
    fileWatcher = new FileSystemWatcher(ConfigurationManager.AppSettings["file_path"]);
    fileWatcher.Filter = "*.txt";
    fileWatcher.EnableRaisingEvents = true;
    fileWatcher.Changed += new FileSystemEventHandler(fileWatcher_Changed);
    fileWatcher.Created += new FileSystemEventHandler(fileWatcher_Created);
}

void fileWatcher_Created(object sender, FileSystemEventArgs e)
{
    bulkData(e.ChangeType);
}

void fileWatcher_Changed(object sender, FileSystemEventArgs e)
{
    bulkData(e.ChangeType);
}

void bulkData(WatcherChangeTypes changeType)
{
    string[] lines = System.IO.File.ReadAllLines(fileWatcher.Path + "\\data.txt");

    using (SqlConnection connection = 
    new SqlConnection(ConfigurationManager.ConnectionStrings["conSet"].ConnectionString))
    {
        connection.Open();
        foreach (string line in lines)
        {
            SqlCommand comm = connection.CreateCommand();
            comm.CommandType = CommandType.StoredProcedure;
            comm.CommandText = changeType == WatcherChangeTypes.Created
                ? "INSERT_PRODUCT"
                : "UPDATE_PRODUCT";
            comm.Parameters.Add(new SqlParameter("@idproduct", 
                Convert.ToInt32(line.Split('-')[0])));
            comm.Parameters.Add(new SqlParameter("@pname", line.Split('-')[1]));
            comm.ExecuteNonQuery();
        }
    }
}
    


It's time to create the installer for the service, right click on the service designer and add a new installer



Select serviceInstaller1 on the designer, and make sure the ServiceName property is set to SWatcher

Now click serviceProcessInstaller1 and set the Account property to LocalSystem. This will cause the service to be installed and to run on a local service account.

To build your project, before set the Startup object to point to your service. In Project Properties, on the Application page, from the Startup object list, click SWatcher.Program



Now build the solution, run Developer Command Prompt as Administrator, navigate to your bin folder, and type the command for installing the service

installutil.exe SWatcher.exe




Check the Service in the Control Panel, with the configuration specified in development, LocalSystem Account

Now we test the service, creating a file with the next data



The result is immediately appreciated

A change in the file will produces the next result



<METHOD SOFTWARE © 2012>