Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 7058 |  Welcome, Guest!   Register  Login
Home > Articles > C# > WMI and .NET

WMI and .NET

1 vote(s)
Rating: 5 out of 5
Article posted by Pavan_Kumar on 5/23/2012 | Views: 2557 | Category: C# | Level: Beginner | Points: 250 red flag

Advertisements

Advertisements
WMI is very helpful to access remote machine details.

Introduction

Windows Management Instrumentation(WMI) Provides access to a rich set of management information and management events about the system, devices, and applications instrumented to the Windows Management Instrumentation (WMI) infrastructure. 

Objective


To understand about basics of WMI.

Using the code

We can read the logs with the help of Event Log class but when I tried to access remote server logs then it failed and started throwing an error. Using Event Log class we can access only local machine logs.

In order to access the remote server details we should use WMI.

WMI gives a way to .net developers to connect to remote machines and access of it.

With the help of WMI we can access remote machine details like event logs, disk space, services, printers, USB details etc.

Let’s try to understand WMI with simple example.

WMI classes reside under system.Management namespace.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml.Linq;

using System.Management;

using System.Diagnostics;

using System.Collections;

 

namespace WMI

{

    class EventLogDetails

    {

        public string Message { get; set; }

        public string Type { get; set; }

        public DateTime TimeGenerated { get; set; }

        public string Category {get;set;}

        public string MachineName {get;set;}

        public string SourceName{get;set;}

        public DateTime TimeWritten{get;set;}

        public string User{get;set;}

        /// <summary>

        ///

        /// </summary>

        /// <returns></returns>

        public Dictionary<string, string> GetInfo()

        {

            //dictionary object to hold the values

            Dictionary<string, string> dictInfo = new Dictionary<string, string>();

            dictInfo.Add("Message", "");

            dictInfo.Add("Source", "");

            dictInfo.Add("Type ", "");

            dictInfo.Add("Category ", "");

            dictInfo.Add("TimeWritten", "");

            dictInfo.Add("MachineName", "");

            

            //create our WMI searcher

            ManagementPath mPath_EventLog;

            ManagementScope mgmtScope;

            ManagementObjectCollection moc;

            ManagementClass mc;

            ConnectionOptions options;

 

            System.Management.ObjectQuery qury = new ObjectQuery();

 

            string Host = "Machine Name";

            // Remote machine connection details

            options = new ConnectionOptions();

            options.Username = "UserName";

            options.Password = "Password";

            options.Authority = "ntlmdomain:" + " XYZ ";

            options.Authentication = AuthenticationLevel.PacketPrivacy;

            options.EnablePrivileges = true;

           //By default impersonation  is Impersonate

            options.Impersonation = ImpersonationLevel.Impersonate;

             mgmtScope = new ManagementScope("\\\\" + Host + "\\root\\cimv2", options);

            mPath_EventLog = new ManagementPath();

             //execute the query using WMI

            qury = new ObjectQuery("Select * from Win32_NTLogEvent

                  Where (Logfile = 'Application') AND (Type = 'Error')");

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(mgmtScope, qury);

               //Create a XML doc

            var xdoc = new XDocument();

            XElement xroot = new XElement("root");

            xdoc.Add(xroot);

            //now loop through all the item found with the query

            foreach (ManagementObject obj in searcher.Get())

            {

                dictInfo = new Dictionary<string, string>();

                dictInfo ["Message"] = obj.Properties["Message"].Value.ToString();

                dictInfo ["Source"] = obj.Properties["Source"].Value.ToString();

                dictInfo ["Type"] = obj.Properties["Type"].Value.ToString();                                     dictInfo ["Category"] = obj.Properties["Category"].Value.ToString();

                dictInfo ["TimeWritten"] = obj.Properties["TimeWritten"].Value.ToString();

                dictInfo ["MachineName"] = obj.Properties["MachineName"].Value.ToString();

                xroot.Add(dictInfo.Select(ent => new XElement(ent.Key, ent.Value)));

               //Save the xml

                xdoc.Save("D:\\Test\\WMI.xml", SaveOptions.None);

            }

            //return the info

            return dictInfo;

        }       

 

    }

}

Now all the details will be saved in WMI.xml file. Next step is to retrieve the required information from xml and display it.

Conclusion

Have a fun with exploring WMI classesJ.

Please provide feedback below.

Reference

MSDN

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Latest Articles from Pavan_Kumar

About Pavan Kumar

Experience:2 year(s)
Home page:
Member since:Monday, February 06, 2012
Level:Starter
Status: [Member]
Biography:From past two year working with CGI in Dot net technology.
 Responses
Posted by: Gautam028 | Posted on: 24 May 2012 09:59:24 AM | Points: 25

Hi Pavan,

Good work...This is really helpful in learning WMI basics...Keep posting.

Thanks...:)

>> Write Response - Respond to this post and get points
Related Posts

Iterative statements repeat a particular statement block until a condition has been satisfied.

The article describes most of the common Design patterns we often require while we do our code, using C#.

This Article explains the Purpose and use of interfaces. We can learn when and where we need to use interfaces and how it helps us in Object oriented programming.

Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy.

In this article we will be exploring the RDLC reporting feature of .NET.In VS 2010 Crystal Reports are not supported and to create Reporting Systems we can use rdlc feature.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/18/2013 7:44:01 PM