Community discussion forum

Creating a Windows Service in VB.NET

This is a comment thread discussing Creating a Windows Service in VB.NET
  • 10 years ago

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

  • 6 years ago
    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.


  • 6 years ago

    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)?

  • 6 years ago

    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

  • 6 years ago

    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

  • 6 years ago
    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)
  • 6 years ago

    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

  • 6 years ago

    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

  • 6 years ago

    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.

  • 5 years ago
    How could you run the installer in a Setup Project???
  • 5 years ago

    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

  • 5 years ago

    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



  • 5 years ago
  • 5 years ago

    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

  • 5 years ago

    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.

  • 5 years ago

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

  • 5 years ago

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

  • 5 years ago
    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
  • 5 years ago
    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
  • 5 years ago

    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.

  • 5 years ago

    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

  • 5 years ago

    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?

  • 5 years ago
    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
  • 5 years ago
    Thanks   Actually I have resolved this already by Adding A "Installer" Class type.  But still thanks for the effort
  • 5 years ago
    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,

  • 5 years ago
    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.
  • 5 years ago

    After following the directions, I get:


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


    Help!

  • 5 years ago

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

  • 5 years ago

    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.

  • 5 years ago

    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!

  • 5 years ago

    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

  • 5 years ago

    Greetings,


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

  • 5 years ago
    Well, how do i can use the Log information from my service LogFile for put it in my WinForm?
  • 5 years ago
    hmm, you but is impossible per programm way...
    you need to create a winApplication and insert into a ServiceController.
  • 5 years ago
    search info about Service Controller
  • 5 years ago

    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

  • 5 years ago

    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)

  • 5 years ago
  • 5 years ago
    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
  • 5 years ago

    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

  • 5 years ago

    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


  • 5 years ago


    I'm also interested in that


    Regards,


    Adrian Korsuas

  • 5 years ago
    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.
  • 4 years ago

    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

  • 4 years ago

    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?

  • 4 years ago

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


  • 4 years ago

    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!

  • 4 years ago

    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

  • 4 years ago

    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?

  • 4 years ago

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

  • 4 years ago

    That worked.
    Thanks.

  • 4 years ago

    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



  • 4 years ago
    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

  • 4 years ago
    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
  • 4 years ago
    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
  • 4 years ago

    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.

  • 4 years ago

    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.

  • 4 years ago

    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

  • 4 years ago

    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

  • 4 years ago

    hi;


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


    thankx.

  • 4 years ago
    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
       
  • 4 years ago
    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,

  • 4 years ago

    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.

  • 4 years ago

    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

  • 4 years ago

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

  • 4 years ago

    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

  • 4 years ago

    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

  • 4 years ago

    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.

  • 4 years ago

    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.

  • 4 years ago
    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?
  • 4 years ago
    Is there any way to start a WinForm App from a VB .Net Service?
  • 4 years ago
    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.
  • 4 years ago
    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.
  • 4 years ago
    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
  • 4 years ago

    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!!

  • 4 years ago

    "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

  • 4 years ago

    sorry there was a spelling mistake in the last reply.


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


    ~vanj

  • 4 years ago

    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

  • 4 years ago

    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"

  • 4 years ago

    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

  • 4 years ago

    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

  • 3 years ago
    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.....
  • 3 years ago
    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
  • 3 years ago

    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"


  • 3 years ago
    Hi! How can I create and debug a windows service with Visual Studio 2005?

    Thanks.

    Marco.
  • 3 years ago
    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
  • 3 years ago

    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.

  • 3 years ago

    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.

  • 3 years ago

    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

  • 3 years ago

    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

  • 3 years ago

    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!

  • 3 years ago

    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

  • 3 years ago

    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

  • 3 years ago

    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









  • 3 years ago

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

  • 3 years ago

    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

     

  • 3 years ago
  • 3 years ago

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

  • 2 years ago
    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!









  • 2 years ago

    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.

  • 2 years ago
    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......








  • 2 years ago

    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

  • 1 year ago

    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 months ago
    **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)
  • 6 months ago
    Is there a way to programatically set the startup type of a windows in vb.net or c#?
  • 5 months ago

    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 months ago

    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 months ago

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

  • 4 months ago

    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

Post a reply

Enter your message below

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

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