Just started looking at c# programming I am trying to write a program that will eventually grab some server metrics %CPU Utilization, %Memory Utilization etc from remote hosts and then post them to InfluxDB using an API call over HTTP. So the Objective is:
To Collect CPU% Util
1. Collate Information of a Server i.e Unixtimestamp|hostip|hostname|value
2. Keep Collecting this metric once every second
3. Post this to Influxdb via a URL
I have made a start on it and only managed to get as far as getting the hostname of localhost.
This is my first project in c# any help would be great. see below code so far. I am using Visual Studio 2017 Community fyi.
using System;
using System.Net;
using System.Diagnostics;
namespace PostMetricsApp
{
class IpProto
{
public static void GetMyIpAddress();
{
string hostName = Dns.GetHostName(); // Retrive the Name of HOST
Console.WriteLine(hostName);
// Get IPAddress
string hostipadd = Dns.GetHostEntry(hostName).AddressList[0].ToString();
Console.WriteLine("My IP Address is :" + hostipadd);
Console.ReadKey();
}
}
class MemMetric
{
static void Main(string[] args)
{
PerformanceCounter ramCounter = new PerformanceCounter();
ramCounter.CategoryName = "Memory";
ramCounter.CounterName = "Available MBytes";
while (true)
{
var hostip = IpProto.host;
string hostname = Environment.MachineName;
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
int totalhits = 0;
float ramPercent = ramCounter.NextValue();
if (ramPercent >= 5)
{
var unused = ramCounter.NextValue(); // first call will always return 0
System.Threading.Thread.Sleep(1000); // wait a second, then try again
//Console.WriteLine("Cpu usage: " + cpuCounter.NextValue() + "%");
Console.WriteLine(unixTimestamp + " "+ hostip + " " + hostname + " " + ramCounter.NextValue() + "MB");
totalhits += 1;
}
else
{
totalhits = 0;
}
}
}
}
}