Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Proper way of developing and setting up a Windows Service Project (step by step)

5.00/5 (2 votes)
10 Feb 2011CPOL4 min read 10.7K  
Creating a Windows Service is easy, but it might be a bit tricky especially for those who are new to developing such a project.

Creating a Windows Service is easy, but it might be a bit tricky especially for those who are new to developing such a project, like me when I developed my first Windows Service. Before, I had to use installutil by invoking such a command:

C:\WINDOWS\Microsoft.NET\Framework\{FrameworkVersion}\InstallUtil.exe C:\MyDemoService.exe

Also, the Setup project wizard in Visual Studio is not that straightforward, so if you are looking for a step by step walk-through on how to achieve this task, then look no further as I will explain everything from development to the set up of a project in the least amount of steps possible.

Now let's start by creating a Windows Service Project:

Image 1

Once it is created, you can now do the coding by switching to the code view:

Image 2

Now for our sample, we will write items on an event log every 5 seconds; this makes sure that we know that the service is running as expected. So copy the code below to your project:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;

namespace Demo_Windows_Service
{
    public partial class Service1 : ServiceBase
    {
        Timer myTimer = new Timer();
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //Starting 

            //Handle Elapsed Event
            myTimer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

            //Set Interval to 1 Second 
            myTimer.Interval = 5000;

            //Enable the Timer
            myTimer.Enabled = true;
        }

        protected override void OnStop()
        {
        }
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            myTimer.Enabled = false;

            //Perform Processing Here
            DoSomething();

            myTimer.Enabled = true;
        }

        private void DoSomething()
        {
            string sSource;
            string sLog;
            string sEvent;

            sSource = "Demo Windows Service";
            sLog = "Log Something : " + DateTime.Now.ToString();
            sEvent = "Event Fired";

            if (!EventLog.SourceExists(sSource))
                EventLog.CreateEventSource(sSource, sLog);

            EventLog.WriteEntry(sSource, sEvent);
            EventLog.WriteEntry(sSource, sEvent, 
                     EventLogEntryType.Information, 100);

        }
    }
}

Once finished, add an installer to your service; this piece of configuration will be invoked by the setup project. So go to Service1.cs [Design] and right-click on the open area, then choose “Add Installer”.

Image 3

Once done, you will have two objects to configure, which are serviceProcessInstaller1 and serviceInstaller1.

Image 4

Now let's configure serviceProcessInstaller1. This defines who the service will run as. These are the things you see in the Logon tab of the service property. Now you can choose whether you want it to be User, LocalSystem, NetworkService, or LocalService.

If you don’t know the difference between them, then here is a description:

  • User - This can be a domain user or a local user account, these are non built-in accounts that are given rights by an Administrator, so access rights might vary, so check with your administrator.
  • Local System or “NT AUTHORITY\SYSTEM” – This is a built-in account with a very high-privilege on the local system, and it acts as the computer on the network.
  • Local Service or “NT AUTHORITY\LOCAL SERVICE” – This is a built-in account that has the same privilege as members of the Users group, which means it has limited access. This account accesses the network resources as a null session without credentials.
  • Network Service or “NT AUTHORITY\NETWORK SERVICE” - This is a built-in account that has more privileges than the members of the Users group. This account accesses the network resources by using the credentials of the computer account.

Image 5

Now let's configure serviceInstaller1. This section defines how the service will behave and it will also contain the description and name of the service you are setting up. These are the things you see in the General tab of the service property.

Image 6

Now you are done with your installer. The next thing to do now is your Setup project; do that by adding a new project in your solution.

Image 7

Choose 'Setup Project' under “Other project types”.

Image 8

Once chosen, you will be directed to the file system editor; if it does not happen, you can always right-click the project, then choose “View” -> “File System”. Once in the File System Properties, choose Application Folder and right-click on it to add a “Project Output”. This is where you define what the output of your project is, which can be an executable file, Class Library, or even a third-party DLL. In our case, it is a Class Library.

Image 9

Just choose the Service Project as the Primary Output, click OK.

Image 10

Now it will display all the output plus the dependencies if you have any on your Windows Service Project.

Image 11

Image 12

Now choose Custom Actions; this defines what is copied on Install, Commit, Rollback, and Uninstall.

Image 13

Choose the items you defined on the File System Properties by going to “Application Folder”.

Image 14

Then choose the Primary Output of your Service:

Image 15

Now it will show you that they are now configured on Install, Commit, Rollback, and Uninstall.

Image 16

Now you are left with the properties; you can place your Installer description, author, manufacturer, installer behaviour etc. This is the what is shown on Add Remove Programs:

Image 17

Now build your solution, then build your setup project. Once done, go to the Setup project folder and copy your setup to where you want to install your Windows Service.

Image 18

Now run the setup and just follow the wizard:

Image 19

Once finished, you are all good to go; type services.msc on the Run command to see if your service was successfully installed.

Image 20

You can also see Programs and Features, you can uninstall from there.

Image 21

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)