OK, so were goin to create a very simple Windows Service.  It won't do anything.  We will simply be able to start and stop it upon demand and have it write some highly exciting text to the machines event log.

The only goal that we have is to create this service and install it.  Pure and simple - no mucking about.

The Method

First off, we'll need to create a new project to contain our service.  You'll find plenty of places that will say "ooh - create a blank project and add everything manually because its better".  In my opinion, you're reading an article about how to create a simple service, so you probably are not ready for building absolutely everything from scratch just yet.  In which case, the Visual Studio template is a ver good place to start.

Open up Visual Studio (I'm using Visual Studio 2005 here) and go to File > New > Project as shown in the screenshot below:

Creating a new project in Visual Studio

When the New Project dialog window appears, select Visual C# > Windows > Windows Service as shown below.

Creating the Windows Service in Visual Studio


This will create all of the basics that we need in our project to create the service itself.  Visual Studio will have created the following files for us:
  • Program.cs
  • Service1.cs (if you have the correct options set in the Solution Explorer, you will also be able to see Service1.Designer.cs and Service1.resx)
We're not going to touch Program.cs, it does what we need for now and we'll leave it at that.  We are interested in Service1.cs.  In here, the template already contains two overridden methods from ServiceBase: OnStart() and OnStop().  As their name might suggest, these are the methods that are called when the service is stopped and started.  We're going to add some code to these methods to make them do something that we want.  In that case, modify the code so that is looks as follows:

        protected override void OnStart(string[] args)
        {
            if(!EventLog.SourceExists(this.ServiceName,Environment.MachineName))
            {
                EventLog.CreateEventSource(
                    new EventSourceCreationData(
                        this.ServiceName,
                        Environment.MachineName
                        )
                );
            }

            EventLog.WriteEntry(this.ServiceName, "The OnStart event has been called");
        }

        protected override void OnStop()
        {
            EventLog.WriteEntry(this.ServiceName, "The OnStop event has been called");
        }

All this is going to do is pop some entries in the event log to let us know that the service is there when we stop and start it.  What you might notice is that I have used this.ServiceName as the event source name.  This is that name that the service will run under when you install it.  It can be set in the properties window of the design view (by default, just double click the file in the Solution Explorer) of Service1.cs as is shown below:

Setting the service name

Normally, we would want the OnStart event to do something much more interesting to do some actual work.  For now however this will suit our purposes.  Quite a few articles that I have read finish at this point and tell you that you can just compile and install the service.  I find however that it is not quite that simple because as it is, this service will not actually install yet.  We need to make a few more steps.

What we need is an installer class.  When we run the install utility, this installer class tells the utility what to install and how to do it.  So lets add one by right-clicking on the project in the Solution Explorer and adding a new item:

Adding a new item

We will then be presented with a New Item dialog, in which we need to select ''Installer Class".  In my sample, I renamed the file to SampleWindowsServiceInsatller.cs.  Now, on its own, this doesn't do too much, we still need to tell the Installer what it needs to install.  To do this, we're going to modify the one method that the created file creates to read as follows:

        public SampleWindowsServiceInstaller()
        {
            ServiceProcessInstaller oServiceProcessInstaller = new ServiceProcessInstaller();
            ServiceInstaller oServiceInstaller = new ServiceInstaller();

            oServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
            oServiceProcessInstaller.Username = null;
            oServiceProcessInstaller.Password = null;

            oServiceInstaller.ServiceName = "SimpleWindowsService";
            oServiceInstaller.Description = "A sample service that simply starts and stops.  This is of no use whatsoever.";
            oServiceInstaller.StartType = ServiceStartMode.Manual;
            oServiceInstaller.DisplayName = "Simple Windows Service";

            this.Installers.Add(oServiceProcessInstaller);
            this.Installers.Add(oServiceInstaller);
        }

What these lines of code do is to:
  1. Tell the Installer itself what the name and description are of the service is that we want to install
  2. Tell the installer what credentials we want to assign to the service when it is installed.
If you want to find more information about these, then you can look at the links below:
We are now ready to install build and then install the service, so lets build the project from Visual Studio's Build menu.  Assuming everything goes well here, we can now close Visual Studio.

To actually install the service, we will need to use a .Net Command Prompt.  This is available from the Visual Studio Tools folder in your start menu (You can use a normal command prompt if you like, but you will need to know where the .Net Framework assemblies are so that you can access the tools).

In the command prompt, navigate to the location for your newly built project.  As an example, my project was built in the following location:

C:\_PROJECTS\Matt\_.Net 2.0\SimpleWindowsService\SimpleWindowsService\bin\Debug

Then, at the command prompt, run the following command:

InstallUtil /i SimpleWindowsService.exe

This tells the InstallUtil tool to look at our compiled project and use the installer class to install the service.  Once installed, go to Computer Management in the Administrative Tools in your Control Panel.  You should be able to stop and start your service and see the evens written in to the computers Event Log.

Happy Hunting


Related Link


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Wednesday, January 09, 2008 9:36 PM |

Comments

Gravatar
# re: Creating a Windows Serivce in C# .Net
Posted by Arun
on 7/30/2008 2:25 PM
HI,
Good article !!!!!
Thanks you very Much.

Aarun
Gravatar
# re: Creating a Windows Serivce in C# .Net
Posted by Dennis
on 8/1/2008 10:30 AM
Thanks! Works perfect for me!
Gravatar
# re: Creating a Windows Serivce in C# .Net
Posted by Stephen
on 1/29/2009 2:28 PM
Thanks - best description I found (which still did not make it appear in the services panel) until I found this:
http://support.microsoft.com/kb/816169
which did the job first time.
Gravatar
# re: Creating a Windows Serivce in C# .Net
Posted by Matt
on 1/29/2009 2:46 PM
Thanks Stephen, I'll make an edit and link to the KB you suggested. Its a good one by MS for a change :)
Gravatar
# re: Creating a Windows Serivce in C# .Net
Posted by Amit
on 2/5/2009 3:16 PM
Hi

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 4 and 8 and type the answer here: