Library tutorials & articles

Creating a Windows Service in VB.NET

Page 3 of 4
  1. Introduction
  2. What is Windows Service
  3. Adding an Installer to the Project
  4. Conclusion

Adding an Installer to the Project

Open the service1.vb design window, right click on it and select Add Installer option, which will add an installer project (called ProjectInstaller.vb) with two controls -- ServiceProcessInstaller1 and ServiceInstaller1 -- to our existing project.

Select the ServiceInstaller1 control and open the property window. Change the ServiceName property and DisplayName property to MyService (this is the name you want to appear in the list of services in the services window). Select the ServiceProcessInstaller1 control and open the property window. Change the Account property to LocalSystem (this needs to be specified as we need to run the service on our local machine).

Now it's time for us 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 our service we need to use the InstallUtil program, which is a .NET utility to install Windows services. You can find it in C:\WINNT\Microsoft.NET\Framework\v1.0.3705

Note: This directory might be different on your computer, depending upon the version of the .NET framework you are working with

Alternatively, you could run a .NET Command Window by selecting Start –> Programs -> Microsoft Visual Studio .NET -> Visual Studio .NET Tools >- Visual Studio .NET Command Prompt, which sets all of the required paths for you.

Type the following command in the command window:

InstallUtil "d:\My documents\development\applications\MyService\bin\Myservice.exe"

This is the path for the executable of the service we just created. Remember that VB.NET created the executable in the Bin folder under the project folder, so make sure you change this to your executable path.

Starting the service

Running a service and starting a service are two different things -- when you install the service with InstallUtil you are running the service, but have yet have to start it.

To view and start the service, open Control Panel -> Administrative Tools. Now click Services, locate MyService, right click on it and select Start to start it:

Our service is now started. Open the Event Viewer from Administrative Tools and click 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

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

InstallUtil /U "d:\My documents\development\applications\MyService\bin\Myservice.exe"

(or the executable path on your computer).

Take note of the message to confirm that the service was 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 a user interface, inputs and message boxes in the service application.
  • Open ProjectInstaller.vb, select the ServiceInstaller1 control, and open the property window. Change the StartType property to automatic if you want to start the service automatically.
  • If you want to debug your windows service, it isn't quite as straight forward as usual. Start your service, then go to Debug|Processes in the Visual Studio IDE. Find MyService.exe (you may need to check a box to display system processes), and attach the debugger. Then you'll be able to set breakpoints as usual - but not in the Start procedure.

 

