Creating Windows Services using Topshelf - International Days

International Days

Internationally important Days

Breaking

Home Top Ad

Post Top Ad

Monday, 13 November 2017

Creating Windows Services using Topshelf

Creating Windows Services using Topshelf  
 Windows services are computer programs which runs in background for doing some specific tasks automatically it is also known as NT services .Which is not having a specific interface to display or indicator to view its prograss. This will automatically starts when the computer boots up. We can also pause and restart this application.
    Windows services are ideal for whenever we need a long running app which doesn't need a user interface with other system users. I have created windows service application for checking data change in Dynamic CRM in a regular intervene(say 100 seconds). Also sending push notifications to mobile client apps.Now you got the idea of what is windows services and in which scenario is best for windows application. In web applications we use windows service in order to reduce the service load by executing process which needs regular check up and does excite some particular process.
    We can monitor which all are the windows services that runs in our machine background by typing “Services.msc” in Run. Which will open a new window , we can see the services running on background here. We can stop,start the services from here.

 Below I have explained how to create a windows service using Topshelf step by step.

What is TopShelf ?

  Topshelf is a third party platform for creating a windows service . It simplifies the windows service creation . We can create,edit and Install windows service in an easy way using Topshelf.
We can focus more on our bossiness logic rather than interacting with built in windows service applications . The developers no need to worry about the complex service classes. In short it will helps us to create windows service without worry about the service classes. We can achieve this by using a console application and a single service manager class .

Step 1:
  Create new console application . We are going to implement the windoes - service using a simple console application . First Opens the .Net IDE and creare a new console application. It can be created by File>New Project>Select 'Console application ' In the window Opened and give an apropriate name for your application and Press 'OK' .


Step 2:
   Add topshelf library from NeuGet Package


Step 3:
  Create a service class for applying your business logic. In this example , I have just added to save some text to a Log-file. You can replace here your Logic. Please see the blow code 

 public class SynchingManager
 {
   private CancellationTokenSource cts = new CancellationTokenSource();
   private Task mainTask = null;

   public void Start()
   {
   LogUtil.Info("Service Started");
   mainTask = new Task(SampleTask, cts.Token, TaskCreationOptions.LongRunning);
   mainTask.Start();
   }

   private void SampleTask()
   {
   CancellationToken cancellation = cts.Token;
   TimeSpan interval = TimeSpan.Zero;
   while (!cancellation.WaitHandle.WaitOne(interval))
   {
   try
   {
   //Start a new task for sending message.
   mainTask = new Task(() => this.SyncData(interval));
   mainTask.Start();
   // check the cancellation state.
   if (cancellation.IsCancellationRequested)
   {
   //If cancelation requested, break.
   break;
   }
   //Set time interval ,Interval time is given in app.config file 
   interval = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["SYNCInterval"]));
   }
   catch (Exception ex)
   {
   //continue poll.
   interval = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["SYNCInterval"]));
   }
   }
   }

   private void SyncData(TimeSpan interval)
   {
   //Time interval customized Logic go here
   LogUtil.Info("Windows service Running........... " );
   }

   /// <summary>
   /// Stop
   /// </summary>
   public void Stop()
   {
   LogUtil.Info("Service Stopped");

   cts.Cancel();
   if (mainTask != null)
   mainTask.Wait();

   }
   }

 The app config date is as given below

<appSettings>
  <add key="SYNCInterval" value="1"/>
</appSettings>


Step 4 :

      Modify the Main class to create instance of manager class and instruct topshelf to how to run and stop the services.

internal class Program
{
   private static int Main()
   {
   var exitCode = HostFactory.Run(host => // Here we are setting up the host using hostfactory
   {
    host.Service<SynchingManager>(service => // Here we are instructing the Topshelf that there is a service manager class
   // and invoking it using 'service' Param
   {
   service.ConstructUsing(()=>new SynchingManager()); //Tells topshelf to create instance of  Manager class
   service.WhenStarted(a => a.Start()); //This is how Topshelf starter service
   service.WhenStopped(a => a.Stop()); //This is how it ends service
   });
   host.SetDescription("Topshelf service."); //Service Description
   host.SetDisplayName("Topshelf-Test"); // Service Display Name
   host.SetServiceName("Topshelf-Test"); // Service Name
   });

   return (int)exitCode;
   }
   }

Step 5 :
Install the service using Command line Command. We can use  "install" command for install the service syntax is :
  [console application exe file Full path] Install


Step 6 :
  Now we can see the service that we have created listed in the services .msc window. We can start/stop the service by right clicking it. When we runs it the application will starts log in log file




Step 6 :
Uninstall the service form computer using Command line command.
Command :  
             "sc delete [Service Name]"

Please enter your opinion about this article as comment ,which will help me to improve my blog 



No comments:

Post a Comment

Post Bottom Ad

Pages