Go to DotNetFunda.com
 Online : 3121 |  Welcome, Guest!   Login
 
Home > Articles > .NET Framework > Introduction to Windows Service(Process Killer)

  • Download the OOPS, ASP.NET and ADO.NET Training Videos for FREE, click here.

Submit Article | Articles Home | Search Articles |

Introduction to Windows Service(Process Killer)

 Download source file
 Posted on: 11/17/2008 3:27:38 AM by Vuyiswamb | Views: 2740 | Category: .NET Framework | Level: Advance | Print Article
This Article will introduce you to the Windows Service. Our Example is a Service that kills unwanted Processes.

.NET Training Videos!
Buy online comprehensive training video pack just for $35.00 only, see what's inside it.

Introduction

Have you ever had a Process in your Server that takes up all the Memory? , did you wonder how you going to kill that process when it occurs? In this Article we are going to use Windows Service to kill the Process in every defined time intervals. Please note that you have to identity the culprit Service or Process. First of all you have to know what Windows Services are.

What is a Windows Service

Wikipedia says that 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. They are similar in concept to a Unix daemon. Many appear in the processes list in the Windows Task Manager, most often with a username of SYSTEM, LOCAL SERVICE or NETWORK SERVICE, though not all processes with the SYSTEM username are services. The remaining services run through svchost.exe as DLLs loaded into memory.

Code

Well you only need you Visual Studio, well am using VS2005. Now when we create Windows Service, we dont create them like other Applications, we dont need a Form, because this is a Service, it does not need any interaction while it’s running. So Go to your Visual Studio and go to FILE--> NEW-->VISUAL C# and Collapse the tree and Choose "Windows”, and Choose Windows Service. Give it a Proper name like mine is Process_Killer, and Choose the Proper location where your Project will be saved. I have created a Folder for it, you can do that as well. This will be easier when you do the installation.

 

 The First Step is to add an App.config file, we are going to use it to Store the Time and the Process to Kill. after you have done that go to Solution Explorer and rename the Component from Service1 to "Process_killer", when done double Click on the Brownish area to view the Code , you will see that VS has already structured some code for you. Make sure that your Code looks like this

Config File

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key ="Process" value ="NotePad"/>

<add key ="Time" value ="50000"/>

</appSettings>

</configuration>

 

//and this

 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.ServiceProcess;

using System.Text;

using System.Configuration;

using System.Threading;

namespace Process_Killer

{

public partial class Process_Killer : ServiceBase

{

String Process_Kill = ConfigurationSettings.AppSettings.Get("Process");

int Time = Convert.ToInt32(ConfigurationSettings.AppSettings.Get("Time"));

public Process_Killer()

{

InitializeComponent();

}

protected override void OnStart(string[] args)

{

 

 

Thread thread = new Thread(new ParameterizedThreadStart(DoWork));

thread.Start(Process_Kill);

}

 

protected override void OnStop()

{

// TODO: Add code here to perform any tear-down necessary to stop your service.

}

 

public void FindAndKillProcess(String name)

{

Process[] procList = Process.GetProcessesByName(name);

for (int i = procList.Length - 1; i >= 0; i--)

{

procList[i].Kill();

}

}

public void DoWork(object data)

{

string Process_Kill = data.ToString();

while (true)

{

FindAndKillProcess(Process_Kill);

Thread.Sleep(Time);

}

}

}

}

//Let me tell you what is happening above here. The First two lines

String Process_Kill = ConfigurationSettings.AppSettings.Get("Process");

int Time = Convert.ToInt32(ConfigurationSettings.AppSettings.Get("Time"));

//We are declaring two Variables and initializing them with the Value that is stored in a Configuration file. Using "System.Configuration" is responsible for the above.

 

protected override void OnStart(string[] args)

{

 

 

Thread thread = new Thread(new ParameterizedThreadStart(DoWork));

thread.Start(Process_Kill);

}

//Here is what should happen when the Service Starts. We create a Thread that will Call the Process_kill method that will follow soon.

public void FindAndKillProcess(String name)

{

Process[] procList = Process.GetProcessesByName(name);

for (int i = procList.Length - 1; i >= 0; i--)

{

procList[i].Kill();

}

}

//This is the Function that will look for the Process from the Running Processes and Kill the Process.

 

public void DoWork(object data)

{

string Process_Kill = data.ToString();

while (true)

{

FindAndKillProcess(Process_Kill);

Thread.Sleep(Time);

}

}

 

 

