Communicating with the Service


Up to this point, you’ve learned how to do the following:

  • Create a Windows Service using Visual Basic.

  • Start and stop a service with the Server Explorer in Visual Studio 2005 or the Service Control Manager in the Control Panel.

  • Make a service work with a system-level function such as a performance counter.

If these procedures are sufficient to start, stop, and check on the service through the Server Explorer or Service Control Manager, and there is no need to do any other communication with the service, then this is all you need. However, it is often helpful to create a specialized application to manipulate your service. This application will typically be able to start and stop a service, and check on its status. The application may also need to communicate with the service to change its configuration. Such an application is often referred to as a control panel for the service, even though it does not necessarily reside in the operating system’s Control Panel. A commonly used example of such an application is the SQL Server Service Manager, whose icon appears in the tray on the taskbar (normally in the lower right section of the screen) if you have SQL Server installed.

Such an application needs a way to communicate with the service. The .NET Framework base class that is used for such communication is the ServiceController class. It is in the System.ServiceProcess namespace. You need to add a reference to System.ServiceProcess.dll (which contains this namespace) before a project can use the ServiceController class.

The ServiceController class provides an interface to the Service Control Manager, which coordinates all communication with Windows Services. However, you don’t have to know anything about the Service Control Manager to use the ServiceController class. You just manipulate the properties and methods of the ServiceController class, and any necessary communication with the Service Control Manager is accomplished on your behalf behind the scenes.

It’s a good idea to use exactly one instance of the ServiceController class for each service you are controlling. Multiple instances of ServiceController that are communicating with the same service can have timing conflicts. Typically, that means using a module-level object variable to hold the reference to the active ServiceController, and instantiating the ServiceController during the initialization logic for the application. The following example uses this technique.

The ServiceController Class

The constructor for the ServiceController requires the name of the Windows Service with which it will be communicating. This is the same name that was placed in the ServiceName property of the class that defined the service. You’ll see how to instantiate the ServiceController class shortly.

The ServiceController class has several members that are useful in manipulating services. Here are the most important methods, followed by another table of the most important properties:

Open table as spreadsheet

Method

Purpose

Start

A method to start the service

Stop

A method to stop the service

Refresh

A method to make sure the ServiceController object contains the latest state of the service (needed because the service might be manipulated from another program)

ExecuteCommand

A method used to send a custom command to the service. This method is covered later in the section “Custom Commands.”

Here are the most important properties:

Open table as spreadsheet

Property

Purpose

CanStop

A property indicating whether the service can be stopped

ServiceName

A property containing the name of the associated service

Status

An enumerated property that indicates whether a service is stopped, started, in the process of being started, and so on. The ToString method on this property is useful for getting the status in a string form for text messages. The possible values of the enumeration are as follows:

  • ContinuePending - The service is attempting to continue.

  • Paused - The service is paused.

  • PausePending - The service is attempting to go into a paused state.

  • Running - The service is running.

  • StartPending - The service is starting.

  • Stopped - The service is not running.

  • StopPending - The service is stopping.

ServiceType

A property that indicates the type of service. The result is an enumerated value. The enumerations are as follows:

  • Win32OwnProcess - The service uses its own process (this is the default for a service created in .NET).

  • Win32ShareProcess - The service shares a process with another service (this advanced capability is not covered here).

  • Adapter, FileSystemDriver, InteractiveProcess, KernelDriver, RecognizerDriver - These are low-level service types that cannot be created with Visual Basic because the ServiceBase class does not support them. However, the value of the ServiceType property may still have these values for services created with other tools.

Integrating a ServiceController into the Example

To manipulate the service, we’ll enhance the CounterTest program created earlier. Here are step-by-step instructions to do that:

  1. Add three new buttons to the CounterTest form, with the following names and text labels:

    Open table as spreadsheet

    Name

    Text

    BtnCheckStatus

    Check Status

    BtnStartService

    Start Service

    BtnStopService

    Stop Service

  2. Add a reference to the DLL that contains the ServiceController class: Select Project image from book Add Reference. On the .NET tab, highlight the System.ServiceProcess.dll option and press OK.

  3. Add this line at the top of the code for Form1:

      Imports System.ServiceProcess 

  4. As discussed, the project needs only one instance of the ServiceController class. Create a module-level object reference to a ServiceController class by adding the following line of code within the Form1 class:

      Dim myController As ServiceController 

  5. Create a Form Load event in Form1, and place the following line of code in it to instantiate the ServiceController class:

      myController = New ServiceController("CounterMonitor") 

You now have a ServiceController class named myController that you can use to manipulate the CounterMonitor Windows Service. In the click event for btnCheckStatus, place the following code:

  Dim sStatus As String myController.Refresh() sStatus = myController.Status.ToString MsgBox(myController.ServiceName & " is in state: " & sStatus) 

In the click event for btnStartService, place this code:

  Try     myController.Start() Catch exp As Exception     MsgBox("Could not start service or the service is already running") End Try 

In the click event for btnStopService, place this code:

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

Run and test the program. The service may already be running because of one of your previous tests. Make sure the performance counter is high enough to make the service beep, and then test starting and stopping the service.

More About ServiceController

ServiceController classes can be created for any Windows Service, not just those created in .NET. For example, you could instantiate a ServiceController class that was associated with the Windows Service for Internet Information Server (IIS) and use it to start, pause, and stop IIS. The code would look just like the code used earlier for the application that controlled the CounterMonitor service. The only difference is that the name of the service would need to be changed in the line that instantiates the ServiceController (Step 5).

Keep in mind that the ServiceController is not communicating directly with the service. It is working through the Service Control Manager. That means the requests from the Service Controller to start, stop, or pause a service do not behave synchronously. As soon as the ServiceController has passed the request to the ServicesControlManager, it continues to execute its own code without waiting for the Service Control Manager to pass on the request, or for the service to act on the request.




Professional VB 2005 with. NET 3. 0
Professional VB 2005 with .NET 3.0 (Programmer to Programmer)
ISBN: 0470124709
EAN: 2147483647
Year: 2004
Pages: 267

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