The ServiceController Class

I l @ ve RuBoard

The ServiceController Class

Interaction with Windows services is made possible through the ServiceController class. Using this class, you can essentially control all aspects of a Windows service, including starting and stopping, pausing and continuing, and sending custom commands to the service.

The ServiceController class resides in the System.ServiceProcess namespace, which is where you'll find all classes that deal with Windows services. The use of the ServiceController class couldn't be much easier. Starting a service involves three steps:

  1. Create an instance of the ServiceController class by dragging a Service ­Controller component from the Toolbox to the designer. You can also easily create a ServiceController instance in code, as in the following code example, or by dragging a specific service from the Services node in the Visual Studio .NET Server explorer for a specific machine.

  2. Set the ServiceName property of the ServiceController instance. You can also optionally set the MachineName property if the service resides on another machine.

  3. Call the Start method.

The following subroutine starts a service:

 ImportsSystem.ServiceProcess PrivateSubStartService(ByValserviceNameAsString) DimmyControllerAsNewServiceController(serviceName) Try myController.Start() myController.WaitForStatus(ServiceControllerStatus.Running,_ NewTimeSpan(0,0,30)) MsgBox(String.Format("The{0}ServicehasBeenStarted",_ serviceName)) CatchexAsSystem.InvalidOperationException MsgBox(String.Format(_  "The{0}ServicecouldnotbeStarted.Details:{1}",_ serviceName,ex.ToString())) CatchexAsSystem.ServiceProcess.TimeoutException MsgBox(String.Format(_  "The{0}ServiceTimedoutAttemptingtoStart.Details:{1}",_ serviceName,ex.ToString())) Finally myController.Close() EndTry EndSub 

As you can see, the ServiceController class also provides a method named WaitForStatus . This method contains two overloads ”one that simply blocks until the service reaches the specified status and another that takes a second argument, which is a TimeSpan argument. If a TimeSpan is specified and the value of the TimeSpan expires before the service reaches the desired state, a TimeoutException is thrown.

The code for stopping a Windows service is almost identical to that for starting the service, with one additional comment. The ServiceController class has properties such as CanStop and CanPauseAndContinue so you can avoid throwing unnecessary exceptions if a service doesn't support a particular action. The following code checks the CanStop property of the service before attempting to stop it.

 ImportsSystem.ServiceProcess PrivateSubStopService(ByValserviceNameAsString) DimmyControllerAsNewServiceController(serviceName) Try If(myController.CanStop)Then myController.Stop() 'Wait30secondsfortheServicetoStop ' myController.WaitForStatus(ServiceControllerStatus.Stopped,_ NewTimeSpan(0,0,30)) MsgBox(String.Format("The{0}ServicehasBeenStopped",_ serviceName)) Else MsgBox(String.Format(_  "The{0}ServicedoesnotsupportStopping",serviceName)) EndIf CatchexAsSystem.InvalidOperationException MsgBox(String.Format("The{0}ServicecouldnotbeStopped." &_  " Details:{1}",serviceName,ex.ToString())) CatchexAsSystem.ServiceProcess.TimeoutException MsgBox(String.Format("The{0}ServiceTimedoutAttemptingtoStop." _ & " Details:{1}",serviceName,ex.ToString())) Finally myController.Close() EndTry EndSub 

The code for pausing or continuing a service using the ServiceController class is similar to that for stopping the service. The ServiceController class will be discussed further in the next section. This will include a sample application which provides buttons to control the non-device-driver services on the machine the application is running on.

The Service Manager Application

The Service Manager sample application provides buttons that allow the user to start, stop, pause, and continue services running on the local machine.

Figure 7-4. The Service Manager sample application.

graphics/f07pn04.jpg

Note

Another button, the Dependent Services button, invokes a simple system dialog box that lists the dependent services for the currently highlighted service in List View.


The following code shows how the application does this:

 'DisplaysaMessageboxwhichshowstheDependentServicesofthe 'currentlyselectedService PrivateSubdepButton_Click(ByValsenderAsSystem.Object,_ ByValeAsSystem.EventArgs)HandlesdepButton.Click DimserviceNameAsString=GetServiceName() DimnamesListAsString Me.Cursor=Cursors.WaitCursor IfserviceName<> "" Then DimserviceAsServiceController=NewServiceController(serviceName) DimdepServiceAsServiceController 'IterateoverthearraytogettheDisplaynameofeachService ForEachdepServiceInservice.DependentServices namesList=namesList&depService.DisplayName&vbCrLf Next IfnamesList<> "" Then MsgBox(namesList) EndIf service.Close() EndIf Me.Cursor=Cursors.Default EndSub 

Notice the call to service.Close() . It is good practice to call the Close method after you finish with a ServiceController object that you created. The Close method disconnects from the service, freeing handles and other resources that were allocated when the ServiceController was created.

Tables 7-2 and 7-3 describe the properties and the methods of the ServiceController class, respectively.

Table 7-2. ServiceController Properties

Property

Description

CanStop

Specifies whether the service can be stopped ( True or False ).

CanShutdown

A value of True specifies that the service should be notified when the computer is shutting down.

CanPauseAndContinue

A value of True specifies that the service supports Pause and Continue commands. OnPause and OnContinue base class methods should be overridden if this property is True .

DependentServices

Returns an array of ServiceController instances that depend on this service.

DisplayName

The name that is used to identify the service.

MachineName

The name of the machine that the service resides on.

ServiceName

Set or gets the short name of the service.

ServicesDependedOn

Returns an array of ServiceController instances that a service depends on.

ServiceType

Returns a bitwise Or combination of the ServiceType enum member. These include Adapter , FileSystemDriver , InteractiveProcess , KernelDriver , RecognizerDriver , Win32OwnProcess , and Win32ShareProcess .

Status

An enum that depicts what state the service is in: Running , Stopped , Paused , PausePending , StopPending , StartPending , or ContinuePending .

Table 7-3. ServiceController Methods

Method

Description

Close

Closes the ServiceController instance and frees all resources that it allocated

Continue

Resumes a paused service

ExecuteCommand

Sends a custom command to the service

GetDevices (Shared)

Returns an array of ServiceController instances that represent the device-driver-specific services on the machine

GetServices (Shared)

Returns an array of ServiceController instances that represent services that are not device drivers

Pause

Pauses the service

Refresh

Resets the ServiceController instance properties back to their defaults

Start

Starts the service

Stop

Stops the service

WaitForStatus

Waits for the service to reach a particular status or timeout period

The majority of services log the starting, stopping, and other state transitions to the Windows Event Log. Before diving into creating a service, a brief overview of the Windows Event Log will be given, with code examples that write to the Windows Event Log using Visual Basic .NET.

I l @ ve RuBoard


Designing Enterprise Applications with Microsoft Visual Basic .NET
Designing Enterprise Applications with Microsoft Visual Basic .NET (Pro-Developer)
ISBN: 073561721X
EAN: 2147483647
Year: 2002
Pages: 103

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net