/// <summary> /// Get number of megabytes of physical memory</summary> /// <returns>Number of megabytes of physical memory</returns> public static int GetPhysicalMemoryMB() { // Available from Windows 2000 and onward; i.e., Environment.OSVersion.Version.Major >= 5 . var memoryStatus = new MEMORYSTATUSEX(); GlobalMemoryStatusEx(memoryStatus); return (int)(memoryStatus.ullTotalPhys / (1024 * 1024));// convert bytes to megabytes }
public GlobalMemoryStatusNativeMethods() { this.memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(this.memStatus)) { this.AvailablePhysicalMemory = this.memStatus.ullAvailPhys; } }
public static float GetGlobalMemoryStatusEX() { MEMORYSTATUSEX statEX = new MEMORYSTATUSEX(); statEX.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX)); GlobalMemoryStatusEx(ref statEX); return (float)statEX.ullTotalPhys; }
public double getTotalMem() { MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { return (double)memStatus.ullTotalPhys; } return 0d; }
static float perBufferSize = 0.05f; // 5 % - величина буфера относительно свободного ОЗУ /* static long CountFreeRAM() { using (PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes")) { return (long)(ramCounter.NextValue() * 1024 * 1024); } } /**/ static ulong SetBuffSize() // 5% от свободной памяти { //ulong freeRAMSize = CountFreeRAM(); MEMORYSTATUSEX memEx = new MEMORYSTATUSEX(); GlobalMemoryStatusEx(memEx); if ((ulong)fsInput.Length >= (ulong)(perFreeRAM * memEx.ullAvailPhys)) // если больше 70% от свободного озу return (ulong)(perBufferSize * memEx.ullAvailPhys); else return (ulong)fsInput.Length; }
public DataSources(List<Meter> meters) { prevFileCheck = new Dictionary<string, DateTime>(); prevFileValue = new Dictionary<string, int>(); monitor = new NetworkMonitor(); adapters = monitor.Adapters; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) TotalRAM = (int)((float)memStatus.ullTotalPhys / 1024 / 1024); bool startedMonitoring = false; foreach (Meter meter in meters) switch (meter.Data) { case "CPU usage": if (cpuCounter == null) { cpuCounter = new PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; } break; case "Available memory": case "Used memory": if (ramCounter == null) ramCounter = new PerformanceCounter("Memory", "Available MBytes"); break; case "Recycle bin file count": case "Recycle bin size": binQuery = new SHQUERYRBINFO(); break; case "Download speed": case "Upload speed": if (!startedMonitoring) { monitor.StartMonitoring(); startedMonitoring = true; } break; case "System volume": case "Audio peak level": if (audioDevice == null) { MMDeviceEnumerator DevEnum = new MMDeviceEnumerator(); audioDevice = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia); } break; } }
public static Info GetMemoryInfo() { var i = new Info(); var data = new MEMORYSTATUSEX(); data.dwLength = 64; GlobalMemoryStatusEx(ref data); i.AvailableRam = data.ullAvailPhys; i.TotalRam = data.ullTotalPhys; i.UsedVirtualMemory = data.ullTotalPageFile - data.ullTotalPhys; i.AvailableVirtualMemory = data.ullAvailPhys - data.ullAvailPageFile; return i; }
private bool GlobalMemoryStatusDetour(IntPtr memStruct) { ////Prevents eve crashes if (_struct == null) { var result = GlobalMemoryStatusEx(memStruct); _struct = (MEMORYSTATUSEX) Marshal.PtrToStructure(memStruct, typeof (MEMORYSTATUSEX)); _struct.ullTotalPhys = _totalPhys*1024*1024; } Marshal.StructureToPtr(_struct, memStruct, true); return true; }
/// <summary>writes exception details to the registered loggers</summary> /// <param name="exception">The exception to log.</param> /// <param name="strCustomMessage"></param> public void LogException(Exception exception, string strCustomMessage) { StringBuilder error = new StringBuilder(); error.AppendLine("Error Message: " + strCustomMessage); error.AppendLine(""); error.AppendLine(""); error.AppendLine("Application: " + Application.ProductName); error.AppendLine("Version: " + Application.ProductVersion); error.AppendLine("Date: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")); error.AppendLine("Computer name: " + SystemInformation.ComputerName); error.AppendLine("User name: " + SystemInformation.UserName); error.AppendLine("OS: " + Environment.OSVersion.ToString()); error.AppendLine("Culture: " + CultureInfo.CurrentCulture.Name); error.AppendLine("Resolution: " + SystemInformation.PrimaryMonitorSize.ToString()); error.AppendLine("System up time: " + GetSystemUpTime()); error.AppendLine("App up time: " + (DateTime.Now - Process.GetCurrentProcess().StartTime).ToString()); MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { error.AppendLine("Total memory: " + memStatus.ullTotalPhys / (1024 * 1024) + "Mb"); error.AppendLine("Available memory: " + memStatus.ullAvailPhys / (1024 * 1024) + "Mb"); } error.AppendLine(""); error.AppendLine("Exception classes: "); error.Append(GetExceptionTypeStack(exception)); error.AppendLine(""); error.AppendLine("Exception messages: "); error.Append(GetExceptionMessageStack(exception)); error.AppendLine(""); error.AppendLine("Stack Traces:"); error.Append(GetExceptionCallStack(exception)); error.AppendLine(""); error.AppendLine("Loaded Modules:"); Process thisProcess = Process.GetCurrentProcess(); foreach (ProcessModule module in thisProcess.Modules) { error.AppendLine(module.FileName + " " + module.FileVersionInfo.FileVersion); } for (int i = 0; i < loggers.Count; i++) { loggers[i].LogError(error.ToString()); } }
public void Start() { Ram_Info ramObject = readXmlToObj(); while (true) { #region OldCode //MemoryStatus stat = new MemoryStatus(); //GlobalMemoryStatus(out stat); //long ram_availbale = (long)stat.AvailablePhysical / 1024; //long ram_total = (long)stat.TotalPhysical / 1024; //long ram_used = ram_total - ram_availbale; #endregion ulong ram_availbale; ulong ram_total; ulong ram_used; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { ram_availbale = memStatus.ullAvailPhys; ram_total = memStatus.ullTotalPhys; ram_used = ram_total - ram_availbale; float CurrentPercentage = (ram_used * 100) / ram_total; if (CurrentPercentage >= ramObject.AlarmPercentage) { AlarmCount += 1; } else { AlarmCount = 0; } AlarmChecker(ramObject); Thread.Sleep(ramObject.SleepTime); } else { LogUtil.WriteLog(LogLevel.ERROR, "Cannot retreive ram value ! " + Environment.NewLine + "**** " + "Date:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); Thread.Sleep(ramObject.SleepTime); } } }
public static ArrayList SystemProfileForHost(SUHost host) { ArrayList profile = new ArrayList(); // App name profile.Add(DictionaryForProfileItem("appName", SULocalizedStrings.StringForKey("Application Name"), host.Name, host.Name)); // App version profile.Add(DictionaryForProfileItem("appVersion", SULocalizedStrings.StringForKey("Application Version"), host.Version, host.Version)); // System version string version = Environment.OSVersion.ToString(); profile.Add(DictionaryForProfileItem("osVersion", SULocalizedStrings.StringForKey("OS Version"), version, version)); //.NET version string frameworkVersion = Environment.Version.ToString(); profile.Add(DictionaryForProfileItem("dotNetVersion", SULocalizedStrings.StringForKey(".NET Version"), frameworkVersion, frameworkVersion)); // 64-bit? if (Environment.Is64BitOperatingSystem) { profile.Add(DictionaryForProfileItem("cpu64bit", SULocalizedStrings.StringForKey("CPU is 64-Bit?"), "true", SULocalizedStrings.StringForKey("Yes"))); } else { profile.Add(DictionaryForProfileItem("cpu64bit", SULocalizedStrings.StringForKey("CPU is 64-Bit?"), "false", SULocalizedStrings.StringForKey("No"))); } // CPU Count profile.Add(DictionaryForProfileItem("ncpu", SULocalizedStrings.StringForKey("Number of CPUs"), Environment.ProcessorCount.ToString(), Environment.ProcessorCount.ToString())); // RAM ulong installedMemory = 0; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { installedMemory = memStatus.ullTotalPhys / 1024 / 1024; } profile.Add(DictionaryForProfileItem("ramMB", SULocalizedStrings.StringForKey("Memory (MB)"), installedMemory.ToString(), installedMemory.ToString())); return profile; }
public Capacity Index() { var memStatus = new MEMORYSTATUSEX(); if (!GlobalMemoryStatusEx(memStatus)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var drive = new DriveInfo(ContainerServiceFactory.GetContainerRoot()); return new Capacity { MemoryInBytes = memStatus.ullTotalPhys, DiskInBytes = (ulong) drive.TotalSize, MaxContainers = MaxContainers, }; }
internal static void WriteSystemInformation() { Logger.Info("Assembly Version: " + Assembly.GetExecutingAssembly().GetName().Version); Logger.Info("OS: " + GaDotNet.Common.Helpers.AnalyticsHelper.GetFriendlyOsVersion()); Logger.Info("Architecture: " + GetOSArchitecture()); Logger.Info("Processor count: " + Environment.ProcessorCount.ToString(CultureInfo.InvariantCulture)); // RAM var memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { ulong installedMemory = memStatus.ullTotalPhys; Logger.Info("Installed RAM: " + (installedMemory / 1024 / 1024).ToString("0,000", CultureInfo.InvariantCulture) + "mb"); Logger.Info("Available RAM: " + (memStatus.ullAvailPhys / 1024 / 1024).ToString("0,000", CultureInfo.InvariantCulture) + "mb"); } }
public static string LogException(Exception exception) { var error = new StringBuilder(); error.AppendLine("Application: " + Application.ProductName); error.AppendLine("Version: " + Application.ProductVersion); error.AppendLine("Date: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")); error.AppendLine("Computer name: " + SystemInformation.ComputerName); error.AppendLine("User name: " + SystemInformation.UserName); error.AppendLine("OS: " + Environment.OSVersion); error.AppendLine("Culture: " + CultureInfo.CurrentCulture.Name); error.AppendLine("System up time: " + GetSystemUpTime()); error.AppendLine("App up time: " + (DateTime.Now - Process.GetCurrentProcess().StartTime)); var memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { error.AppendLine("Total memory: " + memStatus.ullTotalPhys / (1024 * 1024) + "Mb"); error.AppendLine("Available memory: " + memStatus.ullAvailPhys / (1024 * 1024) + "Mb"); } error.AppendLine(""); error.AppendLine("Exception classes: "); error.Append(GetExceptionTypeStack(exception)); error.AppendLine(""); error.AppendLine("Exception messages: "); error.Append(GetExceptionMessageStack(exception)); error.AppendLine(""); error.AppendLine("Stack Traces:"); error.Append(GetExceptionCallStack(exception)); error.AppendLine(""); error.AppendLine("Loaded Modules:"); Process thisProcess = Process.GetCurrentProcess(); foreach (ProcessModule module in thisProcess.Modules) { error.AppendLine(module.FileName + " " + module.FileVersionInfo.FileVersion); } return error.ToString(); }
public long GetValue() { ulong installedMemory = 0; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { installedMemory = memStatus.ullTotalPhys / 1024; } long result; try { result = Convert.ToInt64(installedMemory); //Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", installedMemory.GetType().Name, installedMemory, result.GetType().Name, result); } catch (OverflowException exception) { throw; //Console.WriteLine("The {0} value {1} is outside the range of the UInt64 type.", installedMemory.GetType().Name, installedMemory); } return result; }
public static long GetFreeMemory() { if (IsRuningOnWindows()) { if (IsRuningOnWindows()) { MEMORYSTATUSEX meminfo = new MEMORYSTATUSEX(); GlobalMemoryStatusEx(meminfo); return Convert.ToInt64(meminfo.ullAvailPhys); } } var value = readFile(); if (String.IsNullOrEmpty(value)) return 0; return Int64.Parse(value) * 1024; }
public ulong GetTotalMemory() { if (installedMemory == 0) { var memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) installedMemory = memStatus.ullTotalPhys; } return installedMemory/1024/1024; }
public void ReportError(Exception exception, string state) { var errorReport = new ExceptionInfo { Message = exception.Message, StackTrace = GetExceptionStackTrace(exception), ErrorType = exception.GetType().ToString(), Timestamp = DateTime.UtcNow, ProcessMemory = GC.GetTotalMemory(true), IsServiceRunning = ServiceConnection.Current.IsConnected, IsAdministrator = User.IsAdministrator, ProcessPath = Consts.ApplicationPath, #if NET35 Is64BitSystem = EnvironmentExtensions.Is64BitOperatingSystem, Is64BitProcess = EnvironmentExtensions.Is64BitProcess, #else Is64BitSystem = Environment.Is64BitOperatingSystem, Is64BitProcess = Environment.Is64BitProcess, #endif RuntimeVersion = Environment.Version.ToString(), State = state, ClientVersion = Program.Version }; var memStatus = new MEMORYSTATUSEX(); if (NativeMethods.GlobalMemoryStatusEx(memStatus)) { errorReport.TotalMemory = memStatus.ullTotalPhys; errorReport.AvailableMemory = memStatus.ullAvailPhys; } try { using (var searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem")) errorReport.OsName = searcher.Get().OfType <ManagementObject>().FirstOrDefault()?["Caption"].ToString(); } catch (Exception) { // ignored } if (string.IsNullOrEmpty(errorReport.OsName)) { errorReport.OsName = Environment.OSVersion.ToString(); } var serializer = new Serializer(typeof(List <ExceptionInfo>)); // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(_errorFile)); lock (_fileLock) using (var fileStream = new FileStream(_errorFile, FileMode.OpenOrCreate, FileAccess.Write)) using (var streamWriter = new StreamWriter(fileStream)) streamWriter.WriteLine(Convert.ToBase64String(serializer.Serialize(errorReport))); IsDataAvailable = true; ExceptionsAvailable?.Invoke(this, EventArgs.Empty); }
private static extern bool GlobalMemoryStatusExNative(ref MEMORYSTATUSEX lpBuffer);
static extern internal bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
internal extern static int GlobalMemoryStatusEx(ref MEMORYSTATUSEX memoryStatusEx);
internal static extern Boolean GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
/// <summary>获取实时数据,如CPU、内存、温度</summary> public void Refresh() { #if __CORE__ if (Runtime.Windows) { //var str = ""; //var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage"); //if (cpu != null) //{ // if (cpu.TryGetValue("Name", out str)) Processor = str; // if (cpu.TryGetValue("ProcessorId", out str)) CpuID = str; // if (cpu.TryGetValue("LoadPercentage", out str)) CpuRate = (Single)(str.ToDouble() / 100); //} MEMORYSTATUSEX ms = default; ms.Init(); if (GlobalMemoryStatusEx(ref ms)) { Memory = ms.ullTotalPhys; AvailableMemory = ms.ullAvailPhys; } } // 特别识别Linux发行版 else if (Runtime.Linux) { var str = ""; var dic = ReadInfo("/proc/meminfo"); if (dic != null) { if (dic.TryGetValue("MemTotal", out str)) { Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } if (dic.TryGetValue("MemAvailable", out str) || dic.TryGetValue("MemFree", out str)) { AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } } var file = "/sys/class/thermal/thermal_zone0/temp"; if (File.Exists(file)) { Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000; } else { // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39 file = "/sys/class/hwmon/hwmon0/device/temp_value"; if (File.Exists(file)) { Temperature = File.ReadAllText(file).Trim().Substring(null, ":").ToDouble(); } } //var upt = Execute("uptime"); //if (!upt.IsNullOrEmpty()) //{ // str = upt.Substring("load average:"); // if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble(); //} file = "/proc/loadavg"; if (File.Exists(file)) { CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble(); } } #else AvailableMemory = _cinfo.AvailablePhysicalMemory; //if (_cpuCounter != null) // CpuRate = _cpuCounter.NextValue() / 100; //else // CpuRate = (Single)GetInfo("Win32_PerfFormattedData_PerfOS_Processor where name='_Total'", "PercentProcessorTime").ToDouble() / 100; #endif if (Runtime.Windows) { GetSystemTimes(out var idleTime, out var kernelTime, out var userTime); var current = new SystemTime { IdleTime = idleTime.ToLong(), KernelTime = kernelTime.ToLong(), UserTime = userTime.ToLong(), }; if (_systemTime != null) { var idle = current.IdleTime - _systemTime.IdleTime; var kernel = current.KernelTime - _systemTime.KernelTime; var user = current.UserTime - _systemTime.UserTime; var total = kernel + user; CpuRate = total == 0 ? 0 : (Single)((Double)(total - idle) / total); } _systemTime = current; } }
/// <summary>刷新</summary> public void Init() { #if __CORE__ var osv = Environment.OSVersion; OSVersion = osv.Version + ""; OSName = (osv + "").TrimStart("Microsoft").TrimEnd(OSVersion).Trim(); if (Runtime.Windows) { var str = Execute("wmic", "cpu get ProcessorId"); if (!str.IsNullOrEmpty()) { CpuID = str.TrimStart("ProcessorId").Trim(); } str = Execute("wmic", "cpu get name"); if (!str.IsNullOrEmpty()) { Processor = str.TrimStart("Name").Trim(); } str = Execute("wmic", "csproduct get UUID"); if (!str.IsNullOrEmpty()) { UUID = str.TrimStart("UUID").Trim(); } str = Execute("wmic", "os get Caption"); if (!str.IsNullOrEmpty()) { OSName = str.TrimStart("Caption").TrimStart("Microsoft").Trim(); } str = Execute("wmic", "os get Version"); if (!str.IsNullOrEmpty()) { OSVersion = str.TrimStart("Version").Trim(); } MEMORYSTATUSEX ms = default; ms.Init(); if (GlobalMemoryStatusEx(ref ms)) { Memory = ms.ullTotalPhys; AvailableMemory = ms.ullAvailPhys; } } // 特别识别Linux发行版 else if (Runtime.Linux) { OSName = GetLinuxName(); var str = ""; // 树莓派优先 Model var dic = ReadInfo("/proc/cpuinfo"); if (dic != null) { if (dic.TryGetValue("Model", out str) || dic.TryGetValue("Hardware", out str) || dic.TryGetValue("cpu model", out str) || dic.TryGetValue("model name", out str)) { Processor = str; } if (dic.TryGetValue("Serial", out str)) { CpuID = str; } } dic = ReadInfo("/proc/meminfo"); if (dic != null) { if (dic.TryGetValue("MemTotal", out str)) { Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } if (dic.TryGetValue("MemAvailable", out str) || dic.TryGetValue("MemFree", out str)) { AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } } var file = "/sys/class/thermal/thermal_zone0/temp"; if (File.Exists(file)) { Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000; } var dmi = Execute("dmidecode")?.SplitAsDictionary(":", "\n"); if (dmi != null) { if (dmi.TryGetValue("ID", out str)) { CpuID = str.Replace(" ", null); } if (dmi.TryGetValue("UUID", out str)) { UUID = str; } //if (TryFind(dmi, new[] { "Serial Number" }, out str)) Guid = str; } } #else // 性能计数器的初始化非常耗时 Task.Factory.StartNew(() => { _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total") { MachineName = "." }; _cpuCounter.NextValue(); }); var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); if (reg != null) { Guid = reg.GetValue("MachineGuid") + ""; } if (Guid.IsNullOrEmpty()) { reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); if (reg != null) { Guid = reg.GetValue("MachineGuid") + ""; } } var ci = new ComputerInfo(); OSName = ci.OSFullName.TrimStart("Microsoft").Trim(); OSVersion = ci.OSVersion; Memory = ci.TotalPhysicalMemory; _cinfo = ci; Processor = GetInfo("Win32_Processor", "Name"); CpuID = GetInfo("Win32_Processor", "ProcessorId"); UUID = GetInfo("Win32_ComputerSystemProduct", "UUID"); // 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现 var str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature"); if (!str.IsNullOrEmpty()) { Temperature = (str.ToDouble() - 2732) / 10.0; } #endif }
private static extern int GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
static void Main() { TcpListener tcp = null; try { tcp = new TcpListener(IPAddress.Any, 65535); tcp.Start(); } catch { MessageBox.Show("The port 65535 cannot be binded to, make sure it is open and another process is not already using it.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } bool free = false; List <int> Intermediate = new List <int>(256); int[] Proc = new int[0]; ISAAC isaac = new ISAAC(); isaac.Isaac(); MouseEventHandler dMove = delegate(object sender, MouseEventArgs e) { total += 2; Intermediate.Add(e.X); Intermediate.Add(e.Y); }; MouseEventHandler dDown = delegate(object sender, MouseEventArgs e) { total++; if (e.Button == MouseButtons.Left) { Intermediate.Add(0x00); } else if (e.Button == MouseButtons.Middle) { Intermediate.Add(0x01); } else if (e.Button == MouseButtons.Right) { Intermediate.Add(0x02); } else { Intermediate.Add(0x03); } }; MouseEventHandler dWheel = delegate(object sender, MouseEventArgs e) { total++; Intermediate.Add(e.Delta); }; KeyEventHandler dKey = delegate(object sender, KeyEventArgs e) { total++; Intermediate.Add(e.KeyValue); }; HookManager.MouseMove += dMove; HookManager.MouseDown += dDown; HookManager.MouseWheel += dWheel; HookManager.KeyDown += dKey; NotifyIcon ico = new NotifyIcon(); ico.Icon = Properties.Resources.wec; ContextMenu cm = new ContextMenu(); MenuItem cm1 = new MenuItem("Exit..."); cm1.DefaultItem = true; cm1.Click += delegate { free = true; }; cm.MenuItems.Add(cm1); ico.ContextMenu = cm; ico.Text = "Windows Entropy Collection"; ico.MouseClick += delegate(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ico.ShowBalloonTip(3, "Stats", "Entropy collected: " + total + "b\r\nTumbled " + tumble + " times", ToolTipIcon.Info); } }; ico.Visible = true; BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += delegate { while (!weregoingdownbuddy) { total += 3; Intermediate.Add(Cursor.Position.X); Intermediate.Add(Cursor.Position.Y); Intermediate.Add((int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { total += 3; Intermediate.Add((int)memStatus.ullAvailPhys); Intermediate.Add((int)memStatus.ullAvailVirtual); Intermediate.Add((int)memStatus.ullAvailPageFile); } memStatus = null; tumbling = true; Proc = Intermediate.ToArray(); Intermediate.Clear(); for (int i = 0; i < Proc.Length; i++) { isaac.mem[i % ISAAC.SIZE] = isaac.mem[i % ISAAC.SIZE] ^ Proc[i]; } isaac.Isaac(); tumbling = false; entropyindex = 0; bindex = 0; tumble++; for (int i = 0; i < 10; i++) { if (weregoingdownbuddy) { break; } Thread.Sleep(100); } //Check for exit every 100ms for 10 seconds until the next tumble } itsbeenapleasuretoprocesswithyou = true; }; bg.RunWorkerAsync(); BackgroundWorker serve = new BackgroundWorker(); serve.DoWork += delegate { while (!weregoingdownbuddy) { if (tcp.Pending() == true) { TcpClient client = tcp.AcceptTcpClient(); NetworkStream st = client.GetStream(); st.WriteByte(0x06); //ACK (Acknowledgment) try { if (tumble > 2) //Make sure we have tumbled data available and to an acceptable degree, otherwise we would be feeding possibly predictable data { int wait = 100; while (tumbling) { Thread.Sleep(10); } while (client.Available < 1) { wait--; if (wait < 1) { break; } Thread.Sleep(10); } //Wait for the client to send us the amount of entropy to release if (wait > 0) //If we havent timed out release the requested amount of entropy, if that amount of entropy isn't available just release whatever we have { int num = (int)st.ReadByte(); int max = ISAAC.SIZE * 4; for (int i = 0; i < num && i < max; i++) { byte b = 0; if (bindex == 0) { b = (byte)((isaac.rsl[entropyindex] & 0xFF000000) >> 24); bindex++; } else if (bindex == 1) { b = (byte)((isaac.rsl[entropyindex] & 0x00FF0000) >> 16); bindex++; } else if (bindex == 2) { b = (byte)((isaac.rsl[entropyindex] & 0x0000FF00) >> 8); bindex++; } else if (bindex == 3) { b = (byte)((isaac.rsl[entropyindex] & 0x000000FF)); bindex = 0; entropyindex++; } st.WriteByte(b); } } } st.WriteByte(0x04); //EOT (End of Transmission) } catch { } st.Close(); } Thread.Sleep(10); } }; serve.RunWorkerAsync(); while (!free) { Application.DoEvents(); Thread.Sleep(5); } HookManager.MouseMove -= dMove; HookManager.MouseDown -= dDown; HookManager.MouseWheel -= dWheel; HookManager.KeyDown -= dKey; weregoingdownbuddy = true; while (!itsbeenapleasuretoprocesswithyou) { Thread.Sleep(100); } ico.Dispose(); tcp.Stop(); }
private void GetInfo() { lOEM.Clear(); lSoftware.Clear(); lUSB.Clear(); string ia; try { ManagementObjectCollection moReturn; ManagementObjectSearcher moSearch; moSearch = new ManagementObjectSearcher("Select * from Win32_OperatingSystem"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { try { if (mo["ProductType"] != null) { ia = CheckTypeOS(Convert.ToInt32(mo["ProductType"].ToString())); } else { ia = ""; } TypeSystem = ia; } catch { } } //NET lOEM.Add("-= NET =-"); lOEM.Add(TypeSystem + ": " + System.Net.Dns.GetHostName()); lOEM.Add("IP: " + GetLocalIPAddress()); lOEM.Add(""); //CPU lOEM.Add("-= CPU =-"); moSearch = new ManagementObjectSearcher("Select Name,ProcessorID,SocketDesignation from Win32_Processor"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { ia = mo["Name"].ToString().Trim().ToUpper(); // Model += ia + " "; lOEM.Add("Name: " + ia); try { ia = mo["ProcessorID"].ToString().Trim().ToUpper(); lOEM.Add("ProcessorID: " + ia); ia = mo["SocketDesignation"].ToString().Trim().ToUpper(); if (!ia.ToUpper().Contains("N/A")) { lOEM.Add("SocketDesignation: " + ia); } } catch { } lOEM.Add(""); } //Motherboard lOEM.Add("-= Motherboard =-"); moSearch = new ManagementObjectSearcher("Select * from Win32_BaseBoard");//Manufacturer,Model,Product,Version,SerialNumber,OtherIdentifyingInfo,PartNumber moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { ia = mo["Manufacturer"].ToString().Trim().ToUpper(); Manufacturer += ia + " "; lOEM.Add("Manufacturer: " + ia); try { ia = mo["Model"].ToString().Trim().ToUpper(); lOEM.Add("Model: " + ia); } catch { } try { ia = mo["OtherIdentifyingInfo"].ToString().Trim().ToUpper(); lOEM.Add("OtherIdentifyingInfo: " + ia); } catch { } ia = mo["Product"].ToString().Trim().ToUpper(); Model += "MB: " + ia + " "; lOEM.Add("Product: " + ia); try { ia = mo["PartNumber"].ToString().Trim().ToUpper(); lOEM.Add("PartNumber: " + ia); } catch { } ia = mo["Version"].ToString().Trim().ToUpper(); if (!ia.ToUpper().Contains("N/A")) { lOEM.Add("Version: " + ia); } ia = mo["SerialNumber"].ToString().Trim().ToUpper(); if (!ia.ToUpper().Contains("SERIAL NUMBER") && !ia.ToUpper().Contains("N/A") && !ia.ToUpper().Contains("O.E.M.") && !ia.ToUpper().Contains("EMPTY") && ia.Trim().Length > 1) { lOEM.Add("Serial Number: " + ia); } lOEM.Add(""); } //BIOS lOEM.Add("-= BIOS =-"); moSearch = new ManagementObjectSearcher("Select SerialNumber,Manufacturer,SMBIOSBIOSVersion,Version from Win32_BIOS"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { ia = mo["Manufacturer"].ToString().Trim().ToUpper(); lOEM.Add("Manufacturer: " + ia); ia = mo["SMBIOSBIOSVersion"].ToString().Trim().ToUpper(); lOEM.Add("SMBIOSBIOSVersion: " + ia); ia = mo["Version"].ToString().Trim().ToUpper(); lOEM.Add("Version: " + ia); ia = mo["SerialNumber"].ToString().Trim().ToUpper(); if (!ia.ToUpper().Contains("SERIAL NUMBER") && !ia.ToUpper().Contains("O.E.M.") && !ia.ToUpper().Contains("EMPTY") && ia.Trim().Length > 1) { lOEM.Add("Serial Number: " + ia); } lOEM.Add(""); } //Video lOEM.Add("-= Video =-"); moSearch = new ManagementObjectSearcher("Select Caption,AdapterRAM,DriverVersion,AdapterDACType from Win32_VideoController"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { try { ia = mo["Caption"].ToString().Trim().ToUpper(); Model += @" Video: " + ia + " "; lOEM.Add("Caption: " + ia); } catch { } try { double ib = Convert.ToDouble(mo["AdapterRAM"].ToString().Trim()) / 1024 / 1024; lOEM.Add("Adapter RAM, MB: " + ib.ToString("#.##") + " MB"); ia = mo["DriverVersion"].ToString().Trim().ToUpper(); lOEM.Add("Driver Version: " + ia); ia = mo["AdapterDACType"].ToString().Trim().ToUpper(); lOEM.Add("AdapterDACType: " + ia); } catch { } lOEM.Add(""); } //RAM lOEM.Add("-= RAM =-"); ulong installedMemory; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { installedMemory = memStatus.ullTotalPhys; lOEM.Add("Available Memory: " + Math.Round((double)installedMemory / 1024 / 1024, 0) + " MB"); } moSearch = new ManagementObjectSearcher("Select * from Win32_PhysicalMemory"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { string sMod = ""; try { sMod = ", Model - " + mo["Model"].ToString().ToUpper().Trim(); } catch { } try { if (!mo["SerialNumber"].ToString().ToUpper().Contains("SERNUM") && mo["SerialNumber"].ToString().Trim().Length < 2) { sMod += ", s/n - " + mo["SerialNumber"].ToString().ToUpper().Trim(); } } catch { } try { double dSpeed = Convert.ToDouble(mo["Speed"].ToString().Trim()); if (dSpeed > 10) { sMod += ", Type - " + dSpeed + " "; } else { sMod += ", Freq - " + Math.Round((1000 / dSpeed), 0) + " MHz"; } } catch { } lOEM.Add("banklabel: " + mo["banklabel"].ToString().ToUpper().Trim() + " " + (Convert.ToDouble(mo["Capacity"].ToString().Trim()) / 1024 / 1024).ToString("#") + " MB, Type - " + CheckTypeMemory(Convert.ToInt32(mo["MemoryType"].ToString().Trim())) + ", Formfactor - " + CheckFormFactorMemory(Convert.ToInt32(mo["FormFactor"].ToString().Trim()))); if (sMod.Trim().Length > 1) { lOEM.Add(" " + sMod); } } //RAM Win32_PhysicalMemoryArray moSearch = new ManagementObjectSearcher("Select * from Win32_PhysicalMemoryArray"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { if (mo["MaxCapacity"].ToString().Trim().Length < 0) { lOEM.Add("Maximum size: " + (Convert.ToDouble(mo["MaxCapacity"].ToString().Trim()) / 1024 / 1024).ToString("#") + " GB"); } } lOEM.Add(""); //Mass Storage lOEM.Add("-= Mass Storage =-"); moSearch = new ManagementObjectSearcher("Select * from Win32_DiskDrive"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { try { ia = mo["Caption"].ToString().ToUpper(); lOEM.Add("Caption: " + ia); } catch { } try { double ib = Convert.ToDouble(mo["Size"].ToString().Trim()) / 1024 / 1024 / 1024; lOEM.Add("Size: " + ib.ToString("#.##") + " GB, " + "InterfaceType: " + mo["InterfaceType"].ToString().ToUpper().Trim()); } catch { } try { ia = mo["Signature"].ToString().ToUpper().Trim(); // lOEM.Add("Signature: " + ia); ia = mo["Partitions"].ToString().ToUpper().Trim(); // lOEM.Add("Partitions: " + ia); } catch { } try { ia = mo["SerialNumber"].ToString().Trim().ToUpper(); lOEM.Add("SerialNumber: " + ia); } catch { } try { // ia = mo["MediaType"].ToString().ToUpper(); // lOEM.Add("MediaType: " + ia); } catch { } lOEM.Add(""); } //OS lOEM.Add("-= OS =-"); moSearch = new ManagementObjectSearcher("Select * from Win32_OperatingSystem"); moReturn = moSearch.Get(); foreach (ManagementObject mo in moReturn) { if (mo["Caption"] != null) { ia = mo["Caption"].ToString().Trim().ToUpper(); } else { ia = ""; } lOEM.Add("Name: " + ia); if (mo["OperatingSystemSKU"] != null) { ia = CheckTypeProductOS(Convert.ToInt32(mo["OperatingSystemSKU"].ToString().Trim())); } else { ia = ""; } lOEM.Add("Product Info: " + ia); if (mo["CSDVersion"] != null) { ia = mo["CSDVersion"].ToString().Trim().ToUpper(); } else { ia = ""; } if (mo["Version"] != null) { ia += "." + mo["Version"].ToString().Trim().ToUpper(); } else { ia += ""; } if (mo["BuildNumber"] != null) { ia += "." + mo["BuildNumber"].ToString().Trim().ToUpper(); } else { ia += ""; } lOEM.Add("SP: " + ia); if (mo["OSArchitecture"] != null) { ia = mo["OSArchitecture"].ToString().Trim().ToUpper(); } else { ia = ""; } lOEM.Add("OS Arch: " + ia); if (mo["ProductType"] != null) { ia = CheckTypeOS(Convert.ToInt32(mo["ProductType"].ToString().Trim())); } else { ia = ""; } lOEM.Add("Type of System: " + ia); TypeSystem = ia; if (mo["SystemDirectory"] != null) { ia = mo["SystemDirectory"].ToString().Trim().ToUpper(); } else { ia = ""; } lOEM.Add("System directory of OS: " + ia); WindowsPath = ia; var key = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64); key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false); if (key != null) { DateTime startDate = new DateTime(1970, 1, 1, 0, 0, 0); object objValue = key.GetValue("InstallDate"); //InstallTime string stringValue = objValue.ToString(); Int64 regVal = Convert.ToInt64(stringValue); DateTime installDate = startDate.AddSeconds(regVal); ia = installDate.ToString("yyyy-MM-dd HH:MM"); } lOEM.Add("Install Date: " + ia); if (mo["LastBootUpTime"] != null) { ia = mo["LastBootUpTime"].ToString(); } else { ia = ""; } DateTime LastBootUpTime = ManagementDateTimeConverter.ToDateTime(ia); lOEM.Add("Last BootUp Time: " + LastBootUpTime.ToString("yyyy-MM-dd HH:MM")); double dDay = 0; string sUpTime = ""; if (UpTime.TotalHours / 24 > 1) { dDay = Math.Round(UpTime.TotalHours / 24, 0); } if (dDay > 0) { sUpTime = dDay.ToString() + " days and " + (UpTime.TotalHours - dDay * 24).ToString("#.##" + " hours"); } else { sUpTime = UpTime.TotalHours.ToString("#.##" + " hours"); } lOEM.Add("Up Time: " + sUpTime); } moSearch.Dispose(); moReturn.Dispose(); } catch (Exception expt) { MessageBox.Show(expt.ToString()); } GetOtherSoftwareInfo(); SearchUSB(); }
public static string LogException(Exception exception) { try { if (exception == null) { return(null); } StringBuilder error = new StringBuilder(); error.AppendLine("Application: " + Application.ProductName); error.AppendLine("Version: " + Application.ProductVersion); error.AppendLine("Date: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); error.AppendLine("Computer name: " + SystemInformation.ComputerName); error.AppendLine("User name: " + SystemInformation.UserName); error.AppendLine("OS: " + Environment.OSVersion.ToString()); error.AppendLine("Culture: " + CultureInfo.CurrentCulture.Name); error.AppendLine("Resolution: " + SystemInformation.PrimaryMonitorSize.ToString()); error.AppendLine("System up time: " + GetSystemUpTime()); error.AppendLine("App up time: " + (DateTime.Now - Process.GetCurrentProcess().StartTime).ToString()); MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { error.AppendLine("Total memory: " + memStatus.ullTotalPhys / (1024 * 1024) + "Mb"); error.AppendLine("Available memory: " + memStatus.ullAvailPhys / (1024 * 1024) + "Mb"); } error.AppendLine(""); error.AppendLine("Exception classes: "); error.Append(GetExceptionTypeStack(exception)); error.AppendLine(""); error.AppendLine("Exception messages: "); error.Append(GetExceptionMessageStack(exception)); error.AppendLine(""); error.AppendLine("Stack Traces:"); error.Append(GetExceptionCallStack(exception)); error.AppendLine(""); //error.AppendLine("Loaded Modules:"); //Process thisProcess = Process.GetCurrentProcess(); //foreach (ProcessModule module in thisProcess.Modules) //{ // try // { // error.AppendLine(module.FileName + " " + module.FileVersionInfo.FileVersion); // } // catch // { // error.AppendLine(module.FileName); // } //} return(error.ToString()); } catch (Exception ex) { MessageBox.Show("LOG发生异常 - " + ex.Message); return(null); } }
internal extern static int GlobalMemoryStatusEx(out MEMORYSTATUSEX lpBuffer);
public static extern void GlobalMemoryStatusEx(out MEMORYSTATUSEX lpBuffer);
public Main() { InitializeComponent(); CompressionLevelCbo.Items.AddRange(new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); ConsoleColorCbo.DataSource = Enum.GetValues(typeof(ConsoleColor)).Cast <ConsoleColor>(); ulong totalmemB = 0; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { totalmemB = memStatus.ullTotalPhys; } int usableMemory; try { usableMemory = Convert.ToInt32((totalmemB / (1024 * 1024)) - ((totalmemB / (1024 * 1024)) % 256)); } catch { usableMemory = int.MaxValue - (int.MaxValue % 256); } MinRamSlider.Maximum = usableMemory / 256; MinRamSlider.Minimum = 0; MinRamSlider.SmallChange = 1; MinRamSlider.TickFrequency = 1; MinRamText.Text = (MinRamSlider.Value * 256).ToString(); MaxRamSlider.Maximum = usableMemory / 256; MaxRamSlider.Minimum = 0; MaxRamSlider.SmallChange = 1; MaxRamSlider.TickFrequency = 1; MaxRamText.Text = (MinRamSlider.Value * 256).ToString(); CurrentSettings = new Settings(); try { if (!Directory.Exists(@"Wrapper")) { Directory.CreateDirectory(@"Wrapper"); } } catch (Exception ex) { ExceptionMessage.PrintException(ex, "Error creating wrapper directory."); return; } CurrentSettings = new Settings(); ServerPath.Text = CurrentSettings.ServerPath; MinRamSlider.Value = CurrentSettings.MinRam / 256; MinRamText.Text = CurrentSettings.MinRam + " MB"; MaxRamSlider.Value = CurrentSettings.MaxRam / 256; MaxRamText.Text = CurrentSettings.MaxRam + " MB"; SameMaxMin.Checked = CurrentSettings.SameMaxMin; BackupSource.Text = CurrentSettings.BackupSource; BackupLocation.Text = CurrentSettings.BackupLocation; BackupInterval.Value = CurrentSettings.BackupInterval; BackupNumber.Value = CurrentSettings.BackupNumber; ConsoleColorCbo.SelectedItem = CurrentSettings.WrapperColor; CompressionLevelCbo.SelectedItem = CurrentSettings.ZipCompressionLevel; ShowRamCpuUsage.Checked = CurrentSettings.ShowCpuRamUsage; if (string.IsNullOrWhiteSpace(ServerPath.Text)) { string[] files = Directory.GetFiles(Path.GetDirectoryName(Application.ExecutablePath)); foreach (string file in files) { if (file.ToLower().Contains("minecraft_server") && file.ToLower().EndsWith(".jar")) { ServerPath.Text = file; return; } } } }
public static extern void GlobalMemoryStatusEx(ref MEMORYSTATUSEX stat);
public static extern bool GlobalMemoryStatusEx(out MEMORYSTATUSEX stat);
public WindowsHardware() { // Get memory MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { // Convert from bytes -> megabytes this._memoryTotal = memStatus.ullTotalPhys / 1024 / 1024; this._memoryFree = memStatus.ullAvailPhys / 1024 / 1024; } // Get disk space foreach (DriveInfo di in DriveInfo.GetDrives()) { if (di.IsReady && di.DriveType == DriveType.Fixed) { this._diskFree += di.TotalFreeSpace / 1024 / 1024; this._diskTotal += di.TotalSize / 1024 / 1024; } } ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name, Manufacturer, Architecture FROM Win32_Processor"); foreach (ManagementObject sysItem in searcher.Get()) { try { this._cpuName = sysItem["Name"].ToString(); if (!string.IsNullOrEmpty(this._cpuName)) { this._cpuName = this._cpuName.Replace("(TM)", ""); this._cpuName = this._cpuName.Replace("(R)", ""); this._cpuName = this._cpuName.Replace(" ", ""); } } catch { this._cpuName = "Unknown"; } try { this._cpuBrand = sysItem["Manufacturer"].ToString(); } catch { this._cpuBrand = "Unknown"; } try { int arch = Convert.ToInt32(sysItem["Architecture"].ToString()); if (arch == 6 || arch == 9) { this._cpuArch = 64; } else { this._cpuArch = 32; } } catch { this._cpuArch = 32; } } }
/// <summary>获取实时数据,如CPU、内存、温度</summary> public void Refresh() { #if __CORE__ if (Runtime.Windows) { var str = ""; var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage"); if (cpu != null) { if (cpu.TryGetValue("Name", out str)) { Processor = str; } if (cpu.TryGetValue("ProcessorId", out str)) { CpuID = str; } if (cpu.TryGetValue("LoadPercentage", out str)) { CpuRate = (Single)(str.ToDouble() / 100); } } MEMORYSTATUSEX ms = default; ms.Init(); if (GlobalMemoryStatusEx(ref ms)) { Memory = ms.ullTotalPhys; AvailableMemory = ms.ullAvailPhys; } } // 特别识别Linux发行版 else if (Runtime.Linux) { var str = ""; var dic = ReadInfo("/proc/meminfo"); if (dic != null) { if (dic.TryGetValue("MemTotal", out str)) { Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } if (dic.TryGetValue("MemAvailable", out str) || dic.TryGetValue("MemFree", out str)) { AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } } var file = "/sys/class/thermal/thermal_zone0/temp"; if (File.Exists(file)) { Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000; } else { // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39 file = "/sys/class/hwmon/hwmon0/device/temp_value"; if (File.Exists(file)) { Temperature = File.ReadAllText(file).Trim().Substring(null, ":").ToDouble(); } } var upt = Execute("uptime"); if (!upt.IsNullOrEmpty()) { str = upt.Substring("load average:"); if (!str.IsNullOrEmpty()) { CpuRate = (Single)str.Split(",")[0].ToDouble(); } } } #else AvailableMemory = _cinfo.AvailablePhysicalMemory; CpuRate = _cpuCounter == null ? 0 : (_cpuCounter.NextValue() / 100); #endif }
public static void LogEnvironmentInformation() { MyMwcLog.WriteLine("MyVideoModeManager.LogEnvironmentInformation - START"); MyMwcLog.IncreaseIndent(); try { ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor"); if (mos != null) { foreach (ManagementObject mo in mos.Get()) { MyMwcLog.WriteLine("Environment.ProcessorName: " + mo["Name"]); } } MyMwcLog.WriteLine("Environment.ProcessorCount: " + Environment.ProcessorCount); MyMwcLog.WriteLine("Environment.OSVersion: " + Environment.OSVersion); MyMwcLog.WriteLine("Environment.Is64BitOperatingSystem: " + Environment.Is64BitOperatingSystem); MyMwcLog.WriteLine("Environment.CommandLine: " + Environment.CommandLine); MyMwcLog.WriteLine("Environment.CurrentDirectory: " + Environment.CurrentDirectory); MyMwcLog.WriteLine("Environment.Version: " + Environment.Version); MyMwcLog.WriteLine("Environment.WorkingSet: " + MyValueFormatter.GetFormatedLong(Environment.WorkingSet) + " bytes"); // Get info about memory var memory = new MEMORYSTATUSEX(); GlobalMemoryStatusEx(memory); MyMwcLog.WriteLine("ComputerInfo.TotalPhysicalMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullTotalPhys) + " bytes"); MyMwcLog.WriteLine("ComputerInfo.TotalVirtualMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullTotalVirtual) + " bytes"); MyMwcLog.WriteLine("ComputerInfo.AvailablePhysicalMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullAvailPhys) + " bytes"); MyMwcLog.WriteLine("ComputerInfo.AvailableVirtualMemory: " + MyValueFormatter.GetFormatedLong((long)memory.ullAvailVirtual) + " bytes"); // Get info about hard drives ConnectionOptions oConn = new ConnectionOptions(); ManagementScope oMs = new ManagementScope("\\\\localhost", oConn); ObjectQuery oQuery = new ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3"); using (ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery)) { ManagementObjectCollection oReturnCollection = oSearcher.Get(); foreach (ManagementObject oReturn in oReturnCollection) { string capacity = MyValueFormatter.GetFormatedLong(Convert.ToInt64(oReturn["Size"])); string freeSpace = MyValueFormatter.GetFormatedLong(Convert.ToInt64(oReturn["FreeSpace"])); string name = oReturn["Name"].ToString(); MyMwcLog.WriteLine("Drive " + name + " | Capacity: " + capacity + " bytes | Free space: " + freeSpace + " bytes"); } oReturnCollection.Dispose(); } } catch (Exception e) { MyMwcLog.WriteLine("Error occured during enumerating environment information. Application is continuing. Exception: " + e.ToString()); } MyMwcLog.DecreaseIndent(); MyMwcLog.WriteLine("MyVideoModeManager.LogEnvironmentInformation - END"); }
private void CollectOnce() { lock (m_collectLock) { // This must be reacquired for every collection and may not be cached because some of the fields like memory // usage are only set in the Process() constructor Process currentProcess = Process.GetCurrentProcess(); // Compute the performance data double?machineCpu = 0.0; double?processCpu = GetProcessCpu(currentProcess); double processThreads = currentProcess.Threads.Count; double processPrivateBytes = currentProcess.PrivateMemorySize64; double processWorkingSetBytes = currentProcess.WorkingSet64; double processHeldBytes = m_collectHeldBytesFromGC ? GC.GetTotalMemory(forceFullCollection: true) : 0; double? machineAvailablePhysicalBytes = null; double? machineTotalPhysicalBytes = null; double? commitTotalBytes = null; double? commitLimitBytes = null; DISK_PERFORMANCE[] diskStats = null; if (!OperatingSystemHelper.IsUnixOS) { machineCpu = GetMachineCpu(); MEMORYSTATUSEX memoryStatusEx = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memoryStatusEx)) { machineAvailablePhysicalBytes = memoryStatusEx.ullAvailPhys; machineTotalPhysicalBytes = memoryStatusEx.ullTotalPhys; } PERFORMANCE_INFORMATION performanceInfo = PERFORMANCE_INFORMATION.CreatePerfInfo(); if (GetPerformanceInfo(out performanceInfo, performanceInfo.cb)) { commitTotalBytes = performanceInfo.CommitTotal.ToInt64() * performanceInfo.PageSize.ToInt64(); commitLimitBytes = performanceInfo.CommitLimit.ToInt64() * performanceInfo.PageSize.ToInt64(); } diskStats = GetDiskCounters(); } else { machineCpu = GetMachineCpuMacOS(); machineTotalPhysicalBytes = OperatingSystemHelper.GetPhysicalMemorySize().Bytes; machineAvailablePhysicalBytes = GetAvailablePhysicalBytesMacOS(); } // stop network monitor measurement and gather data m_networkMonitor?.StopMeasurement(); DateTime temp = DateTime.UtcNow; TimeSpan duration = temp - m_networkTimeLastCollectedAt; m_networkTimeLastCollectedAt = temp; double?machineKbitsPerSecSent = Math.Round(1000 * BytesToKbits(m_networkMonitor?.TotalSentBytes) / duration.TotalMilliseconds, 3); double?machineKbitsPerSecReceived = Math.Round(1000 * BytesToKbits(m_networkMonitor?.TotalReceivedBytes) / duration.TotalMilliseconds, 3); // Update the aggregators lock (m_aggregators) { foreach (var aggregator in m_aggregators) { aggregator.RegisterSample( processCpu: processCpu, processPrivateBytes: processPrivateBytes, processWorkingSetBytes: processWorkingSetBytes, threads: processThreads, machineCpu: machineCpu, machineTotalPhysicalBytes: machineTotalPhysicalBytes, machineAvailablePhysicalBytes: machineAvailablePhysicalBytes, commitTotalBytes: commitTotalBytes, commitLimitBytes: commitLimitBytes, machineBandwidth: m_networkMonitor?.Bandwidth, machineKbitsPerSecSent: machineKbitsPerSecSent, machineKbitsPerSecReceived: machineKbitsPerSecReceived, diskPerformance: diskStats, gcHeldBytes: processHeldBytes); } } // restart network monitor to start new measurement m_networkMonitor?.StartMeasurement(); } }
/// <summary> /// Init with a storage account /// </summary> /// <param name="account">Cloud Storage Account</param> public static ElasticsearchServiceSettings FromStorage(CloudStorageAccount account) { var settings = new ElasticsearchServiceSettings() { _StorageAccount = account, _NodeName = RoleEnvironment.CurrentRoleInstance.Id, _UseElasticLocalDataFolder = CloudConfigurationManager.GetSetting("UseElasticLocalDataFolder"), _JavaInstaller = CloudConfigurationManager.GetSetting("JavaInstallerName"), _JavaDownloadURL = CloudConfigurationManager.GetSetting("JavaDownloadURL"), _JavaDownloadType = CloudConfigurationManager.GetSetting("JavaDownloadType"), _ElasticsearchInstaller = CloudConfigurationManager.GetSetting("ElasticsearchZip"), _ElasticsearchDownloadURL = CloudConfigurationManager.GetSetting("ElasticsearchDownloadURL"), _ElasticsearchDownloadType = CloudConfigurationManager.GetSetting("ElasticsearchDownloadType"), _ElasticsearchPluginContainer = CloudConfigurationManager.GetSetting("ElasticsearchPluginContainer"), _DataShareName = CloudConfigurationManager.GetSetting("ShareName"), _DataShareDrive = CloudConfigurationManager.GetSetting("ShareDrive"), _EndpointName = CloudConfigurationManager.GetSetting("EndpointName"), _DownloadDirectory = RoleEnvironment.GetLocalResource("ArchiveRoot").RootPath, _LogDirectory = RoleEnvironment.GetLocalResource("LogRoot").RootPath, _DataDirectory = RoleEnvironment.GetLocalResource("ElasticDataRoot").RootPath, _ElasticsearchDirectory = RoleEnvironment.GetLocalResource("ElasticRoot").RootPath, _RootDirectory = Environment.GetEnvironmentVariable("ROLEROOT"), _TempDirectory = RoleEnvironment.GetLocalResource("CustomTempRoot").RootPath, _DataBootstrapDirectory = RoleEnvironment.GetLocalResource("DataBootstrapDirectory").RootPath, }; bool.TryParse(CloudConfigurationManager.GetSetting("EnableDataBootstrap"), out settings._EnableDataBootstrap); if (string.IsNullOrWhiteSpace(settings._DataBootstrapDirectory) && settings._EnableDataBootstrap) { settings._EnableDataBootstrap = false; } if (!settings._RootDirectory.EndsWith(@"\")) { settings._RootDirectory += @"\"; } //Set root to approot=App directory settings._RootDirectory = Path.Combine(settings._RootDirectory, "approot"); //Emulator does not copy webrole files to approot if (RoleEnvironment.IsEmulated && IsWebRole) { settings._RootDirectory = Path.Combine(settings._RootDirectory, "bin"); } //Calculate heap size MEMORYSTATUSEX memoryStatus = new MEMORYSTATUSEX(); GlobalMemoryStatusEx(memoryStatus); var totalPhycialBytesInMB = memoryStatus.ullTotalPhys / 1024L / 1024L; //TODO: calculate the lost result which could cause this to throw; settings._ComputedHeapSize = Convert.ToInt32(totalPhycialBytesInMB / 2); return settings; }
public extern static Boolean GlobalMemoryStatusEx( [In][Out] ref MEMORYSTATUSEX lpBuffer );
private static void GetMemoryStatus(out string totalMem, out string availMem) { var memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { totalMem = memStatus.ullTotalPhys/(1024*1024) + "Mb"; availMem = memStatus.ullAvailPhys/(1024*1024) + "Mb"; } else { totalMem = "N/A"; availMem = "N/A"; } }
internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer) { buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX)); return(GlobalMemoryStatusExNative(ref buffer)); }
/// <summary> /// On Windows systems running .NET, gets the total amount of installed physical memory. /// </summary> /// <returns>The total amount of installed physical memory on the system.</returns> private static ulong GetTotalPhysicalMemoryWin() { var memStatus = new MEMORYSTATUSEX(); return GlobalMemoryStatusEx(memStatus) ? memStatus.ullTotalPhys : 0; }
public static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
extern static void GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
/// <summary> /// On Windows systems running .NET, gets the total amount of installed physical memory. /// </summary> /// <returns>The total amount of installed physical memory on the system.</returns> private static ulong GetTotalPhysicalMemoryWin() { var memStatus = new MEMORYSTATUSEX(); return(GlobalMemoryStatusEx(memStatus) ? memStatus.ullTotalPhys : 0); }
public void Start() { Contract.Assume(!m_processStarted); Encoding reportEncoding = Encoding.Unicode; SafeFileHandle childHandle = null; DetouredProcess detouredProcess = m_detouredProcess; using (m_reportReaderSemaphore.AcquireSemaphore()) { SafeFileHandle reportHandle; try { Pipes.CreateInheritablePipe( Pipes.PipeInheritance.InheritWrite, Pipes.PipeFlags.ReadSideAsync, readHandle: out reportHandle, writeHandle: out childHandle); var setup = new FileAccessSetup { ReportPath = "#" + childHandle.DangerousGetHandle().ToInt64(), DllNameX64 = s_binaryPaths.DllNameX64, DllNameX86 = s_binaryPaths.DllNameX86, }; bool debugFlagsMatch = true; ArraySegment <byte> manifestBytes = new ArraySegment <byte>(); if (m_fileAccessManifest != null) { manifestBytes = m_fileAccessManifest.GetPayloadBytes(m_loggingContext, setup, FileAccessManifestStream, m_timeoutMins, ref debugFlagsMatch); } if (!debugFlagsMatch) { throw new BuildXLException("Mismatching build type for BuildXL and DetoursServices.dll."); } m_standardInputTcs = TaskSourceSlim.Create <bool>(); detouredProcess.Start( s_payloadGuid, manifestBytes, childHandle, s_binaryPaths.DllNameX64, s_binaryPaths.DllNameX86); // At this point, we believe calling 'kill' will result in an eventual callback for job teardown. // This knowledge is significant for ensuring correct cleanup if we did vs. did not start a process; // if started, we expect teardown to happen eventually and clean everything up. m_processStarted = true; ProcessId = detouredProcess.GetProcessId(); } catch (AccessViolationException) { int ramPercent = 0, availableRamMb = 0, availablePageFileMb = 0, totalPageFileMb = 0; MEMORYSTATUSEX memoryStatusEx = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memoryStatusEx)) { ramPercent = (int)memoryStatusEx.dwMemoryLoad; availableRamMb = new FileSize(memoryStatusEx.ullAvailPhys).MB; availablePageFileMb = new FileSize(memoryStatusEx.ullAvailPageFile).MB; totalPageFileMb = new FileSize(memoryStatusEx.ullTotalPageFile).MB; } string memUsage = $"RamPercent: {ramPercent}, AvailableRamMb: {availableRamMb}, AvailablePageFileMb: {availablePageFileMb}, TotalPageFileMb: {totalPageFileMb}"; Native.Tracing.Logger.Log.DetouredProcessAccessViolationException(m_loggingContext, (m_reports?.PipDescription ?? "") + " - " + memUsage); throw; } finally { // release memory m_fileAccessManifest = null; // Note that in the success path, childHandle should already be closed (by Start). if (childHandle != null && !childHandle.IsInvalid) { childHandle.Dispose(); } } var reportFile = AsyncFileFactory.CreateAsyncFile( reportHandle, FileDesiredAccess.GenericRead, ownsHandle: true, kind: FileKind.Pipe); StreamDataReceived reportLineReceivedCallback = m_reports == null ? (StreamDataReceived)null : ReportLineReceived; m_reportReader = new AsyncPipeReader(reportFile, reportLineReceivedCallback, reportEncoding, m_bufferSize); m_reportReader.BeginReadLine(); } // don't wait, we want feeding in of standard input to happen asynchronously Analysis.IgnoreResult(FeedStandardInputAsync(detouredProcess, m_standardInputReader, m_standardInputTcs)); }
internal static int GlobalMemoryStatusEx(ref MEMORYSTATUSEX memoryStatusEx) { // ROTORTODO // This API is called from two places in CacheMemoryTotalMemoryPressure // Does it fail gracefully if the API fails? return 0; }
/// <summary>获取实时数据,如CPU、内存、温度</summary> public void Refresh() { if (Runtime.Windows) { MEMORYSTATUSEX ms = default; ms.Init(); if (GlobalMemoryStatusEx(ref ms)) { Memory = ms.ullTotalPhys; AvailableMemory = ms.ullAvailPhys; } } // 特别识别Linux发行版 else if (Runtime.Linux) { var dic = ReadInfo("/proc/meminfo"); if (dic != null) { if (dic.TryGetValue("MemTotal", out var str)) { Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } if (dic.TryGetValue("MemAvailable", out str) || dic.TryGetValue("MemFree", out str)) { AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } } var file = "/sys/class/thermal/thermal_zone0/temp"; if (File.Exists(file)) { Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000; } else { // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39 file = "/sys/class/hwmon/hwmon0/device/temp_value"; if (File.Exists(file)) { Temperature = File.ReadAllText(file).Trim().Substring(null, ":").ToDouble(); } } //var upt = Execute("uptime"); //if (!upt.IsNullOrEmpty()) //{ // str = upt.Substring("load average:"); // if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble(); //} file = "/proc/loadavg"; if (File.Exists(file)) { CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble(); } } if (Runtime.Windows) { GetSystemTimes(out var idleTime, out var kernelTime, out var userTime); var current = new SystemTime { IdleTime = idleTime.ToLong(), KernelTime = kernelTime.ToLong(), UserTime = userTime.ToLong(), }; if (_systemTime != null) { var idle = current.IdleTime - _systemTime.IdleTime; var kernel = current.KernelTime - _systemTime.KernelTime; var user = current.UserTime - _systemTime.UserTime; var total = kernel + user; CpuRate = total == 0 ? 0 : (Single)((Double)(total - idle) / total); } _systemTime = current; } }
private static extern bool GlobalMemoryStatusEx(MEMORYSTATUSEX lpBuffer);
public static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX mem);
public static void OutputRAMInfo() { MEMORYSTATUSEX stat = new MEMORYSTATUSEX(); stat.dwLength = 64; bool res = GlobalMemoryStatusEx(out stat); ulong avail_ram = stat.ullTotalPhys; avail_ram = avail_ram / 1024 / 1024; ulong free_ram = stat.ullAvailPhys; free_ram = free_ram / 1024 / 1024; Console.WriteLine("**********RAM info**********"); Console.WriteLine("Total available memory: " + Math.Round((double)avail_ram / 1024, 2) + " GB"); Console.WriteLine("Total free memory: " + Math.Round((double)free_ram / 1024, 2) + " GB"); Console.WriteLine(); }
private static bool SendCrashDump(string path, string name) { // Get machine UUID or generate one if not valid string uuidString = Api.IcepickRegistry.ReadMachineUUID(); Guid uuid; if (!Guid.TryParse(uuidString, out uuid)) { uuid = Guid.NewGuid(); uuidString = uuid.ToString(); Api.IcepickRegistry.WriteMachineUUID(uuidString); } // Attempt to get version from TTF2SDK.dll string versionString = "unknown"; try { FileVersionInfo sdkVersionInfo = FileVersionInfo.GetVersionInfo(Mods.SDKInjector.SDKDllName); if (sdkVersionInfo.Comments != "") { versionString = sdkVersionInfo.Comments; } } catch (Exception) { } // Get memory information ulong totalMemory = 0; ulong freeMemory = 0; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if (GlobalMemoryStatusEx(memStatus)) { totalMemory = memStatus.ullTotalPhys; freeMemory = memStatus.ullAvailPhys; } // Get disk space information string rootPath = Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory); ulong freeStorage = 0; ulong storageSize = 0; ulong dummy; GetDiskFreeSpaceEx(rootPath, out freeStorage, out storageSize, out dummy); // Get a handle on the file FileStream stream = null; for (int i = 0; i < 10; i++) { try { stream = new FileStream(path, FileMode.Open, FileAccess.Read); break; } catch (IOException) { System.Threading.Thread.Sleep(500); } } if (stream == null) { return(false); } // Send request to sentry HttpContent memorySizeParam = new StringContent(totalMemory.ToString()); HttpContent freeMemoryParam = new StringContent(freeMemory.ToString()); HttpContent storageSizeParam = new StringContent(storageSize.ToString()); HttpContent freeStorageParam = new StringContent(freeStorage.ToString()); HttpContent sdkNameParam = new StringContent("Icepick"); HttpContent sdkVersionParam = new StringContent(Version.Current); HttpContent releaseParam = new StringContent(versionString); HttpContent userIdParam = new StringContent(uuidString); HttpContent fileStreamContent = new StreamContent(stream); using (var client = new HttpClient()) { using (var formData = new MultipartFormDataContent()) { formData.Add(memorySizeParam, "sentry[contexts][device][memory_size]"); formData.Add(freeMemoryParam, "sentry[contexts][device][free_memory]"); formData.Add(storageSizeParam, "sentry[contexts][device][storage_size]"); formData.Add(freeStorageParam, "sentry[contexts][device][free_storage]"); formData.Add(sdkNameParam, "sentry[sdk][name]"); formData.Add(sdkVersionParam, "sentry[sdk][version]"); formData.Add(releaseParam, "sentry[release]"); formData.Add(userIdParam, "sentry[user][id]"); formData.Add(fileStreamContent, "upload_file_minidump", name); var task = client.PostAsync(SentryEndpoint, formData); task.Wait(); return(task.Result.StatusCode == System.Net.HttpStatusCode.OK); } } }
private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer);
internal static unsafe bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer) { buffer.length = sizeof(MEMORYSTATUSEX); return(GlobalMemoryStatusExNative(ref buffer)); }
internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer) { buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX)); return GlobalMemoryStatusExNative(ref buffer); }
public static MemoryStatus GetMemoryStatus() { var stat = new MEMORYSTATUSEX(); if (OSFamily==OS.OSFamily.Windows) GlobalMemoryStatusEx( stat ); return new MemoryStatus() { LoadPct = stat.dwMemoryLoad, TotalPhysicalBytes = stat.ullTotalPhys, AvailablePhysicalBytes = stat.ullAvailPhys, TotalPageFileBytes = stat.ullTotalPageFile, AvailablePageFileBytes = stat.ullAvailPageFile, TotalVirtBytes = stat.ullTotalVirtual, AvailableVirtBytes = stat.ullAvailVirtual }; }
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);