Asp.net mvc4 simple server monitoring and development C # obtain server CPU, RAM, TCP and other system information (on ),

Source: Internet
Author: User

Asp.net mvc4 simple server monitoring and development C # obtain server CPU, RAM, TCP and other system information (on ),

I. background

Some time ago, the server encountered some problems. In addition, due to the increasing academic shortage, there was less and less time to write and share blog posts. Although it is not the first time I have written my experience in the blog, I am very grateful and happy to hear that many of my recent blog posts have been supported and corrected. I hope that you can make good use of your time and share some useful experiences with the people you need. Of course, I still have many questions during the undergraduate course. If there are any mistakes in the article, I hope you can correct them more, you will be taught with an empty mind.

Today, we will share with you how to use c # To obtain the server CPU, RAM, TCP, and disk usage. Some time ago, I did a concurrency test for dozens of people, and the server went down. Later I checked the server data in the test period on the control console. Unfortunately, I did not provide this data. To this end, I want to add a small monitoring function to my web application so that I can call and view the information I want at any time. To implement this function, you must first obtain data on the server: CPU, RAM, TCP, and disk usage data.

 

2. solution or process

First, obtain the CPU usage:

Add the following code:

/// <Summary> /// obtain CPU information /// </summary> public class CPUInfo {// <summary> /// output CPU information /// </ summary> // <returns> </returns> public string GetCPUInfo () {StringBuilder sb = new StringBuilder (); int cpuPercent = Convert. toInt32 (GetCPUCounter (); sb. append (cpuPercent); return sb. toString () ;}/// <summary> // obtain CPU information /// </summary> /// <returns> </returns> private static object GetCPUCounter () {PerformanceCounter pc = new PerformanceCounter (); pc. categoryName = "Processor"; pc. counterName = "% Processor Time"; pc. instanceName = "_ Total"; dynamic Value_1 = pc. nextValue (); System. threading. thread. sleep (1000); dynamic Value_2 = pc. nextValue (); return Value_2 ;}}

Then, you can obtain the memory usage data of the current server:

The Code is as follows:

/// <Summary> /// obtain the memory information /// </summary> public class MemoryInfo {// define the memory information structure [StructLayout (LayoutKind. sequential)] public struct MEMORY_INFO {public uint dwLength; public uint dwMemoryLoad; public uint dwTotalPhys; public uint values; public uint dwTotalVirtual; public uint dwAvailVirtual ;} /// <summary> /// kernel32.dll is Windows9x/Me Is a kernel-level file.
/// It controls the system's memory management, data input and output operations, and interrupt processing. When Windows starts, kernel32.dll will reside in a specific write protection area in the memory, make other programs unable to occupy this memory area. /// </Summary> [DllImport ("kernel32")] private static extern void GetWindowsDirectory (StringBuilder WinDir, int count); [DllImport ("kernel32")] private static extern void GetSystemDirectory (StringBuilder SysDir, int count); [DllImport ("kernel32")] private static extern void GlobalMemoryStatus (ref MEMORY_INFO meminfo ); /// <summary> /// obtain the memory information /// </summary> /// <returns> </returns> public string GetMemInfo () {// call the GlobalMemoryStatus function to obtain information about the memory. MEMORY_INFO MemInfo = new MEMORY_INFO (); GlobalMemoryStatus (ref MemInfo); // concatenate the string StringBuilder sb = new StringBuilder (); return MemInfo. dwMemoryLoad. toString ();}}

The next step is to use data to obtain the disk. Because my server has only one C disk, I am writing a dead disk here. If you have multiple disks, you can write a List and obtain the information of the total disk in the same way:

The Code is as follows:

/// <Summary> /// obtain disk information /// </summary> public class DiskInfo {/// <summary> /// obtain the total space of the specified drive (unit: B) /// you only need to enter the letter representing the drive (uppercase) /// </summary> /// <param name = "str_HardDiskName"> </param> /// <returns> </returns> public float GetHardDiskSpace (string str_HardDiskName) {float totalSize = new float (); str_HardDiskName = str_HardDiskName + ":\\"; System. IO. driveInfo [] drives = System. IO. driveInfo. getDrives (); foreach (System. IO. driveInfo drive in drives) {if (drive. name = str_HardDiskName) {totalSize = drive. totalSize/(1024*1024*1024);} return totalSize;} public string GetHardDiskSpace () {string str_HardDiskName = "C"; float totalSize = new float (); str_HardDiskName = str_HardDiskName + ": \"; System. IO. driveInfo [] drives = System. IO. driveInfo. getDrives (); foreach (System. IO. driveInfo drive in drives) {if (drive. name = str_HardDiskName) {totalSize = drive. totalSize/(1024*1024*1024);} string TotalSize = totalSize. toString (); return TotalSize ;}/// <summary> /// obtain the total space remaining for the specified drive (unit: B) /// just enter the letter representing the drive. /// </summary> /// <param name = "str_HardDiskName"> </param> /// <returns> </ returns> public string GetHardDiskFreeSpace (string str_HardDiskName) {long freeSpace = new long (); string FreeSpace = ""; str_HardDiskName = str_HardDiskName + ":\\"; System. IO. driveInfo [] drives = System. IO. driveInfo. getDrives (); foreach (System. IO. driveInfo drive in drives) {if (drive. name = str_HardDiskName) {freeSpace = drive. totalFreeSpace/(1024*1024*1024);} FreeSpace = freeSpace. toString (); return FreeSpace ;}}

Finally, the number of TCP connections:

The Code is as follows:

/// <Summary> // obtain the number of port connections /// </summary> public class TCPInfo {public string Get_TCP_Count () {string TCPCount = ""; IPGlobalProperties properties = IPGlobalProperties. getIPGlobalProperties (); TcpConnectionInformation [] connections = properties. getActiveTcpConnections (); TCPCount = connections. count (). toString (); return TCPCount ;}}

Here we also need to add a class Trans, which can help convert the format, such as converting byte to GB:

/// <Summary> /// conversion /// </summary> public class Trans {public static decimal ConvertBytes (string B, int iteration) {long iter = 1; for (int I = 0; I <iteration; I ++) iter * = 1024; return Math. round (Convert. toDecimal (B)/Convert. toDecimal (iter), 2, MidpointRounding. awayFromZero );}}

 

Iii. Summary and opinions

The above code may be a bit incomplete, because it is removed from the project, so some of the missing code must be supplemented. If you have any questions, please leave a message. If my ideas and methods are incorrect, please correct me and ask for advice with an empty mind.Reprinted, please indicate the source and source. Thank you for your cooperation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.