Creating a Windows Service in VB.NET

Environment: .NET, Visual Basic

Introduction

You want to write an application that constantly monitors some files, creates a log, or whatever, and one that ran constantly in the background while the machine is busy doing something else. The best way to do this was to run a Windows application continuously or at a regular interval with the use of the Windows scheduler. But there was one big disadvantage: Someone had to log on to the system to start this application.

This is no longer a problem because the best way to do all this is to create a Windows Service for Windows 2000/Windows NT.

What Is Windows Service (Previously Called NT Service)?

The core function of a Windows Service is to run an application in the background. A few things that make them different from a Windows application are that a Windows Service starts before any user logs on to the system (if it has been set up to start at boot up). The service can be set up in such a way that it requires the user to start it manually.

Also, Windows Service has its own process; hence, it runs very efficiently. Normally, a Windows Service will not have a user interface for the simple reason that it can be run even if no one is logged on to the system. This is not a rule; you can still have a Windows Service with a user interface.

In Windows 2000, you can view all the services running on your computer by opening Control Panel, Administrative Tools, and then clicking Services.

Creating a Windows Service in VB.NET

Prior to VB.NET, creating a Windows Service was a lot of work. You had to use some system-level procedure that was not very easy, but thanks to VB.NET this has become very easy. We shall now learn how to create a Windows Service.

You should know a few things before we dive in. Windows Service is not available in Windows 95, 98, or ME. You need to have Windows NT or Windows 2000 to run Services.

The advantage to using .NET is that the framework incorporates all the classes. This shall help us to create, install, and control Windows Service.

Open your Visual Studio .NET, create a new Windows Service Project, which we shall call MyService, and then click OK.

Add the Timer control from the Toolbar in the Components tab. In the properties window of Timer1, change the Interval property to 10000, which is 10 seconds.

The Source Code

Double-click the Timer1 control to open a code window for Timer1_Elapsed and type the following code. (This code shall execute every 10 seconds.)

  Dim MyLog As New EventLog() ' create a new event log
  ' Check if the the Event Log Exists
  If Not MyLog.SourceExists("MyService") Then
    MyLog.CreateEventSource("MyService", "Myservice Log")
  ' Create Log
  End If
  MyLog.Source = "MyService"
  ' Write to the Log
  MyLog.WriteEntry("MyService Log", "This is log on " & _
                    CStr(TimeOfDay), _
                    EventLogEntryType.Information)

Type the following code in the OnStart procedure. (This procedure is called when you start the service, which shall enable the timer.)

    Timer1.Enabled = True

And type the following code in the OnStop procedure. (This procedure is called when you stop the service, which shall disable the timer.)

    Timer1.Enabled = False

Our application is now ready, but a few things still need to be done before we move ahead. When we build this application, the executable created is not a Windows application; hence, you can't just click and run it. It needs to be installed as a service but don't worry; we don't have to do it manually. VB.Net has a facility to add an installer to our program and then use a utility to install the service.

Adding Installer to the Project

Open the Service1.vb design window and right-click and then select the Add Installer option. This adds an installer project, ProjectInstaller.vb, with two controls, ServiceProcessInstaller1 and ServiceInstaller1, in our existing project.

Select the ServiceInstaller1 control and open the property window. Change the ServiceName and DisplayName properties to MyService. (This is the name you want to appear in the list of services in Services windows.)

Select the ServiceProcessInstaller1 control and open the property window. Change the Account property to LocalSystem. (This needs to be specified because we need to run this on our local machine.)

Now it time to build the application and create an executable. Select Build Solution from the Build menu to create an executable with installation instructions for the service.

Installing the Service

To install this service, we need to use the InstallUtil program, which is a .NET utility, to install Windows Service. You can find this in folder C:\WINNT\Microsoft.NET\Framework\v1.0.3705. (This might be different on your computer, depending upon the version you are using.)

Alternatively, you could run the .NET Command Window by selecting Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt. This sets all the required paths for you.

Type the following command in that window: InstallUtil C:\tgol\Myservice\Bin\Myservice.exe. (This is the path for the executable of the service we just created. Remember, VB.NET created the executable in the Bin Folder under the project folder. Please make sure you change this to your executable path.) Please look at the message and log to make sure the service is installed properly.

Starting the Service

Running a service and starting a service are two different things. When we install the service with InstallUtil, we are now running the service but have yet to start it. To view and start the service, open the Control Panel. Open Administrative Tools, click Services, locate MyService, and right-click and select Start to start this service.

