WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 57 users


WorldofASP.NET >> General .NET >> Applications

Creating Windows Services in .NET

Basic example and tutorial about Windows Services in .NET
Published Date : 22 Sep 2007
Author : James Douglas
Language : VB.NET,C#
Platform : Wins,.NET
Technology : Visual Studio
Views : 23811
Rating : (3 votes so far)



Introduction

This article will guide you on creating a simple WindowsService. WindowsServices are applications that can be automatically started when  the operating system boots. They can run without having an interactive user logged on the system. You can configure a Windows Service to be run from a specially configured user account or from the system user account.

Example of Current Windows Services that available on your machine is

1. WorldWideWeb Publishing service.
2. Microsoft Search Service.

You can view the list of services on your machine with the status (started or stopped) by opening the AdministrativeTools->Services.

Main

Creating Windows Service in .NET framework is particularly easy especially with the help of Visual Studio.
Open Your Visual Studio 2005 and Create New Project. Choose  the WindowsService template Project and named the project SimpleService.

The project template automatically adds a component class that is called Service1 by default and inherits from System.ServiceProcess.ServiceBase.

If you view the source code of the service, you can see the code snippet like below.

 public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}

The OnStart is executed once the service is started. It does not loop or being called multiple times.
If you like to have a repeated operation,you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Timer.Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.

The OnStop Event is executed once the service is stopped. You can write a logging mechanism here to inform that the service is stopped.

Now, Edit your Service properties by opening that in Design Mode. You can open the Service in design mode by double clicking the Service.cs. Set the Service Name to SimpleService.


Adding Functionality to your Windows Services.

To add functionality to your WindowsServices, you just need to write some code inside the OnStart event and OnStop event.
The code snippet below will show you very basic example for WindowsServices.

protected override void OnStart(string[] args)
{
EventLog.WriteEntry("MySimpleService Started");
}
protected override void OnStop()
{
EventLog.WriteEntry("MySimpleService Stopped");
}

The code snippet above will write into the EventLog if the service is started or stopped.

Installing Windows Services.

When you compile and build project, it will make one exe file called SimpleService.exe.  If you try to double click the exe file, you will get error message saying that "Cannot start service from the command line or debugger. A Windows Service must first be installed (using installutil.exe) and then started with the Server Explorer,Windows Service Administrative tools or the NET start command"

From  the error message above, you can see that in order to use the exe as a WindowsService, you need to execute installutil.exe. Installutil.exe file is located inside your .NET Framework folder "C:\windows\microsoft.net\framework\VERSION\

To install the exe as Services in your machine
installutil C:\..\bin\Debug\SimpleService.exe

To uninstall the service from your machine
installutil /u C:\..\bin\Debug\SimpleService.exe Run the application

Once you have install the exe as a Services, you can start and stop the services by using the AdministrativeTools Services console.

Tips for Debugging Windows Services.

If you try to run in Visual Studio 2005 by pressing F5, you will get an error message saying that
"Cannot start service from the command line or debugger. A Windows Service must first be installed (using installutil.exe) and then started with the Server Explorer,Windows Service Administrative tools or the NET start command". This will means that you will not be able to debug your WindowsServices easily.

To debug Windows Services, you can actually write into into text file for every output of your code and then install as services and then start and stop the services. This requires lot of effort and you cannot step in and step into your code by using Visual Studio. This will waste so much of your time. There is an easy way for you to code and debug Windows Services by using Visual Studio 2005.

The code snippet below will show you how to achieve that. Edit your Program.cs file.

static void Main()
{
string[] sArgs;
sArgs = System.Environment.GetCommandLineArgs();if (sArgs.Length > 1)
{
if (sArgs[1].ToLower() == "console")
{
Service1 oService = new Service1();
oService.StartService(sArgs); ;
System.Windows.Forms.Application.Run();return;       
}
}
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Engine(), };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
} 

From the code above, you can see that if we pass the first command line arguments called "console", it will then start the Services by using Windows.Forms.Application.Run method. This will allow you to debug and start the service manually by running the exe file.

You can edit your Visual Studio 2005 project file so that it will run the application using the "console" as a command line arguments. Right Click your projects , Choose Properties, and then Click on Debug Tabs as belows.


After you have set that, try to run the Project by pressing F5, you should be able to debug your windows services easily.

Conclusion

Creating Windows Services in .NET now is so easy with the .NET Framework and Visual Studio 2005. Remember in old days of using Visual Basic, it can be quite hard to code a Windows Services. In visual Studio 2005, you can add a Project Installer into your WindowsService project and then later on add a Deployment Projects if you like to create a installer that will install your windows service automatically.

I have provided a code sample on the example above. You can try and feel free to post any comments on my code.

Download Source Code




Other Related and Popular Articles :

How to Generate Random Numbers in ASP.NET and .NET Framework
Generating Random Number in ASP.NET and .NET Framework


Author Profile : James Douglas

I work in a Software House Company in Malaysia (Kuala Lumpur) and I am MCP Certified in C# and Web Application course.
I originally started my programming in Java but later on changed to Microsoft platform because of the simplicity and ease of use.
I love .NET programming and am doing it almost every day now.

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

#cannot start service from the command line or a debugger.A windows service must
23 Nov 2009 0:15 by : sabiranwer

by default the service or (Service1) does not have the "StartService" method. where did it come from? Unless I need to do something, it will not work...
even i am facing the same issue
yes i am using VS 2005

#Problem
17 Nov 2009 12:45 by : Gustavo Sanchez

Hi i know this is an old thread but i found it very useful except i keep having a problem as soon as the debug hits

System.Windows.Forms.Application.Run();return;

on the main, it stays stuck there and does nothing, any thoughts?

#Error
29 Oct 2008 8:40 by : prasad

Hello,
I tried to us e your example and there is a problem with it.
1. Due to the fact that you call System.Windows.Forms.Application.Run();
you must add Reference System.Windows.Forms.

2. by default the service or (Service1) does not have the "StartService" method. where did it come from? Unless I need to do something, it will not work...

Thanks,
Prasad Gopathi.

#There is a problem with your example.
04 Oct 2007 12:12 by : Vladimir V.

Hello,
I tried to us e your example and there is a problem with it.
1. Due to the fact that you call System.Windows.Forms.Application.Run();
you must add Reference System.Windows.Forms.

2. by default the service or (Service1) does not have the "StartService" method. where did it come from? Unless I need to do something, it will not work...

Thanks,
Vladimir

 
#Re: There is a problem with your example.
04 Oct 2007 20:23 by : James Douglas

The example should work fine and can be compiled successfully.
Are you using VS 2005?

Leave New Comments


Article Content copyright by James Douglas
Everything else Copyright © by WorldofASP.NET 2010

Category
.NET 3.5
AJAX and ATLAS
ASP.NET
C# Programming
Classic ASP
Enterprise Systems
General .NET
VB.NET Programming
Announcements
Earn Cash by writing an article or review
For more info Click here







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2010 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | ASP Hosting | ASP.NET Hosting | Phone Card | Calling Card |Stock Investing