Example #1
0
        private static string GetWindowsArchitecture()
        {
            string result = string.Empty;

            using (var searcher = new System.Management.ManagementObjectSearcher("SELECT Architecture FROM Win32_Processor")) {
                foreach (var cpu in searcher.Get())
                {
                    var type = (ushort)cpu["Architecture"];
                    switch (type)
                    {
                    case 0:
                        result = "x86";
                        break;

                    case 5:
                        result = "ARM";
                        break;

                    case 9:
                        result = "x86_64";
                        break;

                    default:
                        result = String.Format("Rare ({0})", type);
                        break;
                    }

                    break;
                }
                return(result);
            }
        }
Example #2
0
 private void MainForm_Load(System.Object sender, System.EventArgs e)
 {
     try {
         System.Management.ManagementObject         i = null;
         System.Management.ManagementObjectSearcher searchInfo_Processor = new System.Management.ManagementObjectSearcher("Select * from Win32_Processor");
         foreach (System.Management.ManagementObject i_loopVariable in searchInfo_Processor.Get())
         {
             i = i_loopVariable;
             txtProcessorName.Text         = i["Name"].ToString();
             txtProcessorID.Text           = i["ProcessorID"].ToString();
             txtProcessorDescription.Text  = i["Description"].ToString();
             txtProcessorManufacturer.Text = i["Manufacturer"].ToString();
             txtProcessorL2CacheSize.Text  = i["L2CacheSize"].ToString();
             txtProcessorClockSpeed.Text   = i["CurrentClockSpeed"].ToString() + " Mhz";
             txtProcessorDataWidth.Text    = i["DataWidth"].ToString();
             txtProcessorExtClock.Text     = i["ExtClock"].ToString() + " Mhz";
             txtProcessorFamily.Text       = i["Family"].ToString();
         }
         System.Management.ManagementObjectSearcher searchInfo_Board = new System.Management.ManagementObjectSearcher("Select * from Win32_BaseBoard");
         foreach (System.Management.ManagementObject i_loopVariable in searchInfo_Board.Get())
         {
             i = i_loopVariable;
             txtBoardDescription.Text  = i["Description"].ToString();
             txtBoardManufacturer.Text = i["Manufacturer"].ToString();
             txtBoardName.Text         = i["Name"].ToString();
             txtBoardSerialNumber.Text = i["SerialNumber"].ToString();
         }
     } catch (Exception ex) {
         Interaction.MsgBox(ex.Message, MsgBoxStyle.Critical, "Error!");
         System.Environment.Exit(0);
     }
 }
Example #3
0
        public static string Default()
        {
            string name = "";
            var    mos  = new System.Management.ManagementObjectSearcher("Select * from Win32_Printer");

            System.Management.ManagementObjectCollection moc = mos.Get();

            //プリンタを列挙する
            foreach (System.Management.ManagementObject mo in moc)
            {
                //デフォルトのプリンタか調べる
                //mo["Default"]はWindows NT 4.0, 2000で使用できません
                if ((((uint)mo["Attributes"]) & 4) == 4)
                {
                    name = mo["Name"] as string;
                    mo.Dispose();
                    break;
                }
                mo.Dispose();
            }

            moc.Dispose();
            mos.Dispose();
            return(name);
        }
        public static int GetBrightness()
        {
            byte curBrightness = 0;

            try
            {
                //output current brightness
                System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
                System.Management.ManagementObjectCollection moc = mos.Get();

                //store result
                foreach (System.Management.ManagementObject o in moc)
                {
                    curBrightness = (byte)o.GetPropertyValue("CurrentBrightness");
                    break; //only work on the first object
                }

                moc.Dispose();
                mos.Dispose();
            }
            catch (Exception)
            {
            }

            return (int)curBrightness;
        }
Example #5
0
        public byte[] GetBrightnessLevels()
        {
            //define scope (namespace)
            System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");

            //define query
            System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");

            //output current brightness
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);

            System.Management.ManagementObjectCollection moc = mos.Get();

            //store result
            byte[] BrightnessLevels = new byte[0];

            foreach (System.Management.ManagementObject o in moc)
            {
                BrightnessLevels = (byte[])o.GetPropertyValue("Level");
                break; //only work on the first object
            }

            moc.Dispose();
            mos.Dispose();

            return BrightnessLevels;
        }
        static AndroidUsbDriverHelper( )
        {
            try {
                System.Management.ManagementClass wmi = new System.Management.ManagementClass ( );
                System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery ( QUERY );
                System.Management.ManagementScope oMs = new System.Management.ManagementScope ( );
                System.Management.ManagementObjectSearcher oSearcher = new System.Management.ManagementObjectSearcher ( oMs, oQuery );
                System.Management.ManagementObjectCollection oResults = oSearcher.Get ( );
                if ( oResults.Count == 1 ) {
                    foreach ( var item in oResults ) {
                        string dv = string.Format ( CultureInfo.InvariantCulture, "{0}", item["DriverVersion"] );
                        if ( !string.IsNullOrEmpty ( dv ) ) {
                            DriverVersion = new Version ( dv );
                        } else {
                            // default
                            DriverVersion = new Version ( "0.0.0.0" );
                        }

                        string cg = string.Format ( CultureInfo.InvariantCulture, "{0}", item["ClassGuid"] );
                        if ( !string.IsNullOrEmpty ( cg ) ) {
                            IsRevision2Driver = string.Compare ( cg, DRIVER_CLASS_GUID_REVISION2, true ) == 0;
                            IsRevision1Driver = !IsRevision2Driver;
                        } else {
                            // default to cupcake
                            IsRevision1Driver = true;
                            IsRevision2Driver = false;
                        }
                    }
                }
            } catch ( Exception ex ) {
                Logger.LogError ( typeof ( AndroidUsbDriverHelper ), ex.Message, ex );
                DriverVersion = new Version ( "0.0.0.0" );
            }
        }
Example #7
0
        private static int GetNumberOfRunningInstances()
        {
            //yank off the appname.exe from the assemblies location
            string[] parts   = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
            string   appName = parts[parts.Length - 1];

            //build the wmi query
            string query = "select name from CIM_Process where name = '" + appName + "'";

            //load up the managementobjectsearcher with the query
            System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);

            int runcount = 0;

            //iterate the collection and (which should only have 1 or 2 instances, and if 3 then its already running
            //1 instaces would be itself, 2 would be self and the other
            foreach (System.Management.ManagementObject item in searcher.Get())
            {
                runcount++;
                if (runcount > 1)
                {
                    break;               //only need to know if there is more then self running
                }
            }

            return(runcount);
        }
Example #8
0
        public static string GetDriveSerialNumber([NotNull] string drive)
        {
            var driveSerial = string.Empty;

            // No matter what is sent in, get just the drive letter
            var driveFixed = Path.GetPathRoot(drive).Replace(@"\", string.Empty, StringComparison.Ordinal);

            // Perform Query
            using (var querySearch = new System.Management.ManagementObjectSearcher(
                       string.Format(
                           CultureInfo.InvariantCulture,
                           format: "SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '{0}'",
                           driveFixed)))
            {
                using (System.Management.ManagementObjectCollection queryCollection = querySearch.Get())
                {
                    foreach (System.Management.ManagementBaseObject moItem in queryCollection)
                    {
                        driveSerial = Convert.ToString(
                            moItem.GetPropertyValue(propertyName: "VolumeSerialNumber"),
                            CultureInfo.CurrentCulture);
                        break;
                    }
                }
            }

            return(driveSerial);
        }
Example #9
0
        //array of valid brightness values in percent
        public static byte[] GetBrightnessLevels()
        {
            //define scope (namespace)
            System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");

            //define query
            System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");

            //output current brightness
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
            byte[] BrightnessLevels = new byte[0];

            try
            {
                System.Management.ManagementObjectCollection moc = mos.Get();

                //store result

                foreach (System.Management.ManagementObject o in moc)
                {
                    BrightnessLevels = (byte[])o.GetPropertyValue("Level");
                    break; //only work on the first object
                }

                moc.Dispose();
                mos.Dispose();
            }
            catch (Exception)
            {
                // MessageBox.Show("Sorry, Your System does not support this brightness control...");
            }

            return(BrightnessLevels);
        }
Example #10
0
 public void Check()
 {
     try
     {
         //seems WMI is the only way to do this.
         //https://stackoverflow.com/questions/498371/how-to-detect-if-my-application-is-running-in-a-virtual-machine
         Message = "Host not virtualised";
         using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
         {
             using (var items = searcher.Get())
             {
                 foreach (var item in items)
                 {
                     string manufacturer = item["Manufacturer"].ToString().ToLower();
                     if (manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL"))
                     {
                         Message = "Virtualisation detected (Microsoft) [*]";
                     }
                     else if (manufacturer.Contains("vmware"))
                     {
                         Message = "Virtualisation detected (VMWare) [*]";
                     }
                     else if (item["Model"].ToString() == "VirtualBox")
                     {
                         Message = "Virtualisation detected (VirtualBox) [*]";
                     }
                 }
             }
         }
     }
     catch
     {
         Message = "Check failed [*]";
     }
 }
Example #11
0
        public static Size GetMaximumScreenSizePrimary()
        {
            var scope = new System.Management.ManagementScope();
            var q = new System.Management.ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");

            UInt32 maxHResolution;
            UInt32 maxVResolution;

            using (var searcher = new System.Management.ManagementObjectSearcher(scope, q))
            {
                var results = searcher.Get();
                maxHResolution = 0;
                maxVResolution = 0;

                foreach (var item in results)
                {
                    if ((UInt32)item["HorizontalResolution"] > maxHResolution)
                        maxHResolution = (UInt32)item["HorizontalResolution"];

                    if ((UInt32)item["VerticalResolution"] > maxVResolution)
                        maxVResolution = (UInt32)item["VerticalResolution"];
                }
            }

            return new Size((int)maxHResolution, (int)maxVResolution);
        }
Example #12
0
 public bool checkVM()
 {
     try
     {
         using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
         {
             using (var items = searcher.Get())
             {
                 foreach (var item in items)
                 {
                     string manufacturer = item["Manufacturer"].ToString().ToLower();
                     if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL")) ||
                         manufacturer.Contains("vmware") ||
                         item["Model"].ToString() == "VirtualBox")
                     {
                         return(true);
                     }
                 }
             }
         }
         return(false);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #13
0
        static void SetBrightness(byte targetBrightness)
        {
            try
            {
                //define scope (namespace)
                System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");

                //define query
                System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightnessMethods");

                //output current brightness
                System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);

                System.Management.ManagementObjectCollection moc = mos.Get();

                foreach (System.Management.ManagementObject o in moc)
                {
                    o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise!
                    break;                                                                                  //only work on the first object
                }

                moc.Dispose();
                mos.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("8Brightness control is only supported on Laptops", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                Application.Exit();
            }
        }
Example #14
0
        /*
         * Get the array of allowed brightnesslevels for this system
         * */
        static byte[] GetBrightnessLevels()
        {
            //define scope (namespace)
            System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");

            //define query
            System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");

            //output current brightness
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
            byte[] BrightnessLevels = new byte[0];

            try
            {
                System.Management.ManagementObjectCollection moc = mos.Get();

                //store result

                foreach (System.Management.ManagementObject o in moc)
                {
                    BrightnessLevels = (byte[])o.GetPropertyValue("Level");
                    break; //only work on the first object
                }

                moc.Dispose();
                mos.Dispose();

            }
            catch (Exception)
            {
                Console.WriteLine("Sorry, Your System does not support this brightness control...");
            }

            return BrightnessLevels;
        }
Example #15
0
        public List <string> GetInterfacePort()
        {
            System.Management.ManagementObjectCollection moReturn;
            System.Management.ManagementObjectSearcher   moSearch;

            List <string> mComFullName = new List <string>();

            int i, j;

            moSearch = new System.Management.ManagementObjectSearcher("root\\CIMV2", "Select * from Win32_PnPEntity");
            moReturn = moSearch.Get();

            foreach (System.Management.ManagementObject mo in moReturn)
            {
                if (mo.Properties["Name"].Value != null)
                {
                    if (
                        mo.Properties["Name"].Value.ToString().Contains("USB Serial Port") ||
                        mo.Properties["Name"].Value.ToString().Contains("Gadget") ||
                        mo.Properties["Name"].Value.ToString().Contains("ITL USB") ||
                        mo.Properties["Name"].Value.ToString().Contains("ITL BV") ||
                        mo.Properties["Name"].Value.ToString().Contains("USB Serial Device")
                        )
                    {
                        mComFullName.Add(mo.Properties["Name"].Value.ToString());
                    }
                }
            }


            return(mComFullName);
        }
Example #16
0
        private string GetPropertiesOfWMIObjects(string _QueryTarget, string _PropertyName)
        {
            try
            {
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM " + _QueryTarget);

                string propertystring = string.Empty;
                foreach (System.Management.ManagementObject wmi_object in searcher.Get())
                {
                    Object property = wmi_object[_PropertyName];
                    if (property != null)
                    {
                        propertystring += property.ToString();
                    }
                }

                return(propertystring);
            }
            catch (System.Exception ex)
            {
                // Do nothing except log.
                Log.Error("An exception occurred while trying to obtain some WMI object properties: " + ex.Message);
            }

            return(string.Empty);
        }
Example #17
0
        public static bool DetectVirtualMachine()
        {
            using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
            {
                using (var items = searcher.Get())
                {
                    foreach (var item in items)
                    {
                        string manufacturer = item["Manufacturer"].ToString().ToLower();
                        if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL")) ||
                            manufacturer.Contains("vmware") ||
                            item["Model"].ToString() == "VirtualBox" || GetModuleHandle("cmdvrt32.dll").ToInt32() != 0 || GetModuleHandle("SxIn.dll").ToInt32() != 0 ||
                            GetModuleHandle("SbieDll.dll").ToInt32() != 0 || GetModuleHandle("Sf2.dll").ToInt32() != 0 ||
                            GetModuleHandle("snxhk.dll").ToInt32() != 0)
                        {
                            return(true);
                        }


                        var hypervisorPresentProperty
                            = item.Properties
                              .OfType <PropertyData>()
                              .FirstOrDefault(p => p.Name == "HypervisorPresent");

                        if ((bool?)hypervisorPresentProperty?.Value == true)
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        } // End Function GetCommandLine

        /// <summary>
        /// Kill a process, and all of its children, grandchildren, etc.
        /// </summary>
        /// <param name="pid">Process ID.</param>
        public static void KillProcessAndChildren(int pid)
        {
            // Cannot close 'system idle process'.
            if (pid == 0)
            {
                return;
            }

            System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher
                                                                      ("Select * From Win32_Process Where ParentProcessID=" + pid);

            System.Management.ManagementObjectCollection moc = searcher.Get();
            foreach (System.Management.ManagementObject mo in moc)
            {
                KillProcessAndChildren(System.Convert.ToInt32(mo["ProcessID"]));
            }

            try
            {
                System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById(pid);
                proc.Kill();
            }
            catch (System.ArgumentException)
            {
                // Process already exited.
            }
        } // End Sub KillProcessAndChildren
        // Define an extension method for type System.Process that returns the command
        // line via WMI.
        public static string GetCommandLine(System.Diagnostics.Process process)
        {
            string cmdLine = null;

            using (System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(
                       $"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {process.Id}"))
            {
                // By definition, the query returns at most 1 match, because the process
                // is looked up by ID (which is unique by definition).
                System.Management.ManagementObjectCollection.ManagementObjectEnumerator matchEnum = searcher.Get().GetEnumerator();
                if (matchEnum.MoveNext()) // Move to the 1st item.
                {
                    cmdLine = matchEnum.Current["CommandLine"]?.ToString();
                }
            }

            /*
             * if (cmdLine == null)
             * {
             *  // Not having found a command line implies 1 of 2 exceptions, which the
             *  // WMI query masked:
             *  // An "Access denied" exception due to lack of privileges.
             *  // A "Cannot process request because the process (<pid>) has exited."
             *  // exception due to the process having terminated.
             *  // We provoke the same exception again simply by accessing process.MainModule.
             *  var dummy = process.MainModule; // Provoke exception.
             * }
             */

            return(cmdLine);
        } // End Function GetCommandLine
        /// <summary>
        /// Return a string with details of all graphics adapters on the system. The details are get using Windows WMI with the following query: "SELECT * FROM Win32_VideoController".
        /// </summary>
        /// <returns>string with details of all graphics adapters on the system</returns>
        public static string GetVideoControllerDetailsText(int indent = 0)
        {
            try
            {
                var sb = new StringBuilder();

                // Description of properties http://msdn.microsoft.com/en-us/library/aa394512%28v=vs.85%29.aspx
                // Problems with Win32_VideoController in Win8: http://social.msdn.microsoft.com/Forums/wpapps/en-US/0e7d38f5-21be-4afc-ba8d-ddf7b35f6d04/wmi-query-to-get-driverversion-is-broken-after-kb2795944-update
                using (var searcher = new System.Management.ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController"))
                {
                    sb.AppendFormat("{0}<VideoControllers>\r\n", new String(' ', indent));

                    foreach (System.Management.ManagementObject queryObj in searcher.Get())
                    {
                        sb.AppendFormat("{0}<VideoController ", new String(' ', indent + 4));

                        foreach (var property in queryObj.Properties)
                        {
                            sb.AppendFormat("{0}=\"{1}\" ", property.Name, property.Value);
                        }

                        sb.AppendLine("/>");
                    }
                }

                sb.AppendFormat("{0}</VideoControllers>", new String(' ', indent));

                return(sb.ToString());
            }
            catch (System.Management.ManagementException e)
            {
                return(String.Format("{0}<VideoControllers Error=\"An error occurred while querying for Win32_VideoController WMI data: {1}\" />\r\n", new String(' ', indent), e.Message));
            }
        }
Example #21
0
        //get the actual percentage of brightness
        static int GetBrightness()
        {
            //define scope (namespace)
            System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");

            //define query
            System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");

            //output current brightness
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);

            System.Management.ManagementObjectCollection moc = mos.Get();

            //store result
            byte curBrightness = 0;
            foreach (System.Management.ManagementObject o in moc)
            {
                curBrightness = (byte)o.GetPropertyValue("CurrentBrightness");
                break; //only work on the first object
            }

            moc.Dispose();
            mos.Dispose();

            return (int)curBrightness;
        }
        /// <summary>
        /// Returns the number of cores
        /// </summary>
        /// <returns>The number of cores on this computer</returns>
        /// <remarks>
        /// Should not be affected by hyperthreading, so a computer with two 4-core chips will report 8 cores, even if Hyperthreading is enabled
        /// </remarks>
        public int GetCoreCount()
        {
            try
            {
                if (mCachedCoreCount > 0)
                {
                    return(mCachedCoreCount);
                }

                var result    = new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor");
                var coreCount = 0;

                foreach (var item in result.Get())
                {
                    coreCount += int.Parse(item["NumberOfCores"].ToString());
                }

                Interlocked.Exchange(ref mCachedCoreCount, coreCount);

                return(mCachedCoreCount);
            }
            catch (Exception)
            {
                // This value will be affected by hyperthreading
                return(Environment.ProcessorCount);
            }
        }
Example #23
0
        public void GetWMIDisplayInfo()
        {
            var query = "select * from WmiMonitorID";

            using (var wmi = new System.Management.ManagementObjectSearcher("\\root\\wmi", query))
            {
                var results = wmi.Get();
                foreach (var item in results)
                {
                    Trace.WriteLine(item.GetText(System.Management.TextFormat.Mof));
                    var temp = new WmiDisplayInformation();

                    temp.Active                 = (bool)item["Active"];
                    temp.InstanceName           = (string)item["InstanceName"];
                    temp.ManufacturerName       = ((ushort[])item["ManufacturerName"]).Where(v => v != 0).ToArray();
                    temp.ProductCodeID          = ((ushort[])item["ProductCodeID"]).Where(v => v != 0).ToArray();
                    temp.SerialNumberID         = ((ushort[])item["SerialNumberID"]).Where(v => v != 0).ToArray();
                    temp.UserFriendlyName       = ((ushort[])item["UserFriendlyName"]).Where(v => v != 0).ToArray();
                    temp.UserFriendlyNameLength = (int)(ushort)item["UserFriendlyNameLength"];
                    temp.WeekOfManufacture      = (int)(byte)item["WeekOfManufacture"];
                    temp.YearOfManufacture      = (int)(ushort)item["YearOfManufacture"];

                    Trace.WriteLine(temp.ToString());
                }
            }
        }
Example #24
0
        public static bool IsVM()
        {
            var searcher = new System.Management.ManagementObjectSearcher("select * from Win32_Processor");

            searcher.Query = new System.Management.ObjectQuery("select * from Win32_BaseBoard");
            foreach (System.Management.ManagementObject share in searcher.Get())
            {
                // more info: https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-baseboard
                var manufacturer = share.GetPropertyValue("Manufacturer").ToString().ToLower();
                var product      = share.GetPropertyValue("Product").ToString().ToLower();

                if (manufacturer == null || product == null)
                {
                    return(true);
                }

                if ((manufacturer.Contains("microsoft") && product.Contains("virtual")) || manufacturer.Contains("none") || manufacturer.Contains("virtual") ||
                    manufacturer.Contains("vmware") || product.Contains("440BX Desktop Reference Platform".ToLower()))
                {
                    return(true);
                }

                if (product.Contains("virtual"))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #25
0
        public static int GetBrightness()
        {
            byte curBrightness = 0;

            try
            {
                //output current brightness
                System.Management.ManagementObjectSearcher   mos = new System.Management.ManagementObjectSearcher(s, q);
                System.Management.ManagementObjectCollection moc = mos.Get();

                //store result
                foreach (System.Management.ManagementObject o in moc)
                {
                    curBrightness = (byte)o.GetPropertyValue("CurrentBrightness");
                    break; //only work on the first object
                }

                moc.Dispose();
                mos.Dispose();
            }
            catch (Exception)
            {
            }

            return((int)curBrightness);
        }
Example #26
0
        ///-----------------------------------------------------------------
        /// <summary>
        /// 功    能: WMI取硬件信息
        /// 函数调用: HardwareEnum枚举
        /// </summary>
        /// <param name="hardType"></param>
        /// <param name="propKey"></param>
        ///-----------------------------------------------------------------
        public static string[] MulGetHardwareInfo(HardwareEnum hardType, string propKey)
        {
            List <string> strs = new List <string>();

            try
            {
                using (System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("select * from " + hardType))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {
                        if (hardInfo.Properties[propKey].Value != null)
                        {
                            if (hardInfo.Properties[propKey].Value.ToString().Contains("Prolific USB-to-Serial Comm Port"))
                            {
                                strs.Add(hardInfo.Properties[propKey].Value.ToString());
                            }
                        }
                    }
                    searcher.Dispose();
                }
                return(strs.ToArray());
            }
            catch
            {
                return(null);
            }
            finally
            {
                strs = null;
            }
        }
Example #27
0
        public static bool FindSerialPort(string name, out string port_result)
        {
            port_result = "";

            try
            {
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName");
                foreach (var ptr in searcher.Get())
                {
                    Debug.WriteLine(ptr);
                    Debug.WriteLine("\t" + ptr["InstanceName"] + " : " + ptr["PortName"]);

                    if (ptr["InstanceName"].ToString().Contains(name))
                    {
                        Debug.WriteLine("MATCH : " + ptr["InstanceName"] + " => " + ptr["PortName"]);
                        port_result = ptr["PortName"].ToString();

                        return(true);
                    }
                }

                port_result = "Now found " + name;
                return(false);
            }
            catch (Exception e)
            {
                port_result = e.Message;
                return(false);
            }
        }
Example #28
0
        // Returns brightness of first screen
        public static int GetBrightnes()
        {
            int curBrightness = 0;

            // Define scope (namespace)
            System.Management.ManagementScope scope = new System.Management.ManagementScope("root\\WMI");

            // Define query
            System.Management.SelectQuery query = new System.Management.SelectQuery("WmiMonitorBrightness");

            // Get current brightness
            using (System.Management.ManagementObjectSearcher objectSearcher =
                       new System.Management.ManagementObjectSearcher(scope, query))
                using (System.Management.ManagementObjectCollection objectCollection =
                           objectSearcher.Get())
                {
                    // Store result
                    foreach (System.Management.ManagementObject o in objectCollection)
                    {
                        curBrightness = (byte)o.GetPropertyValue("CurrentBrightness");
                        break; // Return brightness of first object
                    }
                }

            return(curBrightness);
        }
Example #29
0
        internal static byte[] GetDmi()
        {
            var scope = new System.Management.ManagementScope("\\\\" + "." + "\\root\\WMI");

            scope.Connect();
            var wmiquery         = new System.Management.ObjectQuery("SELECT * FROM MSSmBios_RawSMBiosTables");
            var searcher         = new System.Management.ManagementObjectSearcher(scope, wmiquery);
            var coll             = searcher.Get();
            var M_ByMajorVersion = 0;
            var M_ByMinorVersion = 0;

            byte[] data = null;
            foreach (var O in coll)
            {
                var queryObj = (System.Management.ManagementObject)O;
                if (queryObj["SMBiosData"] != null)
                {
                    data = (byte[])(queryObj["SMBiosData"]);
                }
                if (queryObj["SmbiosMajorVersion"] != null)
                {
                    M_ByMajorVersion = (byte)(queryObj["SmbiosMajorVersion"]);
                }
                if (queryObj["SmbiosMinorVersion"] != null)
                {
                    M_ByMinorVersion = (byte)(queryObj["SmbiosMinorVersion"]);
                }
                //if (queryObj["Size"] != null) m_dwLen = (long)(queryObj["Size"]);
                //m_dwLen = m_pbBIOSData.Length;
            }

            Version = (ushort)(M_ByMajorVersion << 8 | M_ByMinorVersion);

            return(data);
        }
Example #30
0
        public void get_host_info_async()
        {
            try
            {
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("select * from " + "Win32_Processor");
                string[] CPU_name_split = null;
                System.Management.ManagementObjectCollection sysinfo = searcher.Get();
                foreach (System.Management.ManagementObject share in sysinfo)
                {
                    try
                    {
                        CPU_name_split = share["Name"].ToString().Split(' ');
                        break;
                    }
                    catch
                    {
                    }
                }

                lock (host_info)
                {
                    host_info.cpu_name = "";
                    for (int i = 0; i < CPU_name_split.Length; i++)
                    {
                        if (CPU_name_split[i] != "")
                        {
                            host_info.cpu_name += CPU_name_split[i] + " ";
                        }
                    }
                }
            }
            catch
            {
            }
        }
Example #31
0
        private string GetHDDSerialNumber()
        {
            string msn = "";

            System.Management.ManagementObjectSearcher searcher;
            string query1 = "SELECT * FROM Win32_DiskDrive";
            string query2 = "SELECT * FROM Win32_PhysicalMedia";

            searcher = new System.Management.ManagementObjectSearcher(query1);
            foreach (System.Management.ManagementObject wmi_HD in searcher.Get())
            {
                if (wmi_HD["Model"] != null)
                {
                    msn = wmi_HD["Model"].ToString();
                }
            }

            searcher = new System.Management.ManagementObjectSearcher(query2);
            foreach (System.Management.ManagementObject wmi_HD in searcher.Get())
            {
                if (wmi_HD["SerialNumber"] != null)
                {
                    msn += wmi_HD["SerialNumber"].ToString();
                }
            }
            return(msn);
        }
        private static void installKvaserDriverIfNeeded()
        {
            Console.WriteLine("Searching for kvaser driver...");
            System.Management.SelectQuery query = new System.Management.SelectQuery("Win32_SystemDriver");

            query.Condition = "Name = 'kcanl'";
            System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
            var drivers = searcher.Get();

            if (drivers.Count > 0)
            {
                Console.WriteLine("kvaser leaf driver found");
                return;
            }
            //var result = MessageBox.Show(".\nWould you like to install kvaser leaf driver now?", "kvaser leaf driver NOT FOUND",MessageBoxButton.YesNo);
            //Console.WriteLine("kvaser leaf driver NOT FOUND");
            //Console.WriteLine("Would you like to install kvaser leaf driver now?(Y/N)");
            //string answer = null;
            //if(result==MessageBoxResult.Yes){
            ProcessStartInfo startInfo = new ProcessStartInfo("kvaser_drivers_setup.exe");

            startInfo.WorkingDirectory = Directory.GetCurrentDirectory() + "\\files";
            Process process = Process.Start(startInfo);

            process.WaitForExit();
            //}
        }
        public string GetServiceInstanceName()
        {
            return((string)_cache.GetOrAdd("service-instance-name", key =>
            {
                // Calling System.ServiceProcess.ServiceBase::ServiceNamea allways returns
                // an empty string,
                // see https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024

                // So we have to do some more work to find out our service name, this only works if
                // the process contains a single service, if there are more than one services hosted
                // in the process you will have to do something else

                int processId = Process.GetCurrentProcess().Id;
                String query = $"SELECT * FROM Win32_Service where ProcessId = {processId}";
                System.Management.ManagementObjectSearcher searcher =
                    new System.Management.ManagementObjectSearcher(query);

                foreach (System.Management.ManagementObject queryObj in searcher.Get())
                {
                    return queryObj["Name"].ToString();
                }

                return String.Empty;
            }));
        }
Example #34
0
        public static byte[] GetBrightnessLevels()
        {
            //define scope (namespace)
            System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");

            //define query
            System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");

            //output current brightness
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
            byte[] BrightnessLevels = new byte[0];

            try
            {
                System.Management.ManagementObjectCollection moc = mos.Get();

                //store result
                foreach (System.Management.ManagementObject o in moc)
                {
                    BrightnessLevels = (byte[])o.GetPropertyValue("Level");
                    break; //only work on the first object
                }

                moc.Dispose();
                mos.Dispose();
            }
            catch
            {
                throw new NotSupportedException("This application is not supported on this system!");
            }

            return(BrightnessLevels);
        }
Example #35
0
        private static List<string> GetAllPrintersInternal(int failCounter)
        {
            try
            {
                List<string> printers = new List<string>();

                string selectAllQuery = "SELECT * FROM Win32_Printer";

                System.Management.ObjectQuery oq = new System.Management.ObjectQuery(selectAllQuery);

                System.Management.ManagementObjectSearcher query1 = new System.Management.ManagementObjectSearcher(oq);
                System.Management.ManagementObjectCollection queryCollection1 = query1.Get();

                foreach (System.Management.ManagementObject mo in queryCollection1)
                {
                    System.Management.PropertyDataCollection pdc = mo.Properties;
                    printers.Add(mo["Name"].ToString());
                }

                return printers;
            }
            catch
            {
                if (failCounter > 3)
                    throw;

                Thread.Sleep(new TimeSpan(0, 0, 5));
                return GetAllPrintersInternal(++failCounter);
            }
        }
Example #36
0
        private static void KillProcessTree(int pId)
        {
            System.Management.ManagementObjectSearcher processSearcher = new System.Management.ManagementObjectSearcher
                                                                             ("Select * From Win32_Process Where ParentProcessID=" + pId);
            System.Management.ManagementObjectCollection processCollection = processSearcher.Get();

            try
            {
                Process proc = Process.GetProcessById(pId);
                if (!proc.HasExited)
                {
                    proc.Kill();
                }
            }
            catch (ArgumentException)
            {
                // Process already exited.
            }

            if (processCollection != null)
            {
                foreach (System.Management.ManagementObject mo in processCollection)
                {
                    KillProcessTree(Convert.ToInt32(mo["ProcessID"])); //kill child processes(also kills childrens of childrens etc.)
                }
            }
        }
Example #37
0
        public static byte GetBrightness()
        {
            //define scope (namespace)
            System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");

            //define query
            System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");

            //output current brightness
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);

            System.Management.ManagementObjectCollection moc = mos.Get();

            //store result
            byte curBrightness = 0;

            foreach (System.Management.ManagementObject o in moc)
            {
                curBrightness = (byte)o.GetPropertyValue("CurrentBrightness");
                break; //only work on the first object
            }

            moc.Dispose();
            mos.Dispose();

            return(curBrightness);
        }
Example #38
0
        //Extract proxy configuration from commandline
        private static string GetCommandLine(this System.Diagnostics.Process process)
        {
            try
            {
                string cmdLine = null;
                using (var searcher = new System.Management.ManagementObjectSearcher(
                           string.Format("SELECT CommandLine FROM Win32_Process WHERE ProcessId = {0}", process.Id)))
                {
                    var matchEnum = searcher.Get().GetEnumerator();
                    if (matchEnum.MoveNext())
                    {
                        cmdLine = matchEnum.Current["CommandLine"]?.ToString();
                    }
                }
                if (cmdLine != null && cmdLine.Contains("proxy"))
                {
                    System.Text.RegularExpressions.Regex pattern =
                        new System.Text.RegularExpressions.Regex(@"proxy-server=[^\s]*");
                    System.Text.RegularExpressions.Match match = pattern.Match(cmdLine);
#if DEBUG
                    Console.WriteLine("\tProxy from cmd: {0}", match.ToString().TrimStart('"').TrimEnd('"'));
#endif
                    return(match.ToString().Replace("proxy-server=", "").TrimStart('"').TrimEnd('"'));
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine("[*] An exception occured: {0}", ex.Message);
#endif
            }

            return("");
        }
Example #39
0
		public override void TakeValue()
		{
			System.Management.ManagementObjectSearcher man =
						new System.Management.ManagementObjectSearcher("SELECT LoadPercentage  FROM Win32_Processor");
			List<double> results = new List<double>();
						foreach (System.Management.ManagementObject obj in man.Get())
			{
				results.Add(Convert.ToDouble(obj["LoadPercentage"]));
			}
			this.Value = results.Average().ToString();
		}
Example #40
0
        /// <summary>
        /// Looks for the resolution 5760 x 1080. If the resolution is available, stereo mode is available.
        /// (Looking for the max resolution didn't work because it returned 5760 x 1200.)
        /// </summary>
        /// <returns></returns>
        public static void PrintResolutions()
        {
            var scope = new System.Management.ManagementScope();
            var q = new System.Management.ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");

            using(var searcher = new System.Management.ManagementObjectSearcher(scope, q)) {
                var results = searcher.Get();

                foreach(var item in results) {
                    Console.WriteLine((UInt32)item["HorizontalResolution"] + " x " + (UInt32)item["VerticalResolution"]);
                }
            }
        }
 public static System.Collections.Generic.List<System.Management.ManagementObject> PerformQuery(string Query)
 {
     System.Collections.Generic.List<System.Management.ManagementObject> list = new List<System.Management.ManagementObject>();
     try {
         System.Management.ManagementObjectSearcher searcher;
         System.Management.ObjectQuery query = new System.Management.ObjectQuery(Query);
         searcher = new System.Management.ManagementObjectSearcher(query);
         foreach (System.Management.ManagementObject obj in searcher.Get()) {
             list.Add(obj);
         }
     } catch (Exception) { }
     return list;
 }
Example #42
0
 /// <summary>
 /// Return the graphics card this computer is using
 /// </summary>
 private static string getGraphicDevice()
 {
     try
     {
         System.Management.ManagementObjectSearcher mSearcher = new System.Management.ManagementObjectSearcher(@"root\CIMV2", "SELECT * FROM Win32_VideoController");
         string sData = null;
         foreach (System.Management.ManagementObject tObj in mSearcher.Get())
         {
             sData = System.Convert.ToString(tObj["Description"]);
         }
         return sData;
     }
     catch (System.Exception) { return "Error"; }
 }
        public static List<Adapter> GetAdapters()
        {
            List<Adapter> adapterList = new List<Adapter>();
            string query = "SELECT * FROM Win32_NetworkAdapterConfiguration";

            System.Management.ManagementObjectSearcher searcher;
            System.Management.ObjectQuery q = new System.Management.ObjectQuery(query);
            searcher = new System.Management.ManagementObjectSearcher(q);
            foreach(System.Management.ManagementObject share in searcher.Get()) {
                Adapter ad = new Adapter();
                ad.PropertyData = share;
                adapterList.Add(ad);
            }
            return adapterList;
        }
Example #44
0
        public static string FullName(string COMName)
        {
            var searcher = new System.Management.ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity");

            foreach (var queryObj in searcher.Get())
            {
                if (queryObj["Caption"].ToString().Contains("(COM"))
                {
                    string name = (string)queryObj["Caption"];
                    if (name.Contains(COMName))
                        return name;
                }
            }

            return "";
        }
Example #45
0
        public static string Detect3264()
        {
            System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions();
            System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn);
            System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select AddressWidth from Win32_Processor");
            System.Management.ManagementObjectSearcher oSearcher = new System.Management.ManagementObjectSearcher(oMs, oQuery);
            System.Management.ManagementObjectCollection oReturnCollection = oSearcher.Get();
            string addressWidth = null;

            foreach (System.Management.ManagementObject oReturn in oReturnCollection)
            {
                addressWidth = oReturn["AddressWidth"].ToString();
            }

            return addressWidth;
        }
Example #46
0
        /// <summary>
        /// Looks for the resolution 5760 x 1080. If the resolution is available, stereo mode is available.
        /// (Looking for the max resolution didn't work because it returned 5760 x 1200.)
        /// </summary>
        /// <returns></returns>
        public static bool IsStereoAvailable()
        {
            bool isStereoModeAvailable = false;
            var scope = new System.Management.ManagementScope();
            var q = new System.Management.ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");

            using(var searcher = new System.Management.ManagementObjectSearcher(scope, q)) {
                var results = searcher.Get();

                foreach(var item in results) {
                    if((UInt32)item["HorizontalResolution"] == 5760 && (UInt32)item["VerticalResolution"] == 1080)
                        isStereoModeAvailable = true;
                }
            }

            return isStereoModeAvailable;
        }
Example #47
0
        public void setBrightness(byte targetBrightness)
        {
            //define scope (namespace)
            System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");
            //define query
            System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightnessMethods");
            //output current brightness
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
            System.Management.ManagementObjectCollection moc = mos.Get();

            foreach (System.Management.ManagementObject o in moc)
            {
                o.InvokeMethod("WmiSetBrightness", new Object[] { Int32.MaxValue, targetBrightness}); //note the reversed order - won't work otherwise!
                break; //only work on the first object
            }

            moc.Dispose();
            mos.Dispose();
        }
Example #48
0
        private void SetPrintForm_Load(object sender, EventArgs e)
        {
            //加载打印机列表
            System.Management.ManagementObjectSearcher query;

            System.Management.ManagementObjectCollection queryCollection;

            string _classname = "SELECT * FROM Win32_Printer";
            query = new System.Management.ManagementObjectSearcher(_classname);

            queryCollection = query.Get();

            foreach (System.Management.ManagementObject search in queryCollection)
            {
                cboPrt1.Items.Add(search["Name"].ToString());
                cboPrt2.Items.Add(search["Name"].ToString());

            }

            cboPrt1.SelectedIndex = 0;
        }
        protected String GetServiceName()
        {
            // Calling System.ServiceProcess.ServiceBase::ServiceNamea allways returns
            // an empty string,
            // see https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024

            // So we have to do some more work to find out our service name, this only works if
            // the process contains a single service, if there are more than one services hosted
            // in the process you will have to do something else

            int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
            String query = "SELECT * FROM Win32_Service where ProcessId = " + processId;
            System.Management.ManagementObjectSearcher searcher =
                new System.Management.ManagementObjectSearcher(query);

            foreach (System.Management.ManagementObject queryObj in searcher.Get())
            {
                return queryObj["DisplayName"].ToString();
            }

            throw new Exception("Can not get the ServiceName");
        }
Example #50
0
        static string getFileName()
        {
            try
            {
                //Using the service name to customize the log4net.config file.
                var processId = System.Diagnostics.Process.GetCurrentProcess().Id;
                var query = "SELECT * FROM Win32_Services where ProcessID = " + processId;
                var searcher = new System.Management.ManagementObjectSearcher(query);
                foreach (var obj in searcher.Get())
                {
                    return (obj["Name"] + ".log4net.config").ToLower();
                }

            }
            catch (Exception)
            {

                //swallow
            }

            return "log4net.config";
        }
Example #51
0
        public static void SetNewDefaultPrinter(string newDefaultPrinterName)
        {
            string selectAllQuery = "SELECT * FROM Win32_Printer";

            System.Management.ObjectQuery oq = new System.Management.ObjectQuery(selectAllQuery);

            System.Management.ManagementObjectSearcher query1 = new System.Management.ManagementObjectSearcher(oq);
            System.Management.ManagementObjectCollection queryCollection1 = query1.Get();
            System.Management.ManagementObject newDefault = null;

            foreach (System.Management.ManagementObject mo in queryCollection1)
            {
                System.Management.PropertyDataCollection pdc = mo.Properties;
                if (mo["Name"].ToString().ToUpper().Trim() == newDefaultPrinterName.ToUpper())
                {
                    newDefault = mo;
                    break;
                }
            }

            if (newDefault != null)
            {
                System.Management.ManagementBaseObject outParams = newDefault.InvokeMethod("SetDefaultPrinter", null, null);
                string returnValue = outParams["returnValue"].ToString();
                if (returnValue != "0")
                    throw new ApplicationException(string.Format("Change Printer '{0}' failed. Return Value: {1}", newDefault.ToString(), returnValue));

                var HWND_BROADCAST = new IntPtr(0xffff);
                uint WM_SETTINGCHANGE = 0x001A;
                UIntPtr innerPinvokeResult;
                var pinvokeResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, UIntPtr.Zero,
                    IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out innerPinvokeResult);
            }
            else
            {
                throw new ApplicationException(string.Format("Change Printer '{0}' failed. Managemengt object not found", newDefaultPrinterName));
            }
        }
Example #52
0
        private List<Process> GetChildProcesses(Process process)
        {
            var results = new List<Process>();

            // Query the management system objects for any process that has the current
            // process listed as it's parentprocessid
            string queryText = string.Format("select processid from win32_process where parentprocessid = {0}", process.Id);
            using (var searcher = new System.Management.ManagementObjectSearcher(queryText))
            {
                foreach (var obj in searcher.Get())
                {
                    object data = obj.Properties["processid"].Value;
                    if (data != null)
                    {
                        // Process may be not alive
                        try
                        {
                            // Retrieve the process
                            var childId = Convert.ToInt32(data);
                            var childProcess = Process.GetProcessById(childId);

                            if (!m_skipProcesses.Contains(childProcess.ProcessName))
                            {
                                results.Add(childProcess);
                            }

                            results.AddRange(GetChildProcesses(childProcess));
                        }
                        catch (Exception ex)
                        {
                            Log(ex.ToString());
                        }
                    }
                }
            }

            return results;
        }
Example #53
0
        public static bool isMachineReachable(string hostName)
        {
            try {
                System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(hostName);
                //System.Net.IPHostEntry host = System.Net.Dns.Resolve(hostName);
                //System.Net.IPHostEntry host = System.Net.Dns.GetHostByName(hostName);
                //System.Net.IPHostEntry host = null;

                if (host.AddressList != null) {
                  foreach (System.Net.IPAddress addr in host.AddressList) {
                    logger.Debug("IsMachineReachable: hostname {0} resolved to {1}", hostName, addr);
                    logger.Debug("IsMachineReachable: using first resolved address");
                  }
                }

                string wqlTemplate = "SELECT StatusCode FROM Win32_PingStatus WHERE Address = '{0}'";

                System.Management.ManagementObjectSearcher query = new System.Management.ManagementObjectSearcher();

                query.Query = new System.Management.ObjectQuery(string.Format(wqlTemplate, host.AddressList[0]));

                query.Scope = new System.Management.ManagementScope("//localhost/root/cimv2");

                System.Management.ManagementObjectCollection pings = query.Get();

                foreach (System.Management.ManagementObject ping in pings) {
                    if (Convert.ToInt32(ping.GetPropertyValue("StatusCode")) == 0)
                        return true;
                }
            }
            catch (Exception e) {
                logger.ErrorException(string.Format("Error in IsMachineReachable({0}){1}", hostName, Environment.NewLine), e);
            }

            logger.Debug("Machine not reachable: hostname {0}", hostName);

            return false;
        }
Example #54
0
        public static ExecutionResult ExecuteActions(List<Action> Actions)
        {
            ExecutionResult SNDBSResult = ExecutionResult.TasksSucceeded;
            if (Actions.Count > 0)
            {
                string SCERoot = Environment.GetEnvironmentVariable("SCE_ROOT_DIR");

				bool bSNDBSExists = false;
				if( SCERoot != null )
				{
					string SNDBSExecutable = Path.Combine(SCERoot, "Common/SN-DBS/bin/dbsbuild.exe");

					// Check that SN-DBS is available
					bSNDBSExists = File.Exists(SNDBSExecutable);
				}

                if( bSNDBSExists == false )
                {
                    return ExecutionResult.Unavailable;
                }

                // Use WMI to figure out physical cores, excluding hyper threading.
                int NumCores = 0;
                if (!Utils.IsRunningOnMono)
                {
                    try
                    {
                        using (var Mos = new System.Management.ManagementObjectSearcher("Select * from Win32_Processor"))
                        {
                            var MosCollection = Mos.Get();
                            foreach (var Item in MosCollection)
                            {
                                NumCores += int.Parse(Item["NumberOfCores"].ToString());
                            }
                        }
                    }
                    catch (Exception Ex)
                    {
                        Log.TraceWarning("Unable to get the number of Cores: {0}", Ex.ToString());
                        Log.TraceWarning("Falling back to processor count.");
                    }
                }
                // On some systems this requires a hot fix to work so we fall back to using the (logical) processor count.
                if (NumCores == 0)
                {
                    NumCores = System.Environment.ProcessorCount;
                }
                // The number of actions to execute in parallel is trying to keep the CPU busy enough in presence of I/O stalls.
                MaxActionsToExecuteInParallel = 0;
                // The CPU has more logical cores than physical ones, aka uses hyper-threading. 
                if (NumCores < System.Environment.ProcessorCount)
                {
                    MaxActionsToExecuteInParallel = (int)(NumCores * BuildConfiguration.ProcessorCountMultiplier);
                }
                // No hyper-threading. Only kicking off a task per CPU to keep machine responsive.
                else
                {
                    MaxActionsToExecuteInParallel = NumCores;
                }
                MaxActionsToExecuteInParallel = Math.Min(MaxActionsToExecuteInParallel, BuildConfiguration.MaxProcessorCount);

                JobNumber = 1;
                Dictionary<Action, ActionThread> ActionThreadDictionary = new Dictionary<Action, ActionThread>();

                while( true )
                {
                    bool bUnexecutedActions = false;
                    foreach (Action Action in Actions)
                    {
                        ActionThread ActionThread = null;
                        bool bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionThread);
                        if (bFoundActionProcess == false)
                        {
                            bUnexecutedActions = true;
                            ExecutionResult CompileResult = ExecuteActions(Actions, ActionThreadDictionary);
                            if (CompileResult != ExecutionResult.TasksSucceeded)
                            {
                                return ExecutionResult.TasksFailed;
                            }
                            break;
                        }
                    }

                    if (bUnexecutedActions == false)
                    {
                        break;
                    }
                }

				Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, LogEventType.Console, "-------- Begin Detailed Action Stats ----------------------------------------------------------");
				Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, LogEventType.Console, "^Action Type^Duration (seconds)^Tool^Task^Using PCH");

                double TotalThreadSeconds = 0;

                // Check whether any of the tasks failed and log action stats if wanted.
                foreach (KeyValuePair<Action, ActionThread> ActionProcess in ActionThreadDictionary)
                {
                    Action Action = ActionProcess.Key;
                    ActionThread ActionThread = ActionProcess.Value;

                    // Check for pending actions, preemptive failure
                    if (ActionThread == null)
                    {
                        SNDBSResult = ExecutionResult.TasksFailed;
                        continue;
                    }
                    // Check for executed action but general failure
                    if (ActionThread.ExitCode != 0)
                    {
                        SNDBSResult = ExecutionResult.TasksFailed;
                    }
                    // Log CPU time, tool and task.
                    double ThreadSeconds = Action.Duration.TotalSeconds;

                    Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats,
						LogEventType.Console,
                        "^{0}^{1:0.00}^{2}^{3}^{4}",
                        Action.ActionType.ToString(),
                        ThreadSeconds,
                        Path.GetFileName(Action.CommandPath),
                        Action.StatusDescription,
                        Action.bIsUsingPCH);

                    // Update statistics
                    switch (Action.ActionType)
                    {
                        case ActionType.BuildProject:
                            UnrealBuildTool.TotalBuildProjectTime += ThreadSeconds;
                            break;

                        case ActionType.Compile:
                            UnrealBuildTool.TotalCompileTime += ThreadSeconds;
                            break;

                        case ActionType.CreateAppBundle:
                            UnrealBuildTool.TotalCreateAppBundleTime += ThreadSeconds;
                            break;

                        case ActionType.GenerateDebugInfo:
                            UnrealBuildTool.TotalGenerateDebugInfoTime += ThreadSeconds;
                            break;

                        case ActionType.Link:
                            UnrealBuildTool.TotalLinkTime += ThreadSeconds;
                            break;

                        default:
                            UnrealBuildTool.TotalOtherActionsTime += ThreadSeconds;
                            break;
                    }

                    // Keep track of total thread seconds spent on tasks.
                    TotalThreadSeconds += ThreadSeconds;
                }

                Log.TraceInformation("-------- End Detailed Actions Stats -----------------------------------------------------------");

                // Log total CPU seconds and numbers of processors involved in tasks.
                Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats || BuildConfiguration.bPrintDebugInfo,
					LogEventType.Console, "Cumulative thread seconds ({0} processors): {1:0.00}", System.Environment.ProcessorCount, TotalThreadSeconds);
            }
            return SNDBSResult;
        }
Example #55
0
    public static void _Main()
    {
      const uint _1Mb = 1048576;
      const uint _1Gb = 1073741824;

      //http://stackoverflow.com/questions/105031/how-do-you-get-total-amount-of-ram-the-computer-has
      var counter_name = "System Code Total Bytes";
      var pc = new System.Diagnostics.PerformanceCounter("Memory", counter_name);
      Console.WriteLine("PerformanceCounter Memory {0}: {1}", counter_name, pc.RawValue);

      var pc_class = new System.Management.ManagementClass("Win32_ComputerSystem");
      System.Management.ManagementObjectCollection moc = pc_class.GetInstances();
      foreach (System.Management.ManagementObject item in moc)
      {
        double n=Convert.ToDouble(item.Properties["TotalPhysicalMemory"].Value);
        Console.WriteLine("\nWin32_ComputerSystem TotalPhysicalMemory: {0:N0} bytes {1:N0}Mb {2:N0}Gb", n,Math.Round(n / _1Mb, 0), Math.Round(n / _1Gb, 0));
      }

      string wmiquery = "SELECT Capacity FROM Win32_PhysicalMemory";
      var searcher = new System.Management.ManagementObjectSearcher(wmiquery);
      decimal capacity = 0L;
      Console.WriteLine($"\n{wmiquery}:");
      foreach (System.Management.ManagementObject wmiobject in searcher.Get())
      {
        decimal n = Convert.ToUInt64(wmiobject.Properties["Capacity"].Value);
        capacity += n;
        Console.WriteLine("{0:N0} bytes {1:N0}Mb {2:N0}Gb", n, Math.Round(n / _1Mb, 0), Math.Round(n / _1Gb, 0));
      }
      Console.WriteLine($"Total capacity: {capacity:N0} bytes {Math.Round(capacity / _1Mb, 0):N0}Mb {Math.Round(capacity / _1Gb, 0)}Gb");

      long memoryKb;
      bool result_code=GetPhysicallyInstalledSystemMemory(out memoryKb);
      double b = memoryKb * 1024D;
      Console.WriteLine($"\n(GetPhysicallyInstalledSystemMemory result code: {result_code}) {b:N0} bytes {Math.Round(b / _1Mb, 0):N0}Mb {Math.Round(b / _1Gb, 0)}Gb");

      //https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx
      var memory_status = new MEMORYSTATUSEX();
      result_code = GlobalMemoryStatusEx(memory_status);
      Console.WriteLine($"\n(GlobalMemoryStatusEx result code: {result_code})");
      foreach (var field in memory_status.GetType().GetFields())
      {
        Console.WriteLine($"{field.Name} = {field.GetValue(memory_status):N0}");
      }

      //https://msdn.microsoft.com/en-us/library/windows/desktop/ms683210(v=vs.85).aspx
      var performance_data = new PERFORMANCE_INFORMATION();
      uint input_size = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(PERFORMANCE_INFORMATION));
      result_code = GetPerformanceInfo(out performance_data, input_size);
      Console.WriteLine($"\n(Global GetPerformanceInfo result code: {result_code})");
      foreach (var field in performance_data.GetType().GetFields())
      {
        object xx = field.GetValue(performance_data);
        ulong v=xx is UIntPtr? ((UIntPtr)xx).ToUInt64():(uint)xx;
        Console.WriteLine($"{field.Name} = {v:N0}");
      }

      var this_process = System.Diagnostics.Process.GetCurrentProcess();
      counter_name = "Working Set Peak";
      var instanceName = "ConsoleApplication1";
      pc = new System.Diagnostics.PerformanceCounter("Process", counter_name, instanceName);
      decimal raw_value = pc.RawValue;
      Console.WriteLine("\nPerformanceCounter Process {0} {1}:\t{2:N0} bytes {3:N0}Mb {4:N0}Gb ({5:N0})", instanceName, counter_name, raw_value, Math.Round(raw_value / _1Mb, 0), Math.Round(raw_value / _1Gb, 0), this_process.PeakWorkingSet64);
      counter_name = "Working Set";
      instanceName = "ConsoleApplication1";
      pc = new System.Diagnostics.PerformanceCounter("Process", counter_name, instanceName);
      raw_value = pc.RawValue;
      Console.WriteLine("PerformanceCounter Process {0} {1}:\t\t{2:N0} bytes {3:N0}Mb {4:N0}Gb ({5:N0})", instanceName, counter_name, raw_value, Math.Round(raw_value / _1Mb, 0), Math.Round(raw_value / _1Gb, 0), this_process.WorkingSet64);
    }
