Windows Management Instrumentation (WMI) Tutorial
http://www.csharpfriends.com
World's Greatest C# Community    
Home Articles C# Forums Books C# Syntax C# Spec C# Jobs free Source Code Advertise About
 

Control Panel

[ Sign In / register ]
Points   
Notes 
My Forums
My Tutorials
My Profile

Resources

Learn
 Articles
 QuickStarts
 C# Spec
 Whitepapers
 Tools
 Class Browser
 C# Code Generator
 Links
 Misc Rss Feeds
 Code Highlight
 411 Directory
 FREE magazines
 freevb.net

Reviews
  ASP.NET Hosting

Source Code
 Get Version 1.0



C# Consulting
AspDotNetStoreFront
Chapter:   UnCategorized
Current Lesson:
Windows Management Instrumentation (WMI) Tutorial
[Latest Content]
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ALL
[prev. Lesson]  Calling .NET From COM [next Lesson]  Download And Upload A File Using C#
Windows Management Instrumentation (WMI) Tutorial
  by: Gsuttie

Windows Management Instrumentation (WMI) Tutorial

by: GSuttie

WMI is one of those things you hear about but never take any notice until you look into a little bit and you realise the huge potential for monitoring your application.

This tutorial will let you interrgoate things such as the IIS Service and the MSSqlServer service. Note the potential with WMI is staggering - al you need is some thought about what you want to do with it.

Create a web application and call it WMI2 - just so you can cut and paste all of this code straight in.

Code behind Below
Code behind Below

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Management;

namespace WMI2
{
/// 
/// Summary description for WebForm2.
/// 
public class WebForm2 : System.Web.UI.Page
{
    protected System.Web.UI.WebControls.Label Label1;
    protected System.Web.UI.WebControls.Button Button1;
    protected System.Web.UI.WebControls.Button Button2;
    protected System.Web.UI.WebControls.Button Button3;
    protected System.Web.UI.WebControls.Button Button4;
    protected System.Web.UI.WebControls.Button Button5;
    protected System.Web.UI.WebControls.Button Button6;
    protected System.ServiceProcess.ServiceController serviceController2;
    protected System.Web.UI.WebControls.Button Button7;
    protected System.Web.UI.WebControls.Label Label2;
    protected System.Web.UI.WebControls.Button Button8;
    protected System.Web.UI.WebControls.Button Button9;
    protected System.ServiceProcess.ServiceController serviceController1;

    private void Page_Load(object sender, System.EventArgs e)
    {
        string SQLstatus;
        SQLstatus = serviceController1.Status.ToString();
        Label1.Text =  SQLstatus.ToString();
    }

#region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web 
        // Form Designer.
        
        InitializeComponent();
        base.OnInit(e);
    }

    /// 
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// 
    private void InitializeComponent()
    {    
        this.serviceController1 = new System.ServiceProcess.ServiceController();
        this.serviceController2 = new System.ServiceProcess.ServiceController();
        this.Button5.Click += new System.EventHandler(this.Button5_Click);
        this.Button1.Click += new System.EventHandler(this.Button1_Click);
        this.Button2.Click += new System.EventHandler(this.Button2_Click);
        this.Button3.Click += new System.EventHandler(this.Button3_Click);
        this.Button4.Click += new System.EventHandler(this.Button4_Click);
        this.Button6.Click += new System.EventHandler(this.Button6_Click);
        // 
        // serviceController1
        // 
        this.serviceController1.MachineName = "gregor";
        this.serviceController1.ServiceName = "MSSQLSERVER";
        // 
        // serviceController2
        // 
        this.serviceController2.MachineName = "gregor";
        this.serviceController2.ServiceName = "IISADMIN";
        this.Button7.Click += new System.EventHandler(this.Button7_Click);
        this.Button8.Click += new System.EventHandler(this.Button8_Click);
        this.Button9.Click += new System.EventHandler(this.Button9_Click);
        this.Load += new System.EventHandler(this.Page_Load);

    }
#endregion

