Windows Service Sample


Windows Service

When?

We can use windows services in all issues that needs scheduled treatment like ( sending emails ,write logs,call other services in certain time)

Why?

Windows service is a long-running executable that performs specific functions and which is designed not to require user intervention. Windows services can be configured to start when the operating system is booted and run in the background as long as Windows is running, or they can be started manually when required

How?

We will discuss a sample project to show how to

  1. Code it
  2. Install/Register into windows service list
  3. Run
  4. Uninstall

windows service with easy way

———————————

1- Code it

we will use Visual studio 2008, so create new project >> Select Windows Service and Name it as the following

After creating the project you will see the solution explorer as follow:

you must add reference to System.ServiceProcess if it doesn’t exists,

Go to MyService.cs code you will see it as the following

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace NewService
{
public partial class MyService : ServiceBase
{
public MyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
so we will goes to every event to handle it
  • onStart Event: we will starting the timer object and set it’s interval (at every ?? the windows service will run)

protected override void OnStart(string[] args)

{

try

{

//timer object is a global object

timer = new Timer();

//timer interval in milliseconds

timer = new System.Timers.Timer(10000);

timer.Enabled = true;

//Trace step 1

EventLog.WriteEntry(“Go To Event“);

//what will be done when timer start!

timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

//start timer (working)

timer.Start();

}

catch (Exception ex)

{

//Trace any problem to event log

EventLog.WriteEntry(ex.ToString());

}

}

  • timer_Elapsed Event: service core work “every 1000 milliseconds the code will be executed!”, in out example we will create text file to write current datetime as the following

public void timer_Elapsed(object sender, ElapsedEventArgs e)

{

try

{

EventLog.WriteEntry(“Writing…..”);

using (FileStream fstrem = new FileStream(@”C\:history.txt”, FileMode.OpenOrCreate, FileAccess.Write))

{

using (StreamWriter sWriter = new StreamWriter(fstrem))

{

sWriter.WriteLine(“————————————–“);

sWriter.WriteLine(string.Format(“Current DateTime is :{0}”, DateTime.Now.ToString()));

sWriter.Flush();

sWriter.Close();

fstrem.Close();

}

}

}

catch (Exception ex)

{

//Trace any problem and record it into event log

EventLog.WriteEntry(ex.ToString());

}

}

  • onStop Event: what we will do when the windows service is stopped

protected override void OnStop()

{

try

{

// stop the timer.

timer.Stop();

timer.Enabled = false;

//Trace Closing

EventLog.WriteEntry(“Closed”);

}

catch (Exception ex)

{

//Trace any problem and record it into event log

EventLog.WriteEntry(ex.ToString());

}

}

Build Your Project

2- Install/Register into windows service list

To be able to register your custom windows service you must add Service Installer to your project as the following

a) Add new item to the solution

b)Select windows service name it as ex MyServiceInstaller

c) Go to it’s code

d) it will be looks like the following

e) add reference to System.Configuration.Install

[RunInstaller(true)]

public partial class ProjectInstaller : Installer

{

private ServiceInstaller serviceInstaller;

private ServiceProcessInstaller processInstaller;

public ProjectInstaller()

{

InitializeComponent();

processInstaller = new ServiceProcessInstaller();

serviceInstaller = new ServiceInstaller();

// Service will run under system account

processInstaller.Account = ServiceAccount.LocalSystem;

// Service will have Start Type of Manual

serviceInstaller.StartType = ServiceStartMode.Manual;

//Service Name = The Name that will be shown in windows services list

serviceInstaller.ServiceName = “Alert“;

Installers.Add(serviceInstaller);

Installers.Add(processInstaller);

}

}

Build your project Again!

3- Run it!

  • open project folder >> bin folder >> find .exe file
  • save the complete path
  • open cmd
  • open the following path by comand cd “path”   C:\Windows\Microsoft.NET\Framework\v2.0.50727\
  • write Installutil “exe path”
  • well done! you will notice your service into windows service list as the following

  • Right click on it and choose start
  • Go To C:\  “File path at the code”
  • you will see the file “history.txt
  • open it and this is the result

4-Uninstall

  • open cmd
  • open the following path C:\Windows\Microsoft.NET\Framework\v2.0.50727\
  • write the following command Installutil /u “exe path”
  • /u for uninstalling utility

as you see from this article now you can develop/install – register/run/unistall any windows service is simple steps

hope it’s useful for You

Regards,

Ahmed Samir
Advertisements

2 thoughts on “Windows Service Sample

  1. hi samir thanks so much, there is a small change int he code, as a developer they can find but some one may structed, please dont mind
    Instead of @”C\:history.txt”, @”C:\history.txt” back slash need to change.

  2. Thank you Eng AHMED SAMIR for this article its very simple
    you added to my knowledge in a simple way
    we expected more useful articles

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s