Now our service has started. Open the Event Viewer from Administrative Tools and click the Application Log to see the logs created by the Service (MyService) every 10 seconds. (If you don't see any logs, click Refresh [F5]. You will have to keep refreshing to see the latest event logs.

Stopping the Service

Open Control Panel, open Administrative Tools, click Services, right-click MyService, and select Stop to stop the service.

Uninstalling the Service

This procedure is similar to installing the service, but now we shall run the InstallUtil with /U Parameter, which uninstalls the service:

InstallUtil /U C:\tgol\Myservice\Bin\Myservice.exe (or executable path on your computer). Please look at the message to confirm that the service is uninstalled properly.

Tips

  • Stop the service and close the Service window before you install/uninstall the service.
  • Always uninstall/install if you make any changes to the service application.
  • Try avoiding user interface, inputs, and msgbox in the Service Application.
  • Open ProjectInstaller.vb, select ServiceInstaller1 control, and open the property window. Change the StartType property to Automatic if you want to start the service automatic.

Conclusion

Windows Service is often overlooked. Use Windows Service instead of a standard application when you have to monitor or administer something in the background. The only disadvantage is the installation procedure, but I bet there are more positive aspects then negative when selecting Windows Service over applications running Windows Scheduler.



Comments

  • window service

    Posted by Dunamis on 06/09/2014 06:40pm

    how to handle error in windows service? thanks :D

    Reply
  • Step

    Posted by Sneha on 08/10/2012 12:10am

    HI Can you please give a steps how i can go with

    Reply
  • Change an installed windows service startup type

    Posted by ghendric on 04/23/2009 01:24pm

    Is there a way to change the startup type of an already installed service using code?

    Reply
  • Window Service

    Posted by tonymathewt on 01/16/2007 10:39pm

    Your article on Window service was excellent. I have tried your example as well. But tried to write a simple code on a window service like showing a message box in every 10 secs once the service is started. The service got installed using the InstallUtil command but it could not be started. When we opt start from services window it brings up a dialog saying that "The service returned no error. This could be a problem with internal Window....". Is it possible to write such pure VB code as we do in a typical Window Application? I have written an application that does some website monitoring at regular intervals, I would like turn it into a Service. Please reply. Thankyou

    Reply
  • 8.3 Naming versus Long File Naming

    Posted by joe@dns on 11/01/2006 02:25pm

    This example is very easy to follow, and nicely demonstrates how to set up a service. However, my file paths do not follow the 8.3 naming format that is used in this example. If your path to the exe is in the long format (contains spaces or is longer than 8 characters) make sure to enclose the path in quotes: InstallUtil "C:\Visual Studio 2005\Projects\Myservice\Bin\Myservice.exe"

    Reply
  • uninstall windows service

    Posted by syap on 01/19/2006 07:44pm

    Should I restart the computer after I uninstall win service, even I have closed the SERVICE window? What happen is that I cannot delete the .exe file and I cannot install again.

    Reply
  • Its Excellent information

    Posted by manishkaushik on 12/20/2005 01:38am

    Thanks Jayesh
    and it will more help full if u have mentioned some real life situation where one can use the Windows Services.
    
    Manish

    • Problem with my own Windows Service

      Posted by cmfchong on 12/22/2008 12:06am

      I created my service using VB.NET.  But it runs fine in XP, and when I try to run it in Windows Server 2003 or 2008 --  it fails.  Pls help.  Thanks.  Desperate for help.
      
      MF
      cmfchong@hotmail.com

      Reply
    Reply
  • How to add Service Description?

    Posted by BruceDimon on 08/12/2005 07:24am

    Good overview. I'm writing my first service now and this article helped. However, I have a question. The control applet used to start and stop the services has a column for a Description. How do we add a Description for our service?

    • Dude

      Posted by Chuck on 01/24/2013 05:35pm

      You can set the service description on the ServiceInstaller1 properies.

      Reply
    Reply
  • The inner exception System.Security.SecurityException

    Posted by Legacy on 12/12/2003 12:00am

    Originally posted by: Mike B.

    I get the following error when I attempt to install th service on my local XP machine:


    Unable to create an instance of the MBService.ProjectInstaller installer type.
    System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
    The inner exception System.Security.SecurityException was thrown with the following error message: Security error..
    Installing assembly 'h:\my documents\visual studio projects\mbservice\bin\mbservice.exe'.
    Affected parameters are:
    assemblypath = h:\my documents\visual studio projects\mbservice\bin\mbservice.exe
    logfile = h:\my documents\visual studio projects\mbservice\bin\mbservice.InstallLog

    Reply
  • Service Description

    Posted by Legacy on 12/09/2003 12:00am

    Originally posted by: vbdev

    Where can I type the service description yhat appear in the service windows?

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Is your sales and operations planning helping or hurting your bottom line? Here are 5 useful tips from the experts at Quintiq to guide you to a better S&OP strategy.

  • Mobile is introducing sweeping changes throughout your workplace. As a senior stakeholder driving mobile initiatives in your organization, you may be lost in a sea of technologies and claims from vendors promising rapid delivery of applications to your employees, customers, and partners. To help explain some of the topics you will need to be aware of, and to separate the must-haves from the nice-to-haves, this reference guide can help you with applying a mobile strategy in the context of application …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds