ASP. NET MVC4 Simple Server monitoring Development C # Get Server CPU, RAM, TCP and other system information (on)

Source: Internet
Author: User
Tags disk usage server memory

I. BACKGROUND

A few days ago, the server had some problems, plus more and more tension in school, writing blog share less time. Although not the first time to write experience in the blog park, but recently shared blog has been a lot of friends to support and correction, in the heart very grateful and happy. Hope that in the future can seriously use a good time, some useful experience to share to the needs of the people, of course, I still have a lot of undergraduate stage do not understand, if there are errors in the article, I hope that you will be educated.

Today's share is to get server CPU, RAM, TCP, disk usage using C #. Some time ago, did a dozens of-person concurrency test, server down, and later on the control console check the test time period of the server data, unfortunately there is no provision of this piece of data. To do this, I want to add a small monitoring feature to the Web program to make it easy to call and view the information I want at any time. To achieve this, first get some data on the server: CPU, RAM, TCP, disk usage data.

Second, solve the idea or process

First get the CPU usage:

    1. Create Class SystemMonitor.cs in the MVC directory, introducing namespaces: Using system.runtime.interopservices;//provides a wide variety of members that support COM interop and platform invoke services. Using the System.diagnostics;//system.diagnostics namespace, this namespace provides classes for interacting with event logs, performance counters, and system processes. You can keep this monitoring code enabled in the production application and view the information when a problem occurs.

Add the following code:

 /// <summary>    ///Get CPU Information/// </summary>     Public classCPUInfo {/// <summary>        ///Output CPU Information/// </summary>        /// <returns></returns>         Public stringGetcpuinfo () {StringBuilder sb=NewStringBuilder (); intCpupercent =Convert.ToInt32 (Getcpucounter ()); Sb.                       Append (cpupercent); returnsb.        ToString (); }        /// <summary>        ///Get CPU Information/// </summary>        /// <returns></returns>        Private Static ObjectGetcpucounter () {PerformanceCounter PC=NewPerformanceCounter (); Pc. CategoryName="Processor"; Pc. CounterName="% Processor time"; Pc. InstanceName="_total"; DynamicValue_1 =pc.            NextValue (); System.Threading.Thread.Sleep ( +); Dynamicvalue_2 =pc.            NextValue (); returnvalue_2; }    }

Then get the current server memory usage data:

    1. Structs and dllimport["" are needed here, and the Kernel32.dll used here is a very important 32-bit dynamic-link library file in windows9x/me, which belongs to the kernel-level file. It controls the system's memory management, data input and output operations, and interrupt handling, and when Windows starts, Kernel32.dll resides in memory-specific write-protected areas, making it impossible for other programs to occupy this area of memory.

The code is as follows:

 /// <summary>    ///Get memory Information/// </summary>     Public classMemoryinfo {//Define the information structure of the memory[StructLayout (layoutkind.sequential)] Public structMemory_info { Public UINTdwlength;  Public UINTdwMemoryLoad;  Public UINTdwTotalPhys;  Public UINTdwAvailPhys;  Public UINTdwTotalPageFile;  Public UINTdwAvailPageFile;  Public UINTdwtotalvirtual;  Public UINTdwavailvirtual; }        /// <summary>        ///Kernel32.dll is a very important 32-bit dynamic link library file in windows9x/me, which belongs to the kernel level file.
It controls the system's memory management, data input and output operations, and interrupt handling, and when Windows starts, Kernel32.dll resides in memory-specific write-protected areas, making it impossible for other programs to occupy this area of memory. /// </summary>[DllImport ("kernel32")] Private Static extern voidGetWindowsDirectory (StringBuilder windir,intcount); [DllImport ("kernel32")] Private Static extern voidGetSystemDirectory (StringBuilder Sysdir,intcount); [DllImport ("kernel32")] Private Static extern voidGlobalMemoryStatus (refmemory_info meminfo); /// <summary> ///Get memory Information/// </summary> /// <returns></returns> Public stringGetmeminfo () {//Call the GlobalMemoryStatus function to get information about memoryMemory_info Meminfo =NewMemory_info (); GlobalMemoryStatus (refmeminfo); //Stitching StringsStringBuilder SB =NewStringBuilder (); returnMemInfo.dwMemoryLoad.ToString (); } }

Then the disk using data acquisition, because my server has only a C drive, so it is written dead, there are many friends can write a list, the same way to get the information of the general disk:

The code is as follows:

 /// <summary>    ///Get disk information/// </summary>     Public classDiskInfo {/// <summary>        ///gets the total space size of the specified drive (in units b)///simply enter the letter that represents the drive (uppercase)/// </summary>        /// <param name= "Str_harddiskname" ></param>        /// <returns></returns>         Public floatGetharddiskspace (stringstr_harddiskname) {            floatTotalSize =New float(); Str_harddiskname= Str_harddiskname +":\\"; System.io.driveinfo[] Drives=System.IO.DriveInfo.GetDrives (); foreach(System.IO.DriveInfo Driveinchdrives) {                if(Drive. Name = =str_harddiskname) {TotalSize= drive. TotalSize/(1024x768*1024x768*1024x768); }            }            returntotalsize; }         Public stringGetharddiskspace () {stringStr_harddiskname ="C"; floatTotalSize =New float(); Str_harddiskname= Str_harddiskname +":\\"; System.io.driveinfo[] Drives=System.IO.DriveInfo.GetDrives (); foreach(System.IO.DriveInfo Driveinchdrives) {                if(Drive. Name = =str_harddiskname) {TotalSize= drive. TotalSize/(1024x768*1024x768*1024x768); }            }            stringTotalSize =totalsize.tostring (); returntotalsize; }        /// <summary>        ///gets the total size of the remaining space in the specified drive (in units b)///simply enter the letter that represents the drive/// </summary>        /// <param name= "Str_harddiskname" ></param>        /// <returns></returns>         Public stringGetharddiskfreespace (stringstr_harddiskname) {            LongFreeSpace =New Long(); stringFreeSpace =""; Str_harddiskname= Str_harddiskname +":\\"; System.io.driveinfo[] Drives=System.IO.DriveInfo.GetDrives (); foreach(System.IO.DriveInfo Driveinchdrives) {                if(Drive. Name = =str_harddiskname) {FreeSpace= drive. Totalfreespace/(1024x768*1024x768*1024x768); }} FreeSpace=freespace.tostring (); returnFreeSpace; }    }

Finally, the number of TCP connections:

The code is as follows:

/// <summary>    ///gets the number of port connections/// </summary>     Public classTcpinfo { Public stringGet_tcp_count () {stringTcpcount =""; Ipglobalproperties Properties=ipglobalproperties.getipglobalproperties (); Tcpconnectioninformation[] Connections=Properties.                        Getactivetcpconnections (); Tcpcount=connections. Count ().            ToString (); returnTcpcount; }    }

There is also a 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 decimalConvertbytes (stringBintiteration) {            LongITER =1;  for(inti =0; I < iteration; i++) ITER*=1024x768; returnMath.Round (Convert.todecimal (b))/Convert.todecimal (ITER),2, Midpointrounding.awayfromzero); }    }

Iii. Summary and views

The above code may have some parts, because this is what I stripped out of the project, so the lack of some code to fill in, if there are questions please leave a message. If my thoughts and methods are wrong, I implore you to correct me, and humbly ask for advice. Please indicate the source and origin, thank you for your cooperation by the point will not be

ASP. NET MVC4 Simple Server monitoring Development C # Get Server CPU, RAM, TCP and other system information (on)

Related Article

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.