    #region OperatingSystem
    private void OperatingSystem()
    {
        //List a few operating System variales
        //List is alomost endless of things you can query against
        try
        {
            ManagementObjectSearcher query1 = new
            ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem") ;
            ManagementObjectCollection queryCollection1 = query1.Get();
            foreach( ManagementObject mo in queryCollection1 ) 
            {
                Response.Write("Name : " + mo["name"].ToString());
                Response.Write("
"); Response.Write("Version : " + mo["version"].ToString()); Response.Write("
"); Response.Write("Manufacturer : " + mo["Manufacturer"].ToString()); Response.Write("
"); Response.Write("Computer Name : " + mo["csname"].ToString()); Response.Write("
"); Response.Write("Windows Directory : " + mo["WindowsDirectory"].ToString()); Response.Write("
"); } } catch(Exception ex) { Response.Write(ex.Message); } } #endregion #region Start Sql Server Service Button private void Button1_Click(object sender, System.EventArgs e) { //Start the Sql Server windows service try { //only start it if its not currently running if (serviceController1.Status.ToString() != "Running") { serviceController1.Start(); } } catch(Win32Exception myEx) { Response.Write (myEx.Message); } catch(Exception ex) { Response.Write(ex.Message); } } #endregion #region Stop Sql Server Service Button private void Button2_Click(object sender, System.EventArgs e) { //Stop the Sql Server windows service try { if (serviceController1.Status.ToString() != "Stopped") { serviceController1.Stop(); } } catch(Win32Exception myEx) { Response.Write (myEx.Message); } catch(Exception ex) { Response.Write(ex.Message); } } #endregion #region StartedServices - Lists all Services which are running. private void StartedServices() { //List all currently started windows services try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE Started = TRUE"); foreach (ManagementObject service in searcher.Get()) Response.Write("Service = " + service["Caption"] + "
"); } catch(Exception e) { Response.Write(e.Message); } } #endregion #region StoppedServices - Lists all Services which arent running. private void StoppedServices() { //List all currently stopped windows services try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE Started = False"); foreach (ManagementObject service in searcher.Get()) Response.Write("Service = " + service["Caption"] + "
"); } catch(Exception e) { Response.Write(e.Message); } } #endregion #region Started Service Button private void Button3_Click(object sender, System.EventArgs e) { //Lists all Services which are running StartedServices(); } #endregion #region Stopped Service Button private void Button4_Click(object sender, System.EventArgs e) { //Lists all Services which arent running StoppedServices(); } #endregion #region Operating System Button private void Button5_Click(object sender, System.EventArgs e) { //Display a few Operating system values OperatingSystem(); } #endregion #region EventLog private void EventLog() { //List all currently started windows services try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NTLogEvent"); foreach (ManagementObject service in searcher.Get()) { Response.Write("Service = " + service.Path.Path + "
"); Response.Write("Service = " + service.Path.RelativePath.ToString() + "
"); } } catch(Exception e) { Response.Write(e.Message); } } #endregion private void Button6_Click(object sender, System.EventArgs e) { EventLog(); } private void Button7_Click(object sender, System.EventArgs e) { string IISStatus; IISStatus = serviceController2.Status.ToString(); Label2.Text = IISStatus; } private void Button8_Click(object sender, System.EventArgs e) { //Start the IIS Admin Service try { //only start it if its not currently running if (serviceController2.Status.ToString() != "Running") { serviceController2.Start(); } } catch(Win32Exception myEx) { Response.Write (myEx.Message); } catch(Exception ex) { Response.Write(ex.Message); } } private void Button9_Click(object sender, System.EventArgs e) { //Stop the Sql Server windows service try { if (serviceController2.Status.ToString() != "Stopped") { serviceController2.Stop(); } } catch(Win32Exception myEx) { Response.Write (myEx.Message); } catch(Exception ex) { Response.Write(ex.Message); } } } }
HTML Page code also below:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" 
    Inherits="WMI2.WebForm2" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
    <title>WebForm1</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
    <TABLE id="Table1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px"
                    cellSpacing="1" cellPadding="1" width="100%" border="0">
        <TR>
            <TD align="right">
                SQL Server Status:
                <asp:Label id="Label1" runat="server" 
                        Width="188px"></asp:Label></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button5" runat="server" 
                Text="Display some Operating System details"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button1" runat="server" 
                    Text="Start SQL Server"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button2" runat="server" 
                    Text="Stop Sql Server"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button3" runat="server" 
                    Text="List all running services"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button4" runat="server" 
                    Text="List all stopped services"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button6" runat="server" 
                    Text="Event Log Stuff"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Label id="Label2" runat="server"></asp:Label>
                <asp:Button id="Button7" runat="server" 
                    Text="IIS Admin"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button8" runat="server" 
                    Text="Restart IIS"></asp:Button></TD>
        </TR>
        <TR>
            <TD align="right">
                <asp:Button id="Button9" runat="server" 
                    Text="Stop IIS"></asp:Button></TD>
        </TR>
    </TABLE>
</form>
</body>
</HTML>
You will need to install the add-on below and add an instance of the MSSQL server service and the IIS Admin Service from the services listed within Server Explorer in the IDE.

You can download thr very cool add-on for Visual Studio which will make the task of monitoring your application as simple as drag and drop here http://www.microsoft.com/downloads/release.asp?releaseid=34182

More info can be found at http://www.iseeman.com/docs/wmi.html and http://msdn.microsoft.com/library/default.asp?url=/library/en-us/Dndotnet/html/csharpsqlxmlhttp.asp?frame=true


1 


Build Your Own ASP.NET Website Using C# & VB.NET

Chapter:  UnCategorized
Current Lesson:
Windows Management Instrumentation (WMI) Tutorial
[Latest Content]
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ALL
[prev. Lesson]  Calling .NET From COM [next Lesson]  Download And Upload A File Using C#


Today's Top Movers
vulpes 6800
MadHatter 2220
jal 867
Jeff1203 857
muster 791

Yesterday Top Movers
shakti sin.. 9
MadHatter 3
C#fanatic 2
Al_Pennywo.. 2
carlos_roc.. 1

Monthly Leaders
vulpes 6800
MadHatter 2260
jal 867
Jeff1203 857
muster 791

Top Members
mosessaur 18457
Rincewind 7074
stanleytan 6995
vulpes 6800
Gsuttie 6046

Great Offers
.net hosting
Go To My Pc
Remote Pc Control
zonealarm
spam blocker
web hosting directory
ad server   C#
snadtech GoToMyPc

Top of Page

Advertise | About | Link To Us | Privacy Notice Copyright © 2003 - 2005 CSharpFriends.com  All Rights Reserved  Visual C# Developer Center