Exemplo n.º 1
0
 private static DateTime?GetUsersLogonTimestamp(DprCurrentUsers user)
 {
     if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Domain) || Win32.WellKnownSids.ContainsKey(user.Sid))
     {
         return(null);
     }
     WmiHelpers.ForEachWithScope(user.ComputerName, @"SELECT * FROM Win32_LogonSession", (obj, scope) => {
         try {
             var roq = new RelatedObjectQuery(string.Format(@"associators of {{Win32_LogonSession.LogonId='{0}'}} WHERE AssocClass = Win32_LoggedOnUser", WmiHelpers.GetString(obj, @"LogonId")));
             using (var searcher = new ManagementObjectSearcher(scope, roq)) {
                 foreach (var mobObj in searcher.Get( ))
                 {
                     Helpers.AssertNotNull(mobObj, @"WMI Error, null value returned.");
                     var mob    = (ManagementObject)mobObj;
                     var name   = WmiHelpers.GetString(mob, @"Name");
                     var domain = WmiHelpers.GetString(mob, @"Domain");
                     if (!name.Equals(user.UserName) || !domain.Equals(user.Domain))
                     {
                         continue;
                     }
                     user.LastLogon = WmiHelpers.GetNullableDate(obj, @"StartTime");
                     return(false);                            // Found, stop loop
                 }
             }
         } catch (ManagementException ex) {
             GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"Error finding last logon on {0} for {1}\{2}\n{3}", user.ComputerName, user.Domain, user.UserName, ex.Message);
         }
         return(true);
     }, false, false);
     return(user.LastLogon);
 }
Exemplo n.º 2
0
    public static void Main(string[] args)
    {
        RelatedObjectQuery q =
            new RelatedObjectQuery("Win32_Service='TCP/IP'");

        q.RelationshipClass = "Win32_DependentService";
    }
    public static void Main(string[] args)
    {
        RelatedObjectQuery q =
            new RelatedObjectQuery("Win32_ComputerSystem='MySystem'");

        q.RelatedClass = "Win32_Service";
    }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            ManagementScope scope = new ManagementScope("\\\\.\\root\\cimv2");

            string queryString = "select * from win32_logonsession";                          // for all sessions
            //string queryString = "select * from win32_logonsession where logontype = 2";     // for local interactive sessions only

            ManagementObjectSearcher   sessionQuery  = new ManagementObjectSearcher(scope, new SelectQuery(queryString));
            ManagementObjectCollection logonSessions = sessionQuery.Get();

            foreach (ManagementObject logonSession in logonSessions)
            {
                string logonID = logonSession["LogonId"].ToString();
                string status  = "";// logonSession["Status"].ToString();
                Console.WriteLine("=== {0}, type {1} === statu {2}", logonID, logonSession["LogonType"].ToString(), status);
                RelatedObjectQuery         relatedQuery = new RelatedObjectQuery("associators of {Win32_LogonSession.LogonId='" + logonID + "'} WHERE AssocClass=Win32_LoggedOnUser Role=Dependent");
                ManagementObjectSearcher   userQuery    = new ManagementObjectSearcher(scope, relatedQuery);
                ManagementObjectCollection users        = userQuery.Get();
                foreach (ManagementObject user in users)
                {
                    Console.WriteLine(user.GetPropertyValue("Name"));
                    Console.WriteLine(user.GetPropertyValue("Status"));
                }
            }
            Console.Read();
        }
Exemplo n.º 5
0
        public void Static_Related_Instances()
        {
            using (var searcher = new ManagementObjectSearcher())
            {
                var relatedObjectQuery = new RelatedObjectQuery("Class3.Class3Key='Three2'");
                searcher.Scope.Path.NamespacePath = WmiTestHelper.Namespace;
                searcher.Query = relatedObjectQuery;
                ManagementObjectCollection instances = searcher.Get();
                Assert.Equal(1, instances.Count);

                foreach (ManagementObject instance in instances)
                {
                    Assert.Equal("Class4", instance.Path.ClassName);
                }
            }
        }
