Example #1
0
        private decimal GetProcessorUsage()
        {
            System.Diagnostics.PerformanceCounter cpuCounter = null;
            try
            {
                cpuCounter = new System.Diagnostics.PerformanceCounter
                {
                    CategoryName = "Processor",
                    CounterName  = "% Processor Time",
                    InstanceName = "_Total"
                };

                cpuCounter.NextValue();
                Thread.Sleep(500);
                return(Convert.ToDecimal(Math.Round(cpuCounter.NextValue(), 4)));
            }
            catch (Exception ex)
            {
                throw new RMSAppException(this, "0500", "GetProcessorUsage failed. " + ex.Message, ex, false);
            }
            finally
            {
                if (cpuCounter != null)
                {
                    cpuCounter.Dispose();
                }
            }
        }
Example #2
0
        public static int GetCpuUsage()
        {
            var cpuCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);

            cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            return((int)cpuCounter.NextValue());
        }
Example #3
0
 static double get_cpu_usage()
 {
     System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", true);
     double cpu = pc.NextValue();
     Thread.Sleep(1000);
     cpu = pc.NextValue();
     return cpu;
 }
Example #4
0
        static double get_cpu_usage()
        {
            System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", true);
            double cpu = pc.NextValue();

            Thread.Sleep(1000);
            cpu = pc.NextValue();
            return(cpu);
        }
Example #5
0
        protected override async Task Handle(MetricRequest <CpuUsageWidget> request, CancellationToken cancellationToken)
        {
            using var counter = new System.Diagnostics.PerformanceCounter(CategoryName, CounterName, InstanceName);

            counter.NextValue();

            await Task.Delay(500, cancellationToken).ConfigureAwait(false);

            request.Context.Value = Math.Round(counter.NextValue());

            request.Context.Status = Status.OK;
        }
Example #6
0
 public void RefreshCpuInfo()
 {
     if (cpuTotalCntr != null)
     {
         this.GaugeValue = (int)cpuTotalCntr.NextValue();
     }
 }
Example #7
0
        private int __available() //MB単位
        {
            if (NWEnviroment.isWindows())
            {
                string mem      = "Memory";
                string countMem = "Available Mbytes";
                System.Diagnostics.PerformanceCounter pcMem = new System.Diagnostics.PerformanceCounter(mem, countMem);
                float available = pcMem.NextValue();
                pcMem.Close();
                pcMem.Dispose();
                return((int)available);
            }
            else
            {
                string free = LinuxCommand.execute("free -m");
                using (StringReader sr = new StringReader(free)){
                    string line = "";
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.Contains("-/+"))
                        {
                            string[] parts     = Regex.Split(line, @"\s+");
                            int      available = int.Parse(parts[parts.Length - 1]);
                            sr.Close();
                            sr.Dispose();
                            return(available);
//                            Console.WriteLine("rate:{0}",(int)(100*int.Parse(parts[2])/(int.Parse(parts[3])+int.Parse(parts[2]))));
                        }
                    }
                }
            }
            return(0);//TODO: Exception?
        }
        private static System.Diagnostics.Process FindPidFromIndexedProcessName(string indexedProcessName)
        {
            System.Diagnostics.PerformanceCounter parentId =
                new System.Diagnostics.PerformanceCounter("Process", "Creating Process ID", indexedProcessName);

            return(System.Diagnostics.Process.GetProcessById((int)parentId.NextValue()));
        }
        private void UpdatePosition()
        {
            int CpuTime = Convert.ToInt32(pfcCPU.NextValue());

            pgbCPU.Text     = "     CPU Usage: " + CpuTime.ToString() + " %";
            pgbCPU.Position = CpuTime;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                if (!stoppingToken.IsCancellationRequested)
                {
                    //TODO : get metrics from local perfmon
                    _connectionCnt.NextValue();
                    _messageCnt.NextValue();
                    _requestsCnt.NextValue();
                    _errorsCnt.NextValue();

                    //TODO : push it in database with servername key
                    var newEntry = _context.SignalrMetrics.Add(new SignalRMetric()
                    {
                        CreationDate = DateTime.Now,
                        HostServer   = currentServer,
                        ExtendedData = new JObject(new { })
                    });

                    //TODO : Check for remove old data
                    await Task.Factory.StartNew(() =>
                    {
                        CheckForClean();
                    });
                }

                await Task.Delay(TimeSpan.FromSeconds(_runIntervall), stoppingToken);
            }
        }
Example #11
0
        internal float getCurrentCpuUsage()
        {
            var ret = cpuCounter.NextValue();

            _sLastCpuUsage = ret;
            return(ret);
        }
Example #12
0
 public double Observe()
 {
     lock (syncObject)
     {
         // NextValue is not thread-safe
         return(counter.NextValue());
     }
 }
Example #13
0
 /// <summary>
 /// Run the CPU monitoring thread
 /// </summary>
 /// <param name="state"></param>
 private static void CPUMonitor(object state)
 {
     while (true)
     {
         SystemCPUUsage = CPUCounter.NextValue();
         System.Threading.Thread.Sleep(1000);
     }
 }
Example #14
0
        public long GetFreeMemory()
        {
            System.Diagnostics.PerformanceCounter pc
                = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            long freeMemory = Convert.ToInt64(pc.NextValue());

            return(freeMemory);
        }
Example #15
0
        public bool check()
        {
            float counterValue = counter.NextValue();

            lastValue = counterValue;
            addValue(counterValue);
            return(isCritical());
        }
Example #16
0
        private void timer1_Tick(object sender, System.EventArgs e)
        {
            int i = (int)CpuUsageCounter.NextValue();

            notifyChart.Value1      = i;
            this.progressBar1.Value = i;
            this.cpu.Text           = i.ToString() + "%";
            this.notifyIcon.Text    = "Current CPU Usage: " + i.ToString() + "%";
        }
Example #17
0
 /// <summary>
 /// Initialize and start our CPU monitor
 /// </summary>
 public static void StartCPUMonitor()
 {
     CPUCounter = new System.Diagnostics.PerformanceCounter();
     CPUCounter.CategoryName = "Processor";
     CPUCounter.CounterName  = "% Processor Time";
     CPUCounter.InstanceName = "_Total";
     SystemCPUUsage          = CPUCounter.NextValue();
     System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(CPUMonitor));
 }
        /// <summary>
        /// method signature to match required EventHandler of DispatcherTimer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void UpdateVisual(object sender, EventArgs e)
        {
            int nextValue = (int)t_perf.NextValue();

            string strValue = nextValue.ToString() + " %";

            this.LblValue.Content = strValue;
            this.progBar.Value    = nextValue;
        }
Example #19
0
        //初始化全局变量
        private void InitGlobalData()
        {
            ServerGlobalData.LogFileType            = ConfigurationManager.AppSettings["LogFileType"];
            ServerGlobalData.ServerDataCacheTimeout = TimeSpan.FromMinutes(int.Parse(ConfigurationManager.AppSettings["ServerDataCacheTimeout"]));
            ServerGlobalData.UserInfoCacheTimeout   = TimeSpan.FromMinutes(int.Parse(ConfigurationManager.AppSettings["UserInfoCacheTimeout"]));
            ServerGlobalData.SysTimerInterval       = int.Parse(ConfigurationManager.AppSettings["SysTimerInterval"]);

            CPUPerformanceCounter.NextValue();
        }
Example #20
0
        /*Summary
         * Updates the CPU Load meter.
         */
        private void PerfTimer_Tick(object sender, EventArgs e)
        {
            //if (bVista) return;

            float cpu = CpuCounter.NextValue();

            CpuBar.Value  = (int)cpu;
            CpuLabel.Text = string.Format("{0} %", (int)cpu);
        }
Example #21
0
        public void Attach(ManagementObject biztalkHostObject, bool bounceHost)
        //{
        //                var bizTalkHostName = managementObject.Properties["HostName"].Value.ToString();

        //    Attach(processName, bizTalkHostName, bounceHost);
        //}
        //public void Attach(string processName, string bizTalkHostName, bool bounceHost = false)
        {
            // Try loop - Visual Studio may not respond the first time.
            var tryCount = 5;

            while (tryCount-- > 0)
            {
                try
                {
                    if (bounceHost)
                    {
                        //owP.OutputString(Environment.NewLine);

                        var i = biztalkHostObject; //GetBiztalkHosts().SingleOrDefault(h => h.Key == bizTalkHostName).Value;

                        if (i != null)
                        {
                            WriteToOutputWindow("Stopping: " + i.Properties["HostName"].Value);
                            i.InvokeMethod("Stop", null);

                            WriteToOutputWindow("Starting: " + i.Properties["HostName"].Value);
                            i.InvokeMethod("Start", null);
                        }
                    }


                    var processName = biztalkHostObject.Properties["HostName"].Value.ToString();
                    var perfCounter = new System.Diagnostics.PerformanceCounter("BizTalk:Messaging", "ID Process", processName);
                    var processID   = perfCounter.NextValue();

                    var processes = _applicationObject.Debugger.LocalProcesses;
                    foreach (var proc in from Process proc in processes /*where proc.Name.IndexOf(processName, StringComparison.OrdinalIgnoreCase) != -1*/ where proc.ProcessID == processID let serviceName = GetServiceName(proc.ProcessID) /*where String.Equals(serviceName, string.Format("btssvc${0}", bizTalkHostName), StringComparison.OrdinalIgnoreCase)*/ select proc)
                    {
                        proc.Attach();

                        WriteToOutputWindow(Environment.NewLine);
                        WriteToOutputWindow(String.Format("Attached to process {0} - {1} successfully.", processName, proc.ProcessID));
                        WriteToOutputWindow(Environment.NewLine);
                        WriteToOutputWindow(Environment.NewLine);

                        break;
                    }
                    break;
                }
                catch (COMException)
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
        public override void Refresh()
        {
            if (this.Control is SfCircularGauge)
            {
                SfCircularGauge dcgCpuUsage   = this.Control as SfCircularGauge;
                int             cpuTotalValue = Convert.ToInt32(Math.Round(cpuTotalCntr.NextValue(), 0));

                dcgCpuUsage.Scales[0].Pointers[0].Value = cpuTotalValue;
            }
        }
 // Проверка параметров генерации.
 public override bool CheckGenerationParams(int instances)
 {
     System.Diagnostics.PerformanceCounter ramCounter = new System.Diagnostics.PerformanceCounter("Memory",
         "Available Bytes");
     int branch = (Int16)GenerationParamValues[GenerationParam.BranchIndex];
     int level = (Int16)GenerationParamValues[GenerationParam.Level];
     UInt32 vertexcount = (UInt32)(System.Math.Pow(branch, level));
     int processorcount = Environment.ProcessorCount;
     return processorcount*vertexcount < ramCounter.NextValue();
 }
Example #24
0
 void MainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     graph.Points.Add(new DataPoint(counter, cpuload.NextValue()));
     counter++;
     if (counter >= 62)
     {
         x.Pan(x.Transform(-1 + x.Offset));
     }
     this.MyModel.InvalidatePlot(true);
 }
Example #25
0
 public string uptime(BotFunctionData BotInput)
 {
     StringBuilder responsebuilder = new StringBuilder();
     try
     {
         System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("System", "System Up Time");
         pc.NextValue();
         TimeSpan ts = TimeSpan.FromSeconds(pc.NextValue());
         responsebuilder.AppendFormat("The PC i'm running on has been up for {0} days, and {1}:{2} hours.", new object[] { ts.Days, ts.Hours, ts.Minutes });
     }
     catch (Exception ex)
     {
         logger.logerror(ex);
         responsebuilder.Append("Couldn't fetch system uptime (Are you admin?).");
     }
     TimeSpan myts = (DateTime.Now - RunVars.starttime);
     responsebuilder.AppendFormat(" My current session has been running for {0}:{1}:{2} ({3} days)", new object[] { myts.Hours, myts.Minutes, myts.Seconds, myts.TotalDays });
     return responsebuilder.ToString();
 }
Example #26
0
 /// <summary>
 /// 本地定时器
 /// </summary>
 private void clockTimer_Tick(object sender, EventArgs e)
 {
     if (supportCPU)
     {
         CPU = (int)pcCPU.NextValue();
     }
     if (supportMEM)
     {
         MEM = (int)pcMem.NextValue();
     }
     TIME = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
 }
Example #27
0
            public string uptime(BotFunctionData BotInput)
            {
                StringBuilder responsebuilder = new StringBuilder();

                try
                {
                    System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("System", "System Up Time");
                    pc.NextValue();
                    TimeSpan ts = TimeSpan.FromSeconds(pc.NextValue());
                    responsebuilder.AppendFormat("The PC i'm running on has been up for {0} days, and {1}:{2} hours.", new object[] { ts.Days, ts.Hours, ts.Minutes });
                }
                catch (Exception ex)
                {
                    logger.logerror(ex);
                    responsebuilder.Append("Couldn't fetch system uptime (Are you admin?).");
                }
                TimeSpan myts = (DateTime.Now - RunVars.starttime);

                responsebuilder.AppendFormat(" My current session has been running for {0}:{1}:{2} ({3} days)", new object[] { myts.Hours, myts.Minutes, myts.Seconds, myts.TotalDays });
                return(responsebuilder.ToString());
            }
Example #28
0
        public static int getCpuUsage()
        {
            System.Diagnostics.PerformanceCounter cpuCounter;
            cpuCounter = new System.Diagnostics.PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName  = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
            float percfloat  = cpuCounter.NextValue();
            int   percentage = (int)percfloat;

            return(percentage);
        }
    static void OnTimerCallback(object state)
    {
        if (System.Threading.Interlocked.CompareExchange(ref lockTimerCounter, 1, 0) == 0)
        {
            if (pcReqsPerSec == null)
            {
                pcReqsPerSec = new System.Diagnostics.PerformanceCounter("W3SVC_W3WP", "Requests / Sec", "_Total", true);
            }

            if (pcReqsPerSec != null)
            {
                try
                {
                    lock (threadLock)
                    {
                        CurrentRequestsPerSecondValue = Convert.ToDecimal(pcReqsPerSec.NextValue().ToString("N2"));
                    }
                }
                catch (Exception) {
                    // We had problem, just get rid of the performance counter and we'll rebuild it next revision
                    if (pcReqsPerSec != null)
                    {
                        pcReqsPerSec.Close();
                        pcReqsPerSec.Dispose();
                        pcReqsPerSec = null;
                    }
                }
            }

            stateCounter++;

            //Check every 5 seconds or so if anybody is still monitoring the server PerformanceCounter, if not shut down our PerformanceCounter
            if (stateCounter % 5 == 0)
            {
                if (System.Environment.TickCount - LastRequestTicks > 5000)
                {
                    Console.WriteLine("Stopping Poll Timer");

                    pollingTimer.Dispose();
                    pollingTimer = null;

                    if (pcReqsPerSec != null)
                    {
                        pcReqsPerSec.Close();
                        pcReqsPerSec.Dispose();
                        pcReqsPerSec = null;
                    }
                }
            }

            System.Threading.Interlocked.Add(ref lockTimerCounter, -1);
        }
    }
        public IActionResult Contact()
        {
            System.Diagnostics.PerformanceCounter cpuCounter;

            cpuCounter = new System.Diagnostics.PerformanceCounter();

            cpuCounter.MachineName = "DEVIIS01";
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            string cpuUsage = cpuCounter.NextValue() + "%";
            System.Threading.Thread.Sleep(1000);
            cpuUsage = cpuCounter.NextValue() *100 + "%";

            ViewData["CPU"] = cpuUsage;

            ViewData["Message"] = "Your contact page.";

            return View();
        }
Example #31
0
        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Stop();

            string text = "CPU: ";

            text       += (int)cpuCounter.NextValue() + "%, ";
            text       += ramCounter.NextValue() + "MB Free";
            label1.Text = text;

            timer.Start();
        }
Example #32
0
        static int TestFunctions()
        {
            Console.WriteLine(" Hit 'S' for sender, or 'R' for receiver, or 'M' for high memory usage, or 'C' for high CPU usage:");
            var key = Console.ReadKey(true).Key;

            if (key == ConsoleKey.S)
            {
                SendDataToReturnQueue(new QueueData());
                return(0);
            }
            else if (key == ConsoleKey.R)
            {
                return(ReceiveFromReturnQueue());
            }
            else if (key == ConsoleKey.M)
            {
                var mu     = new MemoryUser(10000000);
                var memory = GC.GetTotalMemory(true) / 1024 / 1024;
                Console.WriteLine($"Memory used: {memory} MB");
                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
                return(0);
            }
            else if (key == ConsoleKey.C)
            {
                var cu         = new CPUtimeUser(5, Environment.ProcessorCount);
                var cpuCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", true);
                cpuCounter.NextValue();
                cu.StartStressCPU();
                var cpuUsagePercent = cpuCounter.NextValue();
                Console.WriteLine($"CPU used: {cpuUsagePercent} %");
                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
                return(0);
            }
            else
            {
                throw new ArgumentException("not supported: " + key);
            }
        }
Example #33
0
        private void button1_Click(object sender, EventArgs e)
        {
            frmPeakpara = new frmPeakParameters();
            frmPeakpara.ShowDialog();
            //ReadGlycanList();

            System.Diagnostics.PerformanceCounter Proc = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            int freeMemory = Convert.ToInt32(Proc.NextValue() * 0.7f);

            _Raw = new XRawReader(@"D:\Dropbox\for_Yunli_Hu\b1_19_1_07142012.raw");
            //MultiNGlycanESIMultiThreads main = new MultiNGlycanESIMultiThreads(_GlycanList, _Raw, NoOfThread, frmPeakpara.PeakProcessorParameters, frmPeakpara.TransformParameters);
            //main.ProcessWithMultiThreads();
        }
 public JsonResult GetPercentOfCPULoad()
 {
     System.Diagnostics.PerformanceCounter perfomanceCounter = new System.Diagnostics.PerformanceCounter();
     perfomanceCounter.CategoryName = "Processor";
     perfomanceCounter.CounterName = "% Processor Time";
     perfomanceCounter.InstanceName = "_Total";
     float raw = 0;
     while ((raw == 0 || raw == 100))
     {
         raw = perfomanceCounter.NextValue();
     }
     return Json(raw, JsonRequestBehavior.AllowGet);
 }
Example #35
0
        private void button1_Click(object sender, EventArgs e)
        {
            frmPeakpara = new frmPeakParameters();
            frmPeakpara.ShowDialog();
            //ReadGlycanList();



            System.Diagnostics.PerformanceCounter Proc = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            int freeMemory = Convert.ToInt32(Proc.NextValue() * 0.7f);

            _Raw = new XRawReader(@"D:\Dropbox\for_Yunli_Hu\b1_19_1_07142012.raw");
            //MultiNGlycanESIMultiThreads main = new MultiNGlycanESIMultiThreads(_GlycanList, _Raw, NoOfThread, frmPeakpara.PeakProcessorParameters, frmPeakpara.TransformParameters);
            //main.ProcessWithMultiThreads();
        }
