|
We've had a number of forum questions
here relating to discovery of Win32 services and controlling same, so
I thought I'd whip up a quick ASP.NET sample. The key here is the System.Management
class, which provides programmatic access to WMI.
Start up a new ASP.NET VB Web Application
and replace the Code in WebForm1.aspx.vb with this:
Imports
System.Management
' be sure to set a reference to the namespace above in "References"
Public Class WebForm1
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the
Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
If Request.Params("action") = Nothing Then
Dim linkmsg As String
Dim searcher As New ManagementObjectSearcher(New SelectQuery("Win32_Service"))
Dim results As ManagementObjectCollection = searcher.Get()
Dim envVar As Object
Response.Write("<CENTER><H1>Services Status and Control</H1></CENTER>")
Response.Write("<TABLE CELLPADDING =2 cellspacing="2" border="0" align="center">")
Response.Write("<TR BGCOLOR=Gray><TD>Service</TD><TD>State</TD><TD>Action</td></TR>")
For Each envVar In results
If envVar("State") = "Stopped" Then linkmsg = _
"<a href=webform1.aspx?action=start&service=" & envVar("name")
& "> Start</a>"
If envVar("State") = "Running" Then linkmsg = _
"<a href=webform1.aspx?action=stop&service=" & envVar("name")
& "> Stop</a>"
Response.Write("<TR BGCOLOR=lightgrey><TD>" &
envVar("Name") & "</TD><TD>" &
envVar("state") & "</TD><TD>" &
linkmsg & "</TD></TR>")
Next
Response.Write("</table>")
searcher.Dispose()
results.Dispose()
Else
Dim path As ManagementPath = ManagementPath.DefaultPath
path.RelativePath = "Win32_Service.Name='"
& Request.Params("service") & "'"
Dim mo As ManagementObject = New ManagementObject(path)
If mo("state") = "Stopped" And Request.Params("Action")
= "start" Then
mo.InvokeMethod("StartService", Nothing)
End If
If mo("state") = "Running" And Request.Params("action")
= "stop" Then
mo.InvokeMethod("StopService", Nothing)
End If
mo.Dispose()
Response.Redirect("./Webform1.aspx")
End If
End Sub
End
Class
The code is pretty much self explanatory, so I'll let
it stand on its own. Note that we use the ManagementObject.InvokeMethod
method to actually request a stop or start of a specific service.
If you would like a "pre-done" solution example
of this, just download this
zip file.
Peter Bromberg is an independent consultant
specializing in distributed .NET solutions in Orlando and a co-developer
of the NullSkull.com developer
website. He can be reached at info@eggheadcafe.com
|