The Dowork will call the Function and kill the Process and Sleep for a Specified time and wake and Kill the Process if it finds it. In the Time Variable is the time the Thread is going to Sleep and in the Process_Kill is the name of the Process. Another thing to note, a Process is not debugged like other Application. What you have to do is to go to the debug menu and select "Attach to the Process"

 

 

One more step is required. A Process needs to be installed like other Applications, but the Installation too, it’s different from other installation. the First Step is to create an installer for the Service, go back to your Brownish area and right click, Choose "Add Installer" and After that a new Component will be created in your Solution Explorer like this.

 

 

 

When done everything should look like this

 

 

Remember when you build your service, the Debug Folder or the Release Folder will have an Exe with your Service that you have to install. Now lets install the Service

 

Installation

 

 

There are Files that are important to install the Service, a Service can have an installer like other Applications, but there is more to do after installing.  The Option that we are going to use for the installation of this Service is in the Command Mode. Please make sure that there is .NET framework 2.0 installed in the destination System

 

Step One: Copy the installer Files from the Directory, to the Destination Folder preferably C:\.

 

 

Step Two: Go to the Following Directory, Remember this will depend on Operating System you are using, Every time when you install the .NET Framework every files for that framework is stored in the Microsoft directory starting with a V (Version) and a number.  V2.0.50727 is .NET 2.0.

 

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\

 

Go inside this Folder and look for an exe called InstallUtil. This exe is the one we are going to use to install the Service, but now our service installer is sitting in another directory, so copy this File to the Folder you copied from the Share.

 

 

Step Three: Now you have everything is ready to be installed, open the Command Prompt and do the Following, Change Directory to the Installer Files like this

 

 

 

Step Four: Now lets install the Service,

 

 

 

As you can see we are calling the Utility and using the Switch “-i” that means install and this utility is in the same directory as the installer files and the File that we are interested in is Process_killer.exe. After you are done, press Enter

 

 

And this is the Screen that will tell you that the Service has been installed and it has been logged if you are interested in log files you can look at your system log files, and the Service is not automatically started.

 

Step Five: Go to the Services and you will see you service as shown in the Picture and as you can see the Status in nothing, it means that the Service has not been started.

 

Step Six: Right Click on the Service and Start the Service

 

 

Currently this Service is Killing all the note Pads, that change it to kill a Process of your choice, Go to the directory where service files reside and look for a File names Process_Killer.Config, do not be Fooled by that exe, its an XML file.

 

But now to open this File you have to use a NOTEPAD, but remember after 5 Seconds this notepad will close, you cannot be that quick to write to a File. So  to overcome this , Open this File with a WordPad  and the File will look like this

 

 

 

Now as you can see it’s easy, just change that “Notepad” to any process name that you want to kill, remember do not include the extension of the Process and it must always be in those quotes. After you are done save the File then Notepad will not be killed every 5 seconds, another process will die every 5 Seconds.

 

 

Conclusion

 

I hope you like i. i tried to Explain it as much as i can, but for now this is what i have done. I would like to dedicate this Article to my Employer, no, let me say ex-employer, because am currectly serving a notice Period until 5th December 2008.

 

Thank you for everything.

 

Thanks


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


Experience:8 year(s)
Home page:http://www.VuyiswaMaseko.com
Member since:Sunday, July 06, 2008
Level:HonoraryPlatinum
Status: [Member] [Administrator]
Biography:Vuyiswa Junius Maseko is a programmer for ITS abacus and a moderator in ".NetFunda. Vuyiswa has been developing for 8 years now. his major strength are C# 1.1,2.0,3.0,3.5 and vb.net and sql and his interest are in asp.net, c#, smart clients, Robot Programming(embedded programming).He has been doing a lot of windows development and web development, but lately his projects are web based projects. He has been using .net since the beta version of it. Currently he works on 2.0 but has some project running on 3.5. Thanks to people like Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject), Sheo Narayan (.Netfunda).They have made vuyiswa what he is today.
 Latest post(s) from Vuyiswamb

   ◘ How to make your Control Always Available While Scrolling in ASP.NET AJAX posted on 3/11/2010 3:39:02 AM
   ◘ How to Write a Simple login page in Asp.net posted on 3/5/2010 5:53:22 PM
   ◘ How to Execute SSIS Packages in C# ASP.NET Part II posted on 2/24/2010 1:35:03 AM
   ◘ How to Execute SSIS Packages in C# ASP.NET - Part I posted on 2/12/2010 3:05:27 AM
   ◘ How to use Validation Controls in ASP.NET posted on 2/11/2010 8:02:52 AM


Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)