private void OnGetServerUsageAsyncCompleted(ServerLoadData data)
        {
            if (data == null)
            {
                return;
            }

            DataGridViewRow theRow = FindRow(data.ServerName);

            if (theRow == null)
            {
                return;
            }

            int overThresholdCount = 0;

            double cpuThreshold  = Convert.ToDouble(theRow.Cells["ColCPUThreshold"].Value);
            double ramThreshold  = Convert.ToDouble(theRow.Cells["ColRAMThreshold"].Value);
            double diskThreshold = Convert.ToDouble(theRow.Cells["ColDiskThreshold"].Value);

            overThresholdCount += data.CPUUsage > cpuThreshold ? 1 : 0;
            theRow.Cells["ColCPUUsage"].Value           = string.Format("{0}%", data.CPUUsage);
            theRow.Cells["ColCPUUsage"].Style.BackColor = data.CPUUsage > cpuThreshold ? Color.Red : Color.White;
            theRow.Cells["ColCPUUsage"].Style.ForeColor = data.CPUUsage > cpuThreshold ? Color.White : Color.Black;

            overThresholdCount += data.RAMUsage > ramThreshold ? 1 : 0;
            theRow.Cells["ColRAMUsage"].Value           = string.Format("{0}%", data.RAMUsage);
            theRow.Cells["ColRAMUsage"].Style.BackColor = data.RAMUsage > ramThreshold ? Color.Red : Color.White;
            theRow.Cells["ColRAMUsage"].Style.ForeColor = data.RAMUsage > ramThreshold ? Color.White : Color.Black;

            string diskUsageNormal  = string.Empty;
            string diskUsageWarning = string.Empty;

            foreach (string key in data.DiskUsage.Keys)
            {
                if (data.DiskUsage[key] > diskThreshold)
                {
                    overThresholdCount++;
                    diskUsageWarning += string.Format("{0} {1:0}%{2}", key, data.DiskUsage[key], "  ");
                }
                else
                {
                    diskUsageNormal += string.Format("{0} {1:0}%{2}", key, data.DiskUsage[key], "   ");
                }
            }
            theRow.Cells["ColDiskUsageNormal"].Value            = diskUsageNormal;
            theRow.Cells["ColDiskUsageWarning"].Value           = diskUsageWarning;
            theRow.Cells["ColDiskUsageWarning"].Style.BackColor = !string.IsNullOrEmpty(diskUsageWarning) ? Color.Red : Color.White;
            theRow.Cells["ColDiskUsageWarning"].Style.ForeColor = !string.IsNullOrEmpty(diskUsageWarning) ? Color.White : Color.Black;

            theRow.Cells["ColState"].Value = this.imageList1.Images[overThresholdCount == 0 ? 0 : 1];
            if (iMonitorServer == cntMonitorServer)
            {
                btnRefresh.Enabled = true;
                iMonitorServer     = 0;
            }
        }
        private void OnGetServerUsageAsyncCompletedForMail(ServerLoadData data)
        {
            if (data == null)
            {
                return;
            }

            DataGridViewRow theRow = FindRow(data.ServerName);

            if (theRow == null)
            {
                return;
            }

            double cpuThreshold  = Convert.ToDouble(theRow.Cells["ColCPUThreshold"].Value);
            double ramThreshold  = Convert.ToDouble(theRow.Cells["ColRAMThreshold"].Value);
            double diskThreshold = Convert.ToDouble(theRow.Cells["ColDiskThreshold"].Value);

            string diskUsageWarning = string.Empty;

            foreach (string key in data.DiskUsage.Keys)
            {
                if (data.DiskUsage[key] > diskThreshold)
                {
                    diskUsageWarning += string.Format("{0} {1:0}% ", key, data.DiskUsage[key]);
                }
            }

            string CPUUsage = data.CPUUsage > cpuThreshold?string.Format("CPU使用率: {0}%", data.CPUUsage) : string.Empty;

            string RAMUsage = data.RAMUsage > ramThreshold?string.Format("内存使用率: {0}%", data.RAMUsage) : string.Empty;

            string DiskUsageWarning = diskUsageWarning == string.Empty ? string.Empty : string.Format("磁盘使用率: {0}", diskUsageWarning);

            if (CPUUsage != string.Empty || RAMUsage != string.Empty || DiskUsageWarning != string.Empty)
            {
                emailBody += string.Format("<B>{0}: <FONT Color=\"Red\">{1} {2} {3}</FONT></B></P>", data.ServerName, CPUUsage, RAMUsage, DiskUsageWarning);
            }

            if (iServer == cntServer)
            {
                if (emailBody != string.Empty)
                {
                    SendEmail();
                }
                iServer = 0;
            }
        }
        private void GetServerUsageAsyncForMail(object param)
        {
            if (param == null || !(param is ServerConfigurationData))
            {
                //Report Error
                this.BeginInvoke(new Action(() =>
                {
                    MessageBox.Show("Invalid argument: param", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }));
                iServer++;
                if (iServer == cntServer)
                {
                    if (emailBody != string.Empty)
                    {
                        SendEmail();
                    }
                    iServer = 0;
                }
                return;
            }

            ServerConfigurationData configuration = param as ServerConfigurationData;

            try
            {
                ServerLoadData result = ServerLoadHelper.GetServerUsage(configuration.ServerName, configuration.UserName, configuration.Password);

                iServer++;
                //Complete
                this.BeginInvoke(new Action <ServerLoadData>(OnGetServerUsageAsyncCompletedForMail), result);
            }
            catch (Exception ex)
            {
                iServer++;
                if (iServer == cntServer)
                {
                    if (emailBody != string.Empty)
                    {
                        SendEmail();
                    }
                    iServer = 0;
                }
                //Report Error
                this.BeginInvoke(new Action <string, Exception>(ReportErrorForEmail), configuration.ServerName, ex);
            }
        }
        private void GetServerUsageAsync(object param)
        {
            if (param == null || !(param is ServerConfigurationData))
            {
                iMonitorServer++;
                //Report Error
                this.BeginInvoke(new Action(() =>
                {
                    if (iMonitorServer == cntMonitorServer)
                    {
                        btnRefresh.Enabled = true;
                        iMonitorServer     = 0;
                    }
                    MessageBox.Show("Invalid argument: param", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }));
                return;
            }

            ServerConfigurationData configuration = param as ServerConfigurationData;

            //Report Progress
            this.BeginInvoke(new Action <string, decimal>(ReportProgress), configuration.ServerName, new Decimal(0));

            try
            {
                ServerLoadData result = ServerLoadHelper.GetServerUsage(configuration.ServerName, configuration.UserName, configuration.Password);

                iMonitorServer++;
                //Complete
                this.BeginInvoke(new Action <ServerLoadData>(OnGetServerUsageAsyncCompleted), result);
            }
            catch (Exception ex)
            {
                iMonitorServer++;
                //Report Error
                this.BeginInvoke(new Action <string, Exception>(ReportError), configuration.ServerName, ex);
            }
        }
        public static ServerLoadData GetServerUsage(string serverName, string userName, string password)
        {
            // Build an options object for the remote connection
            // if you plan to connect to the remote
            // computer with a different user name
            // and password than the one you are currently using.
            // This example uses the default values.

            ConnectionOptions options = new ConnectionOptions();

            if (serverName != ".")
            {
                options.Username = userName;
                options.Password = password;
            }

            // Make a connection to a remote computer.
            // Replace the "FullComputerName" section of the
            // string "\\\\FullComputerName\\root\\cimv2" with
            // the full computer name or IP address of the
            // remote computer.
            ManagementScope scope = new ManagementScope("\\\\" + serverName + "\\root\\cimv2", options);

            scope.Connect();

            SelectQuery sq = null;
            ManagementObjectSearcher mos    = null;
            ServerLoadData           result = new ServerLoadData();

            result.ServerName = serverName;

            //get CPU usage
            sq = new SelectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");
            using (mos = new ManagementObjectSearcher(scope, sq))
                result.CPUUsage = Convert.ToDouble(mos.Get().Cast <ManagementObject>().First()["PercentProcessorTime"]);
            //mos.Dispose();

            //get RAM usage
            //get Available RAM size
            sq = new SelectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
            Int64 available = 0;

            using (mos = new ManagementObjectSearcher(scope, sq))
            {
                available = Convert.ToInt64(mos.Get().Cast <ManagementObject>().First().Properties["AvailableBytes"].Value);
                //get Total RAM size
                sq = new SelectQuery("SELECT * FROM Win32_ComputerSystem");
            }
            using (mos = new ManagementObjectSearcher(scope, sq))
            {
                Int64 total = Convert.ToInt64(mos.Get().Cast <ManagementObject>().First().Properties["TotalPhysicalMemory"].Value);
                //calculate the RAM usage
                result.RAMUsage = 100 * (total - available) / total;
            }

            //get Disk usage
            Dictionary <string, double> diskUsage = new Dictionary <string, double>();

            sq = new SelectQuery("SELECT * FROM win32_logicaldisk");
            using (mos = new ManagementObjectSearcher(scope, sq))
            {
                foreach (ManagementObject disk in mos.Get())
                {
                    if (disk["DriveType"].ToString() == "3")
                    {
                        double freeSpace = Convert.ToDouble(disk["FreeSpace"]);
                        double totalSize = Convert.ToDouble(disk["Size"]);
                        diskUsage.Add(disk["Name"].ToString(), 100 * (totalSize - freeSpace) / totalSize);
                    }
                }
                result.DiskUsage = diskUsage;
            }

            return(result);
        }