Erm's I.T. Girl – Zelna Ellis

Don't fear when Zel is near…

VB.NET & MySQL: Check Status, Start or Stop Windows Service

Well the title says it all. In this example MySQL Server is used to check whether the service exists. If it is disabled it will set the StartupStatus to Manual. Then it will check whether or not the Service is running, and start it if necessary.
You can just replace it with the Windows Service you need to manipulate.

You can download the code in PDF format here.

Note: tsStatus is a ToolStripStatusLabel that is on the form. Tested on Windows XP SP3

Imports System
‘Remember to add references to the following namespaces:
Imports System.ServiceProcess
Imports System.Management

Public Class MySQLCheck

     Private Sub MySQLCheck_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
          Try
               Dim mo As New Management.ManagementObject("Win32_Service.Name=’MySQL’")
               tsStatus.Text = "Busy…"
               ‘Check if MySQL Service is installed. If not it will close the form.
               Try
                    mo.Get()
               Catch ex As Exception
                    MessageBox.Show("Need to install MySQL Server", "MySQL Server Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Me.Close()
               End Try

               ‘Check if the StartMode = Disabled. If so it will change it to Manual
               If mo("StartMode").ToString = "Disabled" Then
               Dim inParams, outParams As ManagementBaseObject
               Dim result As Integer

               ‘Get an input parameters object for this method
               inParams = mo.GetMethodParameters("ChangeStartMode")
                ‘Set the StartMode to ‘Manual’
               inParams("StartMode") = "Manual"
               outParams = mo.InvokeMethod("ChangeStartMode", inParams, Nothing)
               ‘Check for errors 0 means the request has been accepted.
               result = Convert.ToInt32(outParams("returnValue"))

               ‘Handle errors if any
               If result <> 0 Then
                    Dim myErrMsg As String = ""
                    Select Case result
                         Case 1
                              myErrMsg = "The request is not supported."
                         Case 2
                              myErrMsg = "The user did not have the necessary access."
                         Case 3
                              myErrMsg = "The service cannot be stopped because other services that are running are dependent on it."
                         Case 4
                              myErrMsg = "The requested control code is not valid, or it is unacceptable to the service."
                         Case 5
                              myErrMsg = "The requested control code cannot be sent to the service because the state of the service (Win32_BaseService State property) is equal to 0, 1, or 2."
                         Case 6
                              myErrMsg = "The service has not been started."
                         Case 7
                              myErrMsg = "The service did not respond to the start request in a timely fashion."
                         Case 8
                              myErrMsg = "Interactive process."
                         Case 9
                              myErrMsg = "The directory path to the service executable file was not found."
                         Case 10
                              myErrMsg = "The service is already running."
                         Case 11
                              myErrMsg = "The database to add a new service is locked."
                         Case 12
                              myErrMsg = "A dependency on which this service relies has been removed from the system."
                         Case 13
                              myErrMsg = "The service failed to find the service needed from a dependent service."
                         Case 14
                              myErrMsg = "The service has been disabled from the system."
                         Case 15
                              myErrMsg = " The service does not have the correct authentication to run on the system."
                         Case 16
                              myErrMsg = "This service is being removed from the system."
                         Case 17
                              myErrMsg = "There is no execution thread for the service."
                         Case 18
                              myErrMsg = "There are circular dependencies when starting the service."
                         Case 19
                              myErrMsg = "There is a service running under the same name."
                         Case 20
                              myErrMsg = "There are invalid characters in the name of the service."
                         Case 21
                              myErrMsg = "Invalid parameters have been passed to the service."
                         Case 22
                              myErrMsg = "The account which this service is to run under is either invalid or lacks the permissions to run the service."
                         Case 23
                              myErrMsg = "The service exists in the database of services available from the system."
                         Case 24
                              myErrMsg = "The service is currently paused in the system."

                    End Select
                    Throw New Exception("ChangeStartMode method error code " & result & ControlChars.NewLine & myErrMsg)
               End If
          End If

          ‘Check status of MySQL Server
          ‘If the service is running all is fine
          ‘Else it will wait for the Server to run, or attempt to start the Server
          ‘The status will be updated in the ToolStripStatusLabel tsStatus

          ‘ServiceControllerStatus Meanings
          ‘1 = Stopped – The Service is not running.
          ‘2 = StartPending – The Service is starting.
          ‘3 = StopPending – The Service is stopping.
          ‘4 = Running – The Service is running.
          ‘5 = ContinuePending – The Service continue is pending.
          ‘6 = PausePending – The Service pause is pending.
          ‘7 = Paused – The service is paused.
          Dim sc As New ServiceController("MySQL")
          Select Case sc.Status
               Case 1
                    tsStatus.Text = "MySQL Server is not running, please wait…"
                    sc.Start()
                    tsStatus.Text = "Starting MySQL Server, please wait…"
                    sc.WaitForStatus(ServiceControllerStatus.Running)
                    tsStatus.Text = "Ready"
               Case 2
                    tsStatus.Text = "MySQL Server is starting, please wait…"
                    sc.WaitForStatus(ServiceControllerStatus.Running)
                    tsStatus.Text = "Ready"
               Case 3
                    tsStatus.Text = "MySQL Server is stopping, please wait…"
                    sc.WaitForStatus(ServiceControllerStatus.Stopped)
                    tsStatus.Text = "Starting MySQL Server, please wait…"
                    sc.Start()
                    sc.WaitForStatus(ServiceControllerStatus.Running)
                    tsStatus.Text = "Ready"
               Case 4
                    tsStatus.Text = "Ready"
               Case 5, 6, 7
                    tsStatus.Text = "MySQL Server is stopping, please wait…"
                    sc.Stop()
                    sc.WaitForStatus(ServiceControllerStatus.Stopped)
                    tsStatus.Text = "Starting MySQL Server, please wait…"
                    sc.Start()
                    sc.WaitForStatus(ServiceControllerStatus.Running)
                    tsStatus.Text = "Ready"
          End Select
          Catch ex As Exception
               MessageBox.Show(Err.Description, "MySQL Server Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
               Me.Close()
          End Try
     End Sub
End Class

28 September 2009 - Posted by | .NET & MySQL | , , , , , , , , , , , , , , , ,

5 Comments »

  1. keep geting an error on the
    Dim mo As New Management.ManagementObject(“Win32_Service.Name=’MySQL'”)
    ex = not found, i have tried with other services i know are there any idea

    Comment by Lee | 17 December 2009 | Reply

    • Hi,
      Did you add references to the following namespaces: System.ServiceProcess
      System.Management ?

      Comment by zellis | 30 December 2009 | Reply

  2. i am comment to your site… nice is information..

    Comment by marine blog | 12 March 2010 | Reply

  3. Hi, I think this works only if the vb application is running in the server, where MySQL is… Am I wrong? If it is true, How can I know if MySQL is active in a remote server? Thanks in advance.

    Comment by lmiguel | 22 July 2010 | Reply

    • I figure it out … this is the “code”:
      ————————————–
      serverStateLbl.Text = “Checking Server…”
      serverStateLbl.ForeColor = Color.Black

      If DbConn.testConnectionString(“Database=bdrero;” & _
      “Host=localhost;” & _
      “UserName=testing;” & _
      “Password=kanako!”) = 1045 Then
      ‘ 1042-Unable to connect to any of the specified MySQL hosts.
      ‘ 1045-Access denied for user ‘root’@’localhost’ (using password: YES)
      serverStateLbl.Text = “Server Up”
      serverStateLbl.ForeColor = Color.Green
      Else
      serverStateLbl.Text = “Server Down”
      serverStateLbl.ForeColor = Color.Red
      End If
      ————————————–
      As you can see, basically DbConn.testConnectionString just try to connect with an invalid connection string, and if the server return with “1045-Access denied for user” so it means that the server is up. BTW am using ADO.NET.
      Well feel free to ask me.

      Comment by lmiguel | 22 July 2010 | Reply


Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: