Friday, August 5, 2011

Creating a Windows Service in C#.net and call a method every hour




Untitled Page





Untitled Page



In Visual Studio Select File->New->Project Select Windows and select Windows
Service


Right click on the Service1 designer and select Add Installer. This adds ProjectInstaller


Will create a file ProjectInstaller.cs





To avoid Set Service Login prompt being asked about the system username and
password you must change the Account for the serviceProcessInstaller to LocalSystem.

ServiceAccount Enumeration

ServiceAccount

stackoverflow





ServiceProcessInstaller Installs an executable containing classes that extend
ServiceBase. This class is called by installation utilities, such as InstallUtil.exe,
when installing a service application. ServiceInstaller Installs a class
that extends ServiceBase to implement a service. This class is called by the install
utility when installing a service application.



Display Name is show in name column of the service.
Set StartType as Automatic - To make the service to be started after restart/shutdown.

How to Start the service automatically after Installation?




Rename Service1 to to MyService


Create a folder and write the code to write to file


How to check whether the service called function is working or not? Right
click on the Solution(DemoService) and select Add -> New Project This console
application is used to test whether file writing works or not.


How to create Service Installer? Right click on the Solution(DemoService)
and select Add -> New Project Select Other Project Types -> Setup and Deployment
-> Setup Project


We will get the below screen.


Right click on the Setup project


Select the service project








Double click on the Application Folder


Press Ok.


Select the setup project and press F4 Manufacturer will come in path as "C:\Program
Files\ManufacturerValue" Title will come in Setup Wizard





Click on Configuration Manager


Change Debug mode to Release for the Service and Setup projects













To avoid this prompt give LocalSystem to Account property of serviceProcessInstaller.



Type control in run and select Administrative Tools -> Services







Make the service to call every 10 minutes Create a file as the below image


public class WriteToFile
    {
        public WriteToFile()
        {
            string strDateTime = DateTime.Now.ToString();
            StreamWriter sw = new StreamWriter(Path.Combine(System.IO.Path.GetTempPath(), "babu.txt"), true);
            sw.WriteLine(strDateTime);

            sw.Close();
        }
    }
Update the MyService.cs file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using DemoService.Functions;
using System.Timers;

namespace DemoService
{
    public partial class MyService : ServiceBase
    {
        //Make the service to call the for every 5 min
        System.Timers.Timer TimerObj = new System.Timers.Timer(ConvertMinutesToMilliseconds(5));

        public MyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            TimerObj.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            TimerObj.Enabled = true;
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            TimerObj.Enabled = false;
        }

        /// 
        /// At the end of every 5 min the event will be triggered.
        /// 
        ///         /// protected void OnElapsedTime(object source, ElapsedEventArgs e)         {             //Write the current datetime to the file                          WriteToFile objWriteToFile = new WriteToFile();         }         ///          /// Convert minutes to milliseconds                 /// ///                  /// /// ///                  public static double ConvertMinutesToMilliseconds(double minutes)          {              return TimeSpan.FromMinutes(minutes).TotalMilliseconds;          }     } }