ARTICLE

Create a Windows Service using VB.NET

Posted by Mahesh Chand Articles | Visual Basic 2010 January 19, 2000
Windows Services is new name for NT Services you used to develop in previous versions of Visual Studio. This tutorial walks you through how to create and use your Windows Services.
Download Files:
 
Reader Level:

Ok, its time for one more tutorial. This times pick is Windows Services. Creating Windows Services is not a big deal using Visual Basic. Just follow few simple steps and you are all set to run and test your first Windows Service.

Windows Services is new name for NT Services you used to develop in previous versions of Visual Studio. This tutorial walks you through how to create and use your Windows Services. This Service writes some text to a text file when stop and start the service. The base idea is taken from MSDN but its more elaborated. You can modify it according to your needs.

Step 1. Create Skeleton of the Service

To create a new Window Service, pick Windows Service option from your Visual Basic Projects, give your service a name, and click OK.

The result look like this. The Wizard adds WebService1.vb class to your project.

Set your ServiceName to your own name so it would be easier to recognize your service during testing OR you can set this property programmatically using this line Me.ServiceName = "mcWinService"

This is the name you will be looking for later :).

The default code of WebService1.cs added by the Wizard looks like here

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Configuration
Imports System.Data
Imports System.Web.Services
Imports System.Diagnostics
Imports System.ServiceProcess
Imports System.IO
Namespace mcWebService
' using System.Core;

Public Class WinService1 : Inherits System.ServiceProcess.ServiceBase
''' <summary>
''' Required designer variable.
''' </summary>
Private components As System.ComponentModel.Container
Public Sub New()
' This call is required by the WinForms Component Designer.
InitializeComponent()
' TODO: Add any initialization after the InitComponent call
End Sub

' The main entry point for the process
Shared
Sub Main()
Dim ServicesToRun As System.ServiceProcess.ServiceBase()
' More than one user Service may run within the same process. To add
' another service to this process, change the following line to
' create a second service object. For example,
' ServicesToRun = New System.ServiceProcess.ServiceBase[] {new WinService1(), new MySecondUserService()};
ServicesToRun = New System.ServiceProcess.ServiceBase() { New WinService1() }
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End
Sub

''' <summary>
''' Required method for Designer support - do not modify
''' the contents of this method with the code editor.
''' </summary>
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container ()
'@this.TrayAutoArrange = true;
'@this.TrayLargeIcon = false;
Me.ServiceName = "mcWinService"
End Sub

''' <summary>
''' Set things in motion so your service can do its work.
''' </summary>
Protected
Overrides Sub OnStart(ByVal args As String())
' Create a text file C:\temp\mcb.txt
Dim fs As FileStream = New FileStream("c:\temp\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write)
Dim m_streamWriter As StreamWriter = New StreamWriter(fs)
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End)
m_streamWriter.WriteLine(" mcWindowsService: Service Started " & Constants.vbLf)
m_streamWriter.Flush() 
End Sub

''' <summary>
''' Stop this service.
''' </summary>
Protected
Overrides Sub OnStop()
' Create a text file C:\temp\mcb.txt
Dim fs As FileStream = New FileStream("c:\temp\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write)
Dim m_streamWriter As StreamWriter = New StreamWriter(fs)
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End)
m_streamWriter.WriteLine(" mcWindowsService: Service Stopped " & Constants.vbLf)
m_streamWriter.Flush()
End
Sub
End
Class
End
Namespace

Step 2. Add functionality to your service

As you saw WebService1.vb, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service. I write some text to a text file when you start and stop the service. 

protectedoverride Sub OnStart(ByVal args As String())
Dim fs As FileStream = New FileStream("c:\temp\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write)
Dim m_streamWriter As StreamWriter = New StreamWriter(fs)
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End)
m_streamWriter.WriteLine(" mcWindowsService: Service Started " & Constants.vbLf)
m_streamWriter.Flush()
m_streamWriter.Close()
End Sub

''' <summary>
''' Stop this service.
''' </summary>
Protected
Overrides Sub OnStop()
Dim fs As FileStream = New FileStream("c:\temp\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write)
Dim m_streamWriter As StreamWriter = New StreamWriter(fs)
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End)
m_streamWriter.WriteLine(" mcWindowsService: Service Stopped " & Constants.vbLf)
m_streamWriter.Flush()
m_streamWriter.Close()
End Sub

Step 3: Install and Run the Service

Build of this application makes one exe, mcWinService.exe. You need to call installutil to register this service from command line. 

installutil C:\mcWebService\bin\Debug\mcWebService.exe

You use /u option to uninstall the service. 

installutil /u C:\mcWebService\bin\Debug\mcWebService.exe

Run the application

Step 4: Start and Stop the Service

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer.  

Under Services and Applications, you will see the service mcWinService. Start and Stop menu item starts and stops the service.

Step 5: Test the Service

Go to your temp directory and see if text file is there with contents or not. 

That's it.

References:

  • MSDN

share this article :
post comment
 

hi I am living in IRAN I have a problem in read data from registry in windows service that "getvalue" dose not work in service. please help me thanks

Posted by shahab chubineh Feb 13, 2011

Hi Mahesh,
I am developing a website monitoring tool, it basically reads all the web URL from app.config file and checks if they are working fine or not, if the application finds any error the it sends an email message and text message (SMS) to appropriate person.

Posted by Mitesh Agrawal Dec 14, 2009

I was trying to create a Windows Services that pops up a msgbox whenever the DB table updated! But for testing purpose I just created a Windows service to pop up a msgbox, it doesn't work! And I just wanted a call an application through it, that also didnt work! How can I call a Windows application through a services? and msgbox? Do we have any other way to call these? Advanced Thanks Shailesh Darji

Posted by shailesh darji Sep 29, 2008

I was trying to create a Windows Services that pops up a msgbox whenever the DB table updated! But for testing purpose I just created a Windows service to pop up a msgbox, it doesn't work! And I just wanted a call an application through it, that also didnt work! How can I call a Windows application through a services? and msgbox? Do we have any other way to call these? Advanced Thanks Kirubaa

Posted by Sunderam Kirrubananthan Jan 13, 2008

Hello Mahesh. I create a windows service. I install it through command line. Its properly installed. But my Service name is not shown in windows service

Posted by karthick babu Nov 20, 2007
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Team Foundation Server Hosting
Become a Sponsor