How to get Committed Memory in Windows Server 2012 using .NET - c#

This is how I get the total and used RAM:
PerformanceCounter ramAvailableCounter = new PerformanceCounter("Memory", "Available MBytes");
var ramUsedMB = ramAvailableCounter.NextValue();
var ramTotalMB = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024 / 1024;
var ramPercentageLeft = (ramUsedMB * 100) / ramTotalMB;
But how can I get the "Committed" memory shown below?
Unfortunately the application we use throws an exception when there is only about 15GB free and I would like to send a notification when is close enough.

It can be done as following:
PerformanceCounter percCommittedBytesInUseCounter = new PerformanceCounter("Memory", "% Committed Bytes In Use");

Related

Mono-based Replacement for Microsoft.VisualBasic ComputerInfo

I have following c# code running perfectly fine in visual studio but if want to compile it on mono it simply fails with error CmputerInfo doesn't exists are you missing assembly reference.
// Get Total Available Memory Percentage and if its below a threshhold then send ServiceUnavailable
ComputerInfo computerInfo = new ComputerInfo();
ulong totalPhysicalMemory = computerInfo.TotalPhysicalMemory;
ulong availablePhysicalMemory = computerInfo.AvailablePhysicalMemory;
ulong availablePhysicalMemoryPercentage = (availablePhysicalMemory * 100 / totalPhysicalMemory);
If the above dll doesn't supported by mono. Please tell me how to gather above information in linux.
Thanks
Use this as a replacement:
var pc = new System.Diagnostics.PerformanceCounter("Mono Memory", "Available Physical Memory");
long availableMemory = pc.RawValue;
var pc2 = new System.Diagnostics.PerformanceCounter("Mono Memory", "Total Physical Memory");
long physicalMemory = pc2.RawValue;

How to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?

I am currently looking for a way to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE.
For CPU and ram usage, I use PerformanceCounter Class from System.Diagnostics.
This is the codes:
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
public string getCurrentCpuUsage(){
cpuCounter.NextValue()+"%";
}
public string getAvailableRAM(){
ramCounter.NextValue()+"MB";
}
For disk usage, I am using the DriveInfo class. This is the codes:
using System;
using System.IO;
class Info {
public static void Main() {
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives) {
//There are more attributes you can use.
//Check the MSDN link for a complete example.
Console.WriteLine(drive.Name);
if (drive.IsReady) Console.WriteLine(drive.TotalSize);
}
}
}
Unfortunately .NET Core does not support the DriveInfo and PerformanceCounter classes, hence the code above do not work.
Does anyone know how I can get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?
You can use PerformnceCounter in the System.Diagnostics.PerformanceCounter package
for example, the next code will give you the total processor usage percent
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total",true);
var value = cpuCounter.NextValue();
//Note: In most cases you need to call .NextValue() twice to be able to get the real value
if (Math.Abs(value) <= 0.00)
value = cpuCounter.NextValue();
Console.WriteLine(value);
you can do the same for all OS registered Performance Counters.
Update:
I'm not sure if there is something I should do after creating a new instance of the PerformanceCounter class, but sometimes when I get the next value it comes as 0.
So I've decided to make one instance of PerformanceCounter in at the application level.
e.g.
public static class DiagnosticHelpers
{
static float _systemCPU;
public static float SystemCPU
{
get
{
lock (locker)
{
return _systemCPU;
}
}
}
private static readonly object locker = new object();
static DiagnosticHelpers()
{
SystemCPU = 0;
Task.Run(() =>
{
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
cpuCounter.NextValue(); //prime the counter
while (true)
{
Thread.Sleep(1000); /wait at least 1 second before the first real read
lock (locker)
{
_systemCPU = cpuCounter.NextValue();
}
}
});
}
}
Processor information is available via System.Diagnostics:
var proc = Process.GetCurrentProcess();
var mem = proc.WorkingSet64;
var cpu = proc.TotalProcessorTime;
Console.WriteLine("My process used working set {0:n3} K of working set and CPU {1:n} msec",
mem / 1024.0, cpu.TotalMilliseconds);
DriveInfo is available for Core by adding the System.IO.FileSystem.DriveInfo package
For Windows i'm using this
var memorieLines= GetWmicOutput("OS get FreePhysicalMemory,TotalVisibleMemorySize /Value").Split("\n");
var freeMemory= memorielines[0].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];
var totalMemory = memorielines[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];
var cpuLines = GetWmicOutput("CPU get Name,LoadPercentage /Value").Split("\n");
var CpuUse = cpuLines[0].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];
var CpuName = cpuLines[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];
private string GetWmicOutput(string query, bool redirectStandardOutput = true)
{
var info = new ProcessStartInfo("wmic");
info.Arguments = query;
info.RedirectStandardOutput = redirectStandardOutput;
var output = string.Empty;
using (var process = Process.Start(info))
{
output = process.StandardOutput.ReadToEnd();
}
return output.Trim();
}
For the disk infos you can use this query :
LOGICALDISK get Caption,DeviceID,FileSystem,FreeSpace,Size /Value
if you want a better output formatting give a look to this article : https://www.petri.com/command-line-wmi-part-3
Add this nuget package to your project by double clicking project.
<ItemGroup>
<PackageReference Include="System.Diagnostics.PerformanceCounter" Version="6.0.0" />
</ItemGroup>
When you run the code, you will get an error like below.
Performance counters cannot be initialized! System.UnauthorizedAccessException: Access to the registry key 'Global' is denied.
To solve this error, you have to add your application pool user to "Performance Monitor Users" group.
Open command line in administrator mode, then run this command.
net localgroup "Performance Monitor Users" "IIS APPPOOL\MYAPPPOOL" /add
MYAPPPOOL will be replaced with your real app pool name.
Then restart the machine if iis restart does not solve.

Measure the consumed mb on the internet

I want to get the number of consumed MBs on the internet by code..
I know that it can be done manually:
Settings -> Network & Internet -> Data Usage (Windows 10)
photo:
But how can I find this by code?
I want the number for the whole system, NOT ONLY MY APPLICATION.
For example, I want my code to show: The GB used this month was 3.21!
You can try the following snippet which will give you total sent and received data. You just need to sum it out:
private static void GetTrafficStatistics()
{
PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);
for (int i = 0; i < 10; i++)
{
Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024);
Thread.Sleep(500);
}
}
PS:It is using System.Diagnostics.dll
Hope it will help you out.

How to make a CPU Usage Control in WPF

I want to make a control which is very similar to the one used in Windows Task Manager to show the CPU Performance something like a changing vertical Guage
You can get the CPU usage values via ManagementObjectSearcher using WMI
To get the value, you do something like this
var info = ManagementObjectSearcher(#"\\localhost\root\CIMV2","SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");
ManagementObject queryObj = info.Get().Cast<ManagementObject>().First();
var cpuUsage = Convert.ToInt32(queryObj["PercentIdleTime"]);
Alternatively you can use the System.Diagnostics PerformanceCounter instead
PerformanceCounter cpu = new PerformanceCounter(){
CategoryName = "Processor",
CounterName = "% Processor Time",
InstanceName = "_Total"
};
var yourCpuUsageValue = cpu.NextValue();
Got it...used a Progress Bar to show the values and used PerformanceCounter to get the cpu usage values.
Thanks

Retrieving Total amount of RAM on a computer [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C# - How do you get total amount of RAM the computer has?
The following would retrieve how much ram is available:
PerformanceCounter ramCounter;
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
Console.WriteLine("Total RAM: " + ramCounter.NextValue().ToString() + " MB\n\n");
Of course we will have to use the System.Diagnostics; class.
Does performancecounter have any functionality for retrieving the amount of RAM of a particular machine? I'm not talking about the amount of ram used or unused. I'm talking about the amount of ram the machine has.
This information is already available directly in the .NET framework, you might as well use it. Project + Add Reference, select Microsoft.VisualBasic.
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("You have {0} bytes of RAM",
new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
Console.ReadLine();
}
}
And no, it doesn't turn your C# code into vb.net.
you can try like this
Add a Reference to System.Management.
private static void DisplayTotalRam()
{
string Query = "SELECT MaxCapacity FROM Win32_PhysicalMemoryArray";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);
foreach (ManagementObject WniPART in searcher.Get())
{
UInt32 SizeinKB = Convert.ToUInt32(WniPART.Properties["MaxCapacity"].Value);
UInt32 SizeinMB = SizeinKB / 1024;
UInt32 SizeinGB = SizeinMB / 1024;
Console.WriteLine("Size in KB: {0}, Size in MB: {1}, Size in GB: {2}", SizeinKB, SizeinMB, SizeinGB);
}
}

Categories

Resources