How to find systems cached and free memory using C# - c#

I couldnt able to find the cached and free memory of a system using C#.Help me.......

Add Microsoft.VisualBasic.Devices assembly reference to your project then you can use following
var Available = new ComputerInfo().AvailablePhysicalMemory;
var Total = new ComputerInfo().TotalPhysicalMemory;
var Cheched = Total - Available;
Edit:
Following code works for me, also note that Available amount includes the Free Amount and also includes most of the Cached amount.
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
//total amount of free physical memory in bytes
var Available = new ComputerInfo().AvailablePhysicalMemory;
//total amount of physical memory in bytes
var Total = new ComputerInfo().TotalPhysicalMemory;
var PhysicalMemoryInUse = Total - Available;
Object Free = new object();
foreach (var result in results)
{
//Free amount
Free = result["FreePhysicalMemory"];
}
var Cached = Total - PhysicalMemoryInUse - UInt64.Parse(Free.ToString());
Console.WriteLine("Available: " + ByteToGb(Available));
Console.WriteLine("Total: " + ByteToGb(Total));
Console.WriteLine("PhysicalMemoryInUse: " + ByteToGb(PhysicalMemoryInUse));
Console.WriteLine("Free: " + ByteToGb(UInt64.Parse( Free.ToString())));
Console.WriteLine("Cached: " + ByteToGb(Cached));

Related

foreach (ManagementObject user in users) doesn't seem to be retrieving all local accounts

I use the following method to get all LOCAL user accounts on a machine. It finds 12 of them, but only processes the first one.
ObjectQuery wql = new ObjectQuery(#"SELECT * FROM Win32_UserProfile");
ManagementObjectSearcher usersSearcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection users = usersSearcher.Get();
Console.WriteLine("Users: " + "[" + users.Count + "]"); // Reports 12
foreach (ManagementObject user in users)
{
Console.WriteLine("Checking User: " + GetNameFromSID(user["SID"].ToString()));
}
It seems that it used to report all accounts. Is there a surefire way to get this information?

How to get total system RAM in .NET Standard 2.0?

As the title says, is there a way to get the total (installed) system RAM in .NET Standard 2.0? All my searches only turn up with .NET Framework solutions.
You can use System.Management with NET Standard 2.0. Hope this can help you:
using System;
using System.Diagnostics;
using System.Management;
namespace RamSystem
{
public class RamSystem
{
public static void GetRAM()
{
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
double res;
foreach (ManagementObject result in results)
{
res = Convert.ToDouble(result["TotalVisibleMemorySize"]);
double fres = Math.Round((res / (1024 * 1024)), 2);
Console.WriteLine("Total usable memory size: " + fres + "GB");
Console.WriteLine("Total usable memory size: " + res + "KB");
}
Console.ReadLine();
}
}
}

Real number of TotalPages of a PrintJob (Win32_PrintJob)

I'm querying to Win32_PrintJob WMI class every time there is a change with ManagementEventWatcher, I obtained data about it, such as: Document, HostPrintQueue, JobId, JobStatus, TotalPages, etc. But TotalPages is not representing the real number of page to print, Seems at the moment to obtain these data still the printjob doesn't finished to process and devolving a number of pages to print in that moment but the real total is other number, How to get the real number of a print job when finished it to process?
Here is my code:
ManagementEventWatcher createPrintJobWatcher;
String strComputerName = ".";
// Create event query to be notified within 1 milli second of a change in a service
WqlEventQuery createPrintJobQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 0.001 WHERE TargetInstance ISA \"Win32_PrintJob\"");
createPrintJobWatcher = new ManagementEventWatcher();
createPrintJobWatcher.Scope = new ManagementScope("\\\\" + strComputerName + "\\root\\CIMV2");
createPrintJobWatcher.Query = createPrintJobQuery;
// times out watcher.WaitForNextEvent in 1 seconds
createPrintJobWatcher.Options.Timeout = new TimeSpan(0, 0, 1);
//set the print event handler
createPrintJobWatcher.EventArrived += new EventArrivedEventHandler(createPrintJobListener);
createPrintJobWatcher.Start();
Console.WriteLine("Listening...");
Console.ReadLine();
createPrintJobListener method:
static void createPrintJobListener(object sender, EventArrivedEventArgs e)
{
SelectQuery query = new SelectQuery("Win32_PrintJob");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection printJobs = searcher.Get())
foreach (ManagementObject printJob in printJobs)
{
Console.WriteLine("c1:", printJob);
Console.WriteLine("ID: {0}", printJob.GetPropertyValue("JobId").ToString());
Console.WriteLine("name: {0}", printJob.GetPropertyValue("name").ToString());
Console.WriteLine("status: {0}", printJob.GetPropertyValue("status").ToString());
if (printJob.GetPropertyValue("JobStatus") != null)
{
Console.WriteLine("JobStatus: {0}", printJob.GetPropertyValue("JobStatus").ToString());
}
else
{
Console.WriteLine("JobStatus: NULLLLLL");
}
Console.WriteLine("PC: {0}", printJob.GetPropertyValue("HostPrintQueue").ToString());
Console.WriteLine("TOTOAL PAGES: {0}", printJob.GetPropertyValue("TotalPages").ToString());
}
}
WMI is probably not sufficient to do this.
Windows doesn't reliably provide the page count (or copies etc), so the only way to get accurate info is to pause the job and parse it. This is a non-trivial task, but here's a little more info.

Pivot Excel With NReco, System Out of Memory Exception

