WMI Programming With Visual Basic
WMI Programming With Visual Basic
NET:
Combining with Windows Services
(Page 1 of 5 )
In my previous article, part seven of this series, we looked at permanent subscribers to the WMI
events. This article extends the concept of permanent subscribers to the Windows services level
and integrates it with SQL Server database.
You can download the zip of entire Visual Studio.NET solution (developed for this article) here.
The application that we are going to design now will actually log all the events (state) of any
system service in a database table. We shall subscribe to WMI events through a Windows
Service, which runs as a daemon, without the user's knowledge! In this section, we will create
the table structure in the database and make ready an empty Windows Service to work with
WMI.
I just wanted to log the event information into a very simple database table which contains only
two columns. So, we need to design a table in the SQL Server Database based on the following
structure:
· ServiceName - varchar(50)
· Status - varchar(50)
And we need to store the above structure in a table named “ServiceHistory”.
Let’s start creating the Windows Service:
· Open Visual Studio.NET 2003EnterpriseArchitect
· Go to File -> New -> Project
· In the “New Project” dialog box, select Project Type as “Visual Basic Projects” and
Templates as “Windows Service”.
· Provide the name of the project as “WMIService” and save it at any location you want.
· You should be able to see “Service1.vb” created in the Solution Explorer.
· Double click on “Service1.vb” to open it.
· Right click on the design area and go to properties. Modify properties as follows:
o Name: WMISvc
o ServiceName: WMISvc
· Within the Solution Explorer, right click on “Service1.vb” and rename
it “WMISvc.vb”.
· Again, right click on the same and go to “View Code”.
· Within the Code editor, unhide the region “Component Designer generated Code”.
· Within the same document, find and replace all the instances where the
word “Service1” appears with the word “WMISvc”. You can use “Find and Replace” in
the Edit menu.
· Go to solution explorer, right click on References and choose “Add Reference”.
· Choose “System.Management” within the .NET component list, press the “Select”
button and finally click on OK. You should be able to see “System.Management” within
the list of “References” in the solution explorer.
· Again right click on “WMISvc.vb” in the Solution Explorer and go to “View Code”
(unless you close it).
· Go to menu Project -> WMIService Properties. Change the startup object to
“WMISvc”.
· Add the following lines at the top:
ImportsSystem.Management
ImportsSystem.Data.SqlClient
Thus the first part is completed. Your VS.NET IDE should coincide with the following figure
(Fig 1).
Add these two statements at the class level (above OnStart method):
DimqueryAsWqlEventQuery
DimwatcherAsManagementEventWatcher
Add the following code within the “OnStart” method
query =NewWqlEventQuery( _
"__InstanceModificationEvent", _
NewTimeSpan(0, 0, 1), _
"TargetInstance isa ""Win32_Service""")
watcher =NewManagementEventWatcher(query)
AddHandlerwatcher.EventArrived,AddressOfHandleEvent
' Start listening
watcher.Start()
EventLog.WriteEntry("WMIService", "Started")
Add the following event handler with the same class:
PublicSubHandleEvent(ByValsenderAsObject,ByValeAsEventArrivedEve
ntArgs)
Try
DimevAsManagementBaseObject = e.NewEvent
DimServiceNameAsString=CType(ev("TargetInstance"),
ManagementBaseObject)("DisplayName")
DimStatusAsString=CType(ev("TargetInstance"),
ManagementBaseObject)("State")
DimcnAsNewSqlConnection("data source=.;initial
catalog=northwind;user id=sa")
cn.Open()
DimcmdAsNewSqlCommand("insert into
ServiceHistory(ServiceName,Status) values ('" & ServiceName &
"','" & Status & "')", cn)
cmd.ExecuteNonQuery()
cmd.Dispose()
cn.Close()
CatchexAsException
EventLog.WriteEntry("WMIService", ex.Message)
EndTry
EndSub
Add the following lines to the “OnStop” method:
watcher.Stop()
EventLog.WriteEntry("WMIService", "Stopped")
Make sure you change the connection string according to your requirements. Rebuild the
solution to ensure that there exist no errors. The project should be built successfully at this
moment.
WMI Programming with Visual Basic.NET:
Combining with Windows Services - Adding
the installers and setup
(Page 4 of 5 )
o You should be able to see “ProjectInstaller.vb” created automatically for you with two
components, “ServiceProcessInstaller1” and “ServiceInstaller1”.
o Right click on “ServiceProcessInstaller1”, go to properties and change the property
“Account” to “LocalSystem” as shown in the following figure (Fig 3).
The following steps add setup to your application:
o Within the Solution Explorer, right click on the solution and go to Add -> New project.
o Select Project Type as “Setup and Deployment Projects” and Templates as “Setup
Project”.
o Provide name as “WMIServiceSetup” and store at your location (generally I store it
within the same path of “WMIService”) as shown in the following figure (Fig 4).
o From the Solution Explorer, right click on “WMIServiceSetup” and go to Add ->
Project Output.
o Within the “Add Project Output Group” window, select Project as “WMIService”
(which should be there by default) and choose “Primary Output” in the listbox
below. Finally click OK.
o From the Solution Explorer, right click again on “WMIServiceSetup” and go to View
-> Custom Actions. You will be presented with another tabbed window.
o Right click on “Custom Actions” and choose “Add Custom Action”.
o Select “File System on Target Machine” from the “Look in” drop down list and click
on OK.
o It shows “Applicaton Folder” in the drop down list. Select “Primary output from
WMIService(Active)” from the listbox and click on OK. And you should be able to see
something like the following (Fig 5).
o Right click again on “WMIServiceSetup” project and choose Rebuild. The solution
should be built successfully (with both projects) at this moment.
o To test whether it has successfully started or not, you can check it using “Event
Viewer” from Administration Tools as shown in the following figure (Fig 7).