Example #36
0
        /// <summary>
        /// Obtains a sample value from the <see cref="BaseCounter"/>.
        /// </summary>
        public void Sample()
        {
            try
            {
                if ((object)m_counter != null)
                {
                    float currentSample = m_counter.NextValue();

                    lock (m_samplesLock)
                    {
                        // Update counter sample set
                        m_samples.Add(currentSample);

                        // Maintain counter samples rolling window size
                        while (m_samples.Count > m_samplingWindow)
                        {
                            m_samples.RemoveAt(0);
                        }
                    }

                    // Track lifetime maximum value
                    if (currentSample > m_lifetimeMaximum)
                    {
                        m_lifetimeMaximum = currentSample;
                    }

                    // Track lifetime average components
                    checked
                    {
                        try
                        {
                            m_lifetimeSampleCount++;
                            m_lifetimeTotal += (decimal)currentSample;
                        }
                        catch (OverflowException)
                        {
                            // If we overflow lifetime total, we restart total with current sample
                            m_lifetimeSampleCount = 1;
                            m_lifetimeTotal       = (decimal)currentSample;
                        }
                    }
                }
            }
            catch
            {
                // Not failing if counters cannot be sampled
            }
        }
        public static System.Data.DataTable GetFileSystemCacheBytes()
        {
            System.Data.DataTable tableReturn = new System.Data.DataTable();
            tableReturn.Columns.Add("Cache Bytes", typeof(long));
            tableReturn.Columns.Add("Cache GB", typeof(decimal));
            tableReturn.Columns.Add("Cache Bytes Peak", typeof(long));
            tableReturn.Columns.Add("Cache GB Peak", typeof(decimal));
            tableReturn.Columns.Add("Standby Cache Bytes", typeof(long));
            tableReturn.Columns.Add("Standby Cache GB", typeof(decimal));

            System.Diagnostics.PerformanceCounter pcCacheBytes = new System.Diagnostics.PerformanceCounter("Memory", "Cache Bytes", true);
            System.Diagnostics.PerformanceCounter pcCacheBytesPeak = new System.Diagnostics.PerformanceCounter("Memory", "Cache Bytes Peak", true);

            float fltCacheBytes = pcCacheBytes.NextValue();
            float fltCacheBytesPeak = pcCacheBytesPeak.NextValue();

            float? fltStandbyCacheBytes = null;

            try
            {
                System.Diagnostics.PerformanceCounter pcStandbyCacheBytes = new System.Diagnostics.PerformanceCounter("Memory", "Standby Cache Normal Priority Bytes", true);
                fltStandbyCacheBytes = pcStandbyCacheBytes.NextValue();
                pcStandbyCacheBytes.Close();
            }
            catch { }

            pcCacheBytes.Close();
            pcCacheBytesPeak.Close();

            object[] row = new object[] { 
                (long)fltCacheBytes, 
                decimal.Round((decimal)(fltCacheBytes / 1024 / 1024 / 1024), 2), 
                (long)fltCacheBytesPeak, 
                decimal.Round((decimal)(fltCacheBytesPeak / 1024 / 1024 / 1024), 2), 
                (fltStandbyCacheBytes==null?null:fltStandbyCacheBytes), 
                (fltStandbyCacheBytes==null?(decimal?)null:(decimal?)decimal.Round((decimal)(fltStandbyCacheBytes / 1024 / 1024 / 1024), 2))
            };

            tableReturn.Rows.Add(row);
            return tableReturn;
        }
Example #38
0
 private void timer1_Tick(object sender, EventArgs e)
 {
     System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
     toolStripStatusLabel2.Text = "Залишилось пам'яті: " + pc.NextValue().ToString();
 }
Example #39
0
 private int __available()
 {
     //MB単位
     if(NWEnviroment.isWindows()){
         string mem = "Memory";
         string countMem = "Available Mbytes";
         System.Diagnostics.PerformanceCounter pcMem = new System.Diagnostics.PerformanceCounter(mem,countMem);
         float available = pcMem.NextValue();
         pcMem.Close();
         pcMem.Dispose();
         return (int)available;
     }else{
         string free =LinuxCommand.execute("free -m");
         using(StringReader sr = new StringReader(free)){
             string line = "";
             while((line=sr.ReadLine())!=null){
                 if(line.Contains("-/+")){
                     string[] parts = Regex.Split(line,@"\s+");
                     int available = int.Parse(parts[parts.Length-1]);
                     sr.Close();
                     sr.Dispose();
                     return available;
     //                            Console.WriteLine("rate:{0}",(int)(100*int.Parse(parts[2])/(int.Parse(parts[3])+int.Parse(parts[2]))));
                 }
             }
         }
     }
     return 0;//TODO: Exception?
 }
