Beispiel #1
1
 public static string ShowUserSID(string username)
 {
     // local scope
     string[] unames = username.Split("\\".ToCharArray(),2);
     string d = "";
     string n = "";
     d = unames[0];
     if (unames.Length < 2)
     {
         n = unames[0];
         d = "US_IBS";
     }
     else
         n = unames[1];
     ConnectionOptions co = new ConnectionOptions();
     //co.Username = username;
     ManagementScope msc = new ManagementScope ("\\root\\cimv2",co);
     string queryString = "SELECT * FROM Win32_UserAccount where LocalAccount = false AND SIDType = 1 AND Domain = '" + d+ "' AND Name = '" + n + "'";
     //System.Windows.Forms.MessageBox.Show(queryString);
     SelectQuery q = new SelectQuery (queryString);
     query = new ManagementObjectSearcher(msc, q);
     queryCollection = query.Get();
     string res=String.Empty;
     foreach( ManagementObject mo in queryCollection )
     {
         // there should be only one here!
         res+= mo["SID"].ToString();
         //res+= mo["Name"]+"\n";
     }
     return res;
 }
Beispiel #2
1
        public ViewModel()
        {
            mgt = new ManagementClass("Win32_Processor");
            procs = mgt.GetInstances();

            CPU = new ObservableCollection<Model>();
            timer = new DispatcherTimer();
            random = new Random();
            time = DateTime.Now;
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            ProcessorID = GetProcessorID();
            processes = Process.GetProcesses();
            Processes = processes.Length;
            MaximumSpeed = GetMaxClockSpeed();
            LogicalProcessors = GetNumberOfLogicalProcessors();
            Cores = GetNumberOfCores();
            L2Cache = GetL2CacheSize();
            L3Cache = GetL3CacheSize();
            foreach (ManagementObject item in procs)
                L1Cache = ((UInt32)item.Properties["L2CacheSize"].Value / 2).ToString() + " KB";

            timer.Interval = TimeSpan.FromMilliseconds(1000);
            timer.Tick += timer_Tick;
            timer.Start();
            for (int i = 0; i < 60; i++)
            {
                CPU.Add(new Model(time, 0,0));
                time = time.AddSeconds(1);
            }
        }
Beispiel #3
0
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";

            System.Management.ManagementClass            mc  = new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine("293 " + ex.Message);
                        //Console.ReadKey();
                    }
                }
            }
            return(result);
        }
Beispiel #4
0
        public void InformacaoRede()
        {
            System.Management.ManagementClass            mc  = new ManagementClass("Win32_NetworkAdapterConfiguration");
            System.Management.ManagementObjectCollection moc = mc.GetInstances();

            foreach (System.Management.ManagementBaseObject mo in moc)
            {
                string tt = mo["IPenabled"].ToString();

                if (mo["IPenabled"].ToString() == "True")
                {
                    try
                    {
                        MACRede = mo["MacAddress"].ToString().Trim();
                        return;
                    }
                    catch
                    {
                        MACRede = "";
                    }
                }
                else
                {
                    MACRede = "";
                }
            }
        }
        //public static (int major, int minor, int build) tpGetOSVersion()
        public static void tpGetOSVersion(out int major, out int minor, out int build)
        {
            //var result = (major: 0, minor: 0, build: 0);
            major = 0;
            minor = 0;
            build = 0;

            System.Management.ManagementClass mc =
                new System.Management.ManagementClass("Win32_OperatingSystem");
            System.Management.ManagementObjectCollection moc = mc.GetInstances();

            foreach (System.Management.ManagementObject mo in moc)
            {
                string   ver        = mo["Version"].ToString();
                string[] majorminor = ver.Split(new char[] { '.' }, StringSplitOptions.None);

                major = Convert.ToInt32(majorminor[0]);
                minor = Convert.ToInt32(majorminor[1]);
                build = Convert.ToInt32(mo["BuildNumber"]);

                break;                  // 1回ループで終了(でいいよね)
            }
            moc.Dispose();
            mc.Dispose();

            //return result;
        }
Beispiel #6
0
            //Return a hardware identifier
            private static string identifier(string wmiClass, string wmiProperty)
            {
                string result = "";

                System.Management.ManagementClass mc =
                    new System.Management.ManagementClass(wmiClass);
                System.Management.ManagementObjectCollection moc = mc.GetInstances();
                foreach (System.Management.ManagementObject mo in moc)
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            if (mo[wmiProperty] != null)
                            {
                                result = mo[wmiProperty].ToString();
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                return(result);
            }
Beispiel #7
0
 public VideoController(ManagementObjectCollection queryResult)
 {
     foreach (var obj in queryResult) {
         foreach (var data in obj.Properties) {
             switch (data.Name) {
                 case "AdapterCompatibility":
                     this.AdapterCompatibility = data.Value.ToString();
                     break;
                 case "AdapterRam":
                     this.AdapterRam = data.Value.ToString();
                     break;
                 case "Name":
                     this.Name = data.Value.ToString();
                     break;
                 case "VideoModeDescription":
                     this.VideoModeDescription = data.Value.ToString();
                     break;
                 case "VideoProcessor":
                     try {
                         this.VideoProcessor = data.Value.ToString();
                     } catch (NullReferenceException) {
                         this.VideoProcessor = String.Empty;
                     }
                     break;
                 case "VideoMemoryType":
                     this.VideoMemoryType = data.Value.ToString();
                     break;
             }
         }
     }
 }
Beispiel #8
0
 public Baseboard(ManagementObjectCollection queryResult)
 {
     foreach (var obj in queryResult) {
         foreach (var data in obj.Properties) {
             switch (data.Name) {
                 case "Manufacturer":
                     this.Manufacturer = data.Value.ToString();
                     break;
                 case "Model":
                     try {
                         this.Model = data.Value.ToString();
                     } catch (NullReferenceException) {
                         this.Model = String.Empty;
                     }
                     break;
                 case "Product":
                     this.Product = data.Value.ToString();
                     break;
                 case "SerialNumber":
                     this.SerialNumber = data.Value.ToString();
                     break;
             }
         }
     }
 }
        /// <summary>
        /// Deletes the share.
        /// </summary>
        /// <param name="FolderName">Name of the folder.</param>
        public static void DeleteShare(string FolderName)
        {
            var RootPath      = HostingEnvironment.ApplicationPhysicalPath;
            var StoreLocation = System.IO.Path.Combine(RootPath, FolderName);

            using (System.Management.ManagementClass shareObj = new System.Management.ManagementClass("Win32_Share"))
            {
                System.Management.ManagementObjectCollection shares =
                    shareObj.GetInstances();
                foreach (System.Management.ManagementObject share in shares)
                {
                    Console.WriteLine("Name: " + share["Name"].ToString());
                }
            }

            ManagementScope ms = new ManagementScope(@"\\localhost\root\cimv2");

            ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Share where Name ='" + FolderName + "'");

            ManagementObjectCollection result = searcher.Get();

            foreach (ManagementObject item in result)
            {
                item.InvokeMethod("Delete", null);
            }
        }
        public IpSetForm(MainForm main)
        {
            InitializeComponent();
            ShowInTaskbar = false;// 不能放到OnLoad里,会导致窗体消失

            query = new ManagementObjectSearcher("Select * from Win32_NetWorkAdapterConfiguration where IPEnabled= 'TRUE'");
            moc = query.Get();

            //mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            //moc = mc.GetInstances();
            foreach (ManagementObject network in moc)
            {
                //if (!(bool)network["IPEnabled"])
                //    continue;
                lstNetworks.Items.Add(Convert.ToString(network["Caption"]));
            }
            if (lstNetworks.Items.Count == 0)
            {
                MessageBox.Show("没有找到网卡");
                Close();
            }
            lstNetworks.SelectedIndex = 0;

            this.main = main;
        }
Beispiel #11
0
 public static string GetProcessID()
 {
     try
     {
         StringBuilder sb = new StringBuilder();
         using (System.Management.ManagementClass managementClass = new System.Management.ManagementClass("Win32_Processor"))
         {
             using (System.Management.ManagementObjectCollection managementObject = managementClass.GetInstances())
             {
                 foreach (System.Management.ManagementObject currentResult in managementObject)
                 {
                     sb.Append(currentResult["ProcessorID"].ToString());
                 }
             }
         }
         string ip        = GetIPAddress();
         string processID = sb.ToString() + ip;
         if (processID.Length > 255)
         {
             return(processID.Substring(0, 255));
         }
         else
         {
             return(processID);
         }
     }
     catch (Exception ex)
     {
         _logger.Error("GetProcessID error:" + ex.ToString());
         return("");
     }
 }
        private string identifier(string wmiClass, string wmiProperty)
        //Return a hardware identifier
        {
            string result = "";

            System.Management.ManagementClass            mc  = new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "" && mo[wmiProperty] != null)
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            return(result);
        }
Beispiel #13
0
        /// <summary>
        /// 获取 IP 地址信息
        /// </summary>
        /// <returns></returns>
        public static List <IpInfo> GetIpInfo()
        {
            //定义范型
            List <IpInfo> ipinfos = new List <IpInfo>();

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                try
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        string       mac = mo["MacAddress"].ToString().Replace(':', '-');
                        System.Array ar  = (System.Array)(mo.Properties["IpAddress"].Value);
                        string       ip  = ar.GetValue(0).ToString();
                        ipinfos.Add(new IpInfo(ip, mac));
                    }
                }
                catch { }
            }

            return(ipinfos);
        }
 /// <summary>
 /// Get DCM Baselines (Class SMS_DesiredConfiguration)
 /// </summary>
 /// <param name="refresh">true=reload;false=get cached objects</param>
 /// <returns>Class SMS_DesiredConfiguration</returns>
 public ManagementObjectCollection CCM_DCMBaselines(bool refresh)
 {
     if (refresh)
     {
         oDCMBaselines = null;
     }
     return CCM_DCMBaselines();
 }
Beispiel #15
0
        public static List <Printer> GetAllPrinters()
        {
            List <Printer> printers = new List <Printer>();

            System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer");
            System.Management.ManagementObjectSearcher   mosearcher = new System.Management.ManagementObjectSearcher(oquery);
            System.Management.ManagementObjectCollection moc        = mosearcher.Get();

            if (moc != null && moc.Count > 0)
            {
                //For each printer found, we put it either in the local or network combobox, accordingly.
                foreach (ManagementObject mo in moc)
                {
                    /*bool isLocal = true;
                     * string[] ipAddress = mo["PortName"].ToString().Split('.');
                     *
                     * //network printer
                     * if (mo["PortName"] != null && ipAddress.Length == 4)
                     *  isLocal = false;*/

                    //get availability status
                    printers.Add(new Printer
                    {
                        Prn_name = mo["Name"].ToString(),
                        Pc_name  = mo["SystemName"].ToString(),
                        Status   = mo.Properties["Availability"].Value == null ? "Не подключен" : mo.Properties["Availability"].Value.ToString(),
                        Islocal  = Convert.ToBoolean(mo.Properties["Local"].Value)
                    });

                    #region SetDefaultPrinter
                    //If the printer is found to be the default one, we select it.

                    /* if ((bool)mo["Default"])
                     * {
                     *   if (network)
                     *   {
                     *       cboNetworkPrinters.SelectedItem = mo["Name"].ToString();
                     *       defaultNetwork = true;
                     *   }
                     *   else
                     *   {
                     *       cboLocalPrinters.SelectedItem = mo["Name"].ToString();
                     *       defaultNetwork = false;
                     *   }
                     *
                     *   lblNameValue.Text = mo["Name"].ToString();
                     *   lblPortValue.Text = mo["PortName"].ToString();
                     *   lblDriverValue.Text = mo["DriverName"].ToString();
                     *   lblDeviceIDValue.Text = mo["DeviceID"].ToString();
                     *   lblSharedValue.Text = mo["Shared"].ToString();
                     * }             */
                    #endregion
                }
            }

            return(printers);
        }
Beispiel #16
0
        public WmiResult PopulateClassesList(ManagementObjectCollection pManagementClasses)
        {
            Classes = new List<string>();
            CollectedClasses = pManagementClasses;

            foreach (ManagementObject WmiClass in pManagementClasses)
            {
                Classes.Add(WmiClass["__Class"].ToString());
            }
            return this;
        }
Beispiel #17
0
        public MainWindow() {
            InitializeComponent();

            Bitmap bmp = IpManager.Properties.Resources.icon;
            this.Icon = Icon.FromHandle(bmp.GetHicon());

            loadConfigAndPopulateList();
            if (listBox1.Items.Count > 0)
                listBox1.SelectedIndex = 0;

            adapters = ctrl.getAdapters();
        }
Beispiel #18
0
 public MotherboardDevice(ManagementObjectCollection queryResult)
 {
     foreach (var obj in queryResult) {
         foreach (var data in obj.Properties) {
             switch (data.Name) {
                 case "Manufacturer":
                     this.Manufacturer = data.Value.ToString();
                     break;
             }
         }
     }
 }
Beispiel #19
0
        public Wmi(string d, string f)
        {
            mMScope = new ManagementScope("\\\\.\\root\\cimv2");
            ObjectQuery aObjectQuery = new ObjectQuery("SELECT * FROM " + d +" "+f);
            mObjSea = new ManagementObjectSearcher(mMScope, aObjectQuery);
            mCollection = mObjSea.Get();

            foreach (ManagementObject obj in mCollection)
            {
                Mo = obj;
                break;

            }
        }
Beispiel #20
0
        /// <summary>
        /// Gets the first object in a collection of ManagementObject instances.
        /// </summary>
        /// <param name="collection">The collection of ManagementObject instances.</param>
        /// <returns>The first object in the collection</returns>
        public static ManagementObject GetFirstObjectFromCollection(ManagementObjectCollection collection)
        {
            if (collection.Count == 0)
            {
                throw new ArgumentException("The collection contains no objects", "collection");
            }

            foreach (ManagementObject managementObject in collection)
            {
                return managementObject;
            }

            return null;
        }
 public List<LogFilterRow> GetEventRecordList(ManagementObjectCollection mossos, List<string> searchTermList)
 {
     var eventRecordList = new List<LogFilterRow>();
     int sTCount = searchTermList.Count;
     foreach (var serv in ListOfServersToQuery)
     {
         var insertionStrings = String.Empty;
         foreach (var mo in mossos)
         {
             var eventRec = new LogFilterRow();
             string timeWrittenStr = (mo["TimeWritten"] != null) ? mo["TimeWritten"].ToString() : String.Empty;
             eventRec.Time = ManagementDateTimeConverter.ToDateTime(timeWrittenStr);
             // DateTime.ParseExact(timeWrittenStr, "yyyyMMddHHmmss.ffffff-zzz", provider);
             eventRec.LogType = Global_Const.EVENTLOGTYPE;
             eventRec.Src = serv + "\\EventLog\\" + Global_Const.SOURCE;
             string sourceName = (mo["SourceName"] != null) ? mo["SourceName"].ToString() : String.Empty;
             string message = (mo["Message"] != null) ? mo["Message"].ToString() : String.Empty;
             if (mo["InsertionStrings"] != null)
             {
                 var strList = (String[]) mo["InsertionStrings"];
                 insertionStrings = strList.Aggregate(insertionStrings,
                     (current, insString) => current + (" " + insString));
             }
             else
             {
                 insertionStrings = String.Empty;
             }
             // var eventRec = new EventRecord((ManagementObject)mo);
             //Filter out all data that contains records that we are interested in.
             for (int index = 0; index < sTCount; index++)
             {
                 var searchTerm = searchTermList[index];
                 if (sourceName.Contains(searchTerm) || message.Contains(searchTerm) ||
                     insertionStrings.Contains(searchTerm))
                 {
                    // eventRec.SearchT = "Word_" + index.ToString(CultureInfo.InvariantCulture);
                     eventRec.Msg = message + " -- " + insertionStrings;
                     eventRecordList.Add(eventRec);
                     insertionStrings = String.Empty;
                     message = String.Empty;
                     break;
                 }
                 insertionStrings = String.Empty;
                 message = String.Empty;
             }
         }
     }
     return eventRecordList;
 }
        /// <summary>
        /// Get DCM Baselines (Class SMS_DesiredConfiguration)
        /// </summary>
        /// <returns>Class SMS_DesiredConfiguration</returns>
        public ManagementObjectCollection CCM_DCMBaselines()
        {
            if (oDCMBaselines == null)
            {
                WMI.Provider oProv = new WMI.Provider(oWMIProvider.mScope.Clone());
                oProv.mScope.Path.NamespacePath = @"root\ccm\dcm";
                ManagementObjectCollection MOC = oProv.ExecuteQuery("SELECT * FROM SMS_DesiredConfiguration");
                oDCMBaselines = MOC;
                return MOC;
            }
            else
            {
                return oDCMBaselines;
            }

        }
Beispiel #23
0
        /// <summary>
        /// 获取分区信息
        /// </summary>
        public List <DiskInfo> GetLogicalDrives()
        {
            List <DiskInfo> drives    = new List <DiskInfo>();
            ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");

            System.Management.ManagementObjectCollection disks = diskClass.GetInstances();
            foreach (ManagementObject disk in disks)
            {
                // DriveType.Fixed 为固定磁盘(硬盘)
                if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed)
                {
                    drives.Add(new DiskInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString())));
                }
            }
            return(drives);
        }
        private static string GetID(string wmiClass, string[] wmiProperties)
        {
            string result = "";


            if (searcher2 == null)
            {
                System.Management.EnumerationOptions k = new System.Management.EnumerationOptions();
                k.DirectRead        = true;
                k.EnumerateDeep     = false;
                k.EnsureLocatable   = false;
                k.Rewindable        = false;
                k.ReturnImmediately = false;
                searcher2           = new System.Management.ManagementObjectSearcher();
                searcher2.Options   = k;
            }
            searcher2.Query.QueryString = "select * from " + wmiClass;
            try
            {
                moc = searcher2.Get();
            }
            catch
            {
                return("");
            }
            foreach (System.Management.ManagementObject mo in moc)
            {
                bool found = false;

                foreach (string wmiProperty in wmiProperties)
                {
                    if (mo[wmiProperty] != null)
                    {
                        found   = true;
                        result += mo[wmiProperty].ToString();
                    }
                }
                if (found)
                {
                    // All properties exist in the same ManagementObject
                    break;
                }
            }
            return(result);
        }
Beispiel #25
0
 public BIOS(ManagementObjectCollection queryResult)
 {
     foreach (var obj in queryResult) {
         foreach (var data in obj.Properties) {
             switch (data.Name) {
                 case "Manufacturer":
                     this.Manufacturer = data.Value.ToString();
                     break;
                 case "SerialNumber":
                     this.SerialNumber = data.Value.ToString();
                     break;
                 case "SMBIOSBIOSVersion":
                     this.SMBIOSBIOSVersion = data.Value.ToString();
                     break;
             }
         }
     }
 }
Beispiel #26
0
 public DiskDrive(ManagementObjectCollection queryResult)
 {
     foreach (var obj in queryResult) {
         foreach (var data in obj.Properties) {
             switch (data.Name) {
                 case "Model":
                     this.Model = data.Value.ToString();
                     break;
                 case "Size":
                     this.Size = data.Value.ToString();
                     break;
                 case "Manufacturer":
                     this.Manufacturer = data.Value.ToString();
                     break;
             }
         }
     }
 }
Beispiel #27
0
 public Processor(ManagementObjectCollection queryResult)
 {
     foreach (var obj in queryResult) {
         foreach (var data in obj.Properties) {
             switch (data.Name) {
                 case "Manufacturer":
                     this.Manufacturer = data.Value.ToString();
                     break;
                 case "Name":
                     this.Name = data.Value.ToString();
                     break;
                 case "Description":
                     this.Description = data.Value.ToString();
                     break;
                 case "MaxClockSpeed":
                     this.MaxClockSpeed = data.Value.ToString();
                     break;
                 case "L2CacheSize":
                     this.L2CacheSize = data.Value.ToString();
                     break;
                 case "AddressWidth":
                     this.AddressWidth = data.Value.ToString();
                     break;
                 case "DataWidth":
                     this.DataWidth = data.Value.ToString();
                     break;
                 case "NumberOfCores":
                     this.NumberOfCores = data.Value.ToString();
                     break;
                 case "NumberOfLogicalProcessors":
                     this.NumberOfLogicalProcessors = data.Value.ToString();
                     break;
                 case "ProcessorId":
                     this.ProcessorId = data.Value.ToString();
                     break;
             }
         }
     }
 }
Beispiel #28
0
 public PhysicalMemory(ManagementObjectCollection queryResult)
 {
     foreach (var obj in queryResult) {
         foreach (var data in obj.Properties) {
             switch (data.Name) {
                 case "Capacity":
                     this.Capacity = data.Value.ToString();
                     break;
                 case "DataWidth":
                     this.DataWidth = data.Value.ToString();
                     break;
                 case "FormFactory":
                     this.FormFactory = data.Value.ToString();
                     break;
                 case "MemoryType":
                     this.MemoryType = data.Value.ToString();
                     break;
                 case "Speed":
                     this.Speed = data.Value.ToString();
                     break;
             }
         }
     }
 }
 public PerfFormattedData_Counters_ProcessorInformationCollection(ManagementObjectCollection objCollection)
 {
     privColObj = objCollection;
 }
Beispiel #30
0
 private static void Main()
 {
     mclass = new ManagementClass("WmiMonitorBrightnessMethods") {Scope = new ManagementScope(@"\\.\root\wmi")};
     instances = mclass.GetInstances();
     Loading.OnLoadingComplete += Loading_OnLoadingComplete;
 }
 public BcdObjectEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum)
 {
     privObjEnum = objEnum;
 }
 public BcdObjectCollection(ManagementObjectCollection objCollection)
 {
     privColObj = objCollection;
 }
 public MessageInstanceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum)
 {
     privObjEnum = objEnum;
 }
 public MessageInstanceCollection(ManagementObjectCollection objCollection)
 {
     privColObj = objCollection;
 }
        private void ReportVMMetrics(ManagementObjectCollection vms)
        {
            // Create Management Service
            ManagementObject vsms = hyperv.GetVSMS(this.name);

            // Create Host metrics
            UInt16 numberOfProcs = 0;
            UInt16 processorLoad = 0;
            UInt64 memoryUsage = 0;
            UInt64 hostCapacityBytes = hyperv.GetHostMemoryCapacityBytes(this.name);

            foreach (ManagementObject vm in vms)
            {
                // Name of VM
                string name = vm["ElementName"].ToString();

                // Create Settings
                ManagementObject vmSettings = hyperv.GetVirtualSystemSettingData(this.name, vm["__PATH"].ToString());
                
                // Get VM Settings
                ManagementBaseObject inParams = vsms.GetMethodParameters("GetSummaryInformation");
                inParams["SettingData"] = new string[1] { vmSettings["__PATH"].ToString() };

                // Request CPU Information
                inParams["RequestedInformation"] = new int[4] { 4, 100, 101, 103 };

                ManagementBaseObject outParams = vsms.InvokeMethod("GetSummaryInformation", inParams, null);
                ManagementBaseObject[] value = (ManagementBaseObject[])outParams.GetPropertyValue("SummaryInformation");

                UInt16 state = (UInt16)value[0].GetPropertyValue("EnabledState");
                numberOfProcs += (UInt16)value[0].GetPropertyValue("NumberOfProcessors");
                ReportMetric($"vms/{name}/numberofprocessors", "procs", (UInt16)value[0].GetPropertyValue("NumberOfProcessors"));

                if (state == 2)
                {
                    processorLoad += (UInt16)value[0].GetPropertyValue("ProcessorLoad");
                    ReportMetric($"vms/{name}/processorload", "percent", (UInt16)value[0].GetPropertyValue("ProcessorLoad"));
                    memoryUsage += (UInt64)value[0].GetPropertyValue("MemoryUsage");
                    ReportMetric($"vms/{name}/memoryused", "mibibytes", (UInt64)value[0].GetPropertyValue("MemoryUsage"));
                }

                // Cleanup
                inParams.Dispose();
                outParams.Dispose();
                vmSettings.Dispose();
            }
            vsms.Dispose();

            // Report Host Metrics
            ReportMetric($"host/numberofprocessors", "procs", numberOfProcs);
            ReportMetric($"host/processorload", "percent", processorLoad);
            ReportMetric($"host/vms/memoryused", "mibibytes", memoryUsage);
            ReportMetric($"host/vms/memoryused", "percent", (float)(((Decimal)(memoryUsage * 1048576) / (Decimal)hostCapacityBytes) * 100));
        }
        private void ReportReplicationHealth(ManagementObjectCollection vms)
        {
            // Create Host metrics
            int hostReplicationHealth = 0;

            foreach (ManagementObject vm in vms)
            {
                // Name of VM
                string name = vm["ElementName"].ToString();

                // Get Replication Mode
                hyperv.NewRelicMetric ReplicationMode;
                ReplicationMode = hyperv.GetReplicationMode(vm);

                // Get Replication Health Status
                hyperv.NewRelicMetric ReplicationHealth;
                ReplicationHealth = hyperv.GetReplicationHealth(vm);
                hostReplicationHealth += (int)ReplicationHealth.Metric;

                if (ReplicationMode.Metric == 1)
                {
                    // Primary Replication Node
                    log.Info($"Primary Node {name} - Health: {ReplicationHealth.Description}");
                    ReportMetric($"replication/primary/{name}/health", "errors", ReplicationHealth.Metric);
                }
                else if (ReplicationMode.Metric != 0)
                {
                    // Secondary Replication Node
                    log.Info($"Secondary Node {name} - Health: {ReplicationHealth.Description}");
                    ReportMetric($"replication/secondary/{name}/health", "errors", ReplicationHealth.Metric);
                }
            }

            // Report Host Metrics
            ReportMetric($"host/vms/replicationhealth", "errors", hostReplicationHealth);
        }
        private void ReportVMHealth(ManagementObjectCollection vms)
        {
            // Create Host metrics
            int vmErrors = 0;

            foreach (ManagementObject vm in vms)
            {
                // Name of VM
                string name = vm["ElementName"].ToString();

                // Health of VM
                hyperv.NewRelicMetric HealthMetric;
                HealthMetric = hyperv.GetHealthState(vm);
                vmErrors += (int)HealthMetric.Metric;
                ReportMetric($"vms/{name}/health", "errors", HealthMetric.Metric);
            }

            // Report Host Metrics
            ReportMetric($"host/vms/health", "errors", vmErrors);
        }
        private void ReportVMUptime(ManagementObjectCollection vms)
        {
            foreach (ManagementObject vm in vms)
            {
                // Name of VM
                string name = vm["ElementName"].ToString();

                // Uptime of VM
                UInt64 UpTimeDays = UInt64.Parse(vm["OnTimeInMilliseconds"].ToString()) / (1000 * 60 * 60 * 24);
                UInt64 UpTimeHours = UInt64.Parse(vm["OnTimeInMilliseconds"].ToString()) / (1000 * 60 * 60);
                UInt64 UpTimeMinutes = UInt64.Parse(vm["OnTimeInMilliseconds"].ToString()) / (1000 * 60);

                ReportMetric($"vms/{name}/UpTimeInDays", "Days", UpTimeDays);
                ReportMetric($"vms/{name}/UpTimeInHours", "Hours", UpTimeHours);
                ReportMetric($"vms/{name}/UpTimeInMinutes", "Minutes", UpTimeMinutes);
            }
        }
 public NTLogEventCollection(ManagementObjectCollection objCollection)
 {
     privColObj = objCollection;
 }
 public PerfFormattedData_Counters_ProcessorInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum)
 {
     privObjEnum = objEnum;
 }
 public ComputerSystemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum)
 {
     privObjEnum = objEnum;
 }