• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4565
  • Last Modified:

Stopping and Starting a Service using VB.Net

Hi,

I have written the following piece of code to stop and start a particular service on a remote machine.

Public Sub call_bat()

        Dim proc As New System.Diagnostics.Process
        Dim startinfo As New System.Diagnostics.ProcessStartInfo
        Dim myController As ServiceController
        myController = New ServiceController
        myController.MachineName = "10.144.1.196"
        'myController.MachineName = "10.144.2.44"
        myController.ServiceName = "TSM server1"

        If myController.CanStop Then
            myController.Stop()
        Else
            MsgBox("TSM server1 service cannot be stopped or the service is already stopped")

        End If

        startinfo.FileName = "E:\Program Files\Tivoli\tsm\server1\rest1.bat"
        startinfo.UseShellExecute = True
        startinfo.WorkingDirectory = "E:\Program Files\Tivoli\tsm\server1\"
        startinfo.WindowStyle = ProcessWindowStyle.Normal
        proc.StartInfo = startinfo

        Try
            proc.Start()
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try
        proc.WaitForExit()

        Try
            myController.Start()
            MsgBox("TSM server1 service started")
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try

    End Sub

The machine is : Windows 2000 Advanced Server. The code used to work perferctly. But recently it shows the following error.

" An unhandled exception of type 'System.InvalidOperationException' occurred in system.serviceprocess.dll

Additional information: Cannot open Service Control Manager on computer '10.144.1.196'. This operation might require other privileges. "

Kinldy help on how this can be resolved. Is there any option in Service controller where in we can specify user id / password ?

Regards,

Sreejith
0
sreejithm
Asked:
sreejithm
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
>Kinldy help on how this can be resolved. Is there any option in Service controller where in we can specify user id / password ?
you will need to grant the user that runs your application the permissions to start/stop the services on the remote machine.
the code is indeed fine, you cannot do anything there.
0
 
YoungBonziCommented:
It looks like I can be done with Impersonation.

This person was able to do it in his program: http://www.codeproject.com/csharp/svcmgr.asp
0
 
joachim.claeys@teleatlas.comCommented:
Hi,

Try using the following (wmi) function  to start/stop services on the remote computer:

Parameters:
sComputer: remote host
sName: Service Name
bStart: True = start, False = stop

Hope this helps.

'''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub alterServiceState(ByVal sComputer As String, ByVal sName As String, ByVal bStart As Boolean)
        Dim co As ConnectionOptions = New ConnectionOptions()
        'co.Username = "myuser"
        'co.Password = "mypassword"
        Dim scope As New System.Management.ManagementScope
        Try
            scope = New System.Management.ManagementScope("\\" & sComputer & "\root\cimv2")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        scope.Connect()
        Dim query As ObjectQuery = New ObjectQuery("Select * from Win32_Service Where Name = " & Chr(34) & sName & Chr(34) & " ")
        Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(scope, query)
        Dim observer As ManagementOperationObserver = New ManagementOperationObserver()
        Dim queryCollection As ManagementObjectCollection = searcher.Get()
        Dim m As ManagementObject
        Dim args As Object
        Try
            For Each m In queryCollection
                If m.Item("Started").Equals("True") Then
                    If Not bStart Then
                        m.InvokeMethod("StopService", args)
                    End If
                Else
                    If bStart Then
                        m.InvokeMethod("StartService", args)
                    End If
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
sreejithmAuthor Commented:
Hi joachim

Sorry for the delay in responding. I was down with fever.

I tried using your code. But it says "Access Denied". I am working with the administrator ID.

Regards,
0
 
sreejithmAuthor Commented:
Hi

I just modifed the code by joachim and checked if I'm able to connect to WMI

Sub test_wmi()
        Dim myConnectionOptions As New System.Management.ConnectionOptions
        With myConnectionOptions
            .Username = "MESADXBDWNBRAED\Administrator"
            .Password = "Password2"

            Dim myManagementScope As System.Management.ManagementScope

            Dim myServerName As String = "."
            myManagementScope = New System.Management.ManagementScope("\\" & "MESADXBDWNBRAED"         & "\root\cimv2", myConnectionOptions)

            myManagementScope.Connect()
            If myManagementScope.IsConnected = False Then
                MsgBox("Could not connect to WMI namespace")
            ElseIf myManagementScope.IsConnected = True Then
                MsgBox("connected to WMI namespace")
            End If
End Sub

----------------

This code works perfectly.. I'm able to connect to WMI.

However When I query the namespace like in the below code,

 Dim myObjectSearcher As System.Management.ManagementObjectSearcher
            Dim myCollection As System.Management.ManagementObjectCollection
            Dim myObject As System.Management.ManagementObject
            myObjectSearcher = New System.Management.ManagementObjectSearcher( _
              myManagementScope.Path.ToString, "Select * From Win32_Product")
            myCollection = myObjectSearcher.Get()

            For Each myObject In myCollection
                Console.WriteLine(myObject.GetPropertyValue("Caption"))
            Next

I get the access denied error at the like "myCollection = myObjectSearcher.Get()".

--------------------

Is there any need to specify any access /login rights at the server itself ?

Regards,

0
 
joachim.claeys@teleatlas.comCommented:

Try to replace your code with this: ( untested - should work )
Change options.username, options.password and strComputername to the appropriate values.

        Dim scope As ManagementScope = New ManagementScope
        Dim strComputerName As String = "MyServerName"
        Dim query As ObjectQuery
        Dim searcher As ManagementObjectSearcher        
        Dim queryCollection As ManagementObjectCollection
        Dim options As ConnectionOptions = New ConnectionOptions
        options.Username = "testAccount"
        options.Password = "fooo"
        Dim query As New SelectQuery("Win32_Product")
        scope = New ManagementScope("\\" & strComputerName & "\root\cimv2", options)
        scope.Connect()
        queryCollection = searcher.Get()
        For Each m As ManagementObject In queryCollection
            Console.WriteLine(myObject.GetPropertyValue("Caption"))
        Next
Regards,
Joachim
0
 
sreejithmAuthor Commented:
Hi Joachim,

Thanks a lot. The code works for majority of our servers. However it shows "Access Denied " error on some of our
servers. Few of my teammates are of the opinion that there are some WMI parameters that needs to be configured on these servers inorder to allow remote access to the root\cimv2 namespace. But we are not sure how this can be done.
 Or is there any other solution to this ?

Thanks and best regards,

0
 
joachim.claeys@teleatlas.comCommented:
Which WMI parameters are you unable to access ?

Thanks,
Joachim
0
 
sreejithmAuthor Commented:
Hi Joachim,

Basically I've written my code to work with the TSM service on our servers.. So I query Win32_Service from root\cimv2 for this service and then work with that.

On some servers I get the error "Access Denied" for the line scope.Connect() as per your code.

Regards,

0
 
joachim.claeys@teleatlas.comCommented:
Hi,

This article from Microforge.net helps you identify WMI "Acccess Denied" errors:

http://www.microforge.net/kb/62

Hope this gets you further ...

Joachim.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now