Creating a service for Visual Basic 2008 Express

Find this post interesting? Do you like interesting things? Maybe you would like my invention, a connectible candle called a WickBrick!

Get one here http://wickbrick.etsy.com/

WickBrick

One of the drawbacks to using VB 2008 express is that some of the functionality is removed. This is perfectly fair, I mean you can download and use it for free!

Well how do you go about creating a service with it then? Well this kind soul has so helpfully created a template that you can load into visual studio.

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4511&lngWId=10

Alternate download here http://sites.google.com/site/mellerbeck/Home/Windows_Se1973412152006.zip?attredirects=0

Ok, so the trick with that is to place the zip file under “My Documents\Visual Studio 2005\Templates\ProjectTemplates\C:\Documents and Settings\Luiz.BRASVALOR\Meus documentos\Visual Studio 2005\Templates\ProjectTemplates\Visual Basic”

Now, when you go to new projects you should be able to see the Windows Service as a template. So select that, now for a quick test you could follow this example

http://www.dotheweb.net/articles/dotnet/services.aspx

Basically add a timer (Right clicking on the Toolbox, and Choose Items, add System.Timers.Timer) Do not use the forms timer!

Add the Following Code to the Timer1_Elapsed:

Dim eventlog1 As New EventLog
If Not EventLog.SourceExists(“MyApp1”) Then
EventLog.CreateEventSource(“MyApp1”, “Application”)
End If
EventLog1.Source = “MyApp1”
EventLog1.WriteEntry(“This is a simple event log entry”)

End Sub

And For OnStart():

Protected Overrides Sub OnStart(ByVal args() As String)
‘ Add code here to start your service. This method should set things
‘ in motion so your service can do its work.
Timer1.Enabled = True
End Sub

Here is where you have to take a different path though, since we are using Express we can’t go right click add installer. Instead, as it shows here http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller(VS.71).aspx

You need to add your own installer code. So, right click on your project in the solutions explorer and go add new class.

Then copy and paste this in.

Imports System
Imports System.Collections
Imports System.Configuration.Install
Imports System.ServiceProcess
Imports System.ComponentModel

<RunInstallerAttribute(True)> _
Public Class MyProjectInstaller
Inherits Installer
Private serviceInstaller1 As ServiceInstaller
Private processInstaller As ServiceProcessInstaller

Public Sub New()
‘ Instantiate installers for process and services.
processInstaller = New ServiceProcessInstaller()
serviceInstaller1 = New ServiceInstaller()

‘ The services will run under the system account.
processInstaller.Account = ServiceAccount.LocalSystem

‘ The services will be started manually.
serviceInstaller1.StartType = ServiceStartMode.Manual

‘ ServiceName must equal those on ServiceBase derived classes.
serviceInstaller1.ServiceName = “Your Service”

‘ Add installers to collection. Order is not important.
Installers.Add(serviceInstaller1)
Installers.Add(processInstaller)
End Sub
End Class

The only important thing that you might need to change is the ServiceName = “Your Service” change to what ever you want your service to be called.

Ok, build your service.

Now you need to install your service. One way is to use the installutil.exe, this is located in

C:\WINDOWS\Microsoft.NET\Framework\   your dot net version here \ InstallUtil.exe

So run InstallUtil.exe and pass it the path to your compiled service. If all goes well if you go start, run, services.msc, your should see what ever you named your service show up. Go ahead and start your service and you should see sample messages appear in your event log.

Now, my newest favorite method of installing services is using an undocumented method call

This post talks about it http://anotherlab.rajapet.net/2006/06/self-installing-services-in-net.html

Add a reference to System.Configuration.Install and then

Imports System.Configuration.Install

Just create a form with two buttons and then paste
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Try
System.Configuration.Install.ManagedInstallerClass.InstallHelper(New String() {“C:\Test\YourService1.exe”})
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
System.Configuration.Install.ManagedInstallerClass.InstallHelper(New String() {“/u”, “C:\Test\YourService1.exe”})
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Then you can just click on the buttons to install and remove your service!

Advertisement

