C# Windows Service Visual Studio 2008

Creating a program that can run in the background of the operating system has any benefits, this is very important as the program can run without a graphic user interface. Complex service that are to run are longer time, and without the need the user to login the system. Windows services are harder to develop, debug, and test. But if you software are to run in server that require to start up automatically with the server is turn on, Windows service is your choice.

Here I will demo you how to create a windows service project using C# and using .NET Framework 3.5, to cover the latest of technologies. Older framework are not much different in developing, you can find how to develop older framework Windows service from Google. I’m going to teach you how to develop a windows service

Creating your skeleton project in Visual Studio 2008

To create a Windows Service project in Visual Studio 2008, you must select from the Visual C# Windows Projects. Give your Windows Service a name, and then select OK.

As a result Visual Studio 2008 creates you an empty solution with a Windows Service project as a default to the development.

Switch to code view, to start developing.

As you can see that Visual Studio 2008 has simplify the layout and initialization of the code for Windows Service development. Now let’s start by creating the PingJob() method;


static
void PingJob()

{


while (true)

{


try

{

System.Net.IPHostEntry objIPHE = System.Net.Dns.GetHostEntry(“www.google.com”);

System.Threading.Thread.Sleep(15000); // wait 15 seconds

}


catch (Exception ex)

{


EventLog.WriteEntry(“PingTest Service”, ex.Message, EventLogEntryType.Warning);

}

}

}

As you can see that I use the method of resolving the DNS with ISP nameservers, this is more reliable method on checking the internet connection is working. And also windows service can’t output to a Windows Console to report the exception error, therefore you will have utilize method that doesn’t interact with the graphic user interface. Here I use the Windows EventLog, you can find more about this EventLog from Google (who know all).

Ok now you will have to call PingJob() method from OnStart(), I will make this PingJob() run as a separate thread from the main, and let it run until the operating system is shutdown, or the service is stopped.


protected
override
void OnStart(string[] args)

{

System.Threading.ThreadStart job = new System.Threading.ThreadStart(PingJob);

System.Threading.Thread thread = new System.Threading.Thread(job);

thread.Start();

}



protected
override
void OnStop()

{


Environment.Exit(-1);

}

Do a Build Solution (Ctrl+Shift+B) to make sure that all your codes don’t have any bugs.

<–nextpage–>

Creating an Installer for you Windows Service

From you solution select File>Add>New Project… from menu

Then from Add New Project, select Other Project Types, and choose Setup Project

Then Visual Studio 2008 will prepare a setup shell for you configure the set require of Solution, and now let add our Windows Service to our installer. From the Application Folder right-click, select Add>Project Output.

From the Add Project Output Group windows select the Primary output and make sure that your Windows Service Project is select has the project, then select OK.

From the Setup properties configure your properties of your installer;

Now that you would like to preconfigure your windows service application, when the user install the application into their operating system. Let us add a project installer configuration code to our project. Right-click from service class in your windows service project within design mode, and choose “Add Installer” from the menu, then ProjectInstaller class will create for you.

Switch to code mode to start configure the behavior of your windows service application, doing this by selecting ProjectInstaller.Designer.cs.

Modify the service installer as you require, as for me I usually modify account the service will run as, the service startup type, and the service name that will appear in Windows Service MMC.



private
void InitializeComponent()

{


this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();


this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();


//


// serviceProcessInstaller1


//


this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;


//this.serviceProcessInstaller1.Password = null;


//this.serviceProcessInstaller1.Username = null;


this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);


//


// serviceInstaller1


//


this.serviceInstaller1.ServiceName = “PingTestService”;


this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;


// ProjectInstaller


//


this.Installers.AddRange(new System.Configuration.Install.Installer[] {


this.serviceProcessInstaller1,


this.serviceInstaller1});

}

Do a Build Solution to test that does your solution contains any bugs, let’s hope the best. Then Build the Installer from the Setup project by right-click on the Setup project, and choose build the project. Therefore you can see that there is Install/Uninstall option if you complete building the installer, and that you right-click again.

Let’s trying installing our Windows Service, as you can see that our setup wizard will show up, cool!

After you have you done.

kick it on DotNetKicks.com


