VB.NET making a Windows Service terminate itself

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
HAMMER33333Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

iboutchkineCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HAMMER33333Author Commented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.