Solved

Stopping and Starting a Service using VB.Net

Posted on 2006-11-25
10
4,499 Views
Last Modified: 2007-12-19
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
Comment
Question by:sreejithm
10 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 18011472
>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
 
LVL 8

Expert Comment

by:YoungBonzi
ID: 18011995
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
 
LVL 3

Expert Comment

by:joachim.claeys@teleatlas.com
ID: 18011999
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:sreejithm
ID: 18034447
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
 

Author Comment

by:sreejithm
ID: 18034728
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
 
LVL 3

Expert Comment

by:joachim.claeys@teleatlas.com
ID: 18034809

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
 

Author Comment

by:sreejithm
ID: 18035764
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
 
LVL 3

Expert Comment

by:joachim.claeys@teleatlas.com
ID: 18036202
Which WMI parameters are you unable to access ?

Thanks,
Joachim
0
 

Author Comment

by:sreejithm
ID: 18036630
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
 
LVL 3

Accepted Solution

by:
joachim.claeys@teleatlas.com earned 500 total points
ID: 18039063
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Auto-indent certain lines in Notepad++ 10 144
Getting the Error "User-defined type not defined" in MS Access 2013 16 82
Help Required 3 117
ejb entity bean example 2 35
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

749 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