WMI Programming with Visual Basic.NET: Combining with Windows Services

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.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 10
August 08, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement


You can download the zip of entire Visual Studio.NET solution (developed for this article) here.

Pre-requisites for this article

This article is bit advanced in its implementation of .NET technologies.  It not only focuses on WMI, but also a bit on Windows Services and ADO.NET. To work with this article, you should be familiar with the concepts of Windows Services and implementations as well. I will not explain the concept (or architecture) of Windows Services in this article, as it is beyond the scope of this series. If you really don’t know what a Windows Service is and how to implement it in .NET, I request you not to work through this article until you become familiar with those concepts.

In general, if you are a beginner to .NET programming, certainly you should be working with ADO.NET to connect to databases. Since this article also uses ADO.NET as another technology, you should be familiar with this one as well. But somehow you can understand the code even if you don’t know ADO.NET, as I am working with only basics.

In brief, the goal of this article is to integrate WMI events with a Windows Service and get them logged into a database. I am quite sure that this article will be very helpful in debugging or monitoring a full-fledged Distributed Application Design. Not only that, this article would also help system administrators to audit almost all the activities of every host present in a network very easily. 

You can also extend this article from Windows Services to Web Services (or even .NET Remoting), making the system monitoring available to being accessed through the Internet or even through mobile devices. You can further extend it to notify an administrator with an email, based on a particular event. Again, the sky is the limit for extending this article.

Another important issue is that, you should have understood all the issues of WMI events, which I discussed in part six and part seven of this series. If you don’t know understand the concept of a WMI event, I don’t think you can understand this article.

So, guys, let’s start joyfully.

Designing and preparing the essentials

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).

Implementing the logic

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,ByValeAsEventArrivedEventArgs)

       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.

Adding the installers and setup

The following steps add service installers to your application:

o       Switch to the design mode of “WMISvc.vb” (or just double click on “WMISvc.vb” in solution explorer).

o       Right click on the empty space and choose “Add Installer” as shown in the following figure (Fig 2).

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.

Installing, executing and testing the windows service

Take the following steps to install the Windows service.

o       From the Solution Explorer, right click on “WMIServiceSetup” and choose install.

o       Click Next in the setup wizard.

o       Choose the “EveryOne” radio button in the next screen and click on next (you can also choose your own location to install it).

o       Click Next again to start the installation.

o       After successful installation, it should give the message “WMIServiceSetup has been successfully installed.” Finally, click on close to end up the installation.

Take the following steps to execute the Windows service.

o       Go to Start -> Run.

o       Type “Services.msc” and press OK.

o       Within the list of Services you should be able to see “WMISvc”. Right click on it and choose “start” as shown in the following figure (Fig 6).

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).

How do you test it?

  • With the list of “Services”, try to stop and start (or even pause and resume) any service which does not harm your routines, like “Indexing Service.” You can do that any number of times for any number of services.
  • Open your SQL Server Enterprise manager. If you open your “ServiceHistory” table, you should be able to see all the names of the services along with their status history.
  • To record date and time along with service history, add a new column to you table with TIMESTAMP as data type.
blog comments powered by Disqus
VISUAL BASIC.NET ARTICLES

- Basic Form Properties and Modality in VB.NET
- Multiple Document Interfaces in Visual Basic
- Visual Basic for Beginners
- ASP.NET Image to PDF with VB.Net
- MySQL in ASP.NET: Mono using VB.NET
- AsyncFileUpload File Type and File Size Vali...
- Visual Studio: Adding Functionality and Style
- Clocks and Countdowns
- User-defined Functions using Visual Basic Ap...
- Understanding Object Binding in VBA
- Mastering the Message Box
- Testing a Windows Forms Application
- Using Visual Basic.NET Features to Code a Wi...
- Correcting Code in a Windows Forms Applicati...
- Write Readable Code and Comments for Windows...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials