NextValue() public method

public NextValue ( ) : float
return float
Beispiel #1
1
        public static String GetCounterValue(PerformanceCounter pPerformanceCounter)
        {
            String retval = "";

            // Retrieve PerformanceCounter result based on its CounterType.
            switch (pPerformanceCounter.CounterType)
            {
                case PerformanceCounterType.NumberOfItems32:
                    retval = pPerformanceCounter.RawValue.ToString();
                    break;

                case PerformanceCounterType.NumberOfItems64:
                    retval = pPerformanceCounter.RawValue.ToString();
                    break;

                case PerformanceCounterType.RateOfCountsPerSecond32:
                    retval = pPerformanceCounter.NextValue().ToString();
                    break;

                case PerformanceCounterType.RateOfCountsPerSecond64:
                    retval = pPerformanceCounter.NextValue().ToString();
                    break;

                case PerformanceCounterType.AverageTimer32:
                    retval = pPerformanceCounter.NextValue().ToString();
                    break;

                default:
                    retval = null;
                    break;
            }

            return retval;
        }
Beispiel #2
1
 public int RAM_Count()
 {
     PerformanceCounter perfMemCount = new PerformanceCounter("Memory", "Available MBytes");
     perfMemCount.NextValue();
     short currentAvailableMemory = (short)perfMemCount.NextValue();
     return currentAvailableMemory;
 }
Beispiel #3
0
        public byte[] Request(byte[] header)
        {
            string newheader = "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n";

            string processmsg = Encoding.UTF8.GetString(header);

            if (processmsg.Contains(@"/status/all"))
            {
                PerformanceCounter cpuCounter = new PerformanceCounter("Processor Information", "% Processor Time");
                PerformanceCounter ramCounter;

                cpuCounter.CategoryName = "Processor";
                cpuCounter.CounterName = "% Processor Time";
                cpuCounter.InstanceName = "_Total";
                cpuCounter.NextValue();

                ramCounter = new PerformanceCounter("Memory", "Available MBytes");

                string jsoncpu = "{\"cpu\" : \"" + cpuCounter.NextValue() + "%\"}";
                string jsonmem = "{\"memory\" : \"" + ramCounter.NextValue() + "MB\"}";

                string json = "[" + jsonmem + "," + jsoncpu + "]";
                return System.Text.Encoding.UTF8.GetBytes(newheader + json);
            }

            return null;
        }
        /// <summary>
        /// This method is responsible for monitoring system resource and user activity with the computer
        /// And periodically changes the shared variable 'crawlerState'
        /// </summary>
        public void Scheduler()
        {
            PerformanceCounter pc = new PerformanceCounter("Processor", "% Idle Time", "_Total", true);

            LASTINPUTINFO info = new LASTINPUTINFO();
            info.cbSize = Marshal.SizeOf(typeof(LASTINPUTINFO));
            while (GlobalData.RunScheduler)
            {
                if (GetLastInputInfo(ref info))
                {
                    if ((Environment.TickCount - info.dwTime) / 1000 > 5 && (int)pc.NextValue() > 40)
                    {
                        crawlerState = CrawlerState.Run;
                    }
                    else
                    {
                        crawlerState = CrawlerState.Stop;
                        if ((Environment.TickCount - info.dwTime) / 1000 <= 5)
                            GlobalData.lIndexingStatus.Text = string.Format("Indexing is paused and will be resumed in {0} sec of computer inactivity [ CPU Idle : {1:F2}% ]", 5 - (Environment.TickCount - info.dwTime) / 1000, pc.NextValue());
                    }
                }
                Thread.Sleep(1000);
            }
            pc.Close();
        }
        public float CollectMetric(PluginResource pluginResource, string option = null)
        {
            // get a handle on the service first
            var service = ServiceController.GetServices().FirstOrDefault(s => s.DisplayName == option);
            if (service == null)
            {
                throw new Exception(string.Format("Windows service by name '{0}' not found", option));
            }

            if (service.Status == ServiceControllerStatus.Stopped)
            {
                return default(float);
            }
            else if (pluginResource.ResourceTextKey == StatusResource)
            {
                return 1;
            }

            // get a handle on the process
            var serviceMgtObj = new ManagementObject(@"Win32_Service.Name='" + service.ServiceName + "'");
            var serviceProcess = Process.GetProcessById(Convert.ToInt32(serviceMgtObj["ProcessId"]));

            // return perfomance counter value for process
            var perfCounter = new PerformanceCounter("Process", pluginResource.Label, serviceProcess.ProcessName);

            var value = perfCounter.NextValue();
            if (value == 0.0)
            {
                Thread.Sleep(1000);
                value = perfCounter.NextValue();
            }

            return value;
        }
Beispiel #6
0
 private void CPUUsage()
 {
     Task.Factory.StartNew(() =>
     {
         PerformanceCounter cpuCounter = new PerformanceCounter();
         cpuCounter.CategoryName = "Processor";
         cpuCounter.CounterName = "% Processor Time";
         cpuCounter.InstanceName = "_Total";
         cpuCounter.NextValue();
         Thread.Sleep(20);
         cpu = cpuCounter.NextValue();
         while (true)
         {
             try
             {
                 Thread.Sleep(1000);
                 cpu = cpuCounter.NextValue();
             }
             catch (Exception e)
             {
                 ShowBalloon("CPU", e);
                 Thread.Sleep(10000);
             }
         }
     });
 }
Beispiel #7
0
 protected void Page_Load(object sender, EventArgs e)
 {
     PerformanceCounter cpuCounter = new PerformanceCounter();
     PerformanceCounter ramCounter = new PerformanceCounter();
     cpuCounter.CategoryName = "Processor";
     cpuCounter.CounterName = "% Processor Time";
     cpuCounter.InstanceName = "_Total";
     ramCounter = new PerformanceCounter("Memory", "Available MBytes");
     System.Threading.Thread.Sleep(1000);
     cpuCounter.NextValue();
     System.Threading.Thread.Sleep(1000);
     Response.Write("Worker State: " + status + "<br>");
     Response.Write("CPU Utilization: " + cpuCounter.NextValue() + " <br>");
     Response.Write("RAM Utilization: " + ramCounter.NextValue() + " <br>");
     Response.Write("Urls Crawled: " + " <br>");
     Response.Write("Last 10 URLs crawled" + " <br>");
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
     CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
     CloudQueue urlQ = queueClient.GetQueueReference("pagequeue");
     urlQ.CreateIfNotExists();
     int? messageCount = urlQ.ApproximateMessageCount;
     Response.Write(messageCount.ToString());
     Debug.WriteLine("ApproximateMessageCount: " + urlQ.ApproximateMessageCount);
     Response.Write("Size of Queue: " + urlQ.ApproximateMessageCount + " <br>");
     Response.Write("Size of Index: " + " <br>");
     Response.Write("Errors and URLs: " + " <br>");
 }
Beispiel #8
0
        public ActionResult ImportExcel()
        {
            var httpFileCollection = Request.Files["file"];

            if (httpFileCollection.ContentLength > 0)
            {
                string extension = System.IO.Path.GetExtension(httpFileCollection.FileName).ToLower();
                string path      = string.Format("{0}/{1}", Server.MapPath("~/ExcelData/Uploads"), Request.Files["file"].FileName);
                if (!Directory.Exists(path)) // if upload folder path does not exist, create one.
                {
                    Directory.CreateDirectory(Server.MapPath("~/ExcelData/Uploads"));
                }

                string[] validFileTypes = { ".xls", ".xlsx", ".csv" };
                if (validFileTypes.Contains(extension))
                {
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path); // if file exist previously, delete previous one
                    }
                    httpFileCollection.SaveAs(path);

                    var performance = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
                    Console.WriteLine(performance.NextValue());

                    XslLibrary.ReadDataTable(path);
                    Console.WriteLine(performance.NextValue());
                    XslLibrary.ImportFromExcelNpoi(path);
                    Console.WriteLine(performance.NextValue());
                }
            }
            TempData["Success"] = "Success";
            return(new ContentResult());
        }
Beispiel #9
0
        //Function will read and display current CPU usage
        public static async void CPUMonitoring(TextBox usageTextBox, TextBox warningTextBox)
        {

            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            while (true)
            {
                //First value always returns a 0
                var unused = cpuCounter.NextValue();
                await Task.Delay(1000);

                usageTextBox.Invoke(new Action(() =>
                {
                    CPUCounter = cpuCounter.NextValue();
                    usageTextBox.Text = CPUCounter.ToString("F2") + "%";
                }));
                CPUCalculations();
                CPUAnomalies.StartAnomalyDetection(warningTextBox);

                if (mainMenu.done)
                    break;
            }
        }
 public TimeSpan UpTime()
 {
     using (var uptime = new PerformanceCounter("System", "System Up Time"))
         {
             uptime.NextValue();       //Call this an extra time before reading its value
             return TimeSpan.FromSeconds(uptime.NextValue());
         }
 }
Beispiel #11
0
 // This sets the System uptime using the perf counters
 // this gives the best result but on a system with corrupt perf counters
 // it can freeze
 internal void GetPerformanceCounterUptime()
 {
     using (var uptime = new PerformanceCounter("System", "System Up Time"))
     {
         uptime.NextValue();
         Uptime = TimeSpan.FromSeconds(uptime.NextValue());
     }
 }
Beispiel #12
0
 public string cpu()
 {
     var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
     cpuCounter.NextValue();
     Thread.Sleep(1000);
     var usage = cpuCounter.NextValue();
     return Convert.ToInt16(usage).ToString();
 }
Beispiel #13
0
 private static TimeSpan getSystemUpTime()
 {
     using (var upTime = new PerformanceCounter("System", "System Up Time"))
     {
         upTime.NextValue();
         return TimeSpan.FromSeconds(upTime.NextValue());
     }
 }
Beispiel #14
0
 //Get the CPU usage for the core passed in
 public static int getCoreUsage(String core)
 {
     //Generate a new counter for core x
     PerformanceCounter coreUsage = new PerformanceCounter("Processor", "% Processor Time", core);
     coreUsage.NextValue();
     System.Threading.Thread.Sleep(750);
     int corePercentage = (int)coreUsage.NextValue();
     return corePercentage;
 }
        public static void th_cpu()
        {
            PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            float useless = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(100);
            float cpuval = cpuCounter.NextValue();

            Console.Out.WriteLine(cpuval);
        }
 public double getProcessCpuUsage(Process process)
 {
     using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", process.ProcessName, true)) {
     for (int i = 0; i < 4; i++) {
       pcProcess.NextValue();
       Thread.Sleep(200);
     }
     return pcProcess.NextValue() / Environment.ProcessorCount;
       }
 }
Beispiel #17
0
 private double CurrentCPUusage(string category, string name, string instance)
 {
     cpuCounter = new PerformanceCounter();
     cpuCounter.CategoryName = category;
     cpuCounter.CounterName = name;
     cpuCounter.InstanceName = instance;
     cpuCounter.NextValue();
     Thread.Sleep(500);
     return cpuCounter.NextValue();
 }
 async public Task<float> TotalCPUAsync()
 {
     PerformanceCounter cpuCounter = new PerformanceCounter();
     cpuCounter.CategoryName = "Processor";
     cpuCounter.CounterName = "% Processor Time";
     cpuCounter.InstanceName = "_Total";
     cpuCounter.NextValue();
     await Task.Delay(1000);
     return cpuCounter.NextValue();
 }
 async public Task<float> ProcessCPUAsync(string processName)
 {
     PerformanceCounter cpuCounter = new PerformanceCounter();
     cpuCounter.CategoryName = "Process";
     cpuCounter.CounterName = "% Processor Time";
     cpuCounter.InstanceName = processName;
     cpuCounter.NextValue();
     await Task.Delay(1000);
     return cpuCounter.NextValue();
 }
Beispiel #20
0
 public override void OnStop()
 {
     Trace.TraceInformation("OnStop called from WebRole");
       var rcCounter = new PerformanceCounter("ASP.NET", "Requests Current", string.Empty);
       while (rcCounter.NextValue() > 0)
       {
       Trace.TraceInformation("ASP.NET Requests Current = " + rcCounter.NextValue().ToString());
       System.Threading.Thread.Sleep(1000);
       }
 }
        /// <summary>
        /// Gets the available ram.
        /// </summary>
        public float GetAvailableRam()
        {
            using (var memory = new PerformanceCounter("Memory", "Available MBytes"))
            {
                // Call this an extra time before reading its value
                memory.NextValue();

                return memory.NextValue();
            }
        }
Beispiel #22
0
        /// <summary>
        /// This event handler is called whenever the 1 second CPU timer elapses. It calls the 
        /// SetText method in a thread safe manner in order to update the CPU usage text box.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            int cpu = (int)cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            cpu = (int)cpuCounter.NextValue();
            _cpuUsage = cpu;

            ObjectDelegate cpuTextDel = new ObjectDelegate(SetCPUText);    //enable the manual start button
            cpuTextDel.Invoke(_cpu);
        }
Beispiel #23
0
 public override void OnStop()
 {
     Trace.TraceInformation("OnStop called from WebRole");
     var counter = new PerformanceCounter("ASP.NET", "Request Current", "");
     while (counter.NextValue()>0)
     {
         Trace.TraceInformation("ASP.NET Request Current: " + counter.NextValue().ToString());
         System.Threading.Thread.Sleep(1000);
     }
     base.OnStop();
 }
 private UInt64 GetTotalCpuUsage()
 {
     var counter = new PerformanceCounter
     {
         CategoryName = "Processor",
         CounterName = "% Processor Time",
         InstanceName = "_Total"
     };
     counter.NextValue();
     Thread.Sleep(1000);
     return (UInt64)counter.NextValue();
 }
        /// <summary>
        /// パソコンの稼働時間を24時間に対してのパーセンテージで求める
        /// </summary>
        /// <returns></returns>
        private double GetSystemUpTimePercentage()
        {
            //パソコン稼働時間取得
            PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");
            upTime.NextValue();

            double upTimeTotalMinutes = (TimeSpan.FromSeconds(upTime.NextValue())).TotalMinutes;
            //パーセンテージ
            double upTimePercentage = upTimeTotalMinutes / TimeSpan.FromHours(24).TotalMinutes;

            return upTimePercentage * 100;
        }
Beispiel #26
0
 //解法三:调用性能计数器
 static void CPUUsage3(float level)
 {
     PerformanceCounter p = new PerformanceCounter("processor","% Processor Time","_Total");
     while(true)
     {
         Console.WriteLine(p.NextValue());
         if (p.NextValue() > level)
         {
             Thread.Sleep(10);
             Console.WriteLine("sleep");
         }
     }
 }
 public static void MeasureProcessCpu()
 {
     using (var pc = new PerformanceCounter(
             "Process",
             "% Processor Time",
             "CPUSTRES"))
     {
         pc.NextValue();
         Thread.Sleep(1000);
         var nextValue = pc.NextValue() / Environment.ProcessorCount;
         Console.WriteLine(nextValue.ToPercentage());
     }
 }
Beispiel #28
0
        public static int GetCpuValue()
        {
            //categories similar to the existnig ones in perfmon.exe (windows)
            var CpuCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");

            //skipping first sample
            CpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);

            //recording sample between two different time stamps
            int gapValue = (int)CpuCounter.NextValue();

            return(gapValue);
        }
   public RamCpu GetServerPerformance()
   {
       var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
       var ramCounter = new PerformanceCounter("Memory", "Available MBytes");
 
      cpuCounter.NextValue();
      Thread.Sleep(1000);
      var value = Math.Round(cpuCounter.NextValue(), 0).ToString();
      return new RamCpu()
      {
          RamUsage = ramCounter.NextValue().ToString(),
          CpuUsage = value
      };
  }
        public static void MeasureTotalCpu()
        {
            using (var pc = new PerformanceCounter(
                    "Processor Information",
                    "% Processor Time",
                    "_Total"))
            {
                pc.NextValue();
                Thread.Sleep(1000); // sleep for the first time after asking for the counter it's always 0 and needs to wait a bit
                var nextValue = pc.NextValue();

                Console.WriteLine(nextValue.ToPercentage());
            }
        }
Beispiel #31
0
        public static void getCPUCOunter()
        {
            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            // will always start at 0
            dynamic firstValue = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            // now matches task manager reading
            string secondValue = cpuCounter.NextValue().ToString();

            Data.cpuUsage = secondValue;
        }
Beispiel #32
0
        public async Task <int> GetCpuUsageAsync(string machineName)
        {
            if (string.IsNullOrWhiteSpace(machineName))
            {
                machineName = ".";
            }

            var counter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", machineName);

            counter.NextValue();

            await Task.Delay(1000).ConfigureAwait(false);

            return((int)counter.NextValue());
        }
Beispiel #33
0
        public int GetCpuUsage(string machineName)
        {
            if (string.IsNullOrWhiteSpace(machineName))
            {
                machineName = "localhost";
            }

            var counter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", machineName);

            counter.NextValue();

            Thread.Sleep(1000);

            return((int)counter.NextValue());
        }
Beispiel #34
0
        public MonitorPerformanceCounter(string Category, string Metric, string Instance = "", string ReportingName = null)
        {
            FriendlyName = string.IsNullOrWhiteSpace(ReportingName) ? Metric : ReportingName;

            _performanceCounter = new System.Diagnostics.PerformanceCounter(Category, Metric, Instance);
            _performanceCounter.NextValue(); // always grab one sample on creation to ensure validity
        }
Beispiel #35
0
        internal static double getMemSize(string svc)
        {
            // slow, doesn't work most of the time for wtf reason
            try
            {
                ServiceController service = new ServiceController(svc);
                string            foo     = service.ServiceName;

                System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter();
                pc.CategoryName = "Process";
                pc.CounterName  = "Working Set - Private";
                pc.InstanceName = foo;
                double memsize = (double)(pc.NextValue() / 1024 / 1024); // mb

                //Process[] localByName = Process.GetProcessesByName(svc);
                //foreach (Process p in localByName)
                //{
                //    //Console.WriteLine("Private memory size64: {0}", (p.PrivateMemorySize64 / f).ToString("#,##0"));
                //    memsize += p.WorkingSet64 / 1024/ 1024;
                //    //Console.WriteLine("Peak virtual memory size64: {0}", (p.PeakVirtualMemorySize64 / f).ToString("#,##0"));
                //    //Console.WriteLine("Peak paged memory size64: {0}", (p.PeakPagedMemorySize64 / f).ToString("#,##0"));
                //    //Console.WriteLine("Paged system memory size64: {0}", (p.PagedSystemMemorySize64 / f).ToString("#,##0"));
                //    //Console.WriteLine("Paged memory size64: {0}", (p.PagedMemorySize64 / f).ToString("#,##0"));
                //    //Console.WriteLine("Nonpaged system memory size64: {0}", (p.NonpagedSystemMemorySize64 / f).ToString("#,##0"));
                //}

                return(Math.Round(memsize, 2));
            }
            catch
            {
                return(-1);
            }
        }
Beispiel #36
0
 private void LoadAllMemoryDetails(object temp)
 {
     try
     {
         float totheapsize, fgen0heapsize, fgen1heapsize, fgen2heapsize;
         pcclrmemmngr.MachineName  = mcname;
         pcclrmemmngr.InstanceName = "aspnet_wp";                //System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString().Substring(0, 14);
         pcclrmemmngr.CategoryName = ".NET CLR Memory";
         pcclrmemmngr.CounterName  = "# Bytes in all Heaps";
         totheapsize              = pcclrmemmngr.NextValue();
         lbltotheapsize.Text      = totheapsize + " Bytes";
         pcclrmemmngr.CounterName = "Gen 0 heap size";
         fgen0heapsize            = pcclrmemmngr.NextValue();
         gen0heapsize.Text        = fgen0heapsize.ToString() + " Bytes" + " (" + ((fgen0heapsize / totheapsize) * 100) + ")" + "%";
         pcclrmemmngr.CounterName = "Gen 1 heap size";
         fgen1heapsize            = pcclrmemmngr.NextValue();
         gen1heapsize.Text        = fgen1heapsize.ToString() + " Bytes" + " (" + ((fgen1heapsize / totheapsize) * 100) + ")" + "%";
         pcclrmemmngr.CounterName = "Gen 2 heap size";
         fgen2heapsize            = pcclrmemmngr.NextValue();
         gen2heapsize.Text        = fgen2heapsize.ToString() + " Bytes" + " (" + ((fgen2heapsize / totheapsize) * 100) + ")" + "%";
         pcclrmemmngr.CounterName = "# Total committed Bytes";
         lblgctime.Text           = pcclrmemmngr.NextValue().ToString() + " Bytes";
         pcclrmemmngr.CounterName = "# Total reserved Bytes";
         label1.Text              = pcclrmemmngr.NextValue().ToString() + " Bytes";
         pcclrmemmngr.CounterName = "Large Object Heap size";
         label7.Text              = pcclrmemmngr.NextValue().ToString() + " Bytes";
     }
     catch
     {
     }
 }
Beispiel #37
0
        public void Run()
        {
//			// To get POS.exe stats
//			fnGetPOSProcessInfo GetPOSProcessInfo = new fnGetPOSProcessInfo();
//			GetPOSProcessInfo.Run();

//	        // These global variables are returned
//			public static int       POSHandleCount = 0;
//			public static int       POSThreads = 0;
//			public static int       POSUsedMemory = 0;
//			public static int       POSGDIObjects = 0;
//			public static int       POSUserObjects = 0;
//			public static int       POSCurrentCPUUsage = 0;

//			if (Global.RegisterRunningRetech) ProcessName = "source";
//			if (Global.RegisterRunningIPOS) ProcessName = "pos";
//			if (Global.RegisterRunningIPOS & Global.CurrentScenario <= 30)
//				ProcessName = "pos";
//
//			if (Global.RegisterRunningRetech & Global.CurrentScenario > 30)
//				ProcessName = "source";

            System.Diagnostics.Process [] localByName = System.Diagnostics.Process.GetProcessesByName(Global.ProcessName);
            IntPtr POSHandlePtr = localByName[0].Handle;

            Global.POSHandleCount = localByName[0].HandleCount;
            Global.POSThreads     = localByName[0].Threads.Count;
            Global.POSUsedMemory  = (int)localByName[0].WorkingSet64 / (1024 * 1024);

            Global.POSGDIObjects  = (int)GetGuiResources(localByName[0].Handle, 0);             // GDI
            Global.POSUserObjects = (int)GetGuiResources(localByName[0].Handle, 1);             // User

            // Get Current Cpu Usage
            System.Diagnostics.PerformanceCounter CPUUsage;
            CPUUsage = new System.Diagnostics.PerformanceCounter();
            CPUUsage.CategoryName = "Processor";
            CPUUsage.CounterName  = "% Processor Time";
            CPUUsage.InstanceName = "_Total";
            CPUUsage.NextValue();
            System.Threading.Thread.Sleep(1000);
            Global.POSCurrentCPUUsage = (int)CPUUsage.NextValue();
        }
Beispiel #38
0
        public float GetValue(PerformanceCounter item)
        {
            var counter = new System.Diagnostics.PerformanceCounter
            {
                CategoryName = item.CategoryName,
                CounterName  = item.CounterName,
                InstanceName = item.InstanceName,
                MachineName  = item.MachineName
            };

            return(counter.NextValue());
        }
Beispiel #39
0
        public void Update(GameTime gameTime)
        {
            _elapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (_elapsedTime >= 1.0f)
            {
                CPUUsage     = _cpuCounter.NextValue();
                RAMavailable = _ramCounter.NextValue();
                _elapsedTime = 0;
            }
            CurrentProcessMemoryUsage     = _currentProcess.PrivateMemorySize64;
            CurrentAllocatedManagedMemory = GC.GetTotalMemory(false);
        }
        public static void GetStatus(Process process, string exename)
        {
            프로세스_CPU_사용량 = 0.0f;
            전체_CPU_사용량   = 0.0f;
            메모리_사용량      = 0;

            if (process != null)
            {
                프로세스_CPU_사용량 = GetUsage(process, out 전체_CPU_사용량);

                var objMemory = new System.Diagnostics.PerformanceCounter("Process", "Working Set - Private", exename);
                메모리_사용량 = (int)objMemory.NextValue() / 1000000;
            }
        }
 public String BuildTree()
 {
     ramCounter = new PerformanceCounter("Memory", "Available MBytes");
     try
     {
         using (StreamReader sr = new StreamReader(path))
         {
             string cur;
             Double availableRam = ramCounter.NextValue();
             while (((cur = sr.ReadLine()) != null) && (availableRam > 40))
             {
                 dict.Add(cur.ToLower());
                 availableRam = ramCounter.NextValue();
             }
             Debug.WriteLine("Tree has maxed out its RAM capacity...");
             return("Memory has been maxed out to its capacity");
         }
     }
     catch (IOException)
     {
         Debug.WriteLine("File could be used by another process");
         return("Failed...");
     }
 }
        private void sw_Tick(object source, ElapsedEventArgs e)
        {
            //GET AVAILABLE MEMORY
            var ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes", true);

            try
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    freeram.Content = Convert.ToInt32(ramCounter.NextValue() / 1024).ToString() + "GB";
                    if (Convert.ToInt32(ramCounter.NextValue() / 1024) <= 2)
                    {
                        errorlowram.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        errorlowram.Visibility = Visibility.Hidden;
                    }
                }));
            }
            catch
            { }
            //GET TOTAL MEMORY
        }
        public HowTo()
        {
            Window1.singleton.MenuToggleButton.IsEnabled = false;
            Window1.singleton.popupbox.IsEnabled         = false;
            Window1.singleton.homeButton.IsEnabled       = false;
            InitializeComponent();
            var ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes", true);

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                freeram.Content = Convert.ToInt32(ramCounter.NextValue() / 1024).ToString() + "GB";
            }));
            sw.Start();
            sw.Elapsed += new ElapsedEventHandler(sw_Tick);
            sw.Interval = 2000; // in miliseconds
        }
Beispiel #44
0
        static void PerfCounter_Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var timerEnabled = _perfCounterTimer.Enabled;

            _perfCounterTimer.Enabled = false;

            try
            {
                _cpuUsage = _cpuCounter.NextValue();
                _perfCounterTimer.Enabled = timerEnabled;
            }
            catch (Exception ex) //logged
            {
                Logger.WriteException(new Exception("Error when trying to get value of CPU counter. ", ex));

                _perfCounterTimer.Enabled = false;
            }
        }
Beispiel #45
0
 private void ScanMarketEvent(int si, System.Diagnostics.PerformanceCounter performanceCounter)
 {
     // 可以讀到正確的值
     //Console.Write(string.Format("{0} ", si));
     try
     {
         if (performanceCounter == null)
         {
             return;
         }
         int val = (int)performanceCounter.NextValue();
         SetChart(si, val);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error! " + ex.Message);
         Debug.WriteLine(ex.Message);
     }
 }
Beispiel #46
0
        private void TimerTick(object sender, EventArgs e)
        {
            //if (!PerformanceCounterCategory.Exists("Processor"))
            //{
            //  Console.WriteLine("Object Processor does not exist!");
            //  return;
            //}

            //if (!PerformanceCounterCategory.CounterExists(@"% Processor Time", "Processor"))
            //{
            //  Console.WriteLine(@"Counter % Processor Time does not exist!");
            //  return;
            //}



            //while (true)
            //{
            //  Debug.WriteLine("@");

            //try
            //{
            //  Debug.WriteLine(@"Current value of Processor, %Processor Time, _Total= " + mCounter.NextValue().ToString());
            //}

            //catch
            //{
            //  Debug.WriteLine(@"_Total instance does not exist!");
            //  return;
            //}
            mPointsX.Add(mX++);
            var wY = mCounter.NextValue();

            Debug.WriteLine(@"_Total= " + wY);
            mPointsY.Add(wY);
            mLineGraph.Plot(mPointsX, mPointsY);

            //  Thread.Sleep(10000);
            //}
        }
Beispiel #47
0
        private static bool WaitForQuietCpu(float maxCpuSpike = 25, int minSecondsOfQuiet = 2, int maxSecondsBeforeGiveUp = 30)
        {
            using (var pc = new System.Diagnostics.PerformanceCounter()) {
                pc.CategoryName = "Processor";
                pc.CounterName  = "% Processor Time";
                pc.InstanceName = "_Total";

                TimeSpan samplingInterval      = TimeSpan.FromMilliseconds(1000);
                TimeSpan minimumQuietTime      = TimeSpan.FromSeconds(minSecondsOfQuiet);
                TimeSpan maximumTimeBeforeBail = TimeSpan.FromSeconds(maxSecondsBeforeGiveUp);
                DateTime startTryingStamp      = DateTime.Now;
                int      hitsRequired          = (int)(minimumQuietTime.TotalMilliseconds / samplingInterval.TotalMilliseconds);
                while (DateTime.Now - startTryingStamp < maximumTimeBeforeBail)
                {
                    int hits;
                    for (hits = 0; hits < hitsRequired; hits++)
                    {
                        float currentCpuUtilization = pc.NextValue();
                        if (currentCpuUtilization > maxCpuSpike)
                        {
                            ////Console.WriteLine("Miss: CPU at {0}% utilization", currentCpuUtilization);
                            break;
                        }

                        ////Console.WriteLine("Hit: CPU at {0}% utilization", currentCpuUtilization);
                        Thread.Sleep(samplingInterval);
                    }

                    if (hits == hitsRequired)
                    {
                        return(true);
                    }

                    Thread.Sleep(samplingInterval);
                }

                return(false);
            }
        }
Beispiel #48
0
        partial void InitializeWindowsPerformanceCounters()
        {
            this._pcActiveThreads      = new System.Diagnostics.PerformanceCounter();
            this._pcInUseThreads       = new System.Diagnostics.PerformanceCounter();
            this._pcQueuedWorkItems    = new System.Diagnostics.PerformanceCounter();
            this._pcCompletedWorkItems = new System.Diagnostics.PerformanceCounter();

            //
            // pcActiveThreads
            //
            this._pcActiveThreads.CategoryName = "SmartThreadPool";
            this._pcActiveThreads.CounterName  = "Active threads";
            this._pcActiveThreads.InstanceName = "Test SmartThreadPool";
            //
            // pcInUseThreads
            //
            this._pcInUseThreads.CategoryName = "SmartThreadPool";
            this._pcInUseThreads.CounterName  = "In use threads";
            this._pcInUseThreads.InstanceName = "Test SmartThreadPool";
            //
            // pcQueuedWorkItems
            //
            this._pcQueuedWorkItems.CategoryName = "SmartThreadPool";
            this._pcQueuedWorkItems.CounterName  = "Work Items in queue";
            this._pcQueuedWorkItems.InstanceName = "Test SmartThreadPool";
            //
            // pcCompletedWorkItems
            //
            this._pcCompletedWorkItems.CategoryName = "SmartThreadPool";
            this._pcCompletedWorkItems.CounterName  = "Work Items processed";
            this._pcCompletedWorkItems.InstanceName = "Test SmartThreadPool";

            _getActiveThreads      = () => (long)_pcActiveThreads.NextValue();
            _getInUseThreads       = () => (long)_pcInUseThreads.NextValue();
            _getQueuedWorkItems    = () => (long)_pcQueuedWorkItems.NextValue();
            _getCompletedWorkItems = () => (long)_pcCompletedWorkItems.NextValue();
        }
Beispiel #49
0
        private void CollectInternalCounters()
        {
            memoryUsed.Add(GC.GetTotalMemory(false));
            gcGen0.Add(GC.CollectionCount(0));
            gcGen1.Add(GC.CollectionCount(1));
            gcGen2.Add(GC.CollectionCount(2));
            if (AppDomain.MonitoringIsEnabled)
            {
                memorySurvived.Add(AppDomain.CurrentDomain.MonitoringSurvivedMemorySize);

                cpuUsage.Add((long)(AppDomain.CurrentDomain.MonitoringTotalProcessorTime.TotalMilliseconds * 100 / PollPeriod_ms / Environment.ProcessorCount));
            }

            //Collect windows perf counters
            foreach (var item in windowsPerfCountersList)
            {
                myCounter.CategoryName = "Process";
                myCounter.CounterName  = item.Name;
                myCounter.InstanceName = Process.GetCurrentProcess().ProcessName;
                var raw = (long)(myCounter.NextValue());

                item.Add(raw);
            }
        }