Kick It on DotNetKicks.com

  • Nemanja

    Thanks mate, very helpful.

  • Larry Teng

    I got this error from Visual Studio 2008… Is it normal?

    Error 1 ‘WindowsService1.ProjectInstaller’ does not contain a definition for ‘serviceProcessInstaller1_AfterInstall’ and no extension method ‘serviceProcessInstaller1_AfterInstall’ accepting a first argument of type ‘WindowsService1.ProjectInstaller’ could be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\teng\My Documents\Visual Studio 2008\Projects\WindowsService1\WindowsService1\ProjectInstaller.Designer.cs 39 117 WindowsService1

  • http://www.sarin.mobi Sarin Na Wangkanai

    You must have change the method name that serviceProcessInstaller1_AfterInstall is using. try checking if the method is name correctly.

  • CJHInNashville

    Hi Sarin, I’ve received the same error as Larry Teng. I have not changed the method name that serviceProcessInstaller1_AfterInstall is using. Could you go back and check your code? Thanks!

  • CJHInNashville

    I found the solution Larry Teng. Update your ProjectInstaller.cs class to look like this…
    public partial class ProjectInstaller : Installer
    {
    public ProjectInstaller()
    {
    InitializeComponent();
    }
    private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {

    }
    }

    There is a similar post here: http://74.125.47.132/search?q=cache:_bs6FDWCh7YJ:an-it-solution.blogspot.com/2009/05/how-to-make-windows-service-using-c.html this.serviceProcessInstaller1.AfterInstall&cd=2&hl=en&ct=clnk&gl=us

  • lokuge

    Thank you very much Sarin.This articale is short and sweet.

    thank you for CJHInNashville also.He sorted out the mising part of this blog.

    Note:

    That is u have to enable the serviceProcessInstaller1_AfterInstall event on serviceProcessInstaller1 object inside the
    ProjectInstaller.cs(design) container.

    Happy Programming !

  • Stavo

    Hi

    Thank you very much for the article, it was nice and easy (they way I see it). My problem is that once I install the service, it doesnt show on the Services mmc. It does show on Add/Remove programs.

    What could be the cause of this? Has anybody encountered this before?

    Thank you in advance

  • Nachi

    Stavo,

    I did encounter the same same problem. I am not able to see ‘PingTest’ service in my Services MMC. It is seen in Add/remove Programs. Not sure how to resolve this. Did anyone identified a solution for this?

    Thanks,
    Nachi

  • Joe

    You need to install the service. Just running setup isn’t enough. Here are the details:

    http://msdn.microsoft.com/en-us/library/aa984379(VS.71).aspx

  • http://www.sarin.mobi Sarin Na Wangkanai

    That is where; comes in

    this.serviceProcessInstaller1.AfterInstall = new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);

    I think under vista/7 is different

  • http://www.e-path.co.uk Paul

    Yes is there a better way to make the service automatically run without having to use installutil? Ideally I just want the setup program to install the service for me. However, it doesn’t seem to.

  • Chuck

    The link below will help to add the service into the MMC during the installation.

    http://stackoverflow.com/questions/1560407/c-windows-service-not-appearing-in-services-list-after-install

  • Paul

    I tries this, but I get the following message when I try to install…

    c:\windows\microsoft.net\framework\v2.0.50727\InstallUtil PingTest.exe
    Microsoft (R) .NET Framework Installation utility Version 2.0.50727.4016
    Copyright (c) Microsoft Corporation. All rights reserved.

    Running a transacted installation.

    Beginning the Install phase of the installation.
    See the contents of the log file for the C:\Users\Paul\Documents\Visual Studio 2
    008\Projects\PingTest\PingTest\bin\Debug\PingTest.exe assembly’s progress.
    The file is located at C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingT
    est\PingTest\bin\Debug\PingTest.InstallLog.
    Installing assembly ‘C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingTes
    t\PingTest\bin\Debug\PingTest.exe’.
    Affected parameters are:
    logtoconsole =
    assemblypath = C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingTest\P
    ingTest\bin\Debug\PingTest.exe
    logfile = C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingTest\PingTe
    st\bin\Debug\PingTest.InstallLog
    Installing service PingTestService…
    Creating EventLog source PingTestService in log Application…

    An exception occurred during the Install phase.
    System.Security.SecurityException: The source was not found, but some or all eve
    nt logs could not be searched. Inaccessible logs: Security.

    The Rollback phase of the installation is beginning.
    See the contents of the log file for the C:\Users\Paul\Documents\Visual Studio 2
    008\Projects\PingTest\PingTest\bin\Debug\PingTest.exe assembly’s progress.
    The file is located at C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingT
    est\PingTest\bin\Debug\PingTest.InstallLog.
    Rolling back assembly ‘C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingT
    est\PingTest\bin\Debug\PingTest.exe’.
    Affected parameters are:
    logtoconsole =
    assemblypath = C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingTest\P
    ingTest\bin\Debug\PingTest.exe
    logfile = C:\Users\Paul\Documents\Visual Studio 2008\Projects\PingTest\PingTe
    st\bin\Debug\PingTest.InstallLog
    Restoring event log to previous state for source PingTestService.
    An exception occurred during the Rollback phase of the System.Diagnostics.EventL
    ogInstaller installer.
    System.Security.SecurityException: The source was not found, but some or all eve
    nt logs could not be searched. Inaccessible logs: Security.
    An exception occurred during the Rollback phase of the installation. This except
    ion will be ignored and the rollback will continue. However, the machine might n
    ot fully revert to its initial state after the rollback is complete.

    The Rollback phase completed successfully.

    The transacted install has completed.
    The installation failed, and the rollback has been performed.

  • Edinson

    thank’s a lot man…!

  • James Thomas

    I was having the same problem as others, PingTest.exe installed as a program but not as a service.

    So I followed Chuck’s “link” post from Dec. 11, 2009: http://stackoverflow.com/questions/1560407/c-windows-service-not-appearing-in-services-list-after-install

    However, now when I try to install using Setup1.msi, I get a Set Service Login dialogue that asks for Username and Password. I put in my network login info and I get: Error 1001. The account name is invalid or does not exist, or the password is invalid for the account name specified.

    I need to either by pass this or discover what the account name/password is actually looking for.

  • Pingback: VS 2008 Windows Service Installer Doesn’t work | DeveloperQuestion.com

  • Hunt

    Looks cool but difficult to use correctly as images are missing :(

    http://sarin.mobi/images/073151_2144_CWindowsSer1.png for instance is missing!

  • ranakhalil

    The service is installed but not working!
    I can not find it in the services on my pc!
    can you please help

  • Ms11manoj19sharma

    this service is installted successfully…but plz tell me what does it work and how can i use this service..it may be open the google.com on start the computer or any other thing else. 

    thanks for support.

  • Mloffland

    To “enable” the 
    serviceProcessInstaller1_AfterInstall event (at least in Visual Studio 2008): 

    * double-click ProjectInstaller.cs [Design]
    * double-click the serviceProcessInstaller1 object
         - This will auto-write the code for serviceProcessInstaller1_AfterInstall
    * Save ProjectInstaller.cs

    You’re welcome! ;)