Comments

  1. 14 Jul 2009 at 12:40

    Hey, for all you expert Windows developers, the best place for elite software engineering jobs in Switzerland and across western Europe is on http://qual.ch

  2. 27 Jun 2009 at 02:53

    Hi, and what about to make a vb 6.0 a windows service? Is this possible? How? Thanks for the help Templario55

  3. 16 Jun 2009 at 02:38

    FYI, if you are using VisualStudio 2008 you might run into the following problem. Adding Timer from the Components section adds a Timer from Windows.Forms namespace, this timer has a Tick event instead of an Elasped event that the example describes. This Tick event does not work as well with Windows Service(Most of the time it does not get triggered). To fix this, delete the timer from the design view and switch to code view. Add the following code. 'variable declaration Private WithEvents Timer1 As New System.Timers.Timer(120000) 'for 120 seconds 'event declaration Private Sub Timer1_Elasped(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed

    'Your code

    End Sub

    I hope this helps

  4. 01 Jun 2009 at 00:05

    hei, the windows service app is kind of helping me in my ongoing student project, and i thank everyone of you guys for putting this on this blog.

    But i have some problem and i know someone can help. I am only allowed to use HTTP in my school (ie, no FTP is allowed). and i have to upload some file from a specific folder on my PC to a web page at 1 hour intervals automatically (ie, every hour a file is dropped into that folder, and i have to get a windows service or web service that would automatically detect the new file, and the file finally show on my website page, hosted on the school server.). Remember, the files reside in a folder called DAT on my personal computer in my office. Someone to help me?

  5. 23 Apr 2009 at 17:55
    Is there a way to programatically set the startup type of a windows in vb.net or c#?
  6. 21 Mar 2009 at 16:22
    **Create Windows Service quickly using VS2008** you can create installer class just by right clicking in VS2008. See following: [http://urenjoy.blogspot.com/2009/03/create-windows-service-quickly-using.html](http://urenjoy.blogspot.com/2009/03/create-windows-service-quickly-using.html)
  7. 23 May 2008 at 10:35

    select otherlanguage then visual basic then click on windows option then u will find the windows service templete  on the right box.

    try it hope it wiill solve ur problem

    kaushik

  8. 12 Sep 2007 at 12:46

    You might be looking without clicking + sign on Visual Basic projects.Try expending the tree for visual basics projects and then lookin windows project you will see windows service project.

     

    bye

  9. 10 Aug 2007 at 07:28
    Hi Archu,
     I think i may be a Service pack Problem...Here in my system its showing the Windows Service template...
    if u already installed Service Pack or not u try to install it.

    Good Luck

    Regards
    Hari K......








  10. 06 Aug 2007 at 19:04

    I am using VS 2005/ .net 2.0 and when I try to create a project in vb.net environment, I do not see the Windows Service template. I however can see the template when I use the c# environment. Can anybody tell me what could be the issue. Thanks.

  11. 08 Dec 2006 at 23:03
    If you're having problems getting this tutorial to work with VS 2005, it's probably because you need to switch to using a different Timer class.  You can view more info here:
    http://weblogs.asp.net/sibrahim/archive/2004/01/13/58429.aspx

    A half-decent example of how to use the Threading.Timer class can be found here:
    http://www.informit.com/guides/content.asp?g=dotnet&seqNum=203&rl=1

    Hope this helps someone else...took me a couple hours to figure out what was going on!









  12. 07 Jun 2006 at 07:26

    Can this article be written for Visual Basic.Net 2005? It doesn't work if I follow it using VB 2005. :(

  13. 05 Jun 2006 at 18:43
  14. 14 May 2006 at 22:50

    I this example installutil.exe is located here "c:\installutil.exe

    yourService.exe is the Your  Service  

    the code:

    Try

    Process.Start(

    "c:\installutil.exe", ChrW(34) & "C:\yourService\yourService\bin\Debug\yourService.exe" & ChrW(34))

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

     

  15. 22 Apr 2006 at 15:52

    I first tried first method without success so I ran from the command prompt and it worked as advertised.

  16. 22 Apr 2006 at 11:47

    Gr8 help Jayesh Sir !

    it works smoothly; do exactly as written... kindly use double qoutes as well as indicated by him and copy the exact path from your own explorer window to .net command prompt

    my worked though after 2-3 failures

    cheers









  17. 13 Apr 2006 at 13:42

    hi jayesh,

      i followed the steps given by you but i am unable to install the service.

    whenever i double click installutil.exe it open some xml code

    and when i run my program it gives error service not started

    i am working on win xp .

    will this code work on win xp.

     

    thanks

    ravi verma

  18. 13 Apr 2006 at 13:41

    hi jayesh,

      i followed the steps given by you but i am unable to install the service.

    whenever i double click installutil.exe it open some xml code

    and when i run my program it gioves error service not started

    i am working on win xp .

    will this code work on win xp.

     

    thanks

    ravi verma

  19. 09 Feb 2006 at 23:14

    Allthough its of no use to me as i would not be able to make a decent service... Still wanted to say that is an awesome article, definitely something i will look into more now i know the basics :D thanks!

  20. 03 Feb 2006 at 15:12

    Well done.  I had considered threads, but since I'm not familiar with Windows' notion of environment containment, I wasn't sure if that would work.  Glad you got ahead of me there.  I'm going to create another service project and move bits into it from the desktop project.


    Glad the tip worked for ya.  I discovered it quite by accident whilst installing and uninstalling the original service project. For what it saved me in hair-tearing (and I haven't much left!) I thought it might be worth a mention ;-)


    BTW, I was pleasantly surprised with the new tickbox in class projects that will expose a Dot Net component to COM.  In VS2003 it was a PITA to create a COM wrapper for classes you'd like to use with IIS.  Well, boyhowdy, in VS2005, just tick the box and the next time the class compiles, you can take that resulting DLL, plonk it in your \inetpub\www folder and use it as if really had belonged there all along.


    I tried a Hello World ASPx form using my database transport DLL that I created in VS2005 as described and miracle of miracles, it worked perfectly the first time.


    After that, I think I'll quit for the week; not to press my good luck :-D


    Best,
    Bill

  21. 03 Feb 2006 at 07:32

    OK, I got it to work. Here's what I have so far: I created a thread to handle the UI, so basically it creates the form, and runs it


    Code:

    //coding in thin air, likely to have a number of bugs, but I'm sure you'll get the jist of things
    private Form1 myForm = null;
    private Thread myThread = null;


    public override void OnStart()
    {
      myThread = new Thread(new ThreadStart(ThreadEntry));  //or something like that
      myThread.Start();
    }


    public override void OnStop()
    {
      myThread.Abort();
    }


    private void ThreadEntry()
    {
      myForm = new Form1();
      Application.Run(myForm);
    }



    Then, I did some crappy stuff just to see if this works, so I used an overridden OnContinue to show the form


    Code:

    public override void OnContinue()
    {
      myForm.Show();
      base.OnContinue();
    }


    ...and I had a button that would hide the entire form.


    I think the reason your controls weren't showing up was due to a threading issue (i.e. the service is probably busy doing it's own thing, and doesn't get around to refreshing the controls). Errm... other than that, yeah you basically have to have the "Interact with Desktop" thing turned on. I hope this helps. Let me know if you have any questions!


    Oh, and thanks for the great tip about removing the service :) Saved me tons of restarting I bet.


    -Z

  22. 02 Feb 2006 at 13:39

    So far, not so good.  I made my service with two forms that I added to the project once the service class was set up.  My goal was the same as yours -- to have the forms pop up only when they're needed.  One piece of the mystery was to go into Services from the Control Panel, double click my service, then under the second tab, tick the box for "Allow service to interact with the desktop".


    After that, the service would start.  When it found that it was running for the first time and wanted configuration, it dutifully attempted to show the configuration form.  All I got was just the window frame, but none of the controls would display.  The entire application stopped accepting any event except for the shutdown.  At least that worked.


    I read further on MS's site and they suggest that we create two pieces: the service part that runs in the background and the UI part that runs as a typical desktop app.  They suggested that we use named pipes or some other form of IPC to communicate between the two pieces.


    Decidedly, this is a weird and nastily inconvenient way to create a service with a UI.  Me, I'm a *nix kinda guy; I'm used to a service being a program or a program being a service as the situation dictates.  So far, VS2005 and VB.Net are well short of Eclipse, but it's what I've got to work with for a particular small set of customers.


    If you guys find a workaround or decide to use the two-sided approach, would you be so kind as to repost here?  Thanks!
    Bill


    PS: OH! By the way:  if you use InstallUtil.exe to install the service, then wish to use InstallUtil.exe /U to uninstall the service, make sure that you have the Services window of the control panel closed.  Otherwise, the service will be marked for deletion and will remain in the Services window until you reboot.  Nasty, but that's the way it works.

  23. 02 Feb 2006 at 09:37

    I'm also really interested in learning how a service can support a UI.


    dragonsteve: how do you get your forms to come up? I was thinking of having a seperate application somehow "unhiding" the service's UI, and I was wondering if you used a similar approach? Hmm.. that might sound like a dumb idea, but I haven't really gotten to the whole service bit yet. Basically I wrote an application that does a bunch of stuff on a user-defined schedule and I only realized later that it would be very useful to have my app run as a service, so the whole service bit is essentially an afterthought.

  24. 27 Jan 2006 at 21:11
    I got one step further than you, but only the one.  In the Services panel, double-click your new service and go to the second tab, Login.  Check the box that says "allow service to interact with the desktop".

    My service ran after I did that, but if a form displayed, the only thing that showed up was the window frame itself with none of the controls.  The service, form and all stopped accepting events and I had to attach and stop the service from the VS2005 IDE.  (A simple stop service didn't do it.)

    If anyone can demonstrate how to have a service that may occasionally interact with a desktop, we'd love ya forever mean it.

    I created two "use them only if you need them" forms for my service.  One allows interactive configuration and the other is a status form that has some informational boxes and progress meters.

    Breadcrumbs... need 'em.

    Bill
  25. 27 Jan 2006 at 10:29
    Hi! How can I create and debug a windows service with Visual Studio 2005?

    Thanks.

    Marco.
  26. 07 Dec 2005 at 15:13

    I had the same problem.  The command line does not like spaces in the file name without quotes.  It's not bothered by spaces in the path, I guess, because they are delineated by the "\"s.


    Instead of:


    InstallUtil c:\path name\file name.exe


    try...


    InstallUtil "c:\path name\file name.exe"


  27. 05 Dec 2005 at 13:57
    I had the same problem... I have noticed that InstallUtil has problem when you use directory with empty space inside
    (C:\mydata\vb projects\MyService)
    So simply I have tried to create the project in a directory without empty space and it works now..
    (C:\test\MyService)...
    But this is crazy... because the directory with empty space vb projects has been created by .net by default!!!
    I hope this useful for you...
    MAX
  28. 29 Nov 2005 at 12:09
    Quote:
    [1]Posted by akansha_kesarwani on 10 Oct 2005 02:47 PM[/1]
    hi all

    There is a small problem, cud u all help me.
    I created a windows service and when i tried to install it using InstallUtil from .net framework it gives me system.io.filenotfound exception, although the service has been created free of errors n warnings.

    Regards
    Akansha



    Hi evrybody....

               We r also getting the same error as above.....kindly help us.....
  29. 10 Oct 2005 at 14:47

    hi all


    There is a small problem, cud u all help me.
    I created a windows service and when i tried to install it using InstallUtil from .net framework it gives me system.io.filenotfound exception, although the service has been created free of errors n warnings.


    Regards
    Akansha

  30. 20 Sep 2005 at 04:08

    When you build the service (create the exe) it is placed usually under a \bin sub-folder of the project, I have found that you must place every file in that folder in the exactly same directory and drive letter if installing it to another machine.  eg c:\myservice\bin for this example.


    remember that you can't be in the services view, if you want it to uninstall properly.


    Below is a batch file that will install, and start the service you create via the  "Creating a Windows Service in VB.NET" topic.


    c:
    cd \WINNT\Microsoft.NET\Framework\v1.1.4322\
    net stop "MyService"
    pause
    installutil /u "C:\MyService\bin\MyService.exe"
    pause
    installutil "C:\MyService\bin\MyService.exe"
    pause
    net start "MyService"
    pause

  31. 20 Sep 2005 at 01:03

    I have created a VB.Net windows service exactly as you outline, and it works a treat , I have then extended this so it interacts with a MS SQL, this installs and works, "again a treat", on the same machine I developed it on (VS 2003.)  When I install DOTnet on another machine and then install this service, it installs OK, BUT it won't start.  I've trimmed the code right back to find that the problem seems to be  "Public conDB As New ADODB.Connection"

  32. 16 Sep 2005 at 11:16

    Hi,


    in the article you say it is possible to create a service with a user interface.
    I have tryed this but for some reason my service doesn't want to run.
    First I added a windows form to my project.
    In my service I have a global variable that is my form.

    Code:
    Public oForm as FormUI


    In the onStart I set the oForm as new instance.

    Code:
    oForm = new FormUI


    After building my service and installing it with success I try to start the service but I get the following message:

    Code:
    ...service on local computer started and then stopped...


    I can't find any article that describes the implementation of a UI for a service.
    Could somebody please help me out?


    Kind regards,


    Steve

  33. 10 Aug 2005 at 10:47

    sorry there was a spelling mistake in the last reply.


    I meant to create .bat file not .abt file.


    ~vanj

  34. 10 Aug 2005 at 10:45

    "net start ServiceName"  is the command line argument to run the windows service without going to the ControlPanel-->Administrative Tools-->Services.


    I think you can create a .abt file with the above command and run that file from your application.


    And select StartType as Automatic under the ServiceInstaller properties.


    Hope that helps
    ~vanj

  35. 08 Aug 2005 at 23:36

    Need Help!!


    I've created a vb.net windows service using vs.net 2003 and added a setup and deployment project to my solution to install the service.


    The installer works great, the service is installed, however I need to add the ability for the service to be automatically started after the installer is finished. I.E. - the service needs to be started without having to restart the computer or manually go into the service control panel and starting.


    Does anybody know how I can start the service from code thats inside my installer??


    Any help would be greatly appreciated!!

  36. 03 Aug 2005 at 12:18
    As Dot Net frame work has InstallUtil.exe, in the command prompt go to the path where the InstallUtil.exe is present on the machine and run the command --InstallUtil Exename.exe, it will register the windows service
  37. 03 Aug 2005 at 11:31
    Hi all,
    On the machine which has dot net IDE we use
    the .NET command prompt and run InstallUtil ExeName.exe to make it a windows service.

    But when I want to deploy the application on another machine which has only the DOT NET FRAMEWORK and no IDE, how do I do it.

    Regards,
    vanj.
  38. 03 Aug 2005 at 03:46
    If you are programming in .NET, then take alook at the System.ServiceProcess.ServiceController class. It has methods which let you start, stop, pause, query and modify windows services.

    Must say that I've only just started in on this myself today with the kick off of a new project.
  39. 30 Jul 2005 at 05:46
    Is there any way to start a WinForm App from a VB .Net Service?
  40. 29 Jul 2005 at 20:15
    I've been trying to figure out the best way to have a client connect to a Windows Service. Would that be through Remoting or is there another way it can be done? Has anyone tried this?
  41. 26 Jul 2005 at 15:24

    I think the problem is due to :
    MsgBox("Start") under OnStart routine.


    Comment this line of the code and try it should work fine


    good luck!
    vanj.

  42. 26 Jul 2005 at 15:18

    Hi all,


    I would like to create a small UI associated with the service running. So that the user need
    not go to settings-->ControlPanel-->AdminstativeTools-->Services to start or stop a service.


    I want to have something similar to SQL server, which sits in the taskbar and user can start and stop the SQLserver from there.


    Please let me know how I can achieve something similar


    regards,
    vanj.

  43. 26 Jul 2005 at 15:10

    Hi soulliam
     I created the project again with component timer and under timer_elapsed handler have the required code and it works fine.


    thanks
    vanj

  44. 26 Jul 2005 at 15:03

    Yes soulliam,
    I have added the componets timer.


    I wrote the code to write log on to the text file. I am trying to write "Another entry" under the Timer_Tick sub but this message is never written on the text file.


    Find the code below.
    See if you can find anything wrong with it.


    Thanks,
    vanj.


       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.
           LogMessge("Stariting the service")
           Timer1.Enabled = True
           Timer1.Start()
       End Sub


       Protected Overrides Sub OnStop()
           ' Add code here to perform any tear-down necessary to stop your service.
           LogMessge("Stop Service")
           Timer1.Stop()
       End Sub


       Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
           LogMessge("Another entry")
       End Sub


       Private Sub LogMessge(ByVal messge As String)


           Dim objFileStream As FileStream
           Dim objStringBuilder As StringBuilder = New StringBuilder


           ' Append the message
           objStringBuilder.AppendFormat("{0}{1}", messge, Environment.NewLine)


           If (Not Directory.Exists(Path.GetDirectoryName("D:\Testing\MyService\WinServ.txt"))) Then
               Directory.CreateDirectory(Path.GetDirectoryName("D:\Testing\MyService\WinServ.txt"))
           End If


           'Check if the file already exists
           'If file already exists open file in append mode
           'else create file
           If (File.Exists("D:\Testing\MyService\WinServ.txt")) Then
               objFileStream = File.Open("D:\Testing\MyService\WinServ.txt", FileMode.Append, FileAccess.Write)
           Else
               objFileStream = File.Create("D:\Testing\MyService\WinServ.txt")
           End If


           Dim objStreamWriter As New StreamWriter(objFileStream)


           objStreamWriter.Write(objStringBuilder.ToString())
           objStreamWriter.Close()
       End Sub
    End Class

  45. 26 Jul 2005 at 14:35

    Are you using the component timer and not the windows forms timer?  When creating a Service you should use the component objects.

  46. 26 Jul 2005 at 13:25

    I could buid the windows service with the steps mentioned but noticed that the event is not logged on TimerTick event. The event is logged only on the start and stop of the windows service.
    And when I attached the debugger with the service from .NET IDE, it never stepped into the Timer
    Tick routine.
    Please help me to debug the service and let me know how we can log the event on timer click.


    thanks
    vanj

  47. 18 Jul 2005 at 20:27

    Hi,


    I would certainly go the easy way.


    Within the service code, I would put an event handler on any modification on a given directory.
    Thus whenever a file is placed in that directory, the file is parsed by the service and an action can be taken.
    Concerning the file format, I would use an XML file. It's easier to parse and to structure.


    A second possibility is to use a database with a table containing the actions to perform by the service.
    The client writes an entry in the table, the service checks the table on a schedule basis (e.g. a timer event) and do the action.


    A third possibility would be to use a socket.


    It's really up to you.

  48. 18 Jul 2005 at 16:53
    I also would like to create a client/UI that could communicate with my windows service.

    I am looking for an architecture similiar to SQL Server and the Enterprise Manager.  SQL Server is the Service and the Enterprise Manager is a management piece that interacts with the service, to display all available databases, allows for administration of the services configuration, etc.

    Any suggestions welcome,

  49. 15 Jul 2005 at 16:04
    I have written a few services with no major problems, until this last one.  
    When I start this current service I get the message "service started and then stopped".
    The only difference I can tell between this service and another service I wrote is the
    use of threads.  Is there any obvious problem here?



    Imports System.ServiceProcess
    Imports System.Xml
    Imports System.Threading
    Imports System.net

    Public Class Service1
       Inherits System.ServiceProcess.ServiceBase
       Dim initialized As Boolean
       Dim Sent As Boolean
       Dim EMail_From, EMail_To, cc1, Subject, body, SiteUrl, SiteName, Search As String
       Dim done As Boolean
       Dim page As Thread
       Dim reset As Thread
       Dim timeout As Thread
       Dim failedsite(0)
       Dim timecount As Integer


    #Region " Component Designer generated code "

       Public Sub New()
           MyBase.New()

           ' This call is required by the Component Designer.
           InitializeComponent()

           ' Add any initialization after the InitializeComponent() call

       End Sub

       'UserService overrides dispose to clean up the component list.
       Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
           If disposing Then
               If Not (components Is Nothing) Then
                   components.Dispose()
               End If
           End If
           MyBase.Dispose(disposing)
       End Sub

       ' The main entry point for the process
       <MTAThread()> _
       Shared Sub Main()
           Dim ServicesToRun() As System.ServiceProcess.ServiceBase

           ' More than one NT 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 Service1, New MySecondUserService}
           '
           ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1}

           System.ServiceProcess.ServiceBase.Run(ServicesToRun)

           

       End Sub

       'Required by the Component Designer
       Private components As System.ComponentModel.IContainer

       ' NOTE: The following procedure is required by the Component Designer
       ' It can be modified using the Component Designer.  
       ' Do not modify it using the code editor.
       Friend WithEvents Timer1 As System.Timers.Timer
       <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
           Me.Timer1 = New System.Timers.Timer
           CType(Me.Timer1, System.ComponentModel.ISupportInitialize).BeginInit()
           '
           'Timer1
           '
           Me.Timer1.Enabled = True
           Me.Timer1.Interval = 15000
           '
           'Service1
           '
           Me.ServiceName = "Service1"
           CType(Me.Timer1, System.ComponentModel.ISupportInitialize).EndInit()

       End Sub

    #End Region

       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.
           
           timecount = 0
           MsgBox("Start")
       End Sub

       Protected Overrides Sub OnStop()
           ' Add code here to perform any tear-down necessary to stop your service.
       End Sub

       Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed
             
           done = False
           timecount = timecount + 1
           page = New Thread(AddressOf Me.getInfo)
           timeout = New Thread(AddressOf Me.Expire)

           page.Start()
           timeout.Start()
           
           Call ResetFailure()

       End Sub

       Public Sub ResetFailure()
           Dim i As Integer
           If timecount >= 5 Then
               For i = 0 To failedsite.Length
                   failedsite(i) = ""
               Next
               failedsite.Clear(failedsite, 0, failedsite.Length)
               timecount = 0
           End If
       End Sub


       Public Sub Expire()
           Thread.CurrentThread.Sleep(60000)
           If done = False Then
               page.Abort()
               body = "Time out: "
           End If
       End Sub

       Public Sub getInfo()
           Dim reader As XmlTextReader
           Dim reader2 As XmlTextReader
           Dim i As Integer
           Dim found As Boolean


           reader = New XmlTextReader("C:\Init2.xml")
           reader2 = New XmlTextReader("C:\Init2.xml")
           While reader.Read()
               If reader.NodeType = XmlNodeType.Element Then
                   If reader.Name = "EMail_To" Then
                       EMail_To = reader.GetAttribute(0)
                   ElseIf reader.Name = "cc1" Then
                       cc1 = reader.GetAttribute(0)
                   ElseIf reader.Name = "EMail_From" Then
                       EMail_From = reader.GetAttribute(0)
                   ElseIf reader.Name = "SiteUrl" Then
                       SiteUrl = reader.GetAttribute(0)
                   ElseIf reader.Name = "SiteName" Then
       
  50. 11 Jul 2005 at 04:54

    hi;


    im facing the same problem.....plzzzzz let me know the solution as soon as possible.


    thankx.

  51. 07 Jul 2005 at 09:47

    Hi Paras,


    I am having the same problem could you let me know what is the solution, you can email it to me at mustaq.hussain@hp.com


    Thanks in Adv


    Regards,
    Mustaq

  52. 29 Jun 2005 at 20:32

    hello sir..


    iam trying to install my window service(called tracking) through InstallUtil command but i got the following error:



    Exception occurred while initializing the installation:
    System.IO.FileNotFoundException: File or assembly name tracking, or one of its dependencies, was not found..


    this service is running fine on start after debugging..


    please help in out..


    thanks in advance


    paras

  53. 29 Jun 2005 at 17:08

    by definition a service is supposed to be able to run even when no-one is logged-on. As a consequence, it doesn't have any UI capabilities.

  54. 04 Jun 2005 at 22:17

    Are there any tips on creating a user interface to work with a windows service.  I would like to create a UI to show whats the service is doing in a simple list box.

  55. 03 May 2005 at 07:23
    1. i need to display  a message box from winservice.
    2. how to execute a axpx page from winservice(this page will retrive data from  oracle database and sending mail using mail object in vb.net)
      can any 1  know solution to this pl.send me(mugu_guru@yahoo.com)
      by
  56. 03 May 2005 at 05:17
    1. i need to display  a message box from winservice.
    2. how to execute a axpx page from winservice(this page will retrive data from  oracle database and sending mail using mail object in vb.net)
      can any 1  know solution to this pl.send me(mugu_guru@yahoo.com)
      by
      mugu
  57. 01 May 2005 at 05:02
    1. Start the service so that it is running.


    2 .Go into the your Visual Studio click debug->processes.   Make sure the show system processes check box is checked.  Find the name of your windows service exe.  Highlight it then click attach.  


    3. In the next dialouge box check Common runtime language only then ok button.


    4 . Visual studio will now be in debug mode.  


    5.  The last and final step is to set a break point if you havent already done so in your project.  The service will then break and you can step through.


    Jason

  58. 11 Apr 2005 at 12:02

    hello sir/mam,



    please give some idea on how to debug window service for sending email via smpt serve.


    I am using vb.net
    window xp



    Please i'll be very thankfull if my request is noticed as soon as possible


    Thank


    Divya Tiwari.
    Software Engineer
    ITShastra.com



  59. 01 Apr 2005 at 16:10

    That worked.
    Thanks.

  60. 01 Apr 2005 at 10:56

    You need to check the "Allow Service To Interact With Desktop" check box in the Service Properties window (Control Panel -> Administrative Tools -> Services)

  61. 31 Mar 2005 at 19:50

    I tried the example and it worked perfectly fine.
    now i wanted to go further and put my own code in to the service.
    the first thing i tried was putting in a msgbox. but its not giving me the message box.
    what am i doing wrong?

  62. 28 Jan 2005 at 18:39

    Here's what my file looks like:


    <configuration>
    <system.runtime.remoting>
     <application name="LiveSnapService">
       <lifetime
           leaseTime = "9999D"
           sponsorshipTimeOut = "10M"
           renewOnCallTime = "100D"
           pollTime = "10S" />
       <service>
         <wellknown type="LiveSnapDotNet.server.MainServer, LiveSnapDotNet"
                    objectUri="LiveSnapDotNet.server.MainServer"
                      mode="Singleton" />
       </service>
       <channels>
         <channel ref="tcp" port="8085">
           <serverProviders>
             <formatter ref="binary" typeFilterLevel="Full" />
           </serverProviders>
         </channel>
       </channels>
     </application>
    </system.runtime.remoting>
    </configuration>


    You can find more info here:


    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT15.asp


    Steph

  63. 28 Jan 2005 at 18:35

    I'm building a service and I would like to have the user have control over one parameter. I've managed to edit the ImagePath in the registry and have it persist, but I don't know how to use that parameter in the  OnStart code. Scope, can you help? (or anyone)


    OR, Steph2004, if I use a config file, what do I put in the config file, what does AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName + ".config" actually return?


    Thanks!

  64. 10 Jan 2005 at 03:32

    I want my Service to have the start status whenever a user logs in. How can i do this ?


  65. 05 Jan 2005 at 06:24

    I read the guide at http://msdn.microsoft.com/msdnmag/issues/01/12/NETServ/default.aspx
    and everything went fine until the end.


    I managed to install the service and see it write in the eventlog. then i used the tool InstallUtil.exe to uninstall the service, just to try it, and it went fine. I then installed the service again, which also went fine, but when i try to start the service now, i get an error.


    translated into english the error message read:
    "The service FileWatcher on local computer could not be started. Service did not return an error. This could be caused by an internal error in windows or the service. Contact your system administrator, if the problem continues."


    Does anyone have a clue why it does this now, and not the first time?

  66. 01 Dec 2004 at 18:25

    It sounds like you need a way to persist the changes made by the FSW.  You could take a few different approaches.  One would be to maintain a thread safe singleton object, i.e. a queue object, like a FIFO queue.  Trap the event raised by the FSW, pull pertinent data into an object and put it into the in memory queue.  On a server timer, check the queue and process the files that you can in an asynchronous fashion.


    You could use the same technique with an XML file, MSMQ, or some RDBMS to persist the data.


    Hope this helps

  67. 16 Nov 2004 at 00:46
    How do I use windows messenger (IM) from a service? I tried with VB 6.0 but did not get it to work. When the programme runs normal (so not as service) I can start a conversation and issue messages. But when the programme runs as a service I really can not get it to work.
    Does anyone have an idea, or even better, an example? Any experience?
    Thanks a lot.
  68. 02 Nov 2004 at 04:52


    I'm also interested in that


    Regards,


    Adrian Korsuas

  69. 26 Oct 2004 at 08:53

    We had a similar program and it use to blow up every time there was a Network error or Computer not available.
    I found that most of times when there was a "Network error or Computer not available", it happens only temporary and hence I modified the code to go to sleep for 10 mins if Network error happens and then check again.
    I give it 3 tries before finally letting the program error out.


    Hope this helps.


    regards
    SM


  70. 15 Oct 2004 at 13:50

    To Whom It May Concern,


    The example that you gave for creating a Windows Service was extremely easy to follow.   I wanted to just say thanks for writing a great article, I will be using the sample service as a foundation to build on for my local Windows XP service that I have been looking to write for quite some time ^^


    Thanks again,


    James

  71. 06 Oct 2004 at 05:14
    Hi

    I wrote and installed a windows service program on a station that monitors a
    share point on another network computer using a File System Watcher.

    It looks for new files dropped into that location and then processes those
    files.

    It works fine as long as the share point computer is available. If the share
    point goes down and then comes up again later, I need to restart the service.

    Any ideas on how to deal with this, short of having to restart the service each
    time?

    Thanks

    Harold Hoffman
  72. 29 Sep 2004 at 12:33
  73. 26 Sep 2004 at 13:55

    just had this problem wish i could have help erlier i just resolved this problem on my home computer :-)
    first of all stop the service then
    go into the registry (regedit) and find
    HKEYLOCALMACHINE\SYSTEM\CurrentControlSet\Services{your service name}
    then you have to edit the image path to include the perameter you want to add
    then refresh the service administartion tool open the property tab on the service in question and behold your edited parameters you can now start the service and the parameter will be persistant
    madified from a knolage base article by me, hope this helps
    soem times its nic to knwo a 16 year old with too much time can configure somethign an over work system admin cant (no offese where whould we be without you guys)

  74. 10 Sep 2004 at 10:19

    I've got through the article by J. Jain and ran on my XP Pro without problem. My question is: if I need to run a job (say checking on files in a fold) every 5 minutes should put the codes in Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed?


    Thanks, Bill

  75. 02 Sep 2004 at 06:40
    search info about Service Controller
  76. 02 Sep 2004 at 06:38
    hmm, you but is impossible per programm way...
    you need to create a winApplication and insert into a ServiceController.
  77. 02 Sep 2004 at 06:35
    Well, how do i can use the Log information from my service LogFile for put it in my WinForm?
  78. 28 Aug 2004 at 00:54

    Greetings,


    i developed a window service and installer setup.So, i want my service started when i run the setup.

  79. 12 Aug 2004 at 01:57

    hai pal,
      plz give me the solution for the question u have provided.
    " have a VB exe which I want to invoke or run from a windows service implemented in VB.NET. I tried the normal way of invoking applications thruough the shell command but it doesn't ..."


    i'm also in need of this.
    shafiq_mohamad@yahoo.com
    bye
    shafiq

  80. 06 Aug 2004 at 15:19

    This was a great and easy to follow article.  I tested it out following your directions and then customized it for my own code. I never knew this was so easy! Thanks again for a great article!

  81. 01 Aug 2004 at 17:58

    After installing the service , right click it (in the services window) and select properties. Then select logon tab and then check the allow to interact with desktop.

  82. 08 Jul 2004 at 10:58

    I repeatedly get an error that my thread pool is full when threading in a windows service. Any thoughts or suggestions.

  83. 19 May 2004 at 08:10

    After following the directions, I get:


    Error 193: 1% is not a valid Win32 application.


    Help!

  84. 18 May 2004 at 05:57
    Nice article. Thanks.
    I have a question. How do you add a form to windows service (in .net that is)?

    I tried but cannot get the form to appear? Any ideas?

    Thank you.
  85. 17 May 2004 at 01:54
    Hello friends,

    I have a VB exe which I want to invoke or run from a windows service implemented in VB.NET. I tried the normal way of invoking applications thruough the shell command but it doesn't seem to work in case of Windows services in VB.NET. Please help me out...this is urgent,

  86. 17 May 2004 at 00:03
    Thanks   Actually I have resolved this already by Adding A "Installer" Class type.  But still thanks for the effort
  87. 16 May 2004 at 23:48
    Well check out the MSDN from microsoft or search for 'runinstaller' via google

    [Visual Basic, C#, C++] The following example specifies that the installer should be run for MyProjectInstaller.

    [Visual Basic]
    <RunInstallerAttribute(True)> _
    Public Class MyProjectInstaller
       Inherits Installer

       ' Insert code here.
    End Class 'MyProjectInstaller

    [C#]
    [RunInstallerAttribute(true)]
    public class MyProjectInstaller : Installer {
       // Insert code here.
    }

    [C++]
    [RunInstallerAttribute(true)]
    __gc class MyProjectInstaller : public Installer {
       // Insert code here.
    };

    read more here:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcomponentmodelruninstallerattributeclasstopic.asp

    Good luck.
    Paul
  88. 25 Apr 2004 at 08:12

    Hi, excellent article by the way...only question remaining was how to create a new Log group - ie, Application, Security - blah de blah - I'd like to create a new one of them - I thought I could as some of the intellisense help displayed "Application, Security...Custom" etc - but nowt happened when I followed the article, it just dumped it into the application group.


    Anyone got any ideas?

  89. 26 Mar 2004 at 07:16

    Just wondering, almost all of the sample in the net is in C#, is this also possible in VB.NET?  I've created an EXE which will prompt the user for sql server connection information.  I've included it on the WebSetup project custom action (Install) but it doesn't run during the installation process.  Any idea ?


    I've been searching for the "[RunInstaller(True)]" counterpart on vb.net, but no luck


    Thanks,


    Enzo

  90. 09 Mar 2004 at 15:18

    There is a way that you can debug a service while in the OnStart procedure. You only need to add Debugger.Launch in the code in the OnStart procedure and you will be prompted which debugger you wish to use. If you have the project open already it will start debugging just as a normal application would. However, according to Windows the service will act as if it had not started. You will still need to stop the service when you have finished debugging though, because it will have started.

  91. 04 Mar 2004 at 13:32
    Here's the solution. It works well!

    protected override void OnStart( string[] args )
    {
       string config;

       if( args != null && args.Length > 0 )
       {
           config = args[ 0 ];
       }
       else
       {
           config = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName + ".config";
       }

       RemotingConfiguration.Configure( config );
    }

    In this way you don't need to hardcode any path, just be sure the config file is always in exe's directory.

    Thanks to Emil from GotDotNet.com

    Stephane
  92. 03 Mar 2004 at 19:45
    I have the same trouble and I haven't found a solution yet. I hope there's a better solution than to make a batch file??

    If anyone has an idea, please post it!

    Stephane
  93. 27 Feb 2004 at 23:09

    We are using a .config file to store the database connection information.

  94. 27 Feb 2004 at 11:52

    I'm having exactly the same problem... Did anyone give you an answer?

  95. 26 Feb 2004 at 07:19

    Add a custom action in the setup project under "Installer" "Commit" "Rollback" and "Uninstall"
    Set this to the project output or assembly which you have your installer in.
    Make sure that the properties for the custom action that InstallerClass is set to true.
    It should then run the service installer when you run the installation to install/uninstall.
    Worked ok for me anyway.

  96. 10 Feb 2004 at 04:05

    You can alway start up the service using a batch file.
    then you cans et the parameters you need on the command line in the file

  97. 07 Jan 2004 at 10:04
  98. 07 Jan 2004 at 10:03

    Visual Basic isn't most appropriate tool for developing of Windows NT/2000/XP services. The problem is, for service development is necessary to use API function CreateThread, which is not supported nether in VB5, nor in VB6. VB allows creation of multi-thread programs, but not using CreateThread function.
    Even if you using create service options build-in Indigorose Setup Factory 6 your *.exe written in VB won't start as a service.
    That's about it.
    regards



  99. 22 Dec 2003 at 09:52

    Make sure that you are using a component timer and not a windows form timer, I made that mistake on my first service.
    In Code it would look like this.
    Correct:
    Friend WithEvents MainTimer As System.Timers.Timer
    Incorrect:
    Friend WithEvents JunkTimer As System.Windows.Forms.Timer


    Hope this helps

  100. 04 Dec 2003 at 22:36
    How could you run the installer in a Setup Project???
  101. 14 Nov 2003 at 16:30

    We have bunch of windows services that are deployed on various machines. They are configuring them self’s by getting the configuration variables from a database when they are started.


    Now we have requirement to create some isolated systems which are small foot print replicas of our main system. So we want to install these windows services on this isolated system with out any changes. That means we will have to make the service look at a different database for configuration values.


    One of the various options we are looking into is "using Start Parameters".


    The problem with the Start Parameters is that they do not persist. When ever we stop and start the service we will have re-enter them.


    So my question is there a way to make these persistent or provide some command line parameters at install or start.

  102. 07 Nov 2003 at 05:51

    i am interested in learning to writhe windows service program . please be good to give instructions and sample code that u have develop .


    i am ishrath from sri lanka.


    thanks
    Ishrath

  103. 24 Oct 2003 at 15:19

    I have an application in VB6 that I want to run as a service.  Can I make it run as a windows service using .Net like this article shows, if so how?


    Does the machine require .Net to use the InstallUtil, or can I use another method to install/register the service on a non-.Net machine.


    Thanks in advance!


    Ron

  104. 14 Oct 2003 at 05:22
    Hi,

    I tried to write a Windows Service application under VB.Net. Problem is, that I'm using the Standard Edition and no service template is available. However MS tells me how to write a service programmatically, which I tried. The service seems to work fine (starts up and writes the first line in the logging file which I created at StartUp).
    I use a Timer to tell it to write a line every 10 sec. This is where the problem starts: the timer doens't seem to start. The logging file isn't updated.

    I have tried this in several ways, but still think a parameter or something has been set wrong (this is what the template normally does).

    Does anyone have a clou.....or a template for me?? I have included a simple project.

    Regards,

    Daniel (danielsn@wxs.nl)
  105. 28 Aug 2003 at 12:01

    Hi,


    I am creating a service using visual basic .net. I am trying to click 'Add installer' and add installers. I get this error "The .Net assembly' System.configuration.Install' could not be found. and "Could not run 'C:\Program Files\Microsoft Visual Studio .NET\Vb7\VBProjectItems\Installer.vsz' wizard.


    Can some one tell me what this means and how to slove this.


    I appreciate your help


    Regards
    Hari V

  106. 03 Jun 2003 at 15:17

    The example was not a very good example. Windows services can be communicated with from other programs. This is also a very important part of windows services and no examples were used to show this part of it

  107. 08 May 2003 at 09:38

    i want to access remote windows services.basically i want to to write some code in onstart event of windows service and install it in server.from client i want to start the server service.



    how can i install windows service remotely(server)?

  108. 15 Mar 2003 at 01:21
    1) You CAN debug the startup code (putting a break point in OnStart), you just have to be tricky about it. I do it by simply putting this code at the begining of OnStart:
    Code:

    #If Debug Then
           ' When debugging a service, you have to attach to a running process. This gives me
           ' time to attach for debugging to slowdown startup so I can set a breakpoint.
           System.Threading.Thread.Sleep(15000)
    #End If

    Obviously this gives me a 15 second window in which I can attach to the process and set my breakpoint in the top of my startup code. It's not a perfect solution, but better than nothing.

    2) InstallUtil is a nice, quick utility for installing and uninstalling, however it lacks some pretty substantial support for certain settings. It doesn't allow you to setup the service at all... for instance you can't have it handle the "Allow service to interact with desktop" option (which ALSO doesn't appear to be an option in the required Installer class you must add to your service) NOR can you use it to set Dependencies to make sure Windows loads your service in the proper order at startup (if you use Automatic)... someone hinted that this could be set in that installer class as well but I've not been able to find that option. The only way I've found to overcome these limitations is by either manually setting it up after installing it (not an option for dependencies), hacking the registry yourself (not a wise choice) or by using a product like InstallShield which can do it all for you quite nicely.


  109. 01 Jan 1999 at 00:00

    This thread is for discussions of Creating a Windows Service in VB.NET.

Leave a comment

Sign in or Join us (it's free).

Jayesh Jain Jayesh Jain is working as a Business Analyst in Auckland, New Zealand. He has several years of n-Tier development experience in developing interactive client solutions. He has a passion for Web dev...
AddThis

Related podcasts

  • xpert to Expert: Inside Concurrent Basic (CB)

    "Concurrent Basic extends Visual Basic with stylish asynchronous concurrency constructs derived from the join calculus. Our design advances earlier MSRC work on Polyphonic C#, Comega and the Joins Library. Unlike its C# based predecessors, CB adopts a simple event-like syntax familiar to VB progr...

We'd love to hear what you think! Submit ideas or give us feedback