Example #56
0
 /// <summary>
 /// Kill a process as well as all childs by PID.
 /// </summary>
 /// <param name="pid">The PID of the target process.</param>
 private void killProcTree(int pid)
 {
     // get child list first
     var childlist = new System.Management.ManagementObjectSearcher(
         "Select * From Win32_Process Where ParentProcessID=" + pid).Get();
     // suicide. Dump exceptions silently.
     try
     {
         System.Diagnostics.Process.GetProcessById(pid).Kill();
     }
     catch (ArgumentException) { }
     // recursive genocide
     foreach (var m in new System.Management.ManagementObjectSearcher(
         "Select * From Win32_Process Where ParentProcessID=" + pid).Get())
     {
         killProcTree(Convert.ToInt32(m["ProcessID"]));
     }
 }
Example #57
0
 public static void SendUsageStats(ulong steamId)
 {
     string systemName = string.Empty;
     System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem");
     foreach (System.Management.ManagementObject os in searcher.Get())
     {
         systemName = os["Caption"].ToString();
         break;
     }
     var data = new System.Collections.Specialized.NameValueCollection();
     data.Add("steamId", steamId.ToString());
     data.Add("os", systemName);
     SteamWeb.Fetch("http://jzhang.net/mist/stats.php", "POST", data);
 }
Example #58
0
 private bool IsNetworkConnected()
 {
     bool connected = SystemInformation.Network;
     if (connected)
     {
         connected = false;
         System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT NetConnectionStatus FROM Win32_NetworkAdapter");
         foreach (System.Management.ManagementObject networkAdapter in searcher.Get())
         {
             if (networkAdapter["NetConnectionStatus"] != null)
             {
                 if (Convert.ToInt32(networkAdapter["NetConnectionStatus"]).Equals(2))
                 {
                     connected = true;
                     break;
                 }
             }
         }
         searcher.Dispose();
     }
     return connected;
 }
        private void LoadShares(string Username, string Password, string Computer)
        {
            List<Share> shares = new List<Share>();
            System.Text.StringBuilder sb = new StringBuilder();
            string qry = "select * from win32_share";
            System.Management.ManagementObjectSearcher searcher;
            System.Management.ObjectQuery query = new System.Management.ObjectQuery(qry);

            if(Username != "" && Password != "" && Computer != "" && !Computer.StartsWith(@"\\localhost")) {
                System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions();
                oConn.Username = Username;
                oConn.Password = Password;
                if(!Computer.StartsWith(@"\\")) Computer = @"\\" + Computer;
                if(!Computer.ToLower().EndsWith(@"\root\cimv2")) Computer = Computer + @"\root\cimv2";
                System.Management.ManagementScope oMs = new System.Management.ManagementScope(Computer, oConn);

                searcher = new System.Management.ManagementObjectSearcher(oMs, query);
            } else {
                searcher = new System.Management.ManagementObjectSearcher(query);
            }

            foreach(System.Management.ManagementObject share in searcher.Get()) {
                Share s = new Share();
                foreach(System.Management.PropertyData p in share.Properties) {
                    switch(p.Name) {
                        case "AccessMask":
                            if(p.Value != null) s.AccessMask = p.Value.ToString();
                            break;
                        case "MaximumAllowed":
                            if(p.Value != null) s.MaximumAllowed = p.Value.ToString();
                            break;
                        case "InstallDate":
                            if(p.Value != null) s.InstallDate = p.Value.ToString();
                            break;
                        case "Description":
                            if(p.Value != null) s.Description = p.Value.ToString();
                            break;
                        case "Caption":
                            if(p.Value != null) s.Caption = p.Value.ToString();
                            break;
                        case "AllowMaximum":
                            if(p.Value != null) s.AllowMaximum = p.Value.ToString();
                            break;
                        case "Name":
                            if(p.Value != null) s.Name = p.Value.ToString();
                            break;
                        case "Path":
                            if(p.Value != null) s.Path = p.Value.ToString();
                            break;
                        case "Status":
                            if(p.Value != null) s.Status = p.Value.ToString();
                            break;
                        case "Type":
                            if(p.Value != null) s._Type = p.Value.ToString();
                            break;
                        default:
                            break;
                    }
                }
                shares.Add(s);
            }
            this.dataGridView1.DataSource = shares;
        }
