?
Solved

VB.NET making a Windows Service terminate itself

Posted on 2003-03-26
2
Medium Priority
?
410 Views
Last Modified: 2012-05-04
I created a VB.NET windows service.  In the OnStart I call a function CheckSettings() that checks if all the data is in place and files are found.  If not, the function returns a false.  I want to stop, end, terminate, kill the service if CheckSettings returns a false.  How do I do it?  I do have a timer which I set to false but it just keeps running and running.  I tried calling the OnStop method and that does not do it either.  Any help would be greatly appreciated.

Thanks,

Hammer
0
Comment
Question by:HAMMER33333
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 28

Accepted Solution

by:
iboutchkine earned 80 total points
ID: 8214598
Here is an example how you start/stop service

'Ref to System.ServiceProcesses.dll

Public Class frmMain
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "
#End Region

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call ReadSvcs()
    End Sub

    Sub ReadSvcs()
        Dim ListSvcs() As ServiceProcess.ServiceController
        Dim SingleSvc As ServiceProcess.ServiceController
        Dim LVW As ListViewItem

        ListSvcs = SingleSvc.GetServices

        lvwServices.Items.Clear()
        Try
            For Each SingleSvc In ListSvcs
                LVW = lvwServices.Items.Add(SingleSvc.DisplayName)
                LVW.SubItems.Add(SingleSvc.ServiceName)
                LVW.SubItems.Add(SingleSvc.Status.ToString)
                LVW.SubItems.Add(SingleSvc.ServiceType.ToString)
            Next
        Catch e As Exception
            MessageBox.Show("Could not initialize Windows Service engine.  Restarting your computer may work", "Fatal Error: " & e.Source)
        End Try
    End Sub

    Private Sub lvwServices_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwServices.Click 'parental
        If lvwServices.SelectedItems(0).Text <> "" Then
            Select Case lvwServices.SelectedItems(0).SubItems(2).Text
                Case "Stopped"
                    cmdStop.Enabled = False
                    cmdStart.Enabled = True

                Case "Running"
                    cmdStop.Enabled = True
                    cmdStart.Enabled = False

                Case Else
                    cmdStop.Enabled = False
                    cmdStart.Enabled = False
            End Select
        End If
    End Sub

    Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
        If lvwServices.SelectedItems(0).Text <> "" Then
            Call StopService(lvwServices.SelectedItems(0).SubItems(1).Text)
        End If 'It has
    End Sub

    Sub StopService(ByVal ServiceName As String)
        Dim ListSvcs() As ServiceProcess.ServiceController
        Dim SingleSvc As ServiceProcess.ServiceController

        ListSvcs = SingleSvc.GetServices

        Try
            For Each SingleSvc In ListSvcs
                If UCase(SingleSvc.ServiceName) = UCase(ServiceName) Then
                    SingleSvc.Stop()
                    Call ReadSvcs()
                    Exit For
                End If
            Next
        Catch e As Exception
            MessageBox.Show("Could not stop service.  Ensure it is not disabled", "Fatal Error: " & e.Source)
        End Try
    End Sub

    Sub StartService(ByVal ServiceName As String)
        Dim ListSvcs() As ServiceProcess.ServiceController
        Dim SingleSvc As ServiceProcess.ServiceController

        ListSvcs = SingleSvc.GetServices

        Try
            For Each SingleSvc In ListSvcs
                If UCase(SingleSvc.ServiceName) = UCase(ServiceName) Then
                    SingleSvc.Start()
                    Call ReadSvcs()
                    Exit For
                End If
            Next
        Catch e As Exception
            MessageBox.Show("Could not start service.  Ensure it is not disabled", "Fatal Error: " & e.Source)
        End Try
    End Sub

    Private Sub cmdStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStart.Click
        If lvwServices.SelectedItems(0).Text <> "" Then
            Call StartService(lvwServices.SelectedItems(0).SubItems(1).Text)
        End If
    End Sub

    Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
        End
    End Sub

    Private Sub cmdRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRefresh.Click
        Call ReadSvcs()
    End Sub

End Class
0
 

Author Comment

by:HAMMER33333
ID: 8218989
Dear iboutchkine,

    Is your answer in Visual Basic .NET?  Below is my code, I am a total newbie.  It sounds like you are very advanced.  I cannot figure out where/what in my code I should place your changes and how they would work.  This is a Windows Service that I compile and start under Settings->Control Panel->Administrative Tools->Services.  I am running it under Windows 2000 and XP.

Thanks in advance for any additional help,

Hammer



Imports System.ServiceProcess
Imports System.Timers

Public Class PROCESS
    Inherits System.ServiceProcess.ServiceBase

    ' Global declarations
    Dim blnGAbort As Boolean
    ' Output file declarations
    Dim oFile As System.IO.File
    Dim oWrite As System.IO.StreamWriter

    'project controls
    ' Private WithEvents aTimer As Timer

#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 PROCESS()}

        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 aTimer As System.Windows.Forms.Timer
    Friend WithEvents aTimer As System.Windows.Forms.Timer
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Me.aTimer = New System.Windows.Forms.Timer(Me.components)
        '
        'aTimer
        '
        Me.aTimer.Interval = 10000
        '
        'PROCESS
        '
        Me.ServiceName = "PROCESS"

    End Sub

#End Region

    ' Check settings
    Private Function CheckSettings() As Boolean
 
        Call WriteMsg("Startup.")
        ' Trouble starting up?
            Return False
        ' Else
             Return True

    End Function

    ' Writes a message to the log file.
    Private Sub WriteMsg(ByVal strPrmMessage As String)
        Dim theDate As Date

        theDate = Date.Now()
        oWrite.WriteLine(theDate & " - " & strPrmMessage)
    End Sub

    ' Do the work
    Private Sub DoWork()

      ' Do the work
 
    End Sub

    ' Declare the sleep method
    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

    Public Sub OnTimedEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)

        If blnGAbort Then
            Exit Sub
        End If
        ' Disable the timer before you begin
        aTimer.Enabled = False
        DoWork()
        aTimer.Enabled = True
        ' Sleep 5 seconds
        Sleep(5000)

    End Sub

    Private Sub aTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles aTimer.Tick
        Dim MyLog As New EventLog() ' create a new event log

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

    End Sub

    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.
        blnGAbort = False
        aTimer.Enabled = False
        If Not CheckSettings() Then
            blnGAbort = True
            Exit Sub
        End If
        aTimer.Enabled = True
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        aTimer.Enabled = False
        Call WriteMsg("Exit the process.")
        oWrite.Close()
    End Sub

End Class
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question