12 comments

  1. Hi Michael,

    Thanks for linking to my blog posting about how to self-install services. I originally wrote that post because the installer tool that I was using at the time could not reliably install .NET 2.0 based services.

    Have you looked ar WIX? It has the ability to install services and it’s a cheap way to created a Windows Installer based setup for a VB Express service.

  2. I am confused. Where am I supposed to unzip the files to? It doesn’t work in:

    C:\Documents and Settings\Dad\My Documents\Visual Studio 2005\Templates\ProjectTemplates

    • You are not supposed to unzip it, simply place it in “C:\Documents and Settings\mellerbeck\My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual Basic”

  3. I couldn’t get the code to work. I think it has something to do with system.timers.timer being broken in this context. One is apparently supposed to use system.threading.timer.

    I changed the OnStart code to :

    Protected Overrides Sub OnStart(ByVal args() As String)
    ‘ Add code here to start your service. This method should set things
    ‘ in motion so your service can do its work.
    Const iTIME_INTERVAL As Integer = 5000 ‘ 60 seconds.
    Dim oTimer As System.Threading.Timer
    Dim tDelegate As Threading.TimerCallback = AddressOf EventAction

    oTimer = New System.Threading.Timer(tDelegate, Me, 0, iTIME_INTERVAL)

    End Sub

    which I got from this blog post:
    http://aspalliance.com/1316_Working_with_Windows_Service_Using_Visual_Studio_2005.all#Page1

    and everything works good now!

  4. I see this is a way to create a service…. but how would i go about just STARTING an existing service with VB.net express.
    ty

    • The .NET Framework has a class for controlling a service, the System.ServiceProcess.ServiceController class. If you do a search on that class, you’ll find plenty of example code for controlling an existing service.

  5. I am having a bit of a problem with the Service Installer portion of this. Every time I try to install the Service, I get the following error message and the service I’ve created is not installed:

    Installing assembly ‘C:\Temp\LAIGetFiles.exe’.
    Affected parameters are:
    logtoconsole =
    assemblypath = C:\Temp\LAIGetFiles.exe
    logfile = C:\Temp\LAIGetFiles.InstallLog
    Installing service LAIGetFiles…
    Creating EventLog source LAIGetFiles in log Application…
    Rolling back assembly ‘C:\Temp\LAIGetFiles.exe’.
    Affected parameters are:
    logtoconsole =
    assemblypath = C:\Temp\LAIGetFiles.exe
    logfile = C:\Temp\LAIGetFiles.InstallLog
    Restoring event log to previous state for source LAIGetFiles.
    An exception occurred during the Rollback phase of the System.Diagnostics.EventLogInstaller installer.
    System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.
    An exception occurred during the Rollback phase of the installation. This exception will be ignored and the rollback will continue. However, the machine might not fully revert to its initial state after the rollback is complete.

    Your help would be greatly appreciated.

    Thanks,
    pete

  6. I don’t get this at all. You first of all say to place the file in ““My Documents\Visual Studio 2005\Templates\ProjectTemplates\C:\Documents and Settings\Luiz.BRASVALOR\Meus documentos\Visual Studio 2005\Templates\ProjectTemplates\Visual Basic”” – which doesn’t seem to be a valid directory.

    Then, in a later comment, you say to place the file in ““C:\Documents and Settings\mellerbeck\My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual Basic””, which doesn’t seem to work either.

    Note that the first directory references VS 2005, and the second 2008. Is this supposed to work for 2005? 2008? both?

    • Yes, it does work for both 2005, and 2008. The trick is to copy the .zip file into the templates folder. Are you able to locate a folder that looks similar to the one mentioned. It will be something like docs and settings\your profile\my docs\vistual studio\templates etc…

  7. Thank you for this tutorial! It was nice and easy to assemble, worked on first attempt.

    Do you know how to add a description to the service that will appear in the MMC?

    Thanks
    Ben W

  8. If you are using the ManagedInstallerClass.InstallHelper method, you’ll need to set the description yourself. Just write a string value for “Description” in the HKLM\System\CurrentControlSet\Services\YourService key. Or use the ChangeServiceDescription() function in advapi32.dll.

Leave a Reply to D Alb Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s