Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

What are the latest methods using C# to Retrieve WMI Data?

Posted on 2009-04-11
2
734 Views
Last Modified: 2013-12-17
Is it me or do we live in a world were no one or nothing can be trusted?
My place of employment has locked down our network to such a degree its becoming more impossible to use the tools that allow us to do our jobs effectively. We have XP SP2 in our environment along with Vista (boo!) trickling in. I'm getting the error when using ManagementScope Class, specifically when running "scope.Connect". Error is: "Access is denied. Exception from HRESULT: (0x80070005 E_ACCESSDENIED)".
What, if any, methods or Classes are available that I can use to get WMI data from remote computers using a Console application developed in C# so I can store it in a DB?
Sincerely and thanks in advance for any help you Experts can provide.
Wally
-------------- C# Code -----------------------------
------- Keep in mind, this is still in development :) ----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Data.SqlClient;
 
namespace CollectEPData
{
    class Program
    {
        public string wkstn;
        public string Wkstn
        {
            get { return wkstn; }
            set { wkstn = value; }
        }
 
        static void Main()
        {
            List<Program> WrkstnList = new List<Program>();
 
            SqlConnection conn = new SqlConnection(SettingsManager.ConnectionString2);
            try
            {
                conn.Open();
 
                string sqlStr = "SELECT Name FROM dbo.Nodes";
                SqlCommand sqlCmd = new SqlCommand(sqlStr, conn);
                sqlCmd.CommandType = System.Data.CommandType.Text;
 
                SqlDataReader rdr = null;
                rdr = sqlCmd.ExecuteReader();
 
                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        Program client = new Program();
                        client.Wkstn = rdr.GetString(0);
                        WrkstnList.Add(client);                       
                    }
 
                    rdr.Close();
                }
 
                if (WrkstnList.Count > 0 )
                {
 
                    // For each client in the WrkstnList collection,
                    // lets connect to it and retrieve WMI data, and then
                    // store in parameters list to send and update DB.
                    foreach (Program client in WrkstnList)
                    {
 
                        // authentication settings needed for WMI Connection
                        // Impersonate - uses the credentials of the caller.
                        // Packet - packet level COM authentication
                        ConnectionOptions mgmtOptions = new ConnectionOptions();
                        mgmtOptions.Impersonation = ImpersonationLevel.Impersonate;
                        mgmtOptions.Authentication = AuthenticationLevel.Connect;
 
                        /* computer path and connection authentication
                         * options passed to th ManagementScope object
                         * named "scope" which then uses the connect
                         * method to pass in parameters and connect to
                         * the computer.
                         */
                        ManagementScope scope = new ManagementScope(@"\\" + client.Wkstn + "\\root\\cimV2", mgmtOptions);
                        scope.Connect(); <-- 0x80070005 E_ACCESSDENIED ERROR OCCURS HERE & EXITS TO CATCH ROUTINE.
 
                        // Management WMI Query to return the specific Hardware data 
                        // using Win32 API Calls.
                        ObjectQuery queryCS = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
                        ObjectQuery queryNA = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter WHERE deviceid = 1");
 
 
                        // ManagementObjectSearcher - retrieves a collection of management objects
                        // based on the specified query.
                        ManagementObjectSearcher objCsSearcher = new ManagementObjectSearcher(scope, queryCS);
                        ManagementObjectSearcher objNaSearcher = new ManagementObjectSearcher(scope, queryNA);
 
                        // Invokes the specificed WMI Query and returns the resulting
                        // collection. ManagementObject - represents a WMI Instance
                        foreach (ManagementObject objQueried in objCsSearcher.Get())
                        {
                            sqlCmd.Parameters.AddWithValue("UserName", objQueried["UserName"]);
                            sqlCmd.Parameters.AddWithValue("Domain", objQueried["Domain"]);
                            sqlCmd.Parameters.AddWithValue("WakeUpType", objQueried["MacAddress"]);
 
                            Console.WriteLine("------------------------------------");
                            Console.WriteLine("Win32_ComputerSystem instance");
                            Console.WriteLine("------------------------------------");
                            Console.WriteLine("Workstation Name: {0}", objQueried["Name"]);
                            Console.WriteLine("User Name: {0}", objQueried["UserName"]);
                            Console.WriteLine("Domain: ", objQueried["Domain"]);
                            Console.WriteLine("Wakeup Type: {0}", objQueried["WakeUpType"]);
                        }
 
                        foreach (ManagementObject objQueried in objNaSearcher.Get())
                        {
                            {
                                Console.WriteLine("------------------------------------");
                                Console.WriteLine("Win32_NetworkAdapterConfiguration instance");
                                Console.WriteLine("------------------------------------");
                                Console.WriteLine("MAC Address: {0}", objQueried["MACAddress"]);
                            }
                        }
 
                        Console.ReadLine();
                    }
                }
            }
            catch
            {
                Console.WriteLine("Database connection failed.");
            }
        }
    }
}

Open in new window

0
Comment
Question by:wally_davis
2 Comments
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 24128871
Since you are using impersonation, the current user doesn't have the necessary access rights.

    mgmtOptions.Impersonation = ImpersonationLevel.Impersonate;

Do you have the option for connecting with any other user credentials?
0
 

Author Closing Comment

by:wally_davis
ID: 31569558
TheLearnedOne. Thank you for responding. You got me on the right track. I needed to add the ManagementOptions "Username" and "Password" options and then also discovered I needed to pass in the Domain\Username correctly using the correct path (and not an escape sequence character, i.e. Domain\Username). The connection (i.e. scope.Connect(); method) worked perfect after that. I'm very pleased that this is now resolved. Thanks!
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Checking a checkbox based on SQL DataReader boolean value in ASP.NET(VB) 2 32
VB.NET 2008 Winforms Signing 13 30
SQL Query Help Top 1 and Distinct? 6 35
Code enhancement 4 20
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

790 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question