Example #40
0
        private string ParseIdentifier(IRCConnection connection, string data)
        {
            //match all words starting with a $
            string identMatch = "\\$\\b[a-zA-Z_0-9.]+\\b";
            Regex ParseIdent = new Regex(identMatch);
            Match m = ParseIdent.Match(data);

            while (m.Success)
            {
                switch (m.Value)
                {
                    case "$me":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.NickName);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$altnick":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.AltNickName);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$ident":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.IdentName);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$host":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.LocalHost);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$fullhost":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.NickName + "!" + connection.ServerSetting.LocalHost);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$fullname":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.FullName);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$ip":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.LocalIP.ToString());
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$network":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.NetworkName);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$port":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.ServerPort);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$quitmessage":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.QuitMessage);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$servermode":
                        data = ReplaceFirst(data, m.Value, string.Empty);
                        break;
                    case "$serverid":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.ID.ToString());
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$server":
                        if (connection != null)
                        {
                            if (connection.ServerSetting.RealServerName.Length > 0)
                                data = ReplaceFirst(data, m.Value, connection.ServerSetting.RealServerName);
                            else
                                data = ReplaceFirst(data, m.Value, connection.ServerSetting.ServerName);
                        }
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$online":
                        if (connection != null)
                        {
                            //check the datediff
                            TimeSpan online = DateTime.Now.Subtract(connection.ServerSetting.ConnectedTime);
                            data = ReplaceFirst(data, m.Value, GetDuration((int)online.TotalSeconds));
                        }
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$serverip":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.ServerIP);
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;
                    case "$localip":
                        if (connection != null)
                            data = ReplaceFirst(data, m.Value, connection.ServerSetting.LocalIP.ToString());
                        else
                            data = ReplaceFirst(data, m.Value, "$null");
                        break;

                    //identifiers that do not require a connection
                    case "$theme":
                        data = ReplaceFirst(data, m.Value, iceChatOptions.CurrentTheme);
                        break;
                    case "$colors":
                        data = ReplaceFirst(data, m.Value, colorsFile);
                        break;
                    case "$appdata":
                        data = ReplaceFirst(data, m.Value, Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToString());
                        break;
                    case "$ossp":
                        data = ReplaceFirst(data, m.Value, Environment.OSVersion.ServicePack.ToString());
                        break;
                    case "$osbuild":
                        data = ReplaceFirst(data, m.Value, Environment.OSVersion.Version.Build.ToString());
                        break;
                    case "$osplatform":
                        data = ReplaceFirst(data, m.Value, Environment.OSVersion.Platform.ToString());
                        break;
                    case "$osbits":
                        //8 on 64bit -- AMD64
                        string arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE").ToString();
                        switch (arch)
                        {
                            case "x86":
                                string arch2 = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432").ToString();
                                if (arch2 == "AMD64")
                                    data = ReplaceFirst(data, m.Value, "64bit");
                                else
                                    data = ReplaceFirst(data, m.Value, "32bit");
                                break;
                            case "AMD64":
                            case "IA64":
                                data = ReplaceFirst(data, m.Value, "64bit");
                                break;

                        }
                        //System.Diagnostics.Debug.WriteLine(System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE").ToString());
                        //System.Diagnostics.Debug.WriteLine(IntPtr.Size);
                        break;
                    case "$os":
                        data = ReplaceFirst(data, m.Value, GetOperatingSystemName());
                        break;
                    case "$icepath":
                    case "$icechatexedir":
                        data = ReplaceFirst(data, m.Value, Directory.GetCurrentDirectory());
                        break;
                    case "$aliasfile":
                        data = ReplaceFirst(data, m.Value,aliasesFile);
                        break;
                    case "$serverfile":
                        data = ReplaceFirst(data, m.Value, serversFile);
                        break;
                    case "$popupfile":
                        data = ReplaceFirst(data, m.Value, popupsFile);
                        break;
                    case "$icechatver":
                        data = ReplaceFirst(data, m.Value, VersionID);
                        break;
                    case "$version":
                        data = ReplaceFirst(data, m.Value, ProgramID + " " + VersionID);
                        break;
                    case "$icechatdir":
                        data = ReplaceFirst(data, m.Value, currentFolder);
                        break;
                    case "$icechathandle":
                        data = ReplaceFirst(data, m.Value, this.Handle.ToString());
                        break;
                    case "$icechat":
                        data = ReplaceFirst(data, m.Value, ProgramID + " " + VersionID + " http://www.icechat.net");
                        break;
                    case "$logdir":
                        data = ReplaceFirst(data, m.Value, logsFolder);
                        break;
                    case "$randquit":
                        Random rand = new Random();
                        int rq = rand.Next(0, QuitMessages.RandomQuitMessages.Length);
                        data = ReplaceFirst(data, m.Value, QuitMessages.RandomQuitMessages[rq]);
                        break;
                    case "$randcolor":
                        Random randcolor = new Random();
                        int rc = randcolor.Next(0, (IrcColor.colors.Length-1));
                        data = ReplaceFirst(data, m.Value, rc.ToString());
                        break;
                    case "$tickcount":
                        data = ReplaceFirst(data, m.Value, System.Environment.TickCount.ToString());
                        break;
                    case "$totalwindows":
                        data = ReplaceFirst(data, m.Value, mainTabControl.TabCount.ToString());
                        break;
                    case "$framework":
                        data = ReplaceFirst(data, m.Value, System.Environment.Version.ToString());
                        break;
                    case "$uptime2":
                        int systemUpTime = System.Environment.TickCount / 1000;
                        TimeSpan ts = TimeSpan.FromSeconds(systemUpTime);
                        data = ReplaceFirst(data, m.Value, GetDuration(ts.TotalSeconds));
                        break;
                    case "$uptime":
                        System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("System", "System Up Time");
                        pc.NextValue();
                        TimeSpan ts2 = TimeSpan.FromSeconds(pc.NextValue());
                        data = ReplaceFirst(data, m.Value, GetDuration(ts2.TotalSeconds));
                        break;
                    case "$mono":
                        if (StaticMethods.IsRunningOnMono())
                            data = ReplaceFirst(data, m.Value, (string)typeof(object).Assembly.GetType("Mono.Runtime").InvokeMember("GetDisplayName", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding, null, null, null));
                        else
                            data = ReplaceFirst(data, m.Value, "Mono.Runtime not detected");
                        break;
                }
                m = m.NextMatch();
            }

            return data;
        }
        private void SplitDataset()
        {
            System.Diagnostics.PerformanceCounter Proc = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            int freeMemory = Convert.ToInt32(Proc.NextValue() * 0.7f);
            int MaxScanInOneSet = Convert.ToInt32(((freeMemory / _noOfThreads) / 45.0f) * 100.0f);
            if (MaxScanInOneSet >= 3000)
            {
                MaxScanInOneSet = 3000;
            }
            XRawReader rawReader = new XRawReader(rawFiles.Peek());
            List<int> MSScanNo = new List<int>();
            _splitDataset = new List<List<int>>();
            for (int i = StartScan; i <= EndScan; i++)
            {
                if (rawReader.GetMsLevel(i) == 1)
                {
                    MSScanNo.Add(i);
                }
            }
            int NoOfSet = Convert.ToInt32( Math.Ceiling(MSScanNo.Count / (double)MaxScanInOneSet));

            for (int i = 1; i <= NoOfSet; i++)
            {
                _splitDataset.Add(new List<int>());
            }
            int DataSetIdx = 0;
            for (int i = 0; i < MSScanNo.Count; i++)
            {
                _splitDataset[DataSetIdx].Add(MSScanNo[i]);
                DataSetIdx++;
                if (DataSetIdx == NoOfSet)
                {
                    DataSetIdx = 0;
                }
            }
            rawReader.Close();
        }