Beispiel #50
0
        /*
         * [WebMethod]
         * [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
         * public string AddSuggestion(string q)
         * {
         *  Node current = searcher.Prefix(q);
         *  //if (current.Depth == q.Length && current.FindChild('@') != null)
         *  if (current.Suffix.Contains(q.Substring(q.IndexOf(current.Value) + 1))
         || current.Depth == q.Length && current.Suffix.Contains("@"))
         || {
         ||     return "!" + q + " was found!";
         || }
         || else
         || {
         ||     //searcher.Insert(q);
         ||     // return q + " was added to the suggestions!";
         ||     return q + " was not found!";
         || }
         ||}*/

        private static float getAvailableRAM(System.Diagnostics.PerformanceCounter RAM)
        {
            return(RAM.NextValue());
        }
        /// <summary>
        /// MainLoopAsync
        /// </summary>
        /// <returns></returns>
        private async Task MainLoopAsync(MemoryMappedFile orderMmf)
        {
            Microsoft.VisualBasic.Devices.ComputerInfo systemInfo;

            List <Process> listPs = new List <Process>();

            Dictionary <int, Dictionary <string, Queue <ulong> > > multiCalcuDict = new Dictionary <int, Dictionary <string, Queue <ulong> > >();
            Dictionary <int, ulong> movingAverageWsSum      = new Dictionary <int, ulong>();
            Dictionary <int, ulong> movingAveragePmSum      = new Dictionary <int, ulong>();
            Dictionary <int, ulong> continuousNonResponding = new Dictionary <int, ulong>();

            Dictionary <int, MemoryMappedFile> mmfDict = new Dictionary <int, MemoryMappedFile>();


            System.Diagnostics.PerformanceCounter pcCpuTotal = new System.Diagnostics.PerformanceCounter(Resources.PerformanceCounterCategoryName, Resources.PerformanceCounterCounterName, Resources.PerformaceCounterInstanceName, Resources.PerfomanceCounterMachineName);

            System.Diagnostics.PerformanceCounter[] pcCpuCounterArray;


            Queue <ulong> cpuQueue = new Queue <ulong>();

            movingAverageWsSum[CPU_TOTAL] = 0;

            // Main loop preparation

            List <int>    processIdList;
            List <string> startTimeList;
            List <int>    orderList;

            bool shouldExit = false;
            int  counter    = 0;
            int  v          = interval * 1000 / ORDER_CHECK_INTERVAL;
            int  cpuCount   = Environment.ProcessorCount;

            if (cpuCount >= MAX_CPU_COUNT)
            {
                pcCpuCounterArray = new PerformanceCounter[MAX_CPU_COUNT];
            }
            else
            {
                pcCpuCounterArray = new PerformanceCounter[cpuCount];
            }
            int indedCpuCounter = 0;

            while (indedCpuCounter < pcCpuCounterArray.Length)
            {
                pcCpuCounterArray[indedCpuCounter] = new System.Diagnostics.PerformanceCounter(Resources.PerformanceCounterCategoryName, Resources.PerformanceCounterCounterName, indedCpuCounter.ToString(), Resources.PerfomanceCounterMachineName);
                indedCpuCounter++;
            }

            string        fileNameSysLog  = System.IO.Path.Combine(logDirectory, "MPI_SYS_" + System.DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".log");
            string        fileNameProcLog = System.IO.Path.Combine(logDirectory, "MPI_PROC_" + System.DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".log");
            StringBuilder sbSysLog        = new StringBuilder();
            StringBuilder sbProcLog       = new StringBuilder();

            //Logging
            using (var writerSystemLog = new StreamWriter(fileNameSysLog))
            {
                using (var writerProcessLog = new StreamWriter(fileNameProcLog))
                {
                    if (logging)
                    {
                        await writerSystemLog.WriteLineAsync(Resources.LogHeaderSystem);

                        await writerProcessLog.WriteLineAsync(Resources.LogHeaderProcess);
                    }
                    //Main loop
                    while (!shouldExit)
                    {
                        counter++;

                        //Check Order
                        byte[] arraydata = new byte[ORDER_MEM_FILE_SIZE];
                        byte[] arrayzero = new byte[ORDER_MEM_FILE_SIZE];
                        using (MemoryMappedViewAccessor accessor = orderMmf.CreateViewAccessor())
                        {
                            accessor.ReadArray <byte>(0, arraydata, 0, ORDER_MEM_FILE_SIZE);
                            accessor.WriteArray <byte>(0, arrayzero, 0, ORDER_MEM_FILE_SIZE);
                        }

                        // Check Order
                        processIdList = new List <int>();
                        startTimeList = new List <string>();
                        orderList     = new List <int>();
                        ExtractOrderInfoFromByteArray(arraydata, ref orderList, ref processIdList, ref startTimeList);

                        int index = 0;
                        while (index < orderList.Count())
                        {
                            int order = orderList[index];
                            if (order == 0)
                            {
                                break;
                            }
                            switch (order)
                            {
                            case (int)Order.Add:
                                //Create mmf for target process
                                int     pid;
                                string  pStartTime;
                                Process p;

                                if (processIdList.Count() > MAX_COUNT_OF_PROCESSES)
                                {
                                    throw new Exception(Resources.ExceptionMsgExceededProcesses);
                                }

                                if (processIdList[index] == 0)
                                {
                                    pid        = NO_PROCESS;
                                    pStartTime = NO_PROCESS_TIMESTRNIG;
                                    p          = null;
                                }
                                else
                                {
                                    p          = System.Diagnostics.Process.GetProcessById(processIdList[index]);
                                    pid        = p.Id;
                                    pStartTime = p.StartTime.ToString(PROC_INFO_MEM_FILE_TIMEFORMAT);
                                }


                                if (pStartTime == startTimeList[index])
                                {
                                    var memFileName = Resources.PrefixMemFileName + pid.ToString() + "_" + startTimeList[index];
                                    mmfDict[processIdList[index]] = MemoryMappedFile.CreateNew(memFileName, PROC_INFO_MEM_FILE_SIZE);
                                    multiCalcuDict.Add(pid, new Dictionary <string, Queue <ulong> >());
                                    multiCalcuDict[pid][MonitorItem.ProcessWorkingSet.ToString()]         = new Queue <ulong>();
                                    multiCalcuDict[pid][MonitorItem.ProcessTotalProcessorTime.ToString()] = new Queue <ulong>();
                                    multiCalcuDict[pid][MonitorItem.ProcessPrivateMemorySize.ToString()]  = new Queue <ulong>();
                                    movingAverageWsSum[pid]      = 0;
                                    movingAveragePmSum[pid]      = 0;
                                    continuousNonResponding[pid] = 0;
                                    listPs.Add(p);
                                }
                                else
                                {
                                    throw (new Exception(Resources.ExceptionMsgSameIdButNotSameStarttime));
                                }
                                break;

                            case (int)Order.Terminate:
                                shouldExit = true;
                                break;
                            }
                            index++;
                        }

                        if (counter >= v)
                        {
                            counter = 0;
                            List <Process> nonexistsProcesses = new List <Process>();
                            // Start to Get Info

                            //Checking System CPU Total
                            ulong systemCpu = (ulong)(pcCpuTotal.NextValue() * 100);


                            //Checking System CPU MA
                            ulong systemCpuMA = 0;

                            cpuQueue.Enqueue(systemCpu);
                            movingAverageWsSum[CPU_TOTAL] += systemCpu;
                            if (cpuQueue.Count > number)
                            {
                                movingAverageWsSum[CPU_TOTAL] -= cpuQueue.Dequeue();
                                systemCpuMA = (ulong)movingAverageWsSum[CPU_TOTAL] / (ulong)number;
                            }

                            //Each CPU
                            ulong[] eachCpu = new ulong[EACH_CPU_MEM_FILE_COUNT];

                            int cpuIndex  = 0;
                            int fileIndex = 0;
                            while (cpuIndex < pcCpuCounterArray.Length)
                            {
                                float tempCpu = pcCpuCounterArray[cpuIndex].NextValue();
                                int   shift   = (cpuIndex % 4) << 3;
                                eachCpu[fileIndex] = eachCpu[fileIndex] ^ ((((ulong)(tempCpu)) & 0xff) << shift);
                                cpuIndex++;
                                if (cpuIndex % 4 == 0)
                                {
                                    fileIndex++;
                                }
                            }

                            systemInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();

                            //Checking System Total Physical Memory
                            ulong systemTotalPhysicalMem = systemInfo.TotalPhysicalMemory;


                            //Checkinh System Available Phisycal Memory
                            ulong systemAvailableMem = systemInfo.AvailablePhysicalMemory;


                            //Checking System Total Virtual Memory
                            ulong systemTotalVirtualMem = systemInfo.TotalVirtualMemory;


                            //Checkinh System Avilable Virtual Memory
                            ulong systemAvailableVirtualMem = systemInfo.AvailableVirtualMemory;

                            if (logging)
                            {
                                //System value
                                sbSysLog = new StringBuilder(512);
                                sbSysLog.Append(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.sss,"));

                                sbSysLog.Append(systemCpu.ToString());
                                sbSysLog.Append(',');

                                sbSysLog.Append(systemCpuMA.ToString());
                                sbSysLog.Append(',');

                                foreach (ulong cpuv in eachCpu)
                                {
                                    sbSysLog.Append(cpuv.ToString());
                                    sbSysLog.Append(',');
                                }

                                sbSysLog.Append(systemTotalPhysicalMem.ToString());
                                sbSysLog.Append(',');

                                sbSysLog.Append(systemAvailableMem.ToString());
                                sbSysLog.Append(',');

                                sbSysLog.Append(systemTotalVirtualMem.ToString());
                                sbSysLog.Append(',');

                                sbSysLog.Append(systemAvailableVirtualMem.ToString());

                                await writerSystemLog.WriteLineAsync(sbSysLog.ToString());
                            }

                            //for each processes
                            foreach (Process p in listPs)
                            {
                                var writeValueList = new List <ulong>();

                                //Checking System CPU
                                writeValueList.Add(systemCpu);  // #0

                                //Checking System CPU MA
                                writeValueList.Add(systemCpuMA);  // #1

                                //
                                writeValueList.Add(eachCpu[0]);   //#2

                                writeValueList.Add(eachCpu[1]);   //#3

                                writeValueList.Add(eachCpu[2]);   //#4

                                writeValueList.Add(eachCpu[3]);   //#5

                                //Checking System Total Physical Memory
                                writeValueList.Add(systemTotalPhysicalMem);  // #6

                                //Checkinh System Available Phisycal Memory
                                writeValueList.Add(systemAvailableMem);  // #7

                                //Checking System Total Virtual Memory
                                writeValueList.Add(systemTotalVirtualMem);  // #8

                                //Checkinh System Avilable Virtual Memory
                                writeValueList.Add(systemTotalVirtualMem);  // #9


                                int pid;
                                if (p != null)
                                {
                                    p.Refresh();
                                    pid = p.Id;

                                    try
                                    {
                                        if (p.HasExited)
                                        {
                                            nonexistsProcesses.Add(p);
                                            continue;
                                        }
                                    }
                                    catch
                                    {
                                        nonexistsProcesses.Add(p);
                                        continue;
                                    }

                                    if (!multiCalcuDict.ContainsKey(pid))
                                    {
                                        throw (new KeyNotFoundException(Resources.ExceptionMsgKeyNotFoundInDict + pid.ToString()));
                                    }



                                    // Get WorkingSet
                                    var workingset = (ulong)p.WorkingSet64;
                                    writeValueList.Add(workingset);  // #10



                                    // Calculate Moving Average of Workingset
                                    ulong workingsetMa = 0;
                                    multiCalcuDict[pid][MonitorItem.ProcessWorkingSet.ToString()].Enqueue(workingset);
                                    movingAverageWsSum[pid] += workingset;
                                    if (multiCalcuDict[pid][MonitorItem.ProcessWorkingSet.ToString()].Count > number)
                                    {
                                        movingAverageWsSum[pid] -= multiCalcuDict[pid][MonitorItem.ProcessWorkingSet.ToString()].Dequeue();
                                        workingsetMa             = (ulong)movingAverageWsSum[pid] / (ulong)number;
                                    }
                                    writeValueList.Add(workingsetMa);  // #11


                                    // Get PrivateMemorySize
                                    var privatememory = (ulong)p.PrivateMemorySize64;
                                    writeValueList.Add(privatememory);  // #12



                                    //Get PrivateMemorySizeMA
                                    ulong privateMemoryMa = 0;
                                    multiCalcuDict[pid][MonitorItem.ProcessPrivateMemorySize.ToString()].Enqueue(privatememory);
                                    movingAveragePmSum[pid] += privatememory;
                                    if (multiCalcuDict[pid][MonitorItem.ProcessPrivateMemorySize.ToString()].Count > number)
                                    {
                                        movingAveragePmSum[pid] -= multiCalcuDict[pid][MonitorItem.ProcessPrivateMemorySize.ToString()].Dequeue();
                                        privateMemoryMa          = (ulong)movingAveragePmSum[pid] / (ulong)number;
                                    }
                                    writeValueList.Add(privateMemoryMa);  // #13



                                    // TotalManagedMemoryFromGC
                                    var totalMangedMemory = (ulong)GC.GetTotalMemory(false);
                                    writeValueList.Add(totalMangedMemory);  // #14



                                    // Get Cputime
                                    var cpuTotalTime = (ulong)(p.TotalProcessorTime.TotalMilliseconds);
                                    writeValueList.Add(cpuTotalTime);  // #15


                                    // Calculate Delta CpuTime
                                    ulong cpuTotalTimeDelta = 0;
                                    multiCalcuDict[pid][MonitorItem.ProcessTotalProcessorTime.ToString()].Enqueue(cpuTotalTime);
                                    if (multiCalcuDict[pid][MonitorItem.ProcessTotalProcessorTime.ToString()].Count > number)
                                    {
                                        cpuTotalTimeDelta = cpuTotalTime - multiCalcuDict[pid][MonitorItem.ProcessTotalProcessorTime.ToString()].Dequeue();
                                    }
                                    writeValueList.Add(cpuTotalTimeDelta);  // #16

                                    //Check Responding
                                    var responding = p.Responding;
                                    writeValueList.Add((ulong)(responding ? 1 : 0)); // #17

                                    if (!responding)
                                    {
                                        continuousNonResponding[pid]++;
                                    }
                                    else
                                    {
                                        continuousNonResponding[pid] = 0;
                                    }
                                    writeValueList.Add(continuousNonResponding[pid]);  //#18


                                    //Logging
                                    if (logging)
                                    {
                                        sbProcLog = new StringBuilder(1024);
                                        sbProcLog.Append(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.sss,"));
                                        sbProcLog.Append(pid.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(workingset.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(workingsetMa.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(privatememory.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(privateMemoryMa.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(totalMangedMemory.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(cpuTotalTime.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(cpuTotalTimeDelta.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(responding.ToString());
                                        sbProcLog.Append(',');

                                        sbProcLog.Append(continuousNonResponding[pid].ToString());


                                        await writerProcessLog.WriteLineAsync(sbProcLog.ToString());
                                    }
                                }
                                else
                                {
                                    pid = 0;
                                }

                                // Write to mmf of target pid
                                using (MemoryMappedViewAccessor accessor = mmfDict[pid].CreateViewAccessor())
                                {
                                    accessor.WriteArray <ulong>(0, writeValueList.ToArray(), 0, writeValueList.Count());
                                }
                            }
                            foreach (Process p in nonexistsProcesses)
                            {
                                if (p != null)
                                {
                                    mmfDict[p.Id].Dispose();
                                    multiCalcuDict.Remove(p.Id);
                                    listPs.Remove(p);
                                }
                            }
                        }

                        Thread.Sleep(ORDER_CHECK_INTERVAL);
                    }
                }
            }
            if (!logging)
            {
                Thread.Sleep(100);
                System.IO.File.Delete(fileNameProcLog);
                System.IO.File.Delete(fileNameSysLog);
            }
            //Termination
            foreach (MemoryMappedFile mmf in mmfDict.Values)
            {
                mmf.Dispose();
            }
            orderMmf.Dispose();
        }
Beispiel #52
0
 public float NextValue()
 {
     //Perform any transformations here
     return(_performanceCounter.NextValue());
 }
Beispiel #53
0
 public float GetAvailableMemory()
 {
     return(m_memoryCounter.NextValue());
 }
Beispiel #54
0
 public float GetCPULoad()
 {
     return(m_CPUCounter.NextValue());
 }
    private void GetUserOnlineCount()
    {
        try
        {
            string applicationIntanceName = System.Web.Hosting.HostingEnvironment.ApplicationID.Replace('/', '_');
            System.Diagnostics.PerformanceCounter performanceCounter = new System.Diagnostics.PerformanceCounter("ASP.NET Applications", "Sessions Active", applicationIntanceName);
            lblUserOnlineCount_LocalDateTime.Text = GetLocalResourceObject("UserOnlineLabel") + performanceCounter.NextValue().ToString() + " " + GetLocalResourceObject("PersonLabel");
        }
        catch (Exception)
        {
        }
        //if (Application["UserOnlineCount"] != null)
        //{

        //    lblUserOnlineCount_LocalDateTime.Text = "کاربران آنلاین :" + Application["UserOnlineCount"].ToString() + " نفر";
        //}
    }
Beispiel #56
0
        private void TouchThreadFunc(object state)
        {
            Job job = ((Tuple <Job, JobsDBDataContext, ManualResetEvent>)state).Item1;
            JobsDBDataContext jobsDataContext = ((Tuple <Job, JobsDBDataContext, ManualResetEvent>)state).Item2;
            ManualResetEvent  stopEvent       = ((Tuple <Job, JobsDBDataContext, ManualResetEvent>)state).Item3;
            var    ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            long   curWorkingSet, curGCTotal, curPrivate;
            long   maxWorkingSet = 0;
            long   maxGCTotal = 0;
            long   maxPrivate = 0;
            double curRamAvailMb, minRamAvailMb = double.MaxValue;
            int    fails = 0;

            JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":Touch thread running");
            bool jobDeleted = false;

            while (true)
            {
                Process currentProcess = Process.GetCurrentProcess();
                currentProcess.Refresh();
                curWorkingSet = Environment.WorkingSet;
                curGCTotal    = GC.GetTotalMemory(false);
                curPrivate    = currentProcess.PrivateMemorySize64;
                curRamAvailMb = ramCounter.NextValue();
                if (maxWorkingSet < curWorkingSet)
                {
                    maxWorkingSet = curWorkingSet;
                }
                if (maxGCTotal < curGCTotal)
                {
                    maxGCTotal = curGCTotal;
                }
                if (maxPrivate < curPrivate)
                {
                    maxPrivate = curPrivate;
                }
                if (minRamAvailMb > curRamAvailMb)
                {
                    minRamAvailMb = curRamAvailMb;
                }
                try
                {
                    bool cancelationCheckNeeded = false;
                    lock (jobsDataContext)
                    {
                        JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Touch thread tick", job);
                        bool touched = false;
                        for (int touchTries = 0; touchTries < 5; touchTries++)
                        {
                            try
                            {
                                jobsDataContext.Refresh(RefreshMode.KeepChanges, job);
                                job.Touchtime = DateTime.UtcNow;
                                jobsDataContext.SubmitChanges();
                                touched = true;
                                break;
                            }
                            catch (ChangeConflictException)
                            {
                                //TraceConflicts(jobsDataContext, "updating touch time");
                                JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Failed to update touchtime. attempt {1}", job, touchTries + 1);
                                jobsDataContext.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);
                            }
                        }
                        if (touched)
                        {
                            JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Updated TouchTime", job);
                        }
                        else
                        {
                            JobManager.JobManagerTrace.TraceWarning(this.ToShortString() + ":{0} Failed to update TouchTime", job);
                        }
                        if (job.IsHeavyJob == 0)
                        {
                            var execTimespanSec = (DateTime.UtcNow - job.StartTime.Value).TotalSeconds;
                            if (execTimespanSec > settings.LightJobExecutionPermitedTimeSec)
                            {
                                JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Job considered to be HEAVY", job);

                                for (int retries = 0; retries < 10; retries++)
                                {
                                    try
                                    {
                                        var allParts = jobsDataContext.Jobs.Where(j1 => j1.Hash == job.Hash).ToArray();
                                        foreach (var j in allParts)
                                        {
                                            j.IsHeavyJob = 1;
                                        }

                                        JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Committing HEAVY flag for all jobs part", job);
                                        jobsDataContext.Refresh(RefreshMode.KeepChanges, allParts);
                                        jobsDataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
                                        break;
                                    }
                                    catch (ChangeConflictException)
                                    {
                                        JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Failed to set heavy flag for all parts. attempt {1}", job, retries + 1);
                                        //TraceConflicts(jobsDataContext, "heavy flag committing");
                                        jobsDataContext.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);
                                    }
                                }
                                JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Successfully committed HEAVY flag for all jobs part", job);

                                cancelationCheckNeeded = true;
                            }
                            else
                            {
                                JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} touched job part record. Job still light ({1} execution seconds of {2} permitted)", job, execTimespanSec, settings.LightJobExecutionPermitedTimeSec);
                            }
                        }
                        else
                        {
                            JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} touched job part record. Job is already marked as heavy", job);
                            cancelationCheckNeeded = true;
                        }

                        if (cancelationCheckNeeded)
                        {
                            JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Checking for heavy job cancelation", job);
                            int otherRunningHeavyPartsCount = jobsDataContext.Jobs.Count(j2 => j2.StartTime < job.StartTime && j2.Status == 1 && j2.IsHeavyJob == 1);
                            if (otherRunningHeavyPartsCount >= settings.PermitedHeavyPartWorkers)
                            {
                                JobManager.JobManagerTrace.TraceInfo(this.ToShortString() + ":{0} Aborting working thread as there are {1} other active heavy parts ({2} total permitted)", job, otherRunningHeavyPartsCount, settings.PermitedHeavyPartWorkers);
                                if (workingThread != null)
                                {
                                    workingThread.Abort();
                                }
                            }
                            else
                            {
                                JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} Continuing heavy part as there are {1} other active heavy parts ({2} total permitted)", job, otherRunningHeavyPartsCount, settings.PermitedHeavyPartWorkers);
                            }
                        }
                    }

                    if (stopEvent.WaitOne(TimeSpan.FromSeconds(settings.TouchPeriodInSeconds)))
                    {
                        JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":{0} detected touch thread stop request. stopping touch thread loop...", job);
                        break;
                    }
                }
                catch (InvalidOperationException exc)
                {
                    jobDeleted = true;
                    JobManager.JobManagerTrace.TraceWarning(this.ToShortString() + ":{0} InvalidOperationException. Is job part deleted? ({1})", job, exc.ToString());
                    break;
                }
                catch (ChangeConflictException)
                {
                    lock (jobsDataContext)
                    {
                        if (TraceConflicts(jobsDataContext, "last chance exc") || jobDeleted)
                        {
                            break;
                        }
                    }
                }
                catch (Exception exc)
                {
                    JobManager.JobManagerTrace.TraceWarning(this.ToShortString() + ":{0} Error updating touch time for job {1}", job, exc.ToString());
                    if (fails++ > 3)
                    {
                        break;
                    }
                }

                if (jobDeleted)
                {
                    JobManager.JobManagerTrace.TraceWarning(this.ToShortString() + ":{0} record is deleted. stoping touch thread", job);
                }

                //curPhys = currentProcess.WorkingSet64;
                //curPaged = currentProcess.PagedMemorySize64;
                //curVirtual = currentProcess.VirtualMemorySize64;
                //if (currentLogRecord.PeakPhysicalMemoryUsage < curPhys) currentLogRecord.PeakPhysicalMemoryUsage = curPhys;
                //if (currentLogRecord.PeakPagedMemoryUsage < curPaged) currentLogRecord.PeakPagedMemoryUsage = curPaged;
                //if (currentLogRecord.PeakVirtualMemoryUsage < curVirtual) currentLogRecord.PeakVirtualMemoryUsage = curVirtual;
            }
            JobManager.JobManagerTrace.TraceVerbose(this.ToShortString() + ":Touch thread ending. Peak mem stats: working set {0}Mb, GC.allocated {1}Mb, PrivateMem {2}Mb, min available Ram {3}Mb",
                                                    ((double)maxWorkingSet) / (1024 * 1024), ((double)maxGCTotal) / (1024 * 1024), ((double)maxPrivate) / (1024 * 1024), minRamAvailMb);

            //currentLogRecord.WorkEnd = DateTime.UtcNow;
            //logManager.Insert(currentLogRecord);
        }
Beispiel #57
0
 public float getCurrentCpuUsage()
 {
     return(cpuCounter.NextValue());
 }
Beispiel #58
0
 public float getAvailableRAM()
 {
     return(ramCounter.NextValue());
 }
        static void Main(string[] args)
        {
            if (appFolder.Last() == '\\')
            {
                appFolder = appFolder.Remove(appFolder.Length - 1, 1);
            }

            var path = "";

            log.Add("[" + DateTime.Now.ToLongDateString() + "]");
            log.Add("Environtment directory: " + appFolder);

            if (args.Length > 0)
            {
                log.Add("_Using Command Prompt mode...");
                log.Add("__Command: " + String.Join(" ", args));
                if (!args[0].Equals(""))
                {
                    if (File.Exists(args[0]) && Path.GetExtension(args[0]).Equals(".theme"))
                    {
                        path = args[0];
                    }
                    else if (File.Exists(KAWAII_Theme_Helper.windir + @"\Resources\Themes\" + args[0] + ".theme") || File.Exists(KAWAII_Theme_Helper.windir + @"\Resources\Themes\" + args[0]))
                    {
                        path = KAWAII_Theme_Helper.windir + @"\Resources\Themes\" + args[0] + ".theme";
                        path = path.Replace(".theme.theme", ".theme");
                    }
                    else if (args[0].EqualsIgnoreCase("random"))
                    {
                        var themeList = new DirectoryInfo(KAWAII_Theme_Helper.windir + @"\Resources\Themes").GetFiles("*.theme", SearchOption.TopDirectoryOnly).Select(item => item.FullName).ToArray();
                        path = themeList[ThreadSafeRandom.ThisThreadsRandom.Next(0, themeList.Count() - 1)];
                        while (Path.GetFileNameWithoutExtension(path) == KAWAII_Theme_Helper.GetCurrentThemeName() || Path.GetFileNameWithoutExtension(path) == KAWAII_Theme_Helper.GetCurrentVisualStyleName())
                        {
                            path = themeList[ThreadSafeRandom.ThisThreadsRandom.Next(0, themeList.Count() - 1)];
                        }
                    }
                }
                if (args.Length > 1)
                {
                    if (Path.GetExtension(args[1]).EqualsIgnoreCase(".jpg"))
                    {
                        if (File.Exists(args[1]))
                        {
                            KAWAII_Theme_Helper.ChangeLockscreenBackground(args[1], winVer);
                            log.Add("___Lockscreen applied: " + args[1]);
                        }
                        else if (File.Exists(appFolder + "\\" + args[1]))
                        {
                            KAWAII_Theme_Helper.ChangeLockscreenBackground(appFolder + "\\" + args[1], winVer);
                            log.Add("___Lockscreen applied: " + args[1]);
                        }
                    }
                    else if (args[1].EqualsIgnoreCase("random"))
                    {
                        ChangeLockscreen("random", _blacklist, "", true);
                    }
                    else if (!path.Equals("") && !args[1].Equals(""))
                    {
                        ChangeLockscreen("respective", _blacklist, path, true);
                    }
                }

                if (!path.Equals(""))
                {
                    KAWAII_Theme_Helper.ApplyTheme(path);
                    log.Add("___Theme applied: " + path);
                }
                log.Add("_END");
            }
            else
            {
                log.Add("_Using Standard mode...");
                int exitDelay = 1500;

                if (File.Exists(appFolder + "\\startup.txt"))
                {
                    log.Add("__startup.txt found!");
                    int startupDelay  = -3;
                    var startupParams = File.ReadAllLines(appFolder + "\\startup.txt").Where(a => !a.Replace(" ", "").Equals("")).ToArray();
                    log.Add("__Startup params: " + String.Join(" | ", startupParams));
                    if (startupParams.Count() > 0 && !int.TryParse(startupParams[0].RegexReplace(@"[a-z_ :=]", "", -1), out startupDelay))
                    {
                        startupDelay = -3;
                    }
                    if (startupParams.Count() > 1 && !int.TryParse(startupParams[1].RegexReplace(@"[a-z_ :=]", "", -1), out exitDelay))
                    {
                        exitDelay = 1500;
                    }
                    if (exitDelay < 0)
                    {
                        exitDelay = 1500;
                    }

                    CreateStartupTaskSchedule();

                    if (startupDelay < 0)
                    {
                        log.Add("___Using Smart Delay...");
                        using (System.Diagnostics.PerformanceCounter cpu = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total"))
                        {
                            int hits = 0;
                            startupDelay = startupDelay <= -1000 ? (int)Math.Ceiling(startupDelay / -1000.0) : (int)Math.Ceiling(startupDelay / -1.0);
                            while (hits < startupDelay)
                            {
                                cpu.NextValue();
                                Thread.Sleep(1000);
                                if (cpu.NextValue() < 20)
                                {
                                    hits++;
                                }
                                else
                                {
                                    hits = 0;
                                }
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(startupDelay);
                    }
                }
                else
                {
                    log.Add("__startup.txt NOT found!");
                    RemoveScheduledStartupTask();
                }

                if (File.Exists(appFolder + "\\skip.txt"))
                {
                    log.Add("__skip.txt found!");
                    if (File.ReadAllText(appFolder + "\\skip.txt").Replace(" ", "").Equals(""))
                    {
                        log.Add("___Using 'skip once', deleting skip.txt...");
                        File.Delete(appFolder + "\\skip.txt");
                        log.Add("___END");
                        log.Add("");
                        File.AppendAllLines(appFolder + "\\logs.txt", log);
                        return;
                    }

                    var lns = File.ReadAllLines(appFolder + "\\skip.txt");
                    File.Delete(appFolder + "\\skip.txt");
                    log.Add("__Skip params: " + string.Join(" | ", lns));
                    int rem = int.Parse(lns[0].Replace(" ", "").Split('/')[0]);
                    if (lns.Length == 2)
                    {
                        if (rem <= 0)
                        {
                            log.Add("___Remaining skip has reached Zero! Changing theme...");
                            if (lns[1].Replace(" ", "").Equals("repeat", StringComparison.OrdinalIgnoreCase) || Equals("true", StringComparison.OrdinalIgnoreCase))
                            {
                                log.Add("____'Repeating Skip' enabled!");
                                rem = int.Parse(lns[0].Replace(" ", "").Split('/')[1]);
                                File.WriteAllLines(appFolder + "\\skip.txt", new string[] { rem + "/" + rem, "repeat" });
                            }
                        }
                        else
                        {
                            log.Add("___Remaining skip is " + rem + ", skipping current switch!");
                            rem--;
                            File.WriteAllLines(appFolder + "\\skip.txt", new string[] { rem + "/" + lns[0].Replace(" ", "").Split('/')[1] });
                            if (lns[1].Replace(" ", "").Equals("repeat", StringComparison.OrdinalIgnoreCase) || Equals("true", StringComparison.OrdinalIgnoreCase))
                            {
                                log.Add("____'Repeating Skip' enabled!");
                                File.AppendAllLines(appFolder + "\\skip.txt", new string[] { "repeat" });
                            }
                            log.Add("___END");
                            log.Add("");
                            File.AppendAllLines(appFolder + "\\logs.txt", log);
                            return;
                        }
                    }
                    else
                    {
                        log.Add("___Skip using only 1 parameter!");
                        if (rem > 0)
                        {
                            log.Add("____Remaining skip is " + rem + ", skipping current switch!");
                            rem--;
                            File.WriteAllLines(appFolder + "\\skip.txt", new string[] { rem + "/" + lns[0].Replace(" ", "").Split('/')[1] });
                            log.Add("____END");
                            log.Add("");
                            File.AppendAllLines(appFolder + "\\logs.txt", log);
                            return;
                        }
                    }
                }

                if (File.Exists(appFolder + "\\safetheme.txt"))
                {
                    log.Add("__safetheme.txt found! Asking for switching...");
                    // TODO
                }

                //Load Whitelist if any, else load Blacklist if any
                if (File.Exists(appFolder + "\\whitelist.txt"))
                {
                    log.Add("whitelist.txt found! Loading whitelist...");
                    _whitelist = ReadAllLines(appFolder + "\\whitelist.txt").ToArray();
                    log.Add("__Whitelist count: " + _whitelist.Count());
                }
                else if (File.Exists(appFolder + "\\blacklist.txt"))
                {
                    log.Add("blacklist.txt found! Loading blacklist...");
                    _blacklist = ReadAllLines(appFolder + "\\blacklist.txt").ToArray();
                    log.Add("__Blacklist count: " + _blacklist.Count());
                }

                if (_whitelist != null && _whitelist.Length == 0)
                {
                    log.Add("__Empty whitelist! Theme switch skipped!");
                }
                else
                {
                    //Get latest list for checking new Themes
                    List <string> latestThemeList = new List <string>();
                    foreach (var d in Directory.GetDirectories(KAWAII_Theme_Helper.windir + @"\Resources"))
                    {
                        latestThemeList.AddRange(Directory.GetFiles(d, "*.theme", SearchOption.AllDirectories));
                    }

                    if (_whitelist != null && _whitelist.Length > 0)
                    {
                        latestThemeList = latestThemeList.Where(a => _whitelist.Contains(Path.GetFileNameWithoutExtension(a))).ToList();
                    }
                    else if (_blacklist != null && _blacklist.Length > 0)
                    {
                        latestThemeList = latestThemeList.Where(a => !_blacklist.Contains(Path.GetFileNameWithoutExtension(a))).ToList();
                    }

                    // Theme selection
                    if (File.Exists(appFolder + @"\RSequence.txt"))
                    {
                        if (!File.Exists(appFolder + @"\theme.used"))
                        {
                            File.WriteAllText(appFolder + @"\theme.used", "");
                        }
                        var loaded = ReadAllLines(appFolder + "\\theme.used").ToList();
                        if (ReadAllLines(appFolder + "\\RSequence.txt").Count() == 0)
                        {
                            var rs = latestThemeList.ToList();
                            rs.Shuffle();
                            File.WriteAllLines(appFolder + @"\RSequence.txt", rs);
                        }
                        else
                        {
                            var queue     = ReadAllLines(appFolder + "\\RSequence.txt").ToList();
                            var union     = loaded.Concat(queue);
                            var newThemes = latestThemeList.Except(union);
                            if (newThemes.Count() > 0)
                            {
                                queue.AddRange(newThemes);
                                queue.Shuffle();
                                File.WriteAllLines(appFolder + @"\RSequence.txt", queue);
                            }
                        }
                        var lrse = ReadAllLines(appFolder + "\\RSequence.txt");

                        if (_whitelist != null && _whitelist.Length > 0)
                        {
                            lrse = lrse.Where(a => _whitelist.Contains(Path.GetFileNameWithoutExtension(a)));
                        }
                        else if (_blacklist != null && _blacklist.Length > 0)
                        {
                            lrse = lrse.Where(a => !_blacklist.Contains(Path.GetFileNameWithoutExtension(a)));
                        }
                        var rse = new Queue <string>(lrse);
                        path = rse.Dequeue();
                        loaded.Add(path);
                        File.WriteAllLines(appFolder + @"\theme.used", loaded);
                        File.WriteAllLines(appFolder + @"\RSequence.txt", rse);
                    }
                    else if (File.Exists(appFolder + @"\Sequence.txt"))
                    {
                        if (!File.Exists(appFolder + @"\theme.used"))
                        {
                            File.WriteAllText(appFolder + @"\theme.used", "");
                        }
                        var loaded = ReadAllLines(appFolder + "\\theme.used").ToList();
                        if (ReadAllLines(appFolder + "\\Sequence.txt").Count() <= 0)
                        {
                            var rs = new DirectoryInfo(KAWAII_Theme_Helper.windir + @"\Resources\Themes").GetFiles("*.theme", SearchOption.TopDirectoryOnly).Select(item => item.FullName).ToList();
                            rs = rs.OrderBy(a => a).ToList();
                            File.WriteAllLines(appFolder + @"\Sequence.txt", rs);
                        }
                        else
                        {
                            var queue     = ReadAllLines(appFolder + "\\Sequence.txt").ToList();
                            var union     = loaded.Concat(queue);
                            var newThemes = latestThemeList.Except(union);
                            if (newThemes.Count() > 0)
                            {
                                queue.AddRange(newThemes);
                                queue = queue.OrderBy(a => a).ToList();
                                File.WriteAllLines(appFolder + @"\Sequence.txt", queue);
                            }
                        }
                        var lrse = ReadAllLines(appFolder + "\\Sequence.txt");
                        if (_whitelist != null && _whitelist.Length > 0)
                        {
                            lrse = lrse.Where(a => _whitelist.Contains(Path.GetFileNameWithoutExtension(a)));
                        }
                        else if (_blacklist != null && _blacklist.Length > 0)
                        {
                            lrse = lrse.Where(a => !_blacklist.Contains(Path.GetFileNameWithoutExtension(a)));
                        }
                        var rse = new Queue <string>(lrse);
                        path = rse.Dequeue();
                        loaded.Add(path);
                        File.WriteAllLines(appFolder + @"\theme.used", loaded);
                        File.WriteAllLines(appFolder + @"\Sequence.txt", rse);
                    }
                    else
                    {
                        if (File.Exists(appFolder + @"\theme.used"))
                        {
                            File.Delete(appFolder + @"\theme.used");
                        }
                        path = latestThemeList[ThreadSafeRandom.ThisThreadsRandom.Next(0, latestThemeList.Count() - 1)];
                        while (Path.GetFileNameWithoutExtension(path) == KAWAII_Theme_Helper.GetCurrentThemeName() || Path.GetFileNameWithoutExtension(path) == KAWAII_Theme_Helper.GetCurrentVisualStyleName())
                        {
                            path = latestThemeList[ThreadSafeRandom.ThisThreadsRandom.Next(0, latestThemeList.Count() - 1)];
                        }
                    }
                }

                // Lockscreen Modifier
                if (File.Exists(appFolder + @"\lockscreen.txt"))
                {
                    log.Add("lockscreen.txt found! Loading Lockscreen backgrounds...");
                    var prms = File.ReadAllLines(appFolder + "\\lockscreen.txt").ToList();
                    if (prms.Count == 0)
                    {
                        prms.Add("respective");
                    }
                    ChangeLockscreen(prms[0].RegexReplace(@"[a-z_ ]+[:=]{1} ?", "", -1).ToLower(), _blacklist, path);
                }
                else
                {
                    var regChk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\Personalization");
                    if (regChk.GetValue("NoChangingLockScreen") != null)
                    {
                        Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\Personalization").DeleteValue("NoChangingLockScreen");
                    }
                }

                if (path.Length > 0)
                {
                    // Apply Theme/Visual Style
                    KAWAII_Theme_Helper.ApplyTheme(path, exitDelay);
                    log.Add("___Theme applied: " + path);
                }

                log.Add("_END");
                log.Add("");
            }
            File.AppendAllLines(appFolder + "\\logs.txt", log);
        }
Beispiel #60
-1
        static void Main(string[] args)
        {
            #region Performance counters
            // This will pull the current CPU load in percentage
            PerformanceCounter perfCountCPU = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
            perfCountCPU.NextValue();

            // This will pull the current available memory in Megabytes
            PerformanceCounter perfCountMem = new PerformanceCounter("Memory", "Available MBytes");
            perfCountMem.NextValue();

            // This will get us the system up time (in seconds)
            PerformanceCounter perfCountUpTime = new PerformanceCounter("System", "System Up Time");
            perfCountUpTime.NextValue();

            #endregion
            // This will greet the user in the default voice
            SpeechSynthesizer synth = new SpeechSynthesizer();
            synth.Speak("This is CPU and Memory monitor");
            synth.Speak("Hello, how are you today?");

            synth.SelectVoiceByHints(VoiceGender.Female);
            TimeSpan uptime = TimeSpan.FromSeconds(perfCountUpTime.NextValue());
            string UpTimeMessage = String.Format("The current system up time is {0} days, {1} hours, {2} minutes and {3} seconds", (int)uptime.TotalDays, (int)uptime.Hours, (int)uptime.Minutes, (int)uptime.Seconds);
            Console.WriteLine(UpTimeMessage);
            synth.Speak(UpTimeMessage);

            while (true)
            {
                int currentCpuPercentage = (int)perfCountCPU.NextValue();
                int currentAvailableMemory = (int)perfCountMem.NextValue();

                // Every 1 second print the CPU load in percentage to the screen
                Console.WriteLine("CPU load %: {0}", currentCpuPercentage);
                Console.WriteLine("Available Memory: {0}MB", currentAvailableMemory);

                if (currentCpuPercentage > 80)
                {
                    if (currentCpuPercentage == 100)
                    {
                        synth.SelectVoiceByHints(VoiceGender.Female);
                        synth.Speak("Warning, warning CPU load is 100 percent!");
                    }
                    else
                    {
                        string cpuLoadMessage = String.Format("The current CPU load is {0} percent", currentCpuPercentage);
                        synth.Speak(cpuLoadMessage);
                    }

                }

                if (currentAvailableMemory < 1024)
                {
                    string MemoryMessage = String.Format("The current available memory is {0} megabytes", currentAvailableMemory);
                    synth.Speak(MemoryMessage);
                }

                Thread.Sleep(1000);
            }
        }