private async void MainWindow_Loaded_1(object sender, EventArgs e) { Globals.Windows.MainWindow = this; LauncherSettings.Load(); /*foreach (SavedUser u in LauncherSettings.Default.SecuredLoginInfo) { }*/ WebClient w = new WebClient(); StringReader r = new StringReader(await w.DownloadStringTaskAsync("https://dl.dropbox.com/u/37049399/MCLauncher/LauncherMessage.xaml")); Announcements.Document = (FlowDocument)XamlReader.Load(XmlReader.Create(r)); ImageBrush b = new ImageBrush(); b.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Images/dirt.png")); b.Viewport = new Rect(0.1, 0.1, 0.07, 0.1); b.TileMode = TileMode.Tile; this.Background = b; AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; LoadingText.Content = "Please wait..."; LoadingProgress.IsIndeterminate = true; ComputerInfo i = new ComputerInfo(); SystemInfo.Content = "An error occured getting your system's RAM information. This is not a good sign! D:"; SystemInfo.Content = String.Format("{0} MB ({1} GB) Free/{2} MB ({3} GB) Total", i.AvailablePhysicalMemory / 1024 / 1024, i.AvailablePhysicalMemory / 1024 / 1024 / 1024, i.TotalPhysicalMemory / 1024 / 1024, i.TotalPhysicalMemory / 1024 / 1024 / 1024); await this.GetLatestLauncherInformation(); await this.ApplyLatestBackground(); }
public void getOperatingSystemInfo() { double div = 1000000000; ComputerInfo myCompInfo = new ComputerInfo(); //Console.WriteLine("Checking operating system info....\n"); Program.LogResults("Total Physical Memory= " + (myCompInfo.TotalPhysicalMemory/div).ToString("F") + "GB"); Program.LogResults("Total Virtual Memory= " + (myCompInfo.TotalVirtualMemory / div).ToString("F") + "GB"); Program.LogResults("Available Physical Memory= " + (myCompInfo.AvailablePhysicalMemory / div).ToString("F") + "GB"); Program.LogResults("Available Virtual Memory= " + (myCompInfo.AvailableVirtualMemory / div).ToString("F") + "GB"); Program.LogResults("Installed UI Culture= " + myCompInfo.InstalledUICulture); Program.LogResults("Opetating System= " + myCompInfo.OSFullName); //Create an object of ManagementObjectSearcher class and pass query as parameter. ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_OperatingSystem"); foreach (ManagementObject managementObject in mos.Get()) { if (managementObject["CSDVersion"] != null) { //Display operating system version. Program.LogResults("Operating System Service Pack : " + managementObject["CSDVersion"].ToString()); } } }
public RaygunEnvironmentMessage() { ProcessorCount = Environment.ProcessorCount; #if !WINRT OSVersion = Environment.OSVersion.VersionString; Architecture = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); Cpu = Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER"); WindowBoundsWidth = SystemInformation.VirtualScreen.Height; WindowBoundsHeight = SystemInformation.VirtualScreen.Width; ComputerInfo info = new ComputerInfo(); TotalPhysicalMemory = (ulong)info.TotalPhysicalMemory / 0x100000; // in MB AvailablePhysicalMemory = (ulong)info.AvailablePhysicalMemory / 0x100000; TotalVirtualMemory = info.TotalVirtualMemory / 0x100000; AvailableVirtualMemory = info.AvailableVirtualMemory / 0x100000; Location = CultureInfo.CurrentCulture.DisplayName; OSVersion = info.OSVersion; GetDiskSpace(); //GetCpu(); #else //WindowBoundsHeight = Windows.UI.Xaml.Window.Current.Bounds.Height; //WindowBoundsWidth = Windows.UI.Xaml.Window.Current.Bounds.Width; PackageVersion = string.Format("{0}.{1}", Package.Current.Id.Version.Major, Package.Current.Id.Version.Minor); Cpu = Package.Current.Id.Architecture.ToString(); ResolutionScale = DisplayProperties.ResolutionScale.ToString(); CurrentOrientation = DisplayProperties.CurrentOrientation.ToString(); Location = Windows.System.UserProfile.GlobalizationPreferences.HomeGeographicRegion; SYSTEM_INFO systemInfo = new SYSTEM_INFO(); RaygunSystemInfoWrapper.GetNativeSystemInfo(ref systemInfo); Architecture = systemInfo.wProcessorArchitecture.ToString(); #endif }
/// <summary>获取当前使用的物理内存百分比 /// </summary> /// <returns></returns> public static ulong GetUsedMemoryPercent() { var computerInfo = new ComputerInfo(); var usedPhysicalMemory = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory; var usedMemoryPercent = usedPhysicalMemory * 100 / computerInfo.TotalPhysicalMemory; return usedMemoryPercent; }
/// <summary> /// Runs a memory monitor /// </summary> /// <param name="stick">The BlinkStick to use</param> /// <param name="keepGoing">A callback method; when this returns false, the loop stops</param> public static void Run(BlinkStick stick, Func<bool> keepGoing) { var bands = new SortedDictionary<float, Color> { { 20f, Color.Blue }, { 50f, Color.Green }, { 70f, Color.Yellow }, { 90f, Color.Orange }, { 100f, Color.Red } }; ulong totalMemoryInBytes = new ComputerInfo().TotalPhysicalMemory; float totalMemoryInMegabytes = (float)((double)totalMemoryInBytes / (1024 * 1024)); using (var pc = new PerformanceCounter("Memory", "Available Mbytes")) { while (keepGoing()) { float memoryUsagePercent = (100 * (totalMemoryInMegabytes - pc.NextValue())) / totalMemoryInMegabytes; stick.WriteLine("memoryUsage = {0}", memoryUsagePercent); stick.LedColor = ColorExtensions.ValueToColor(bands, memoryUsagePercent); Thread.Sleep(1000); } } }
private void UpdateUsedMemory() { var totalMemory = new ComputerInfo().TotalPhysicalMemory; var freeMemory = new ComputerInfo().AvailablePhysicalMemory; var usedMemory = totalMemory - freeMemory; long memory = 0; Process[] processes; processes = Process.GetProcesses(); foreach (var process in processes) { memory += process.PrivateMemorySize64; } Console.WriteLine("Bytes: {0}.", memory); Console.WriteLine("KiloBytes: {0}.", memory * 10e-4); Console.WriteLine("MegaBytes: {0}.", memory * 10e-7); Console.WriteLine("GigaBytes: {0}.", memory * 10e-10); var usedGb = usedMemory*10e-10; var totalGb = totalMemory*10e-10; var usedPercent = (int)(usedGb / totalGb * 100f); usedMemoryBar.Value = usedPercent > 100 ? 100 : usedPercent; var usedMemoryText = string.Format("{0:0.##} / {1:0.##} GB", usedGb, totalGb); usedMemoryLabel.Text = usedMemoryText; notifyIcon1.Icon = _statusIcons[(int) Math.Ceiling(usedGb / totalGb * 10)]; notifyIcon1.Text = usedMemoryText; }
public Taskmethods() { cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); ramCounter = new PerformanceCounter("Memory", "Available Bytes"); _compInfo = new ComputerInfo(); _max_ram = _compInfo.TotalPhysicalMemory; }
public ComputerEnvironment() { var cinfo = new ComputerInfo(); is64 = Environment.Is64BitOperatingSystem; os = cinfo.OSFullName; osVerString = Environment.OSVersion.VersionString; if (Environment.OSVersion.ServicePack.Length != 0) { servicePack = Environment.OSVersion.ServicePack; } else { servicePack = "n/a"; } ramTotal = Math.Ceiling(cinfo.TotalPhysicalMemory * 1e-6); ramFree = Math.Ceiling(cinfo.AvailablePhysicalMemory * 1e-6); ramUsed = (1 - (ramFree / ramTotal)) * 100; computerName = Environment.MachineName; timestamp = DateTime.Now; installedSoftware = GetInstalledSoftware(); diskInfo = GetDiskInfo(); }
public RaygunEnvironmentMessage() { WindowBoundsWidth = SystemInformation.VirtualScreen.Height; WindowBoundsHeight = SystemInformation.VirtualScreen.Width; ComputerInfo info = new ComputerInfo(); Locale = CultureInfo.CurrentCulture.DisplayName; DateTime now = DateTime.Now; UtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(now).TotalHours; OSVersion = info.OSVersion; bool mediumTrust = RaygunSettings.Settings.MediumTrust || !HasUnrestrictedFeatureSet; if (!mediumTrust) { try { Architecture = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); TotalPhysicalMemory = (ulong)info.TotalPhysicalMemory / 0x100000; // in MB AvailablePhysicalMemory = (ulong)info.AvailablePhysicalMemory / 0x100000; TotalVirtualMemory = info.TotalVirtualMemory / 0x100000; AvailableVirtualMemory = info.AvailableVirtualMemory / 0x100000; GetDiskSpace(); Cpu = GetCpu(); } catch (SecurityException) { System.Diagnostics.Trace.WriteLine("RaygunClient error: couldn't access environment variables. If you are running in Medium Trust, in web.config in RaygunSettings set mediumtrust=\"true\""); } } }
public static bool IsMemoryEnoughToCacheChunk(ulong chunkSize, uint maxUseMemoryPercent) { var computerInfo = new ComputerInfo(); var maxAllowUseMemory = computerInfo.TotalPhysicalMemory * maxUseMemoryPercent / 100; var currentUsedMemory = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory; return currentUsedMemory + chunkSize <= maxAllowUseMemory; }
public MemoryMonitor() { computerInfo = new ComputerInfo(); counterTotalVirtualMemorySize = new PerformanceCounter("Memory", "Commit Limit"); counterUsedVirtualMemory = new PerformanceCounter("Memory", "Committed Bytes"); counterTotalVirtualMemorySize.NextValue(); counterUsedVirtualMemory.NextValue(); }
private static SystemMemoryModel GetAvailableMemory() { var computerInfo = new ComputerInfo(); var totalMemory = (long)(computerInfo.TotalPhysicalMemory); var freeMemory = (long)(computerInfo.AvailablePhysicalMemory); return new SystemMemoryModel { Total = totalMemory, Used = totalMemory - freeMemory }; }
public ComputerMonitor() { pc = new PerformanceCounter("Processor", "% Processor Time", "_Total"); pc.ReadOnly = true; computerInfo = new ComputerInfo(); management = new ManagementObjectSearcher(@"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature"); networkMonitor = new NetworkMonitor(); networkAdapters = networkMonitor.Adapters; foreach (NetworkAdapter adapter in networkAdapters) { networkMonitor.StartMonitoring(adapter); } }
private string FillEmailTempalte() { var screenHeight = string.Empty; var screenWidth = string.Empty; if (Request.Cookies["screen_width"] != null) screenWidth = Request.Cookies["screen_width"].Value; if (Request.Cookies["screen_height"] != null) screenHeight = Request.Cookies["screen_height"].Value; var browserName = string.Empty; var browserVersion = string.Empty; if (Request.Cookies["browser_name"] != null) browserName =HttpUtility.UrlDecode(Request.Cookies["browser_name"].Value); if (Request.Cookies["browser_version"] != null) browserVersion = Request.Cookies["browser_version"].Value; var srHtmlTemplate = new StreamReader(Server.MapPath(Constants.EmailTemplate)); var htmlTemplate = srHtmlTemplate.ReadToEnd(); var computerInfo = new ComputerInfo(); var browser = Request.Browser; var feedbackProjectName = ConfigurationsUtil.GetProjectName(); var emailModel = new EmailModel { ProjectName = feedbackProjectName, UserOs = computerInfo.OSFullName, ScreenHeight = screenHeight.ToString(CultureInfo.InvariantCulture), ScreenWidth = screenWidth.ToString(CultureInfo.InvariantCulture), Email = tbEmail.Text, Comment = tbComment.Text, Browser = browserName, BrowserVersion = browserVersion, ErrorLogRequestUrl = Session["ErrorLog_RequestURL"].ToString(), ErrorLogMessage = Session["ErrorLog_Message"].ToString(), ErrorLogSource = Session["ErrorLog_Source"].ToString(), ErrorLogStackTrace = Session["ErrorLog_StackTrace"].ToString(), LastVisitPagesList = GetLastVisits() }; var dicEmailModel = typeof(EmailModel).GetProperties(BindingFlags.Public | BindingFlags.Instance) .ToDictionary(p => p.Name, p => (p.GetValue(emailModel, null) ?? string.Empty).ToString()); foreach (var key in dicEmailModel.Keys) { htmlTemplate = htmlTemplate.Replace(String.Format("#{0}#", key), dicEmailModel[key]); } return htmlTemplate; }
public static bool IsMemoryEnoughToCacheChunk(ulong chunkSize, uint maxUseMemoryPercent, out ChunkApplyMemoryInfo applyMemoryInfo) { applyMemoryInfo = new ChunkApplyMemoryInfo(); uint bytesPerMB = 1024 * 1024; var computerInfo = new ComputerInfo(); var usedMemory = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory; applyMemoryInfo.PhysicalMemoryMB = computerInfo.TotalPhysicalMemory / bytesPerMB; applyMemoryInfo.AvailableMemoryMB = computerInfo.AvailablePhysicalMemory / bytesPerMB; applyMemoryInfo.UsedMemoryMB = usedMemory / bytesPerMB; applyMemoryInfo.UsedMemoryPercent = applyMemoryInfo.UsedMemoryMB * 100 / applyMemoryInfo.PhysicalMemoryMB; applyMemoryInfo.ChunkSizeMB = chunkSize / bytesPerMB; applyMemoryInfo.MaxAllowUseMemoryMB = applyMemoryInfo.PhysicalMemoryMB * maxUseMemoryPercent / 100; return applyMemoryInfo.UsedMemoryMB + applyMemoryInfo.ChunkSizeMB <= applyMemoryInfo.MaxAllowUseMemoryMB; }
public void Test() { Memory block = new Memory(1); if (block.Address == IntPtr.Zero) throw new Exception(); if (block.Size != 1) throw new Exception(); block.Release(); if (block.Address != IntPtr.Zero) throw new Exception(); if (block.Size != 0) throw new Exception(); block.Release(); ComputerInfo info = new ComputerInfo(); GC.Collect(); GC.WaitForPendingFinalizers(); long mem = (long)info.AvailablePhysicalMemory; //Allocate 100MB List<Memory> blocks = new List<Memory>(); for (int x = 0; x < 10; x++) blocks.Add(new Memory(10000000)); GC.Collect(); GC.WaitForPendingFinalizers(); long mem2 = (long)info.AvailablePhysicalMemory; //Verify that it increased by more than 50MB if (mem2 > mem + 1000000 * 50) { throw new Exception(); } //Release through collection blocks = null; GC.Collect(); GC.WaitForPendingFinalizers(); //Verify that the difference between the start and the end is less than 50MB long mem3 = (long)info.AvailablePhysicalMemory; if (Math.Abs(mem3 - mem) > 1000000 * 50) { throw new Exception(); } }
private static void SaveCrashDump(object sender, UnhandledExceptionEventArgs e) { ComputerInfo computerInfo = new ComputerInfo(); StreamWriter sr = new StreamWriter(Globals.CrashDumpFilePath, true); sr.WriteLine("Processor Count: " + Environment.ProcessorCount.ToString()); sr.WriteLine("OS Name: " + computerInfo.OSFullName); sr.WriteLine("OS Platform: " + computerInfo.OSPlatform); sr.WriteLine("OS Version: " + computerInfo.OSVersion); sr.WriteLine("Working Set: " + Common.SetSizeLabel((UInt64)Environment.WorkingSet)); sr.WriteLine("Uptime: " + ((Environment.TickCount - Program.startTick) / 1000).ToString()); sr.WriteLine(); sr.WriteLine(e.ExceptionObject.ToString()); sr.Flush(); sr.Close(); sr.Dispose(); MessageBox.Show(e.ExceptionObject.ToString(), Application.ProductName + " - Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
public ConfigForm(ShadowsocksController controller, MenuViewController menu) { ComputerInfo info = new ComputerInfo(); MessageBox.Show("Availible Physical Memory" + Convert.ToDouble(info.AvailablePhysicalMemory)/(1024.0*1024.0*1024.0) + "GB"); this.Font = System.Drawing.SystemFonts.MessageBoxFont; InitializeComponent(); // a dirty hack this.ServersListBox.Dock = System.Windows.Forms.DockStyle.Fill; this.PerformLayout(); UpdateTexts(); this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon()); this.menu = menu; this.controller = controller; controller.ConfigChanged += controller_ConfigChanged; LoadCurrentConfiguration(); }
public void Initialization() { hlBackProjet.NavigateUrl = "~/Espace/Serveurs.aspx" + MySession.GenerateGetParams(); Serveur myServeur = GetServeur(); if (myServeur != null) { projetName.Text = myServeur.libelle; InfosGenerales_Init(myServeur); Microsoft.VisualBasic.Devices.ComputerInfo cptInfo = new Microsoft.VisualBasic.Devices.ComputerInfo(); ulong totalRam = cptInfo.TotalPhysicalMemory; TotalRAM = Convert.ToInt32((totalRam / 1024) / 1024); //TotalRAM = Convert.ToInt32(cptInfo.TotalPhysicalMemory); InitCPU(); InitRAM(); InitStockage(); } }
public MonitPerformance() { //Initialize user Cpu Counter userCpuCounter = new PerformanceCounter(); userCpuCounter.CategoryName = "Processor"; userCpuCounter.CounterName = "% User Time"; userCpuCounter.InstanceName = "_Total"; //userCpuCounter.NextValue(); //Initialize cpu Counter cpuCounter = new PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; //Initialize ram counter ramCounter = new PerformanceCounter(); ramCounter.CategoryName = "Memory"; ramCounter.CounterName = "Available kBytes"; ComputerInfo computerInfo = new ComputerInfo(); totalMemory = Convert.ToDouble(computerInfo.TotalPhysicalMemory / 1024); }
/// <summary> /// Retrieve practical data about the system. /// </summary> /// <returns>Array of doubles, first element is CPU, the second RAM</returns> public static double[] SystemInfo(){ var cCounter = 0; var rCounter = 0; using (var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true)) { cCounter = (int)cpuCounter.NextValue(); System.Threading.Thread.Sleep(1000); cCounter = (int)cpuCounter.NextValue(); } using (var ram = new PerformanceCounter("Memory", "Available MBytes", true)) { rCounter = (int)ram.NextValue(); System.Threading.Thread.Sleep(1000); rCounter = (int)ram.NextValue(); } var cInfo = new Microsoft.VisualBasic.Devices.ComputerInfo(); double total = cInfo.TotalPhysicalMemory / 1024 / 1024; var percentage = (rCounter / total) * 100; return new double[]{cCounter, percentage}; }
/// <summary> /// Retrieve practical data about the system. /// </summary> /// <returns>Array of doubles, first element is CPU, the second RAM</returns> public static double[] SystemInfo() { var cCounter = 0; var rCounter = 0; using (var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true)) { cCounter = (int)cpuCounter.NextValue(); System.Threading.Thread.Sleep(1000); cCounter = (int)cpuCounter.NextValue(); } using (var ram = new PerformanceCounter("Memory", "Available MBytes", true)) { rCounter = (int)ram.NextValue(); System.Threading.Thread.Sleep(1000); rCounter = (int)ram.NextValue(); } var cInfo = new Microsoft.VisualBasic.Devices.ComputerInfo(); double total = cInfo.TotalPhysicalMemory / 1024 / 1024; var percentage = (rCounter / total) * 100; return(new double[] { cCounter, percentage }); }
// Static constructor to init Funcs ;) static StorageSettingManager() { TotalFreeMemory = () => { var computerInfo = new ComputerInfo(); var result = computerInfo.AvailablePhysicalMemory; return result; }; TotalPhysicalMemory = () => { var computerInfo = new ComputerInfo(); var result = computerInfo.TotalPhysicalMemory; return result; }; StorageLayerSegments = () => ConfigurationManager.AppSettings["StorageLayerSegments"]; StorageLayerSegmentSize = () => ConfigurationManager.AppSettings["StorageLayerSegmentSize"]; }
public RaygunEnvironmentMessage() { // Different environments can fail to load the environment details. // For now if they fail to load for whatever reason then just // swallow the exception. A good addition would be to handle // these cases and load them correctly depending on where its running. // see http://raygun.io/forums/thread/3655 try { DateTime now = DateTime.Now; UtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(now).TotalHours; IntPtr hWnd = GetActiveWindow(); RECT rect; GetWindowRect(hWnd, out rect); WindowBoundsWidth = rect.Right - rect.Left; WindowBoundsHeight = rect.Bottom - rect.Top; ProcessorCount = Environment.ProcessorCount; Architecture = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); OSVersion = Environment.OSVersion.VersionString; ComputerInfo info = new ComputerInfo(); TotalPhysicalMemory = (ulong)info.TotalPhysicalMemory / 0x100000; // in MB AvailablePhysicalMemory = (ulong)info.AvailablePhysicalMemory / 0x100000; TotalVirtualMemory = info.TotalVirtualMemory / 0x100000; AvailableVirtualMemory = info.AvailableVirtualMemory / 0x100000; GetDiskSpace(); Locale = CultureInfo.CurrentCulture.DisplayName; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Error getting environment info: {0}", ex.Message)); } }
public OSInfo() { _computer = new ComputerInfo(); }
public static string GetOsFullName() { ComputerInfo info = new ComputerInfo(); return info.OSFullName; }
public RaygunEnvironmentMessage() { #if WINRT //WindowBoundsHeight = Windows.UI.Xaml.Window.Current.Bounds.Height; //WindowBoundsWidth = Windows.UI.Xaml.Window.Current.Bounds.Width; PackageVersion = string.Format("{0}.{1}", Package.Current.Id.Version.Major, Package.Current.Id.Version.Minor); Cpu = Package.Current.Id.Architecture.ToString(); ResolutionScale = DisplayProperties.ResolutionScale.ToString(); CurrentOrientation = DisplayProperties.CurrentOrientation.ToString(); Location = Windows.System.UserProfile.GlobalizationPreferences.HomeGeographicRegion; DateTime now = DateTime.Now; UtcOffset = TimeZoneInfo.Local.GetUtcOffset(now).TotalHours; SYSTEM_INFO systemInfo = new SYSTEM_INFO(); RaygunSystemInfoWrapper.GetNativeSystemInfo(ref systemInfo); Architecture = systemInfo.wProcessorArchitecture.ToString(); #elif WINDOWS_PHONE Locale = CultureInfo.CurrentCulture.DisplayName; OSVersion = Environment.OSVersion.Platform + " " + Environment.OSVersion.Version; object deviceName; DeviceExtendedProperties.TryGetValue("DeviceName", out deviceName); DeviceName = deviceName.ToString(); WindowBoundsWidth = Application.Current.RootVisual.RenderSize.Width; WindowBoundsHeight = Application.Current.RootVisual.RenderSize.Height; DateTime now = DateTime.Now; UtcOffset = TimeZoneInfo.Local.GetUtcOffset(now).TotalHours; PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { CurrentOrientation = frame.Orientation.ToString(); } //ProcessorCount = Environment.ProcessorCount; // TODO: finish other values #elif ANDROID try { Java.Util.TimeZone tz = Java.Util.TimeZone.Default; Java.Util.Date now = new Java.Util.Date(); UtcOffset = tz.GetOffset(now.Time) / 3600000.0; OSVersion = Android.OS.Build.VERSION.Sdk; Locale = CultureInfo.CurrentCulture.DisplayName; var metrics = Resources.System.DisplayMetrics; WindowBoundsWidth = metrics.WidthPixels; WindowBoundsHeight = metrics.HeightPixels; Context context = RaygunClient.Context; if (context != null) { PackageManager manager = context.PackageManager; PackageInfo info = manager.GetPackageInfo(context.PackageName, 0); PackageVersion = info.VersionCode + " / " + info.VersionName; IWindowManager windowManager = context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>(); if (windowManager != null) { Display display = windowManager.DefaultDisplay; if (display != null) { switch (display.Rotation) { case SurfaceOrientation.Rotation0: CurrentOrientation = "Rotation 0 (Portrait)"; break; case SurfaceOrientation.Rotation180: CurrentOrientation = "Rotation 180 (Upside down)"; break; case SurfaceOrientation.Rotation270: CurrentOrientation = "Rotation 270 (Landscape right)"; break; case SurfaceOrientation.Rotation90: CurrentOrientation = "Rotation 90 (Landscape left)"; break; } } } } DeviceName = RaygunClient.DeviceName; Java.Lang.Runtime runtime = Java.Lang.Runtime.GetRuntime(); TotalPhysicalMemory = (ulong)runtime.TotalMemory(); AvailablePhysicalMemory = (ulong)runtime.FreeMemory(); ProcessorCount = runtime.AvailableProcessors(); Architecture = Android.OS.Build.CpuAbi; Model = string.Format("{0} / {1} / {2}", Android.OS.Build.Model, Android.OS.Build.Brand, Android.OS.Build.Manufacturer); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Error getting environment info {0}", ex.Message)); } #elif IOS UtcOffset = NSTimeZone.LocalTimeZone.GetSecondsFromGMT / 3600.0; OSVersion = UIDevice.CurrentDevice.SystemName + " " + UIDevice.CurrentDevice.SystemVersion; Architecture = GetStringSysCtl(ArchitecturePropertyName); Model = UIDevice.CurrentDevice.Model; ProcessorCount = (int)GetIntSysCtl(ProcessiorCountPropertyName); Locale = CultureInfo.CurrentCulture.DisplayName; UIApplication.SharedApplication.InvokeOnMainThread(() => { WindowBoundsWidth = UIScreen.MainScreen.Bounds.Width; WindowBoundsHeight = UIScreen.MainScreen.Bounds.Height; }); CurrentOrientation = UIDevice.CurrentDevice.Orientation.ToString(); TotalPhysicalMemory = GetIntSysCtl(TotalPhysicalMemoryPropertyName); AvailablePhysicalMemory = GetIntSysCtl(AvailablePhysicalMemoryPropertyName); DeviceName = UIDevice.CurrentDevice.Name; PackageVersion = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion").ToString(); #else WindowBoundsWidth = SystemInformation.VirtualScreen.Height; WindowBoundsHeight = SystemInformation.VirtualScreen.Width; ComputerInfo info = new ComputerInfo(); Locale = CultureInfo.CurrentCulture.DisplayName; DateTime now = DateTime.Now; UtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(now).TotalHours; OSVersion = info.OSVersion; if (!RaygunSettings.Settings.MediumTrust) { try { Architecture = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); TotalPhysicalMemory = (ulong)info.TotalPhysicalMemory / 0x100000; // in MB AvailablePhysicalMemory = (ulong)info.AvailablePhysicalMemory / 0x100000; TotalVirtualMemory = info.TotalVirtualMemory / 0x100000; AvailableVirtualMemory = info.AvailableVirtualMemory / 0x100000; GetDiskSpace(); Cpu = GetCpu(); } catch (SecurityException) { System.Diagnostics.Trace.WriteLine("RaygunClient error: couldn't access environment variables. If you are running in Medium Trust, in web.config in RaygunSettings set mediumtrust=\"true\""); } } #endif }
private void Handle_Exception(Exception ex, int CallId) { ManagementObjectSearcher osManagementObjectSearcher; ManagementObject osManagementObject; ComputerInfo osComputerInfo; string osQuery = string.Empty; string osName = string.Empty; string osVersion = string.Empty; string idMachineName = string.Empty; string idUserName = string.Empty; string idIs64BitOS = string.Empty; string idIs64BitProcess = string.Empty; string idProcessors = string.Empty; string idUserDomainName = string.Empty; string memMbUseage = string.Empty; string memMbTotalPhysical = string.Empty; string memMbTotalVirtual = string.Empty; string memMbAvailablePhysical = string.Empty; string memMbAvailableVirtual = string.Empty; string memGbUseage = string.Empty; string memGbTotalPhysical = string.Empty; string memGbTotalVirtual = string.Empty; string memGbAvailablePhysical = string.Empty; string memGbAvailableVirtual = string.Empty; char[] StackTraceDelimiter = new char[] { '\r', '\n' }; string exMessage = string.Empty; string exMessageInner = string.Empty; string exTarget = string.Empty; string exReason = string.Empty; string exLocation = string.Empty; string exLogged = string.Empty; string msgLog = string.Empty; string msgDisplay = string.Empty; int MaxLength = 0; try { //get the operating system information osQuery = "SELECT * FROM Win32_OperatingSystem"; osManagementObjectSearcher = new ManagementObjectSearcher(osQuery); osManagementObject = osManagementObjectSearcher.Get().Cast <ManagementObject>().FirstOrDefault(); osName = osManagementObject.Properties["Caption"].Value.ToString(); osVersion = osManagementObject.Properties["Version"].Value.ToString(); //get the workstation properties idMachineName = System.Environment.MachineName; idUserName = System.Environment.UserName; idIs64BitOS = System.Environment.Is64BitOperatingSystem.ToString(); idIs64BitProcess = System.Environment.Is64BitProcess.ToString(); idProcessors = System.Environment.ProcessorCount.ToString(); idUserDomainName = System.Environment.UserDomainName; //get the current memory in mb osComputerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo(); memMbTotalPhysical = ((double)osComputerInfo.TotalPhysicalMemory / (1024 * 1024)).ToString("###,###,###,###,###,###,###.000 MB"); memMbTotalVirtual = ((double)osComputerInfo.TotalVirtualMemory / (1024 * 1024)).ToString("###,###,###,###,###,###,###.000 MB"); memMbAvailablePhysical = ((double)osComputerInfo.AvailablePhysicalMemory / (1024 * 1024)).ToString("###,###,###,###,###,###,###.000 MB"); memMbAvailableVirtual = ((double)osComputerInfo.AvailableVirtualMemory / (1024 * 1024)).ToString("###,###,###,###,###,###,###.000 MB"); memMbUseage = ((double)GC.GetTotalMemory(false) / (1024 * 1024)).ToString("###,###,###,###,###,###,###.000 MB"); MaxLength = GetMaxStringLength(memMbTotalPhysical, memMbTotalVirtual, memMbAvailablePhysical, memMbAvailableVirtual, memMbUseage); memMbTotalPhysical = FormatStringLength(memMbTotalPhysical, MaxLength); memMbTotalVirtual = FormatStringLength(memMbTotalVirtual, MaxLength); memMbAvailablePhysical = FormatStringLength(memMbAvailablePhysical, MaxLength); memMbAvailableVirtual = FormatStringLength(memMbAvailableVirtual, MaxLength); memMbUseage = FormatStringLength(memMbUseage, MaxLength); //get the current memory in gb memGbTotalPhysical = ((double)osComputerInfo.TotalPhysicalMemory / (1024 * 1024 * 1024)).ToString("###,##0.000 GB"); memGbTotalVirtual = ((double)osComputerInfo.TotalVirtualMemory / (1024 * 1024 * 1024)).ToString("###,##0.000 GB"); memGbAvailablePhysical = ((double)osComputerInfo.AvailablePhysicalMemory / (1024 * 1024 * 1024)).ToString("###,##0.000 GB"); memGbAvailableVirtual = ((double)osComputerInfo.AvailableVirtualMemory / (1024 * 1024 * 1024)).ToString("###,##0.000 GB"); memGbUseage = ((double)GC.GetTotalMemory(false) / (1024 * 1024 * 1024)).ToString("###,##0.000 GB"); MaxLength = GetMaxStringLength(memGbTotalPhysical, memGbTotalVirtual, memGbAvailablePhysical, memGbAvailableVirtual, memGbUseage); memGbTotalPhysical = FormatStringLength(memGbTotalPhysical, MaxLength); memGbTotalVirtual = FormatStringLength(memGbTotalVirtual, MaxLength); memGbAvailablePhysical = FormatStringLength(memGbAvailablePhysical, MaxLength); memGbAvailableVirtual = FormatStringLength(memGbAvailableVirtual, MaxLength); memGbUseage = FormatStringLength(memGbUseage, MaxLength); //set the message variables exMessageInner = Get_Inner_Most_Exception(ex.InnerException, CallId); exMessage = ex.Message.Trim(); if (!string.IsNullOrWhiteSpace(exMessageInner)) { exMessage += Environment.NewLine + exMessageInner; } //split the stack trace string[] StackTrace = ex.StackTrace.Split(StackTraceDelimiter, StringSplitOptions.RemoveEmptyEntries); if (StackTrace != null) { switch (StackTrace.Length) { case 1: exTarget = "Undetermined"; exReason = "Undetermined"; exLocation = StackTrace[0].Substring(6).Trim(); break; case 2: exTarget = "Undetermined"; exReason = StackTrace[0].Substring(6).Trim(); exLocation = StackTrace[1].Substring(6).Trim(); break; case 3: exTarget = StackTrace[0].Substring(6).Trim(); exReason = StackTrace[1].Substring(6).Trim(); exLocation = StackTrace[2].Substring(6).Trim(); break; default: exTarget = StackTrace[0].Substring(6).Trim(); exReason = StackTrace[1].Substring(6).Trim(); exLocation = StackTrace[2].Substring(6).Trim(); break; } } else { exTarget = "Undetermined"; exReason = "Undetermined"; exLocation = "Undetermined"; } var st = new StackTrace(ex, true); var frame = st.GetFrame(0); var line = frame.GetFileLineNumber(); var fullname = ex.GetType().FullName; //create the log exception message msgLog = "Encountered\t\t: " + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine + Environment.NewLine + "Operating System\t: " + osName + " version " + osVersion + Environment.NewLine + "64bit Operating System\t: " + idIs64BitOS + Environment.NewLine + "64bit Process\t\t: " + idIs64BitProcess + Environment.NewLine + "Number of Processors\t: " + idProcessors + Environment.NewLine + Environment.NewLine + "Machine Name\t\t: " + idMachineName + Environment.NewLine + "User Domain Name\t: " + idUserDomainName + Environment.NewLine + "User Name\t\t: " + idUserName + Environment.NewLine + Environment.NewLine + "Application Memory Useage\t: " + memMbUseage + "\t\t: " + memGbUseage + Environment.NewLine + Environment.NewLine + "Total Physical Memory\t\t: " + memMbTotalPhysical + "\t\t: " + memGbTotalPhysical + Environment.NewLine + "Available Physical Memory\t: " + memMbAvailablePhysical + "\t\t: " + memGbAvailablePhysical + Environment.NewLine + Environment.NewLine + "Total Virtual Memory\t\t: " + memMbTotalVirtual + "\t\t: " + memGbTotalVirtual + Environment.NewLine + "Available Virtual Memory\t: " + memMbAvailableVirtual + "\t\t: " + memGbAvailableVirtual + Environment.NewLine + Environment.NewLine + "Exception Name\t\t\t: " + fullname + Environment.NewLine + "Exception Message\t\t: " + exMessage + Environment.NewLine + "Exception Target\t\t: " + exTarget + Environment.NewLine + "Exception Reason\t\t: " + exReason + Environment.NewLine + "Exception Location\t\t: " + exLocation + Environment.NewLine + "Exception Line\t\t\t: " + line; //write the exception to logs switch (LogException(msgLog, CallId)) { case true: exLogged = "The exception was logged."; break; case false: exLogged = "The exception could not be logged."; break; } if (CallId == 1) { //create the display exception message msgDisplay = "The application encountered an exception." + Environment.NewLine + Environment.NewLine + "Message:" + Environment.NewLine + exMessage + Environment.NewLine + Environment.NewLine + "Reason:" + Environment.NewLine + exReason + Environment.NewLine + Environment.NewLine + "Location:" + Environment.NewLine + exLocation + Environment.NewLine + Environment.NewLine + exLogged; //display the exception //MessageBox.Show(msgDisplay, // this.Message_Box_Caption, MessageBoxButton.OK, MessageBoxImage.Warning); } } catch (Exception innerEx) { switch (CallId >= 1 && CallId <= 3) { case true: Handle_Exception(innerEx, CallId + 1); break; case false: //set the message variables exMessage = innerEx.Message; //set the stack trace string StackTrace = innerEx.StackTrace; //create the display exception message msgDisplay = "The application encountered an exception." + Environment.NewLine + Environment.NewLine + "The exception handler could not handle the application exception because the exception handler encountered an exception." + Environment.NewLine + Environment.NewLine + "Message:" + Environment.NewLine + exMessage + Environment.NewLine + Environment.NewLine + "Stack Trace:" + Environment.NewLine + StackTrace + Environment.NewLine + Environment.NewLine + "Check the logs to determine if this exception was logged."; //display the exception //MessageBox.Show(msgDisplay, // this.Message_Box_Caption, MessageBoxButton.OK, MessageBoxImage.Stop); break; } } }
private void initializeCounter() { // Any stat that uses PerformanceCounter will need to be initialized. switch (curStatType) { case statType.CPU: statCounter = new PerformanceCounter(); statCounter.CategoryName = "Processor"; statCounter.CounterName = "% Processor Time"; statCounter.InstanceName = "_Total"; break; case statType.RAM: // Totally cheating here, using VisualBasic libraries to grab the RAM information. // http://stackoverflow.com/questions/105031/c-sharp-how-do-you-get-total-amount-of-ram-the-computer-has compInfo = new ComputerInfo(); break; case statType.DiskActivity: statCounter = new PerformanceCounter(); statCounter.CategoryName = "LogicalDisk"; statCounter.CounterName = "% Disk Time"; statCounter.InstanceName = "_Total"; break; } }
/// <summary> /// Creates and tests lazy memory cache where elements are constructed on demand and evicted based on LRU strategy only if the RAM usage above specified limits. /// </summary> static void testLazyMemCache() { ComputerInfo computerInfo = new ComputerInfo(); //reference to Microsoft.VisualBasic assembly. //construction var memCache = new LazyMemoryCache<int, Image<Gray, int>> ( (currentSize) => { var occupied = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory; var occupiedPercentage = (float)occupied / computerInfo.TotalPhysicalMemory; //WATCH OUT! You can get OutOfMemoryException although the RAM is not full: //when creating fields with zeros I assume there are some OS optimizations like block sharing //if you compile this as 32-bit (when it consumes 2 GiB it will throw OutOfMemoryException) if (occupiedPercentage > 0.45) return true; return false; }, (img) => (ulong)(img.Stride * img.Height), //set false to not to call GC.Collect() when an item is evicted => may fill more RAM than it has been set, but shortens delays caused by GC forceCollectionOnRemoval: true ); Console.WriteLine("Filling lazy cache (with constructors)..."); const int MAX_KEY = 100; //adding elements (you can also use stream as IEnumerable to populate cache) for (int key = 0; key <= MAX_KEY; key++) { memCache.AddOrUpdate(key, () => { //simulate getting image from a disc (slow operation) var img = new Image<Gray, int>(640, 480); img.SetValue(key); Thread.Sleep(60); return img; }, (img) => { img.Dispose(); }); } //accessing elements (run Task Manager to see memory allocation!) Console.WriteLine("Accessing elements (run Task Manager to see memory allocation!):"); Random rand = new Random(); while (!Console.KeyAvailable) { var key = rand.Next(0, MAX_KEY + 1); ILazy<Image<Gray, int>> lazyVal; memCache.TryGetValue(key, out lazyVal); Console.ForegroundColor = lazyVal.IsValueCreated ? ConsoleColor.Green: ConsoleColor.Red; Image<Gray, int> val = null; var elapsed = Diagnostics.MeasureTime(() => { val = lazyVal.Value; }); Console.Write("\r Accessing {0}. Access time: {1} ms.", key, elapsed); } //accessing elements (run Task Manager to see memory allocation!) /*foreach (var item in memCache) { var lazyVal = item.Value; Console.WriteLine(lazyVal.Value); Console.WriteLine(memCache.HardFaults); }*/ }
/// <summary> /// Creates a new instance of LRU cache where elements are evicted based on least frequently usage. /// </summary> static void testLRUCache() { ComputerInfo computerInfo = new ComputerInfo(); //reference to Microsoft.VisualBasic assembly. var lru = new LRUCache<int, Image<Gray, byte>>( (currentSize) => { var occupied = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory; var occupiedPercentage = (float)occupied / computerInfo.TotalPhysicalMemory; if (occupiedPercentage > 0.85) return true; return false; }, (img) => (ulong)(img.Stride * img.Height)); lru.OnRemoveItem += lru_OnRemoveItem; /***************** add some elements ****************/ var image = new Image<Gray, byte>(5 * 1024 * 1024, 1, 0); image.SetValue(5 % 256); lru.Add(1, image); image = new Image<Gray, byte>(5 * 1024 * 1024, 1, 0); image.SetValue(5 % 256); lru.Add(1, image); /***************** add some elements ****************/ List<Image<Gray, byte>> a = new List<Image<Gray, byte>>(); Random rand = new Random(); int i = 0; while (i < 10000) { image = new Image<Gray, byte>(1024 * 1024, 1, 0); image.SetValue(i % 256); lru.Add(i, image); //Thread.Sleep(1); Console.WriteLine(computerInfo.AvailablePhysicalMemory / 1024 / 1024); i++; } //discover more properties and methods! }
private void BwBusiness_DoWork(object sender, DoWorkEventArgs e) { Stopwatch directoryStopwatch = new Stopwatch(); threadCount++; do { //Get available memory var computerInfo = new ComputerInfo(); var availablePhysicalMemory = (decimal)(computerInfo.AvailablePhysicalMemory); var totalPhysicalMemory = (decimal)(computerInfo.TotalPhysicalMemory); var freeMemRatio = availablePhysicalMemory / totalPhysicalMemory; //Memory protection check if (freeMemRatio > (decimal).09) { bool errorFlag = false; if (!directoryStopwatch.IsRunning) { directoryStopwatch.Start(); } //Get file info so that any necessary logging can be written to the //appropriate folder FileInfo fiPeek; fileQueue.TryPeek(out fiPeek); try { Stopwatch swFile = new Stopwatch(); swFile.Start(); bool isCR2Processing = false; //Keep trying to get a file from the queue FileInfo fi; while (!fileQueue.TryDequeue(out fi) && fileQueue.Count() != 0) { } if (fi != null && File.Exists(fi.FullName)) { string filePath = fi.FullName; string directoryPath = fi.DirectoryName; currentDirectory = directoryPath; //Create Subfolders for Processed DNGs and Logs if (fi.Name.ToLower().Contains(".dng")) { fi.Directory.CreateSubdirectory("Dual ISO DNG"); } if (fi.Name.ToLower().Contains(".cr2")) { isCR2Processing = true; fi.Directory.CreateSubdirectory("Dual ISO CR2"); fi.Directory.CreateSubdirectory("Dual ISO Original CR2"); } fi.Directory.CreateSubdirectory("logs"); //Handle condition where application exited before files moved if (File.Exists(fi.FullName.ToLower().Replace(".dng", ".cr2"))) { isCR2Processing = true; } //Get initial image path pre-move string initialImagePath = fi.FullName; //Get initial log path pre-move string initialLogPath = initialImagePath + ".log"; //Get log directory path string logDirectoryPath = fi.Directory.EnumerateDirectories().Where( d => d.Name.Contains("logs")).FirstOrDefault().FullName; //Get destination log path string destLogPath = fi.Directory.EnumerateDirectories().Where( d => d.Name.Contains("logs")).FirstOrDefault().FullName + "\\" + fi.Name + ".log"; //Get destination image path string destImagePath = string.Empty; if (fi.Name.ToLower().Contains(".dng")) { if (!isCR2Processing) { destImagePath = fi.Directory.EnumerateDirectories().Where( d => d.Name.Contains("Dual ISO DNG")).FirstOrDefault().FullName + "\\" + fi.Name; } else { destImagePath = fi.Directory.EnumerateDirectories().Where( d => d.Name.Contains("Dual ISO CR2")).FirstOrDefault().FullName + "\\" + fi.Name; } } else if (fi.Name.ToLower().Contains(".cr2")) { destImagePath = fi.Directory.EnumerateDirectories().Where( d => d.Name.Contains("Dual ISO Original CR2")).FirstOrDefault().FullName + "\\" + fi.Name; } string initialDNGPath = string.Empty; string destDNGPath = string.Empty; if (isCR2Processing) { initialDNGPath = initialImagePath.ToLower().Replace(".cr2", ".dng").ToUpper(); destDNGPath = destImagePath.Replace("Dual ISO Original CR2", "Dual ISO CR2").ToLower().Replace(".cr2", ".dng").ToUpper(); } string output = string.Empty; string errorOutput = string.Empty; //Get available memory availablePhysicalMemory = (decimal)(computerInfo.AvailablePhysicalMemory); totalPhysicalMemory = (decimal)(computerInfo.TotalPhysicalMemory); freeMemRatio = availablePhysicalMemory / totalPhysicalMemory; //Memory protection check if (!formClosed && freeMemRatio > (decimal).09) { // Use ProcessStartInfo class. ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.FileName = "\"" + txtCr2hdrPath.Text + "\""; startInfo.WorkingDirectory = txtCr2hdrPath.Text.Length > 0 ? txtCr2hdrPath.Text.Substring(0, txtCr2hdrPath.Text.IndexOf(".exe")).Substring(0, txtCr2hdrPath.Text.LastIndexOf("\\")) : startInfo.WorkingDirectory; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = "\"" + filePath + "\""; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; Process exeProcess = Process.Start(startInfo); // Start the process with the info we specified. // Call WaitForExit and then the using-statement will close. using (exeProcess) { output = exeProcess.StandardOutput.ReadToEnd(); errorOutput = exeProcess.StandardError.ReadToEnd(); exeProcess.WaitForExit(); output += "\r\nProcess Errored?: "; //Check exitcode to see if process errored or not if (exeProcess.ExitCode == 0) { output += "No"; } else { output += "Yes"; errorCount++; errorFlag = true; } output += "\r\n" + errorOutput; output += "\r\n\r\n" + exeProcess.TotalProcessorTime.ToString() + " process duration."; string processDuration = exeProcess.TotalProcessorTime.ToString(); } //Move Image if Processing was Successful if (!errorFlag) { if (File.Exists(initialImagePath)) { if (!File.Exists(destImagePath)) { fi.MoveTo(destImagePath); } else { if (destImagePath.ToLower().Contains(".dng")) { fi.MoveTo(destImagePath.ToLower().Replace(".dng", "." + Guid.NewGuid().ToString() + ".dng")); } else if (destImagePath.ToLower().Contains(".cr2")) { fi.MoveTo(destImagePath.ToLower().Replace(".cr2", "." + Guid.NewGuid().ToString() + ".cr2")); } } imagesProcessed++; FileInfo subfolderFileInfoDequeued; subFolderFileQueue.TryDequeue(out subfolderFileInfoDequeued); } } swFile.Stop(); output += "\r\n" + swFile.Elapsed.ToString() + " file activity duration."; //Write appropriate flavor of output log if (errorFlag) { File.WriteAllText(filePath + ".ProcessErrored.log", output); } else { File.WriteAllText(filePath + ".log", output); } //Move Log and perform cleanup if Processing was Successful if (!errorFlag) { if (File.Exists(initialLogPath)) { if (!File.Exists(destLogPath)) { File.Move(initialLogPath, destLogPath); } else { File.Move(initialLogPath, destLogPath.Replace(".log", "." + Guid.NewGuid().ToString() + ".log")); } } if (isCR2Processing) { //Move resultant DNG if CR2 was processed if (File.Exists(initialDNGPath)) { if (!File.Exists(destDNGPath)) { File.Move(initialDNGPath, destDNGPath); } else { File.Move(initialDNGPath, (destDNGPath.ToLower().Replace(".dng", "." + Guid.NewGuid().ToString() + ".dng"))); } } else //Resultant DNG leftover while CR2 still in folder { DirectoryInfo dirInfo = new DirectoryInfo(currentDirectory); dirInfo.CreateSubdirectory("Dual ISO Original CR2"); string leftoverInitialCR2Path = initialImagePath.ToLower().Replace(".dng", ".cr2").ToUpper(); string leftoverDestCR2Path = destImagePath.Replace( "Dual ISO CR2", "Dual ISO Original CR2").ToLower().Replace(".dng", ".cr2").ToUpper(); if (File.Exists(leftoverInitialCR2Path)) { if (!File.Exists(leftoverDestCR2Path)) { File.Move(leftoverInitialCR2Path, leftoverDestCR2Path); } else { File.Move(leftoverInitialCR2Path, leftoverDestCR2Path.ToLower().Replace(".cr2", "." + Guid.NewGuid().ToString() + ".cr2")); } } } } string tempDurationPerImage = durationPerImage.ToString(); //Anything else left in the queue? if (fileQueue.Count() > 0) { FileInfo fiPeekNext; while (!fileQueue.TryPeek(out fiPeekNext) && fileQueue.Count() != 0) { } //Switching to a new folder? Clean up logs after making sure there are no images left in folder. if ( (fiPeekNext.DirectoryName != directoryPath && Directory.EnumerateFiles( directoryPath, "*.dng", SearchOption.TopDirectoryOnly).Union(Directory.EnumerateFiles( directoryPath, "*.cr2", SearchOption.TopDirectoryOnly)).Count() == 0) || fiPeekNext == null) { directoryStopwatch.Stop(); subFolderFileQueue = new ConcurrentQueue<FileInfo>( fiPeekNext.Directory.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union( fiPeekNext.Directory.EnumerateFiles("*.cr2", SearchOption.TopDirectoryOnly)).ToList() ); maxSubfolderFileQueueCount = subFolderFileQueue.Count(); string directoryDuration = directoryStopwatch.Elapsed.ToString() + " Directory Duration."; directoryDuration += "\r\n" + tempDurationPerImage + " Duration Per Image."; if (!File.Exists(directoryPath + "\\directoryDuration.log")) { File.WriteAllText(directoryPath + "\\directoryDuration.log", directoryDuration); } directoryStopwatch.Reset(); IEnumerable<FileInfo> logs = new DirectoryInfo(directoryPath).EnumerateFiles("*.log", SearchOption.TopDirectoryOnly); if (logs.Count() > 0) { foreach (FileInfo log in logs) { if (Directory.Exists(log.DirectoryName + "\\logs")) { log.MoveTo(log.DirectoryName + "\\logs\\" + log.Name); } } } } } else { //No more files in queue. Clean up logs for the final time after making sure there are no image files remaining if (Directory.EnumerateFiles(directoryPath, "*.dng", SearchOption.TopDirectoryOnly).Union( Directory.EnumerateFiles(directoryPath, "*.cr2", SearchOption.TopDirectoryOnly)).Count() == 0) { directoryStopwatch.Stop(); string directoryDuration = directoryStopwatch.Elapsed.ToString() + " Directory Duration."; directoryDuration += "\r\n" + tempDurationPerImage + " Duration Per Image."; if (!File.Exists(directoryPath + "\\directoryDuration.log")) { File.WriteAllText(directoryPath + "\\directoryDuration.log", directoryDuration); } directoryStopwatch.Reset(); IEnumerable<FileInfo> logs = new DirectoryInfo(directoryPath).EnumerateFiles("*.log", SearchOption.TopDirectoryOnly); if (logs.Count() > 0) { foreach (FileInfo log in logs) { if (Directory.Exists(log.DirectoryName + "\\logs")) { if (File.Exists(log.FullName)) { log.MoveTo(log.DirectoryName + "\\logs\\" + log.Name); } } } } } } } } else { //Memory protection check failed? Put file back into queue fileQueue.Enqueue(fi); } } if (isCR2Processing) { //If processing CR2, sleep thread for between 5 and 10 seconds Random r = new Random(); Thread.Sleep(r.Next(5000, 10000)); } } catch (Exception ex) { if (fiPeek != null) { File.WriteAllText(fiPeek.DirectoryName + "\\ExceptionLog." + fiPeek.Name + "." + Guid.NewGuid().ToString() + ".log", ex.Message + "\r\n" + ex.StackTrace); } } } } while (fileQueue.Count() > 0 && !((BackgroundWorker)(sender)).CancellationPending && !formClosed); //Queue empty and last worker? Time to clean up logs and signal work completed. if (fileQueue.Count() == 0 && threadCount == 1) { workCompleted = true; if (!bwCancel.IsBusy) { bwCancel.RunWorkerAsync(); Cancel(); //Clean up logs DirectoryInfo di = new DirectoryInfo(txtImageFolderPath.Text); if (di.Exists) { try { IEnumerable<DirectoryInfo> diList = di.EnumerateDirectories("*", SearchOption.AllDirectories).Where( d => d.EnumerateFiles("*.log", SearchOption.TopDirectoryOnly).Count() > 0 && !d.Name.Contains("Dual ISO DNG") && !d.Name.Contains("Dual ISO CR2") && !d.Name.Contains("Dual ISO Original CR2") && !d.Name.Contains("logs")); List<FileInfo> logList = new List<FileInfo>(); //We don't want to clean up the process errored logs, //since we want to keep those next to the files that need to be reprocessed. logList.AddRange(di.EnumerateFiles("*.log", SearchOption.TopDirectoryOnly).Where( lgFile => !lgFile.Name.Contains("ProcessErrored")).ToList()); foreach (DirectoryInfo dInfo in diList) { string path = dInfo.FullName; logList.AddRange(dInfo.EnumerateFiles("*.log", SearchOption.TopDirectoryOnly).Where( lgFile => !lgFile.Name.Contains("ProcessErrored")).ToList()); } foreach (FileInfo log in logList) { if (Directory.Exists(log.DirectoryName + "\\logs")) { log.MoveTo(log.DirectoryName + "\\logs\\" + log.Name); } } } catch (Exception ex) { File.WriteAllText(di.FullName + "\\ExceptionLog.WorkComplete." + Guid.NewGuid().ToString() + ".log", ex.Message + "\r\n" + ex.StackTrace); } } } } threadCount--; }
/// <summary> /// 获取系统剩余内存 /// </summary> /// <returns>剩余内存</returns> public static ulong GetRunmemory() { ComputerInfo ComputerMemory = new Microsoft.VisualBasic.Devices.ComputerInfo(); return(ComputerMemory.AvailablePhysicalMemory / 1048576); }
public ComputerInfoDebugView(ComputerInfo RealClass) { this.m_InstanceBeingWatched = RealClass; }