Wednesday, November 6, 2013

Create Windows Service Step-By-Step

Introduction

This step by step guide will help you to create simple Windows Service in Visual Studio.

Note: to enlarge image click on it.
Step 1:

Start Visual Studio and add new project Windows Service:


Your Solution Explorer should now look like this:


Step 2:

Set project properties as follow:





Step 3:

Add new component file and name it ‘XXXXInstaller.cs’ [XXXX= Windows Service name]


Step 4:

Open your WindowsService.cs ie DistributionService file and add:

using System;
using System.ServiceProcess;
using System.Timers;

namespace DistributionWindowsService
{
    partial class DistributionService : ServiceBase
    {
        private Timer _timer = null;
        public DistributionService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                EventLog.WriteEntry("Email service started : " + DateTime.Now);
                _timer = new Timer();
                _timer.Interval = 10000; //in milliseconds

                 EventLog.WriteEntry("Timer Interval is : " + _timer.Interval);

                // attach a function to elapsed event whenever time interval occur it will call this function
                _timer.Elapsed += timer_Elapsed;

                _timer.Start(); 
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Email service error : " + ex);
            }
            
        }

        protected override void OnStop()
        {
            EventLog.WriteEntry("Email service Stopped : "+DateTime.Now);
        }

        protected void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                _timer.Stop();
                //perform your action here 
                // It will be occur on each time elapsed
            }
            catch (Exception ex)
            {

            }
            finally
            {
                //restart the timer
                _timer.Start();
            }
        }
     
    }
}


Step 5:

Open your WindowsServiceInstaller.cs ie DistributionServiceInstaller.cs file and add:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace DistributionWindowsService
{
    [RunInstaller(true)]
    public partial class DistributionServiceInstaller : Installer
    {     

        public DistributionServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            //# Service Account Information
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            serviceProcessInstaller.Username = null;
            serviceProcessInstaller.Password = null;

            //# Service Information
            serviceInstaller.DisplayName = "MyPerformance Distribution Service";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.Description = "Distribution of scheduled Emails.";

            //# This must be identical to the WindowsService.ServiceBase name
            //# set in the constructor of WindowsService.cs
            serviceInstaller.ServiceName = "DistributionWindowsService";
            serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;   
            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);

        }
        private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            ServiceController sc = new ServiceController("DistributionWindowsService");
            sc.Start();
        }
    }
}


Step 6:

Build your solution

Step 7:

Open visual studio command prompt(if not works try run as administrator):


Step 8:

Open the physical folder and copy the path of WindowsService.exe file from

WindowsService>>Bin>>Debug>> WindowsService.exe

Step 9:

Write command in command prompt:

Installutil –i “complete path of file”

Step 10:

Check Service in “control panel>>Administrative services>>Service” and start the service if it is stop.


Step 11:

To uninstall windows service goto command prompt and write:

Installutil –u “complete path of file”


Step 12:

It is an optional step, if you don't want to run the application from command line then you can create a batch file Installer and Uninstaller for windows service. Add a file installer.bat open it with notepad or any editor:

@ECHO OFF
 
echo Installing WindowsService...
echo ---------------------------------------------------
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "complete path of exe"
echo ---------------------------------------------------
echo Done.
pause

And for uninstaller add uninstaller.bat file and add:


@ECHO OFF
 
echo Un-Installing WindowsService...
echo ---------------------------------------------------
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /u "complete file path of exe"
echo ---------------------------------------------------
echo Done.
pause 

Double click installer and uninstaller for particular actions(if not works try run as administrator).

You may also like to see:
For changing app.config you would need to restart windows service, for details and reasons please visit this page.

2 comments:

  1. I realise this was posted at least 15 months ago and could be considered out of date, but would you be able to correct the missing images?

    ReplyDelete
  2. Steps for creating windows service are still same and will update as soon as required. Can you please point which image is not coming for you as it appearing for me.

    ReplyDelete

Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,