Exemplo n.º 6
0
        public void Related_Instances()
        {
            using (var searcher = new ManagementObjectSearcher())
            {
                var relatedObjectQuery = new RelatedObjectQuery($"Win32_LogicalDisk.DeviceID='{WmiTestHelper.SystemDriveId}'");
                searcher.Query = relatedObjectQuery;
                ManagementObjectCollection instances = searcher.Get();
                Assert.True(instances.Count > 0);

                string[] expectedAssociatedInstanceClasses =
                {
                    "Win32_Directory", "Win32_DiskPartition", "Win32_ComputerSystem", "Win32_QuotaSetting", "Win32_SystemAccount", "Win32_Group"
                };

                foreach (ManagementObject instance in instances)
                {
                    Assert.True(expectedAssociatedInstanceClasses.Contains(instance.Path.ClassName), $"Unexpected instance of class {instance.Path.ClassName}");
                }
            }
        }
Exemplo n.º 7
0
        public List <StorageDTOResponse> GetStorageInfo()
        {
            List <StorageDTOResponse> storage = new List <StorageDTOResponse>();

            try
            {
                // In Windows <= Windows Server 2003 Win32_DiskDrive doesn't have SerialNumber field.
                string query;
                if (osVersionNumber < 6)
                {
                    query = "select Caption, DeviceID, Model from Win32_DiskDrive";
                }
                else
                {
                    query = "select Caption, DeviceID, SerialNumber, Model from Win32_DiskDrive";
                }

                SelectQuery diskDrivesQuery = new SelectQuery(query);
                ManagementObjectSearcher diskDrivesSearcher = new ManagementObjectSearcher(diskDrivesQuery);

                foreach (ManagementObject diskDrive in diskDrivesSearcher.Get())
                {
                    string sn = "";
                    if (osVersionNumber < 6)
                    {
                        // In Windows <= Windows Server 2003 we can find SerialNumber in Win32_PhysicalMedia.
                        SelectQuery snQuery = new SelectQuery("select SerialNumber from Win32_PhysicalMedia where tag='" + GetValueAsString(diskDrive, "DeviceID").Replace(@"\", @"\\") + "'");
                        ManagementObjectSearcher snSearcher = new ManagementObjectSearcher(snQuery);

                        foreach (ManagementObject snObj in snSearcher.Get())
                        {
                            sn = GetValueAsString(snObj, "SerialNumber");
                            break;
                        }
                    }
                    else
                    {
                        sn = GetValueAsString(diskDrive, "SerialNumber");
                    }

                    if (sn.Length == 0 ||
                        sn.StartsWith("QM000") ||
                        Blacklists.IsDiscVendorInBlacklist(GetValueAsString(diskDrive, "Caption").ToLower()) ||
                        Blacklists.IsDiskProductInBlacklist(GetValueAsString(diskDrive, "Model").ToLower())
                        )
                    {
                        continue;
                    }

                    RelatedObjectQuery diskPartitionsQuery = new RelatedObjectQuery(
                        "associators of {Win32_DiskDrive.DeviceID='" +
                        GetValueAsString(diskDrive, "DeviceID") +
                        "'} where AssocClass=Win32_DiskDriveToDiskPartition"
                        );
                    ManagementObjectSearcher diskPartitionsSearcher = new ManagementObjectSearcher(diskPartitionsQuery);

                    foreach (ManagementObject diskPartition in diskPartitionsSearcher.Get())
                    {
                        RelatedObjectQuery logicalDisksQuery = new RelatedObjectQuery(
                            "associators of {Win32_DiskPartition.DeviceID='" +
                            GetValueAsString(diskPartition, "DeviceID") +
                            "'} where AssocClass=Win32_LogicalDiskToPartition"
                            );
                        ManagementObjectSearcher logicalDisksSearcher = new ManagementObjectSearcher(logicalDisksQuery);

                        foreach (ManagementObject logicalDisk in logicalDisksSearcher.Get())
                        {
                            StorageDTOResponse disk = new StorageDTOResponse();
                            disk.Label      = GetValueAsString(diskDrive, "Caption");
                            disk.MountPoint = GetValueAsString(diskDrive, "DeviceID");
                            try
                            {
                                disk.Size = ConvertSizeToMiB(Int64.Parse(logicalDisk["Size"].ToString()), SizeUnits.B).ToString();
                            }
                            catch (Exception e)
                            {
                                Logger.Instance.LogError(e.ToString());
                            }
                            disk.Sn = sn;

                            storage.Add(disk);
                        }
                    }
                }
            }
            catch (ManagementException e)
            {
                Logger.Instance.LogError(e.ToString());
            }

            return(storage);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Returns a list of brief structures representing an attached microbit.
        /// Struct contains information such as COM port and drive letter.
        /// </summary>
        /// <param name="microcontrollerId"></param>
        /// <param name="isFauxbit"></param>
        /// <returns></returns>
        private static List <MicrobitDesc> GetDeviceDesc()
        {
            List <MicrobitDesc> descs = new List <MicrobitDesc>();

            //
            // Find the COM ports.
            //
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(ManagementPath.DefaultPath.ToString(), "SELECT * FROM Win32_PnPEntity");

            // Note:  We're also using this opportuning to test for any Xbox controllers
            // on the system.  This way the system can display the correct icons depending
            // on whether the user has an Xbox 360 controller or an Xbox One controller.
            GamePadInput.Xbox360ControllerFound = false;
            GamePadInput.XboxOneControllerFound = false;

            foreach (ManagementObject queryObj in searcher.Get())
            {
                string caption = (string)queryObj["Caption"];

                if (string.Equals(caption, "Xbox 360 Controller for Windows", StringComparison.InvariantCultureIgnoreCase))
                {
                    GamePadInput.Xbox360ControllerFound = true;
                }

                if (string.Equals(caption, "Xbox Gaming Device", StringComparison.InvariantCultureIgnoreCase))
                {
                    GamePadInput.XboxOneControllerFound = true;
                }

                if (caption != null && caption.StartsWith("mbed Serial Port") && caption.Contains("(COM"))
                {
                    int start = caption.IndexOf("(COM");
                    int end   = caption.IndexOf(")");
                    if (start < end)
                    {
                        string PNPDeviceId = (string)queryObj["PNPDeviceId"];

                        // Create a new desc.
                        MicrobitDesc desc = new MicrobitDesc();
                        descs.Add(desc);

                        desc.COM = caption.Substring(start + 1, end - start - 1);
                        int numIndex = PNPDeviceId.LastIndexOf("\\");
                        if (numIndex > 1)
                        {
                            desc.PNPDeviceId = PNPDeviceId.Substring(numIndex + 1);
                        }
                    }
                }
            }

            //
            // Find the drive letters that match up with COM ports we've already found.
            //
            ManagementScope scope = new ManagementScope(ManagementPath.DefaultPath);

            scope.Connect();

            string qstr = String.Empty;

            try
            {
                qstr = String.Format(@"Select * From Win32_PnPEntity where ClassGuid = '{{4d36e967-e325-11ce-bfc1-08002be10318}}'");
                using (var diskDeviceSearcher = new ManagementObjectSearcher(ManagementPath.DefaultPath.ToString(), qstr))
                    using (var diskDeviceCollection = diskDeviceSearcher.Get())
                    {
                        foreach (var diskDevice in diskDeviceCollection)
                        {
                            qstr = String.Format(@"Select * from Win32_DiskDrive");
                            using (var diskDriveSearcher = new ManagementObjectSearcher(ManagementPath.DefaultPath.ToString(), qstr))
                                using (var diskDriveCollection = diskDriveSearcher.Get())
                                {
                                    foreach (var diskDrive in diskDriveCollection)
                                    {
                                        string Caption = (string)diskDrive["Caption"];

                                        // If not an MDBED device, just skip.
                                        if (!Caption.StartsWith("MBED"))
                                        {
                                            continue;
                                        }

                                        string PNPDeviceID = (string)diskDrive["PNPDeviceID"];

                                        string diskDrive_DeviceID = (string)diskDrive.GetPropertyValue("DeviceID");
                                        UInt32 diskDrive_Index    = (UInt32)diskDrive.GetPropertyValue("Index");
                                        qstr = String.Format(@"Select * from Win32_DiskPartition where DeviceID like 'Disk #{0}%' and PrimaryPartition = True", diskDrive_Index);
                                        using (var primaryPartitionSearcher = new ManagementObjectSearcher(ManagementPath.DefaultPath.ToString(), qstr))
                                            using (var primaryPartitionCollection = primaryPartitionSearcher.Get())
                                            {
                                                foreach (var primaryPartition in primaryPartitionCollection)
                                                {
                                                    string primaryPartition_DeviceID = (string)primaryPartition.GetPropertyValue("DeviceID");
                                                    qstr = String.Format(@"ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{0}'}} WHERE AssocClass = Win32_LogicalDiskToPartition", primaryPartition_DeviceID);
                                                    var query = new RelatedObjectQuery(qstr);
                                                    using (var logicalDiskSearcher = new ManagementObjectSearcher(scope, query))
                                                        using (var logicalDiskCollection = logicalDiskSearcher.Get())
                                                        {
                                                            foreach (var logicalDisk in logicalDiskCollection)
                                                            {
                                                                string logicalDisk_DeviceID = logicalDisk["DeviceID"].ToString();

                                                                // Figure out which device this drive letter works with.  If we don't
                                                                // find a matching desc that means we have a drive without a corresponding
                                                                // port which means we need to install the mbed driver, so set the flag.
                                                                bool found = false;
                                                                foreach (MicrobitDesc desc in descs)
                                                                {
                                                                    if (PNPDeviceID.Contains(desc.PNPDeviceId))
                                                                    {
                                                                        desc.Drive = logicalDisk_DeviceID;
                                                                        found      = true;
                                                                    }
                                                                }
                                                                if (!found)
                                                                {
                                                                    DriverInstalled = false;
                                                                }
                                                            }
                                                        }
                                                }
                                            }
                                    }
                                }
                        }
                    }
            }
            catch (Exception e)
            {
                while (e != null)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                    e = e.InnerException;
                }
                // Don't crash if WMI throws an exception.
                return(null);
            }

            return(descs);
        }   // end of GetDeviceDesc()
Exemplo n.º 9
0
        private static MicrobitDesc GetDeviceDesc(string microcontrollerId)
        {
            string Microbit_COM   = null;
            string Microbit_Drive = null;


            string         qstr  = String.Empty;
            WqlObjectQuery query = new SelectQuery();

            try
            {
                qstr  = String.Format(@"Select * From Win32_PnPEntity where DeviceID like '%{0}%' and ClassGuid = '{{4d36e978-e325-11ce-bfc1-08002be10318}}'", microcontrollerId);
                query = new SelectQuery(qstr);
                results.AppendLine("Executing query: " + query.QueryString);
                using (var serialDeviceSearcher = new ManagementObjectSearcher(scope, query))
                    using (var serialDeviceCollection = serialDeviceSearcher.Get())
                    {
                        foreach (var serialDevice in serialDeviceCollection)
                        {
                            results.AppendLine("Processing: " + serialDevice.ToString());
                            string serialDevice_Caption = (string)serialDevice.GetPropertyValue("Caption");
                            int    start = serialDevice_Caption.IndexOf("(COM");
                            int    end   = serialDevice_Caption.IndexOf(")");
                            if (start < end)
                            {
                                Microbit_COM = serialDevice_Caption.Substring(start + 1, end - start - 1);
                            }
                            // Only process the first serial device.
                            break;
                        }
                    }

                qstr  = String.Format(@"Select * From Win32_PnPEntity where DeviceID like '%{0}%' and ClassGuid = '{{4d36e967-e325-11ce-bfc1-08002be10318}}'", microcontrollerId);
                query = new SelectQuery(qstr);
                results.AppendLine("Executing query: " + query.QueryString);
                using (var diskDeviceSearcher = new ManagementObjectSearcher(scope, query))
                    using (var diskDeviceCollection = diskDeviceSearcher.Get())
                    {
                        foreach (var diskDevice in diskDeviceCollection)
                        {
                            results.AppendLine("Processing: " + diskDevice.ToString());
                            qstr  = String.Format(@"Select * from Win32_DiskDrive where PNPDeviceID like '%{0}%'", microcontrollerId);
                            query = new SelectQuery(qstr);
                            results.AppendLine("Executing query: " + query.QueryString);
                            using (var diskDriveSearcher = new ManagementObjectSearcher(scope, query))
                                using (var diskDriveCollection = diskDriveSearcher.Get())
                                {
                                    foreach (var diskDrive in diskDriveCollection)
                                    {
                                        results.AppendLine("Processing: " + diskDrive.ToString());
                                        string diskDrive_DeviceID = (string)diskDrive.GetPropertyValue("DeviceID");
                                        UInt32 diskDrive_Index    = (UInt32)diskDrive.GetPropertyValue("Index");
                                        qstr  = String.Format(@"Select * from Win32_DiskPartition where DeviceID like 'Disk #{0}%' and PrimaryPartition = True", diskDrive_Index);
                                        query = new SelectQuery(qstr);
                                        results.AppendLine("Executing query: " + query.QueryString);
                                        using (var primaryPartitionSearcher = new ManagementObjectSearcher(scope, query))
                                            using (var primaryPartitionCollection = primaryPartitionSearcher.Get())
                                            {
                                                foreach (var primaryPartition in primaryPartitionCollection)
                                                {
                                                    results.AppendLine("Processing: " + primaryPartition.ToString());
                                                    string primaryPartition_DeviceID = (string)primaryPartition.GetPropertyValue("DeviceID");
                                                    qstr  = String.Format(@"ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{0}'}} WHERE AssocClass = Win32_LogicalDiskToPartition", primaryPartition_DeviceID);
                                                    query = new RelatedObjectQuery(qstr);
                                                    results.AppendLine("Executing query: " + query.QueryString);
                                                    using (var logicalDiskSearcher = new ManagementObjectSearcher(scope, query))
                                                        using (var logicalDiskCollection = logicalDiskSearcher.Get())
                                                        {
                                                            foreach (var logicalDisk in logicalDiskCollection)
                                                            {
                                                                results.AppendLine("Processing: " + logicalDisk.ToString());
                                                                string logicalDisk_DeviceID = logicalDisk["DeviceID"].ToString();
                                                                Microbit_Drive = logicalDisk_DeviceID;
                                                                // Only process the first logical disk.
                                                                break;
                                                            }
                                                        }
                                                    // Only process the first primary partition.
                                                    break;
                                                }
                                            }
                                        // Only process the first disk drive.
                                        break;
                                    }
                                }
                            // Only process the first disk device.
                            break;
                        }
                    }
            }
            catch (Exception e)
            {
                results.AppendLine("Error executing query: " + qstr);
                while (e != null)
                {
                    results.AppendLine(e.Message);
                    e = e.InnerException;
                }
            }

            if (!String.IsNullOrEmpty(Microbit_Drive))
            {
                results.AppendLine(String.Format("Microbit storage device found at {0}", Microbit_Drive));
            }
            else
            {
                results.AppendLine("Failed to find microbit storage device.");
            }
            if (!String.IsNullOrEmpty(Microbit_COM))
            {
                results.AppendLine(String.Format("Microbit serial port found at {0}", Microbit_COM));
            }
            else
            {
                results.AppendLine("Failed to find microbit serial port.");
            }

            if (!String.IsNullOrEmpty(Microbit_COM) && !String.IsNullOrEmpty(Microbit_Drive))
            {
                MicrobitDesc desc = new MicrobitDesc();
                desc.COM   = Microbit_COM;
                desc.Drive = Microbit_Drive;
                return(desc);
            }

            return(null);
        }