Example #42
0
                /// <summary>
                /// �Q�[���̃A�b�v�f�[�g��s���܂��B
                /// �A�b�v�f�[�g��A�N�����ꂽ�����`���[�v���O�����͎����I�ɏI�����܂��B
                /// </summary>
                /// <param name="LauncherPath">�����`���[�iSplash.exe�j�ւ̃t���p�X</param>
                public static void updateGame(string LauncherPath)
                {
                    // Splash.dmy�𒼐ڋN��
                    LauncherPath = LauncherPath.Replace(".exe", ".dmy");

                    bool ignoreDialog = false;

                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
                    psi.FileName = LauncherPath;
                    psi.RedirectStandardInput = false;
                    psi.RedirectStandardOutput = false;
                    psi.UseShellExecute = false;
                    psi.CreateNoWindow = false;
                    // ���݂̃��[�U���Ǘ��Ҍ�����L���Ă��邩�m�F
                    if (Common.isAdmin() == false)
                    {
                        // �Ǘ��҂łȂ���ΊǗ��Ҍ����Ŏ��s����݂�
                        psi.Verb = "runas";
                    }

                    SimpleLogger.WriteLine(LauncherPath);
                    // ����
                    //psi.Arguments = "";

                    SimpleLogger.WriteLine("start Launcher and launch Update.");

                    try
                    {
                        // �N��
                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);

                        // �����`���[�̃v���Z�X��Ď�
                        System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter();
                        pc.CategoryName = "Process";
                        pc.CounterName = "% Processor Time";
                        pc.MachineName = ".";
                        pc.InstanceName = p.ProcessName;
                        float pcp = 0;
                        System.Threading.Thread.Sleep(1000);
                        if (!p.HasExited)
                        {
                            try
                            {
                                pcp = pc.NextValue();
                            }
                            catch (InvalidOperationException ioe)
                            { }
                        }

                        // �ŏ���0%�Ō��o���I���܂�
                        while (!p.HasExited && pcp == 0)
                        {
                            pcp = pc.NextValue();
                            System.Threading.Thread.Sleep(1000);
                        }

                        bool isContinueLauncherMonitor = true;
                        while (isContinueLauncherMonitor)
                        {
                            // �����I��(CPU�g�p��0%)�܂ŊĎ�
                            int zeroCount = 0;
                            while (!p.HasExited && zeroCount < 10)
                            {
                                pcp = pc.NextValue();
                                SimpleLogger.WriteLine(p.ProcessName + ": " + pcp.ToString() + "%");
                                System.Threading.Thread.Sleep(1000);
                                if (pcp > 0)
                                {
                                    zeroCount = 0;
                                }
                                else
                                {
                                    zeroCount++;
                                }
                            }

                            if (p.HasExited == true)
                            {
                                // ���Ƀ����`���[���I�����Ă����ꍇ
                                isContinueLauncherMonitor = false;
                                break;
                            }

                            DialogResult killConfirm = new DialogResult();

                            if (ignoreDialog == false)
                            {
                                killConfirm = MessageBox.Show("�����`���[��I�����܂��B��낵���ł���" + Environment.NewLine +
                                            "���ケ�̃��b�Z�[�W��\�����Ȃ��ꍇ�̓L�����Z����I����Ă��������B" + Environment.NewLine +
                                            "������A�b�v�f�[�g���s���ɂ͍ēx�\������܂��B", "TricksterTools", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                            }

                            if (killConfirm == DialogResult.Cancel)
                            {
                                ignoreDialog = true;
                                MessageBox.Show("�A�b�v�f�[�g������́A��x�����`���[��I�������Ă��������B" + Environment.NewLine +
                                            "TSLoginManager������ɓ���o���Ȃ��Ȃ鋰�ꂪ����܂��B", "TricksterTools", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }

                            if (p.HasExited == true || killConfirm == DialogResult.Yes)
                            {
                                isContinueLauncherMonitor = false;

                                if (p.HasExited == false)
                                    p.Kill();

                                break;
                            }
                        }

                        p.Dispose();
                    }
                    catch (System.ComponentModel.Win32Exception e)
                    {
                        SimpleLogger.WriteLine("Exception!!: " + e.GetType().FullName);
                        SimpleLogger.WriteLine(e.Message);
                        //MessageBox.Show("�A�b�v�f�[�g�̎��s�ɂ͊Ǘ��Ҍ������K�v�ł��B\n�����𒆒f���܂��B", "TSLoginManager", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        DialogResult result = MessageBox.Show("�A�b�v�f�[�g�̎��s�ɂ͊Ǘ��Ҍ������K�v�ł��B\nTSLoginManager��Ǘ��Ҍ����ōċN�����܂����B", "TSLoginManager", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == DialogResult.Yes)
                        {
                            Common.RestartApplicationAtAdministratorAuthority();
                        }
                    }
                }
        private static void ClearStandbyFileSystemCacheByConsumingAvailableMemory()
        {
            //consume all available memory then free it, which will wipe out the standby cache
            Context.TraceEvent(1, 1, "Clearing standby cache by consuming all available memory");

            //get the page size. will need to write at least one byte per page to make sure that page is committed to this process' working set: http://blogs.msdn.com/b/ntdebugging/archive/2007/11/27/too-much-cache.aspx?CommentPosted=true&PageIndex=2#comments
            SYSTEM_INFO sysinfo = new SYSTEM_INFO();
            GetSystemInfo(ref sysinfo);

            Context.TraceEvent(1, 2, "Page size on this server is " + sysinfo.dwPageSize + " bytes");

            System.Diagnostics.PerformanceCounter pcAvailableBytes = null;
            long lngAvailableBytes = 0;

            pcAvailableBytes = new System.Diagnostics.PerformanceCounter("Memory", "Available Bytes", true);
            lngAvailableBytes = (long)pcAvailableBytes.NextValue();
            Context.TraceEvent(1, 3, "Available Bytes after clearing active cache: " + lngAvailableBytes);

            long lngRemainingBytes = lngAvailableBytes - (1024 * 1024); //take up all available memory minus 1MB
            System.Collections.Generic.List<IntPtr> listPtrMem = new System.Collections.Generic.List<IntPtr>();
            try
            {
                Context.TraceEvent(1, 4, "Preparing to consume " + lngRemainingBytes + " bytes of memory");

                while (lngRemainingBytes > 0)
                {
                    //figure out the next allocation size
                    int iAllocLen = (int)Math.Min((long)(sysinfo.dwPageSize * 1024), lngRemainingBytes);
                    lngRemainingBytes -= iAllocLen;

                    //allocate this memory
                    listPtrMem.Add(Marshal.AllocHGlobal(iAllocLen));

                    //write one byte per page which is the minimum necessary to make sure this page gets committed to this process' working set
                    for (int j = 0; j < iAllocLen; j += (int)sysinfo.dwPageSize)
                    {
                        Marshal.WriteByte(listPtrMem[listPtrMem.Count - 1], j, (byte)1);
                    }
                }

                lngAvailableBytes = (long)pcAvailableBytes.NextValue();
                Context.TraceEvent(1, 5, "Available Bytes after consuming memory: " + lngAvailableBytes);

            }
            catch (OutOfMemoryException ex)
            {
                Context.TraceEvent(1, 5, "Received OutOfMemoryException: " + ex.Message);
                Context.TraceEvent(1, 10, "Was able to consume desired memory except for the following number of bytes: " + lngRemainingBytes);
            }
            finally
            {
                // dont forget to free up the memory. 
                foreach (IntPtr ptrMem in listPtrMem)
                {
                    if (ptrMem != IntPtr.Zero)
                        Marshal.FreeHGlobal(ptrMem);
                }
            }

            lngAvailableBytes = (long)pcAvailableBytes.NextValue();
            Context.TraceEvent(1, 6, "Available Bytes after freeing consumed memory: " + lngAvailableBytes);
        }
Example #44
0
        public void Indexing()
        {
            var schema = new Schema("PerfTest", "1.0")
            {
                Fields =
                {
                    new SchemaField{ Name = "ID", Indexed = true, Stored = true, Tokenized = false, Unique = true},
                    new SchemaField{ Name = "Title",Indexed = true, Stored = true, Tokenized = true, Unique = false},
                    new SchemaField{ Name = "Body", Indexed = true, Stored = true, Tokenized = true, Unique = false}
                },
                DefaultSearchField = "Body"
            };

            var docs = new List<Document>();
            var fields = new string[] { "ID", "Title", "Body" };

            foreach (var file in System.IO.Directory.GetFiles("ReutersData", "*.sgm"))
            {
                var text = System.IO.File.ReadAllText(file);
                var matches = reutersSgm.Matches(text);

                foreach (Match match in matches)
                {
                    if (match.Success)
                    {
                        var doc = new Document();
                        doc.Schema = schema;

                        foreach(var key in fields)
                        {
                            doc.Fields.Add(new Field{ Name = key, Values = { match.Groups[key].Value }});
                        }
                        docs.Add(doc);
                    }
                }
            }

            if (System.IO.Directory.Exists("PerfIndex"))
            {
                System.IO.Directory.Delete("PerfIndex", true);
            }

            var idx = Index.Open("PerfIndex");
            idx.Update(schema);

            var rand = new Random();
            var max = docs.Count;

            var results = new List<Mubble.Indexing.IndexWorkItem>();

            var curr = 0;

            Mubble.Treadmill.Func<Mubble.Treadmill.Result> action = () =>
                {
                    var i = System.Threading.Interlocked.Increment(ref curr);
                    if (i > docs.Count)
                    {
                        i = i % docs.Count;
                    }

                    var wi = idx.Update(docs[i]);
                    results.Add(wi);
                    return new Mubble.Treadmill.Result(true, "Indexed!");
                };

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

            Mubble.Treadmill.Func<Mubble.Treadmill.Benchmark> bench = () =>
                {
                    var start = DateTime.Now;
                    var r = idx.Search("Body:output");
                    var msg = string.Concat("Search for output - ", r.Hits.Count, " results");
                    var elapsed = DateTime.Now - start;

                    return new Mubble.Treadmill.Benchmark(msg, elapsed.Milliseconds, DateTime.Now);
                };

            Mubble.Treadmill.Func<Mubble.Treadmill.Benchmark> proc = () =>
            {
                var count = cpu.NextValue();

                return new Mubble.Treadmill.Benchmark("Processor", count, DateTime.Now);
            };

            var actions = new List<Mubble.Treadmill.Command>(1);
            var benchmarks = new List<Mubble.Treadmill.Collect>(1);
            actions.Add(new Mubble.Treadmill.Command(action, "Index doc"));
            benchmarks.Add(new Mubble.Treadmill.Collect(bench));
            benchmarks.Add(new Mubble.Treadmill.Collect(proc));

            var commands = new Mubble.Treadmill.Commands(actions, () =>
            {
                var total = results.Count;
                Mubble.Tests.Indexing.WaitFor(results);
                idx.Dispose();
                return new Mubble.Treadmill.Result(true, string.Concat("Waited for ", total, " operations"));
            });

            Mubble.Treadmill.Runner.Start(50000, 8, commands, benchmarks);
        }
Example #45
0
        private static void GetGenericCounters(string category, string counter, string instance, string[] hosts, int nThreads, int nReads, int sleep, ValueToString func)
        {
            DateTime startTime = DateTime.Now;
            Dictionary<string, float> dtData = new Dictionary<string, float>();

            MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
            new Action<string>(
            delegate(string slave)
            {
                if (string.Compare(slave, "localhost", true) == 0)
                {
                    slave = System.Net.Dns.GetHostName();
                }

                lock (dtData)
                {
                    Console.WriteLine();
                    Console.WriteLine("Waiting to connect: {0}", slave);
                }

                try
                {
                    System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter(category, counter, instance, slave);

                    lock (dtData)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Connected: {0}", slave);
                    }

                    //Initial reading.
                    pc.NextValue();

                    float data = 0;

                    for (int i = 0; i < nReads; i++)
                    {
                        System.Threading.Thread.Sleep(sleep);
                        data += pc.NextValue();
                    }

                    if (nReads > 1)
                    {
                        data = data / (float)nReads;
                    }

                    lock (dtData)
                    {
                        Console.WriteLine();
                        Console.WriteLine("{0}: {1}: {2}", counter, slave, func == null ? data.ToString("N2") : func(data));
                        dtData.Add(slave, data);
                    }
                }
                catch (Exception e)
                {
                    lock (dtData)
                    {
                        Console.Error.WriteLine("Error: {0}: {1}", slave, e.Message);
                    }
                }
            }
            ), hosts, nThreads);

            if (dtData.Count > 0)
            {
                //Sort
                List<KeyValuePair<string, float>> sData = new List<KeyValuePair<string, float>>(dtData);
                sData.Sort(CompareFloat);

                //Max, min
                Console.WriteLine();
                Console.WriteLine("Min {0}: {1}: {2}", counter, sData[0].Key, func == null ? sData[0].Value.ToString("N2") : func(sData[0].Value));
                Console.WriteLine("Max {0}: {1}: {2}", counter, sData[sData.Count - 1].Key, func == null ? sData[sData.Count - 1].Value.ToString("N2") : func(sData[sData.Count - 1].Value));

                double totalData = 0;

                foreach (float f in dtData.Values)
                {
                    totalData += f;
                }

                //Avg
                double avg = totalData / (double)sData.Count;

                Console.WriteLine();
                Console.WriteLine("Avg {0}: {1}", counter, func == null ? avg.ToString("N2") : func(avg));
            }           

            //Dt
            Console.WriteLine();
            Console.WriteLine("Perfmon Request Time: {0}", startTime.ToString());
            Console.WriteLine("Perfmon End Time: {0}", DateTime.Now.ToString());
        }