Example #60
0
		/**
		 * Executes the specified actions locally.
		 * @return True if all the tasks successfully executed, or false if any of them failed.
		 */
		public static bool ExecuteActions(List<Action> Actions)
		{
			// Time to sleep after each iteration of the loop in order to not busy wait.
			const float LoopSleepTime = 0.1f;

			// Use WMI to figure out physical cores, excluding hyper threading.
			int NumCores = 0;
			if (!Utils.IsRunningOnMono)
			{
				try
				{
					using (var Mos = new System.Management.ManagementObjectSearcher("Select * from Win32_Processor"))
					{
						var MosCollection = Mos.Get();
						foreach (var Item in MosCollection)
						{
							NumCores += int.Parse(Item["NumberOfCores"].ToString());
						}
					}
				}
				catch (Exception Ex)
				{
					Log.TraceWarning("Unable to get the number of Cores: {0}", Ex.ToString());
					Log.TraceWarning("Falling back to processor count.");
				}
			}
			// On some systems this requires a hot fix to work so we fall back to using the (logical) processor count.
			if( NumCores == 0 )
			{
				NumCores = System.Environment.ProcessorCount;
			}
			// The number of actions to execute in parallel is trying to keep the CPU busy enough in presence of I/O stalls.
			int MaxActionsToExecuteInParallel = 0;
			if (NumCores < System.Environment.ProcessorCount && BuildConfiguration.ProcessorCountMultiplier != 1.0)
			{
				// The CPU has more logical cores than physical ones, aka uses hyper-threading. 
				// Use multiplier if provided
				MaxActionsToExecuteInParallel = (int)(NumCores * BuildConfiguration.ProcessorCountMultiplier);
			}
			else if (NumCores < System.Environment.ProcessorCount && NumCores > 4)
			{
				// The CPU has more logical cores than physical ones, aka uses hyper-threading. 
				// Use average of logical and physical if we have "lots of cores"
				MaxActionsToExecuteInParallel = (int)(NumCores + System.Environment.ProcessorCount) / 2;
			}
			// No hyper-threading. Only kicking off a task per CPU to keep machine responsive.
			else
			{
				MaxActionsToExecuteInParallel = NumCores;
			}

            if (Utils.IsRunningOnMono)
            {
				// heuristic: give each action at least 1.5GB of RAM (some clang instances will need more, actually)
				long MinMemoryPerActionMB = 3 * 1024 / 2;
				long PhysicalRAMAvailableMB = (new PerformanceCounter ("Mono Memory", "Total Physical Memory").RawValue) / (1024 * 1024);
				int MaxActionsAffordedByMemory = (int)(Math.Max(1, (PhysicalRAMAvailableMB) / MinMemoryPerActionMB));

				MaxActionsToExecuteInParallel = Math.Min(MaxActionsToExecuteInParallel, MaxActionsAffordedByMemory);
            }

			MaxActionsToExecuteInParallel = Math.Max( 1, Math.Min(MaxActionsToExecuteInParallel, BuildConfiguration.MaxProcessorCount) );

            Log.TraceInformation("Performing {0} actions ({1} in parallel)", Actions.Count, MaxActionsToExecuteInParallel);

			Dictionary<Action, ActionThread> ActionThreadDictionary = new Dictionary<Action, ActionThread>();
            int JobNumber = 1;
			using(ProgressWriter ProgressWriter = new ProgressWriter("Compiling C++ source code...", false))
			{
				int ProgressValue = 0;
				while(true)
				{
					// Count the number of pending and still executing actions.
					int NumUnexecutedActions = 0;
					int NumExecutingActions = 0;
					foreach (Action Action in Actions)
					{
						ActionThread ActionThread = null;
						bool bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionThread);
						if (bFoundActionProcess == false)
						{
							NumUnexecutedActions++;
						}
						else if (ActionThread != null)
						{
							if (ActionThread.bComplete == false)
							{
								NumUnexecutedActions++;
								NumExecutingActions++;
							}
						}
					}

					// Update the current progress
					int NewProgressValue = Actions.Count + 1 - NumUnexecutedActions;
					if (ProgressValue != NewProgressValue)
					{
						ProgressWriter.Write(ProgressValue, Actions.Count + 1);
						ProgressValue = NewProgressValue;
					}

					// If there aren't any pending actions left, we're done executing.
					if (NumUnexecutedActions == 0)
					{
						break;
					}

					// If there are fewer actions executing than the maximum, look for pending actions that don't have any outdated
					// prerequisites.
					foreach (Action Action in Actions)
					{
						ActionThread ActionProcess = null;
						bool bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionProcess);
						if (bFoundActionProcess == false)
						{
							if (NumExecutingActions < Math.Max(1,MaxActionsToExecuteInParallel))
							{
								// Determine whether there are any prerequisites of the action that are outdated.
								bool bHasOutdatedPrerequisites = false;
								bool bHasFailedPrerequisites = false;
								foreach (FileItem PrerequisiteItem in Action.PrerequisiteItems)
								{
									if (PrerequisiteItem.ProducingAction != null && Actions.Contains(PrerequisiteItem.ProducingAction))
									{
										ActionThread PrerequisiteProcess = null;
										bool bFoundPrerequisiteProcess = ActionThreadDictionary.TryGetValue( PrerequisiteItem.ProducingAction, out PrerequisiteProcess );
										if (bFoundPrerequisiteProcess == true)
										{
											if (PrerequisiteProcess == null)
											{
												bHasFailedPrerequisites = true;
											}
											else if (PrerequisiteProcess.bComplete == false)
											{
												bHasOutdatedPrerequisites = true;
											}
											else if (PrerequisiteProcess.ExitCode != 0)
											{
												bHasFailedPrerequisites = true;
											}
										}
										else
										{
											bHasOutdatedPrerequisites = true;
										}
									}
								}

								// If there are any failed prerequisites of this action, don't execute it.
								if (bHasFailedPrerequisites)
								{
									// Add a null entry in the dictionary for this action.
									ActionThreadDictionary.Add( Action, null );
								}
								// If there aren't any outdated prerequisites of this action, execute it.
								else if (!bHasOutdatedPrerequisites)
								{
									ActionThread ActionThread = new ActionThread(Action, JobNumber, Actions.Count);
									JobNumber++;
									ActionThread.Run();

									ActionThreadDictionary.Add(Action, ActionThread);

									NumExecutingActions++;
								}
							}
						}
					}

					System.Threading.Thread.Sleep(TimeSpan.FromSeconds(LoopSleepTime));
				}
			}

			Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, LogEventType.Console, "-------- Begin Detailed Action Stats ----------------------------------------------------------");
			Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, LogEventType.Console, "^Action Type^Duration (seconds)^Tool^Task^Using PCH");

			double TotalThreadSeconds = 0;

			// Check whether any of the tasks failed and log action stats if wanted.
			bool bSuccess = true;
			foreach (KeyValuePair<Action, ActionThread> ActionProcess in ActionThreadDictionary)
			{
				Action Action = ActionProcess.Key;
				ActionThread ActionThread = ActionProcess.Value;

				// Check for pending actions, preemptive failure
				if (ActionThread == null)
				{
                    bSuccess = false;
					continue;
				}
				// Check for executed action but general failure
				if (ActionThread.ExitCode != 0)
				{
					bSuccess = false;
				}
                // Log CPU time, tool and task.
				double ThreadSeconds = Action.Duration.TotalSeconds;

				Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats,
					LogEventType.Console,
					"^{0}^{1:0.00}^{2}^{3}^{4}", 
					Action.ActionType.ToString(),
					ThreadSeconds,
					Path.GetFileName(Action.CommandPath), 
                      Action.StatusDescription,
					Action.bIsUsingPCH);

				// Update statistics
				switch (Action.ActionType)
				{
					case ActionType.BuildProject:
						UnrealBuildTool.TotalBuildProjectTime += ThreadSeconds;
						break;

					case ActionType.Compile:
						UnrealBuildTool.TotalCompileTime += ThreadSeconds;
						break;

					case ActionType.CreateAppBundle:
						UnrealBuildTool.TotalCreateAppBundleTime += ThreadSeconds;
						break;

					case ActionType.GenerateDebugInfo:
						UnrealBuildTool.TotalGenerateDebugInfoTime += ThreadSeconds;
						break;

					case ActionType.Link:
						UnrealBuildTool.TotalLinkTime += ThreadSeconds;
						break;

					default:
						UnrealBuildTool.TotalOtherActionsTime += ThreadSeconds;
						break;
				}

				// Keep track of total thread seconds spent on tasks.
				TotalThreadSeconds += ThreadSeconds;
			}

			Log.TraceInformation("-------- End Detailed Actions Stats -----------------------------------------------------------");

			// Log total CPU seconds and numbers of processors involved in tasks.
			Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats || BuildConfiguration.bPrintDebugInfo,
				LogEventType.Console, "Cumulative thread seconds ({0} processors): {1:0.00}", System.Environment.ProcessorCount, TotalThreadSeconds);

			return bSuccess;
		}