I m getting System Out of Memory exception while creating pivot table with NReco ExcelPivotTableWriter
public void Write(PivotTable pvtTbl)
{
var tbl = getPivotDataAsTable(pvtTbl.PivotData);
var rangePivotTable = wsData.Cells["A1"].LoadFromDataTable(tbl, false);
var pivotTable = ws.PivotTables.Add(
ws.Cells[1, 1],
rangePivotTable, "pvtTable");
foreach (var rowDim in pvtTbl.Rows)
pivotTable.RowFields.Add(pivotTable.Fields[rowDim]);
foreach (var colDim in pvtTbl.Columns)
pivotTable.ColumnFields.Add(pivotTable.Fields[colDim]);
pivotTable.ColumGrandTotals = false;
pivotTable.DataOnRows = false;
pivotTable.ColumGrandTotals = false;
pivotTable.RowGrandTotals = false;
if (pvtTbl.PivotData.AggregatorFactory is CompositeAggregatorFactory)
{
var aggrFactories = ((CompositeAggregatorFactory)pvtTbl.PivotData.AggregatorFactory).Factories;
for (int i = 0; i < aggrFactories.Length; i++)
{
var dt = pivotTable.DataFields.Add(pivotTable.Fields[String.Format("value_{0}", i)]);
dt.Function = SuggestFunction(aggrFactories[i]);
string columnName = "";
if (dt.Function == OfficeOpenXml.Table.PivotTable.DataFieldFunctions.Sum)
columnName = ((NReco.PivotData.SumAggregatorFactory)aggrFactories[i]).Field;
else if(dt.Function == OfficeOpenXml.Table.PivotTable.DataFieldFunctions.Average)
columnName = ((NReco.PivotData.AverageAggregatorFactory)aggrFactories[i]).Field;
if (columnNames.ContainsKey(columnName))
dt.Name = columnNames[columnName].ToString();
else
dt.Name = aggrFactories[i].ToString();
}
}
else
{
pivotTable.DataFields.Add(pivotTable.Fields["value"]).Function = SuggestFunction(pvtTbl.PivotData.AggregatorFactory);
}
}
error occures while creating rangePivotTable
var rangePivotTable = wsData.Cells["A1"].LoadFromDataTable(tbl, false);
The LazyTotal mode is true
var ordersPvtData = new PivotData(dimentionsArray, composite, true);
The dataset has 200k rows. It is not too much i think. I have 8 gb ram on windows 10.
NReco is free version.
Any solution ?
8G may not be enough physical memory depending upon how large each of the 200K rows are and the memory consumption of the other applications running on your system.
Before you run this program, start the Windows Task Manager and click on the Performance tab.
Note the Available and Free Memory values. Then run your program and watch how the memory is consumed. If your program does consume all of your available memory, then your options are...
Free up more memory by removing other applications that consume memory.
Add more physical memory to your system.
Modify your program to make it more memory efficient. (this includes removal of memory leaks)
Some combination of the prior three options.
You should be able to slice through 200k rows pretty easily. Try it like this . . .
Workbook workbook = new Workbook();
workbook.LoadFromFile(#"C:\your_path_here\SampleFile.xlsx");
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Data Source";
Worksheet sheet2 = workbook.CreateEmptySheet();
sheet2.Name = "Pivot Table";
CellRange dataRange = sheet.Range["A1:G200000"];
PivotCache cache = workbook.PivotCaches.Add(dataRange);
PivotTable pt = sheet2.PivotTables.Add("Pivot Table", sheet.Range["A1"], cache);
var r1 = pt.PivotFields["Vendor No"];
r1.Axis = AxisTypes.Row;
pt.Options.RowHeaderCaption = "Vendor No";
var r2 = pt.PivotFields["Description"];
r2.Axis = AxisTypes.Row;
pt.DataFields.Add(pt.PivotFields["OnHand"], "SUM of OnHand", SubtotalTypes.Sum);
pt.DataFields.Add(pt.PivotFields["OnOrder"], "SUM of OnOrder", SubtotalTypes.Sum);
pt.DataFields.Add(pt.PivotFields["ListPrice"], "Average of ListPrice", SubtotalTypes.Average);
pt.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium12;
workbook.SaveToFile("PivotTable.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("PivotTable.xlsx");

C# Collect IOps PErformance Data RealTime?

I am trying to build a small Software App which can collect Performance Data from a Windows Machine.
Here is a part of the code i use and PrintScreen which gives me not a right number.
Please Tell me what is wrong in my Code and why is the scale not right in the code.(The default scale is 1)
PrintScreen:
http://postimage.org/image/6za0g7e4t/
ManagementScope oMs = new System.Management.ManagementScope("root\\cimv2");
//Inventory
ObjectQuery InventQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher Inventsearcher = new ManagementObjectSearcher(oMs, InventQuery);
ManagementObjectCollection InventCollection = Inventsearcher.Get();
foreach (ManagementObject mgt in InventCollection)
{
outBox.AppendText(mgt["csname"].ToString() + "\n");
}
//Performance
//ObjectQuery PerfQuery = new ObjectQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk");
ObjectQuery PerfQuery = new ObjectQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_LogicalDisk");
ManagementObjectSearcher Perfsearcher = new ManagementObjectSearcher(oMs, PerfQuery);
ManagementObjectCollection PerfCollection = Perfsearcher.Get();
foreach (ManagementObject mgt in PerfCollection)
{
mgt.SetPropertyQualifierValue("DiskWritesPerSec", "DefaultScale", ScaleBox.Text);
mgt.SetPropertyQualifierValue("DiskReadsPerSec", "DefaultScale", ScaleBox.Text);
outBox.AppendText("Write IOps: " + mgt["Name"].ToString() + " ");
outBox.AppendText("Write IOps: " + mgt["DiskWritesPerSec"].ToString() + " ");
outBox.AppendText("Read IOps: " + mgt["DiskReadsPerSec"].ToString() + "\n");
}

Categories