Example #46
0
        /// <summary>
        /// Binds the data.
        /// </summary>
        private void BindData()
        {
            this.ForumEditor.DataSource = this.Get<IModuleManager<ForumEditor>>().ActiveAsDataTable("Editors");

            // TODO: vzrus: UseFullTextSearch check box is data layer specific and can be hidden by YAF.Classes.Data.CommonDb.FullTextSupported  property.)
            this.DataBind();

            // load Board Setting collection information...
            var settingCollection = new YafBoardSettingCollection(this.Get<YafBoardSettings>());

            // handle checked fields...
            foreach (string name in settingCollection.SettingsBool.Keys)
            {
                Control control = this.HostSettingsTabs.FindControlRecursive(name);

                if (control != null && control is CheckBox && settingCollection.SettingsBool[name].CanRead)
                {
                    // get the value from the property...
                    ((CheckBox)control).Checked =
                        (bool)
                        Convert.ChangeType(
                            settingCollection.SettingsBool[name].GetValue(this.Get<YafBoardSettings>(), null),
                            typeof(bool));
                }
            }

            // handle string fields...
            foreach (string name in settingCollection.SettingsString.Keys)
            {
                Control control = this.HostSettingsTabs.FindControlRecursive(name);

                if (control != null && control is TextBox && settingCollection.SettingsString[name].CanRead)
                {
                    // get the value from the property...
                    ((TextBox)control).Text =
                        (string)
                        Convert.ChangeType(
                            settingCollection.SettingsString[name].GetValue(this.Get<YafBoardSettings>(), null),
                            typeof(string));
                }
                else if (control != null && control is DropDownList && settingCollection.SettingsString[name].CanRead)
                {
                    ListItem listItem =
                        ((DropDownList)control).Items.FindByValue(
                            settingCollection.SettingsString[name].GetValue(this.Get<YafBoardSettings>(), null).ToString());

                    if (listItem != null)
                    {
                        listItem.Selected = true;
                    }
                }
            }

            // handle int fields...
            foreach (string name in settingCollection.SettingsInt.Keys)
            {
                Control control = this.HostSettingsTabs.FindControlRecursive(name);

                if (control != null && control is TextBox && settingCollection.SettingsInt[name].CanRead)
                {
                    // get the value from the property...
                    ((TextBox)control).Text =
                        settingCollection.SettingsInt[name].GetValue(this.Get<YafBoardSettings>(), null).ToString();
                }
                else if (control != null && control is DropDownList && settingCollection.SettingsInt[name].CanRead)
                {
                    ListItem listItem =
                        ((DropDownList)control).Items.FindByValue(
                            settingCollection.SettingsInt[name].GetValue(this.Get<YafBoardSettings>(), null).ToString());

                    if (listItem != null)
                    {
                        listItem.Selected = true;
                    }
                }
            }

            // handle double fields...
            foreach (string name in settingCollection.SettingsDouble.Keys)
            {
                Control control = this.HostSettingsTabs.FindControlRecursive(name);

                if (control != null && control is TextBox && settingCollection.SettingsDouble[name].CanRead)
                {
                    // get the value from the property...
                    ((TextBox)control).Text =
                        settingCollection.SettingsDouble[name].GetValue(this.Get<YafBoardSettings>(), null).ToString();
                }
                else if (control != null && control is DropDownList && settingCollection.SettingsDouble[name].CanRead)
                {
                    ListItem listItem =
                        ((DropDownList)control).Items.FindByValue(
                            settingCollection.SettingsDouble[name].GetValue(this.Get<YafBoardSettings>(), null).ToString());

                    if (listItem != null)
                    {
                        listItem.Selected = true;
                    }
                }
            }

            // special field handling...
            this.AvatarSize.Text = (this.Get<YafBoardSettings>().AvatarSize != 0)
                                       ? this.Get<YafBoardSettings>().AvatarSize.ToString()
                                       : string.Empty;
            this.MaxFileSize.Text = (this.Get<YafBoardSettings>().MaxFileSize != 0)
                                        ? this.Get<YafBoardSettings>().MaxFileSize.ToString()
                                        : string.Empty;

            this.SQLVersion.Text = this.HtmlEncode(this.Get<YafBoardSettings>().SQLVersion);

            if (General.GetCurrentTrustLevel() <= AspNetHostingPermissionLevel.Medium)
            {
                return;
            }

            this.AppCores.Text = Platform.Processors;
            try
            {
                var cpuUsage =
                           new System.Diagnostics.PerformanceCounter
                               {
                                   CategoryName = "Processor",
                                   CounterName = "% Processor Time",
                                   InstanceName = "_Total"
                               };
                float f = cpuUsage.NextValue();
                this.AppCores.Text += " cores, used : " + f.ToType<string>() + "%";
            }
            catch (Exception)
            {
            }

            this.AppMemory.Text = "{0} MB of {1} MB".FormatWith(Platform.AllocatedMemory/ 1000000, 
                 Platform.MappedMemory/1000000);
            this.AppOSName.Text = Platform.VersionString; 
        
            this.AppRuntime.Text = "{0} {1}".FormatWith(Platform.RuntimeName, Platform.RuntimeString);
        }
Example #47
0
        /* /// <summary>
        /// Gets a list of all Processes.
        /// </summary>
        /// <returns>Returns a list of Process.</returns>
        public Process GetAllProcess()
        {
            foreach (Process proc in compProcess.ProcessList)
            {
                proc.UpdateProcessDetails();
            }
            return this.compProcess;
        }*/
        public List<Process> ReturnProcesses()
        {
            ProcList = new List<Process>();

            System.Threading.Tasks.Parallel.ForEach(System.Diagnostics.Process.GetProcesses(), proc =>
             {
                 try
                 {
                     System.Diagnostics.PerformanceCounter pcounter = new System.Diagnostics.PerformanceCounter("Process", "% Processor Time", proc.ProcessName, true);
                     pcounter.NextValue();
                     Thread.Sleep(110); // Required For Accurate Reading
                     ProcList.Add(new Process(proc.ProcessName, proc.Id, Convert.ToInt32(pcounter.NextValue()) / Environment.ProcessorCount, proc.Threads.Count, (int)proc.WorkingSet64 / 1024));
                 }
                 catch (Exception e)
                 {

                 }
             });

            return ProcList;
        }