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()));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates CPU counter
        /// </summary>
        public static SimpleCounter CreateCPUCounter()
        {
            // Créer un compteur par CPU
            System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("Processor");
            SimpleCounter        mainCounter = null;
            List <SimpleCounter> counters    = new List <SimpleCounter>();

            foreach (string instance in category.GetInstanceNames().OrderBy(s => s))
            {
                System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", instance, true);

                SimpleCounter counter = new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100));

                if (instance == "_Total")
                {
                    mainCounter = counter;
                }
                else
                {
                    counters.Add(counter);
                }
            }

            return(new SubPerformanceCounter(mainCounter, counters));
        }
        protected override int GetCurrentPressure()
        {
#if MONO
            var  pc = new System.Diagnostics.PerformanceCounter("Mono Memory", "Available Physical Memory");
            long availableMemory = pc.RawValue;

            int memoryLoad = (int)((100 * availableMemory) / TotalPhysical);
#else
            MEMORYSTATUSEX memoryStatusEx = new MEMORYSTATUSEX();
            memoryStatusEx.Init();
            if (UnsafeNativeMethods.GlobalMemoryStatusEx(ref memoryStatusEx) == 0)
            {
                return(0);
            }

            int memoryLoad = memoryStatusEx.dwMemoryLoad;
#endif
            //if (_pressureHigh != 0) {
            // PerfCounter: Cache Percentage Machine Memory Limit Used
            //    = total physical memory used / total physical memory used limit
            //PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_MACH_MEM_LIMIT_USED, memoryLoad);
            //}

            return(memoryLoad);
        }
Ejemplo n.º 4
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?
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="PerformanceCounter" /> object and optionally
        /// releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                try
                {
                    // This will be done regardless of whether the object is finalized or disposed.
                    if (disposing)
                    {
                        // This will be done only when the object is disposed by calling Dispose().
                        if ((object)m_counter != null)
                        {
                            m_counter.Dispose();
                        }

                        m_counter = null;
                    }

                    Reset();
                }
                finally
                {
                    m_disposed = true;          // Prevent duplicate dispose.
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates virtual memory counter
        /// </summary>
        public static SimpleCounter CreateVirtualMemoryCounter()
        {
            System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes", null, true);
            System.Diagnostics.PerformanceCounter pcMax = new System.Diagnostics.PerformanceCounter("Memory", "Commit Limit", null, true);

            return new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new PerformanceCounter(pcMax));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates counters for each physical disk connected
        /// </summary>
        /// <returns>enumeration of counters</returns>
        public static IEnumerable<SimpleCounter> CreatePhysicalDiskCounters()
        {
            List<SimpleCounter> list = new List<SimpleCounter>();

            System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");
            foreach (string instance in category.GetInstanceNames().OrderBy(s => s))
            {
                if (instance == "_Total") { continue; }

                List<SimpleCounter> subCounterslist = new List<SimpleCounter>();
				System.Diagnostics.PerformanceCounterCategory subCounterCategory = new System.Diagnostics.PerformanceCounterCategory("LogicalDisk");
	            foreach (string subCounterInstance in subCounterCategory .GetInstanceNames().OrderBy(s => s))
	            {
	                if (subCounterInstance == "_Total") { continue; }
	                if (!instance.Contains(subCounterInstance)) { continue; }
	
	                System.Diagnostics.PerformanceCounter subPc = new System.Diagnostics.PerformanceCounter("LogicalDisk", "% Idle Time", subCounterInstance , true);
	                subCounterslist.Add(new ReversePerformanceCounter(new PerformanceCounter(subPc), new StaticPerformanceCounter(100)));
	            }

                System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "% Idle Time", instance, true);
//                list.Add(new ReversePerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100)));
				list.Add(
					new SubPerformanceCounter(
						new ReversePerformanceCounter(
							new PerformanceCounter(pc),
							new StaticPerformanceCounter(100)),
						subCounterslist));
            }

            return list;
        }
Ejemplo n.º 8
0
        private void OnCollected(float counterValue, System.Diagnostics.PerformanceCounter counter, DateTime collectionDateTime)
        {
            DataLogger        logger = new DataLogger(GlobalSettings.WcfHosts[WcfService.DataLog]);
            WindowsPerfMonLog log    = new WindowsPerfMonLog(GlobalDataStore.Manifest.SessionId, collectionDateTime, counter, counterValue);

            logger.SubmitAsync(log);
        }
Ejemplo n.º 9
0
 public StaticPerformanceCounter_Old(string categoryName, string counterName, string instanceName = null)
 {
     counter = instanceName == null
         ? new System.Diagnostics.PerformanceCounter(categoryName, counterName, true)
         : new System.Diagnostics.PerformanceCounter(categoryName, counterName, instanceName, true);
     syncObject = new object();
 }
Ejemplo n.º 10
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();
                }
            }
        }
Ejemplo n.º 11
0
        public DebugQB()
        {
            fpsPosition = new Vector2(Renderer.ScreenWidth - 200, Renderer.ScreenHeight - 80);

            cpuPosition = new Vector2(Renderer.ScreenWidth - 200, 320);
            #if WINDOWS
            ramPosition = new Vector2(Renderer.ScreenWidth - 200, 300);

            if (cpuCounter == null)
            {
                cpuCounter = new System.Diagnostics.PerformanceCounter(
                    "Process",
                    "% Processor Time",
                    System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            }

            if (ramCounter == null)
            {
                ramCounter = new System.Diagnostics.PerformanceCounter(
                    "Process",
                    "Working Set",
                    System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            }
            #endif // WINDOWS

            #if TUNE_DEPTH_BIAS
            depthBiasPosition = new Vector2(20, 200);
            #endif
        }
Ejemplo n.º 12
0
        private void InitializeComponent()
        {
            this.components                 = new System.ComponentModel.Container();
            this.performanceCounter1        = new System.Diagnostics.PerformanceCounter();
            this.performanceCounterChecker1 = new MbUnit.Framework.ComponentModel.PerformanceCounterChecker(this.components);
            this.testCaseComponent1         = new MbUnit.Framework.ComponentModel.TestCaseComponent(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.performanceCounterChecker1)).BeginInit();
//
// performanceCounter1
//
            this.performanceCounter1.CategoryName = ".NET CLR Data";
            this.performanceCounter1.CounterName  = "SqlClient: Current # connection pools";
//
// performanceCounterChecker1
//
            this.performanceCounterChecker1.MaxValue           = 10F;
            this.performanceCounterChecker1.MinValue           = 0F;
            this.performanceCounterChecker1.PerformanceCounter = this.performanceCounter1;
//
// testCaseComponent1
//
            this.testCaseComponent1.Test += new System.EventHandler(this.testCaseComponent1_Test_3);
            ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.performanceCounterChecker1)).EndInit();
        }
 private void InitializeComponent()
 {
     this.components = new System.ComponentModel.Container();
     this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
     this.performanceCounterChecker1 = new MbUnit.Framework.ComponentModel.PerformanceCounterChecker(this.components);
     this.testCaseComponent1 = new MbUnit.Framework.ComponentModel.TestCaseComponent(this.components);
     ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
     ((System.ComponentModel.ISupportInitialize)(this.performanceCounterChecker1)).BeginInit();
     //
     // performanceCounter1
     //
     this.performanceCounter1.CategoryName = ".NET CLR Data";
     this.performanceCounter1.CounterName = "SqlClient: Current # connection pools";
     //
     // performanceCounterChecker1
     //
     this.performanceCounterChecker1.MaxValue = 10F;
     this.performanceCounterChecker1.MinValue = 0F;
     this.performanceCounterChecker1.PerformanceCounter = this.performanceCounter1;
     //
     // testCaseComponent1
     //
     this.testCaseComponent1.Test += new System.EventHandler(this.testCaseComponent1_Test_3);
     ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
     ((System.ComponentModel.ISupportInitialize)(this.performanceCounterChecker1)).EndInit();
 }
Ejemplo n.º 14
0
        private int GetDefaultMemoryCacheLimitMegabytes()
        {
            int totalPhysicalMemoryMegabytes;

            if (Type.GetType("Mono.Runtime") != null)
            {
                var pc = new System.Diagnostics.PerformanceCounter("Mono Memory", "Total Physical Memory");
                totalPhysicalMemoryMegabytes = (int)(pc.RawValue / 1024 / 1024);
                if (totalPhysicalMemoryMegabytes == 0)
                {
                    totalPhysicalMemoryMegabytes = 128;                     // 128MB, the Mono runtime default
                }
            }
            else
            {
#if __MonoCS__
                throw new PlatformNotSupportedException("This build can only run on Mono");
#else
                totalPhysicalMemoryMegabytes =
                    (int)(new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024 / 1024);
#endif
            }

            // we need to leave ( a lot ) of room for other things as well, so we limit the cache size

            var val = (totalPhysicalMemoryMegabytes / 2) -
                      // reduce the unmanaged cache size from the default limit
                      (GetConfigurationValue <int>("Raven/Esent/CacheSizeMax") ?? 1024);

            if (val < 0)
            {
                return(128);                // if machine has less than 1024 MB, then only use 128 MB
            }
            return(val);
        }
Ejemplo n.º 15
0
        public LocalUsage()
        {
            clockTimer = new System.Timers.Timer();
            clockTimer.Interval = 1000;
            clockTimer.Elapsed += clockTimer_Tick;
            try
            {
                pcCPU = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");
            }
            catch
            {
                SupportCPU = false;
            }

            try
            {
                pcMem = new System.Diagnostics.PerformanceCounter("Memory", "% Committed Bytes In Use", "");
            }
            catch
            {
                SupportMEM = false;
            }

            //获取程序集版本
            VER = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
Ejemplo n.º 16
0
        public LocalUsage()
        {
            clockTimer          = new System.Timers.Timer();
            clockTimer.Interval = 1000;
            clockTimer.Elapsed += clockTimer_Tick;
            try
            {
                pcCPU = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");
            }
            catch
            {
                SupportCPU = false;
            }

            try
            {
                pcMem = new System.Diagnostics.PerformanceCounter("Memory", "% Committed Bytes In Use", "");
            }
            catch
            {
                SupportMEM = false;
            }

            //获取程序集版本
            VER = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
Ejemplo n.º 17
0
        public bool saveCounters(List <PerfCounter> perfCounters)
        {
            bool isSaved = true;

            try
            {
                StringBuilder sb = new StringBuilder();

                foreach (PerfCounter perfCounter in perfCounters)
                {
                    System.Diagnostics.PerformanceCounter counter = perfCounter.getCounter();
                    String isAboveSign = perfCounter.isAbove() ? "1" : "0";
                    string counterRow  = string.Format("{0},{1},{2},{3},{4},{5}", counter.CategoryName, counter.InstanceName, counter.CounterName, perfCounter.getQueueSize(), perfCounter.getCritivalValue(), isAboveSign);
                    sb.AppendLine(counterRow);
                }

                System.IO.File.WriteAllText(filePath, sb.ToString());
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                isSaved = false;
            }
            catch (System.IO.IOException)
            {
                isSaved = false;
            }

            return(isSaved);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates virtual memory counter
        /// </summary>
        public static SimpleCounter CreateVirtualMemoryCounter()
        {
            System.Diagnostics.PerformanceCounter pc    = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes", null, true);
            System.Diagnostics.PerformanceCounter pcMax = new System.Diagnostics.PerformanceCounter("Memory", "Commit Limit", null, true);

            return(new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new PerformanceCounter(pcMax)));
        }
Ejemplo n.º 19
0
 public PerformanceAnalyticsCounter(DevicePerformanceCounter deviceCounter)
     : base(deviceCounter)
 {
     _performanceCounter = new PerformanceCounter(deviceCounter.Category,
                                                  deviceCounter.Name,
                                                  deviceCounter.InstanceName);
     _readings = new List <float>();
 }
Ejemplo n.º 20
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;
 }
Ejemplo n.º 21
0
 public SimpleSystemDataProvider()
 {
     this.cpuCounter =
         new System.Diagnostics.PerformanceCounter("Processor", "% processor time", "_Total");
     this.ramCounter =
         new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
     this.loggers = new List <Logger>();
 }
Ejemplo n.º 22
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());
        }
 public static string infoAvailableMemory(this object _object)
 {
     var availableMemory = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes")
                                                 .NextValue()
                                                 .str();
     "AvailableMemory: {0}Mb".info(availableMemory);
     return availableMemory;
 }
Ejemplo n.º 24
0
        public long GetFreeMemory()
        {
            System.Diagnostics.PerformanceCounter pc
                = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            long freeMemory = Convert.ToInt64(pc.NextValue());

            return(freeMemory);
        }
Ejemplo n.º 25
0
 public SimpleSystemDataProvider()
 {
     this.cpuCounter =
         new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");
     this.ramCounter =
         new System.Diagnostics.PerformanceCounter("Mono Memory", "Allocated Objects");
     this.loggers = new List <Logger>();
 }
Ejemplo n.º 26
0
 public C9_CPUSlowdown()
 {
     if ("_9_CPUSlowdown".IsConfiguredAndTRUE())
     {
         maxCou     = "_9_CPUSlowdown_MaxCpu".GetConfigFloat();
         sleepTime  = "_9_CPUSlowdown_Sleep".GetConfigInt();
         cpuCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");
     }
 }
Ejemplo n.º 27
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));
 }
Ejemplo n.º 28
0
        public static string infoAvailableMemory(this object _object)
        {
            var availableMemory = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes")
                                  .NextValue()
                                  .str();

            "AvailableMemory: {0}Mb".info(availableMemory);
            return(availableMemory);
        }
Ejemplo n.º 29
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);
        }
Ejemplo n.º 30
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);
                }
            }
        }
Ejemplo n.º 31
0
        private void InitializeComponent()
        {
            this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
            ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
//
// DataCaseComponent
//
            this.Name = "Test";
            ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
        }
 private void InitializeComponent()
 {
     this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
     ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
     //
     // DataCaseComponent
     //
     this.Name = "Test";
     ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
 }
 // Проверка параметров генерации.
 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();
 }
Ejemplo n.º 34
0
 public CpuUsageControl() : base()
 {
     if (System.Diagnostics.PerformanceCounterCategory.Exists("Processor"))
     {
         cpuTotalCntr = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total", true);
     }
     else
     {
         cpuTotalCntr = new System.Diagnostics.PerformanceCounter("Processor Information", "% Processor Time", "_Total", true);
     }
 }
Ejemplo n.º 35
0
 private void Initialize()
 {
     if (((this.categoryName != null) && (this.counterName != null)) && (this.instanceName != null))
     {
         if (this.counter != null)
         {
             this.counter.Dispose();
         }
         this.counter = new System.Diagnostics.PerformanceCounter(this.categoryName, this.counterName, this.instanceName);
     }
 }
Ejemplo n.º 36
0
        private static int GetDefaultMemoryCacheLimitMegabytesOnMono()
        {
            var pc = new System.Diagnostics.PerformanceCounter("Mono Memory", "Total Physical Memory");
            var totalPhysicalMemoryMegabytes = (int)(pc.RawValue / 1024 / 1024);

            if (totalPhysicalMemoryMegabytes == 0)
            {
                totalPhysicalMemoryMegabytes = 128;                 // 128MB, the Mono runtime default
            }
            return(totalPhysicalMemoryMegabytes);
        }
Ejemplo n.º 37
0
 private void Initialize()
 {
   if (((this.categoryName != null) && (this.counterName != null)) && (this.instanceName != null))
   {
     if (this.counter != null)
     {
       this.counter.Dispose();
     }
     this.counter = new System.Diagnostics.PerformanceCounter(this.categoryName, this.counterName, this.instanceName);
   }
 }
Ejemplo n.º 38
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;
        }
Ejemplo n.º 39
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);
        }
Ejemplo n.º 40
0
 private static IPerformanceCounter GetPerformanceCounter(string categoryName, string counterName, bool isReadOny)
 {
     try
     {
         var performanceCounter = new System.Diagnostics.PerformanceCounter(categoryName, counterName, isReadOny);
         return(new PerformanceCounter(performanceCounter));
     }
     catch
     {
         return(new NullSafePerformanceCounter());
     }
 }
 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);
 }
Ejemplo n.º 42
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();
        }
		private IPerformanceCounter GetPerformanceCounter(string categoryName, string counterName, bool isReadOnly)
		{
			try
			{
				var performanceCounter = new System.Diagnostics.PerformanceCounter(categoryName, counterName, isReadOnly);
				return new PerformanceCounter(performanceCounter, _log);
			}
			catch(Exception ex)
			{
				_log.Error("Error occured during getting performance counter: category = {0}, counter = {1}".Fmt(categoryName, counterName), ex);
				return new NullSafePerformanceCounter();
			}
		}
Ejemplo n.º 44
0
        public Form1()
        {
            InitializeComponent();
            try
            {
                cpuCounter = new System.Diagnostics.PerformanceCounter();
                cpuCounter.CategoryName = "Processor";
                cpuCounter.CounterName = "% Processor Time";
                cpuCounter.InstanceName = "_Total";

                memCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
                totalRam = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes");
                os = new osHelper();
                w_help = new WMI_Info_Helper();
                txbBox1.Text += "Version: " + os.sOperatingSystem + Environment.NewLine;
                txbBox1.Text += "Last Restart: " + os.lastRestart + Environment.NewLine;
                //cpuPercentTimer = new System.Windows.Forms.Timer(Object ob, EventArgs theseEventArgs);
                //cpuPercentTimer.Start();
                txbBox1.Text += "COR PROFILER IS: ";
                if (os.sCorProfiler.ToString().Contains("534F93B28683"))
                {
                    txbBox1.Text += "Dynatrace Application Monitoring";
                }
                else
                {
                    txbBox1.Text += "NOT Dynatrace. PROFILER: " + os.sCorProfiler.ToString();
                }
                txbBox1.Text += Environment.NewLine;
                os.dEnvVars.OrderBy(x => x.Key).ToList();
                foreach (KeyValuePair<string, string> de in os.dEnvVars)
                {
                    txtEnvVars.Text += de.Key + ": " + de.Value + Environment.NewLine;
                }
                UInt32 iTotalRamFree = Convert.ToUInt32(getAvailableRAM());
                txtMem.Text = "Available: " + os.sFreeMemory + " of " + os.sTotalMemory + " GB";
                getCurrentCpuUsage();
                if (os.fNumOfCores == "-1")
                {
                    lblNumCpu.Text = "#INVALID CORE COUNT#";

                }
                else
                {
                    lblNumCpu.Text = os.fNumOfCores;
                }
            } catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Ejemplo n.º 45
0
        public Form1()
        {
            InitializeComponent();

            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

            cpuCounter = new System.Diagnostics.PerformanceCounter();

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

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

            ShowWindow(this.Handle.ToInt32(), SW_SHOWNOACTIVATE);
            SetWindowPos(this.Handle.ToInt32(), HWND_TOPMOST, 10, Screen.PrimaryScreen.Bounds.Height-40, this.Width, this.Height, SWP_NOACTIVATE);
            timer.Start();
        }
        static MemoryMonitor() {
#if MONO
            var pc = new System.Diagnostics.PerformanceCounter ("Mono Memory", "Total Physical Memory");
            s_totalPhysical = pc.RawValue;

            // We should set the the total virtual memory with a system value.
            // But Mono has no such PerformanceCounter and the total virtual memory has little relevance
            // for the rest of the System.Runtime.Caching code.
            s_totalVirtual = 0;
#else
            MEMORYSTATUSEX memoryStatusEx = new MEMORYSTATUSEX();
            memoryStatusEx.Init();
            if (UnsafeNativeMethods.GlobalMemoryStatusEx(ref memoryStatusEx) != 0) {
                s_totalPhysical = memoryStatusEx.ullTotalPhys;
                s_totalVirtual = memoryStatusEx.ullTotalVirtual;
            }
#endif
        }
Ejemplo n.º 47
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();
 }
Ejemplo n.º 48
0
        public PerfCounter(String category, String instance, String counter, int queueSize, float criticalValue, bool above)
        {
            this.counter = new System.Diagnostics.PerformanceCounter();

            ((System.ComponentModel.ISupportInitialize)(this.counter)).BeginInit();
            this.counter.CategoryName = category;
            this.counter.CounterName = counter;
            this.counter.InstanceName = instance;
            ((System.ComponentModel.ISupportInitialize)(this.counter)).EndInit();

            this.queueSize = queueSize;
            this.valuesQueue = new Queue<float>();
            this.lastValue = 0;
            this.avg = 0;
            this.criticalValue = criticalValue;
            string instanceStr = instance == "" ? "" : " (" + instance + ")";
            this.name = category + ": " + counter + instanceStr;
            this.category = category;
            this.above = above;
        }
Ejemplo n.º 49
0
        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();
        }
Ejemplo n.º 50
0
        /// <summary>
        /// コンストラクター
        /// </summary>
        public CpuInfo()
        {
            //カテゴリが存在するか確かめる
            if (!System.Diagnostics.PerformanceCounterCategory.Exists(
                categoryName, machineName))
            {
                Console.WriteLine("登録されていないカテゴリです。");
                return;
            }

            //カウンタが存在するか確かめる
            if (!System.Diagnostics.PerformanceCounterCategory.CounterExists(
                counterName, categoryName, machineName))
            {
                Console.WriteLine("登録されていないカウンタです。");
                return;
            }

            //PerformanceCounterオブジェクトの作成
            pc = new System.Diagnostics.PerformanceCounter(
                categoryName, counterName, instanceName, machineName);
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Creates CPU counter
        /// </summary>
        public static SimpleCounter CreateCPUCounter()
        {
            // Créer un compteur par CPU
            System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("Processor");
            SimpleCounter mainCounter = null;
            List<SimpleCounter> counters = new List<SimpleCounter>();
            foreach (string instance in category.GetInstanceNames().OrderBy(s => s))
            {
                System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", instance, true);

                SimpleCounter counter = new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100));

                if (instance == "_Total")
                {
                    mainCounter = counter;
                }
                else
                {
                    counters.Add(counter);
                }
            }

            return new SubPerformanceCounter(mainCounter, counters);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="PerformanceCounter" /> object and optionally 
        /// releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                try
                {
                    // This will be done regardless of whether the object is finalized or disposed.
                    if (disposing)
                    {
                        // This will be done only when the object is disposed by calling Dispose().
                        if ((object)m_counter != null)
                            m_counter.Dispose();

                        m_counter = null;
                    }

                    Reset();
                }
                finally
                {
                    m_disposed = true;          // Prevent duplicate dispose.
                }
            }
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PerformanceCounter"/> class.
        /// </summary>
        /// <param name="categoryName">The name of the performance counter category (performance object) with which this performance counter is associated.</param>
        /// <param name="counterName">The name of the performance counter.</param>
        /// <param name="instanceName">The name of the performance counter category instance, or an empty string (""), if the category contains a single instance.</param>
        /// <param name="aliasName">The alias name for the <see cref="PerformanceCounter"/> object.</param>
        /// <param name="valueUnit">The measurement unit for the statistical values of the <see cref="PerformanceCounter"/> object.</param>
        /// <param name="valueDivisor">The divisor to be applied to the statistical values of the <see cref="PerformanceCounter"/> object.</param>
        /// <param name="readOnly">Flag that determines if this counter is read-only.</param>
        public PerformanceCounter(string categoryName, string counterName, string instanceName, string aliasName, string valueUnit, float valueDivisor, bool readOnly = true)
        {
            this.AliasName = aliasName;
            this.ValueUnit = valueUnit;
            this.ValueDivisor = valueDivisor;

            m_samplingWindow = DefaultSamplingWindow;
            m_samples = new List<float>();
            m_counter = new System.Diagnostics.PerformanceCounter(categoryName, counterName, instanceName);
            m_counter.ReadOnly = readOnly;

            Reset();
        }
Ejemplo n.º 54
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();
 }
Ejemplo n.º 55
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;
        }
        protected override int GetCurrentPressure() {
#if MONO
            var pc = new System.Diagnostics.PerformanceCounter ("Mono Memory", "Available Physical Memory");
            long availableMemory = pc.RawValue;

            int memoryLoad = (int) ((100 * availableMemory) / TotalPhysical);
#else
            MEMORYSTATUSEX memoryStatusEx = new MEMORYSTATUSEX();
            memoryStatusEx.Init();
            if (UnsafeNativeMethods.GlobalMemoryStatusEx(ref memoryStatusEx) == 0)
                return 0;

            int memoryLoad = memoryStatusEx.dwMemoryLoad;
#endif
            //if (_pressureHigh != 0) {
                // PerfCounter: Cache Percentage Machine Memory Limit Used
                //    = total physical memory used / total physical memory used limit
                //PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_MACH_MEM_LIMIT_USED, memoryLoad);
            //}

            return memoryLoad;
        }
Ejemplo n.º 57
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);
        }
Ejemplo n.º 58
0
 public static void init()
 {
     ThreadWorker = new System.Threading.Thread(updateWork);
     counterCpuUsage = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");
 }
Ejemplo n.º 59
0
    public static void _Main()
    {
      const uint _1Mb = 1048576;
      const uint _1Gb = 1073741824;

      //http://stackoverflow.com/questions/105031/how-do-you-get-total-amount-of-ram-the-computer-has
      var counter_name = "System Code Total Bytes";
      var pc = new System.Diagnostics.PerformanceCounter("Memory", counter_name);
      Console.WriteLine("PerformanceCounter Memory {0}: {1}", counter_name, pc.RawValue);

      var pc_class = new System.Management.ManagementClass("Win32_ComputerSystem");
      System.Management.ManagementObjectCollection moc = pc_class.GetInstances();
      foreach (System.Management.ManagementObject item in moc)
      {
        double n=Convert.ToDouble(item.Properties["TotalPhysicalMemory"].Value);
        Console.WriteLine("\nWin32_ComputerSystem TotalPhysicalMemory: {0:N0} bytes {1:N0}Mb {2:N0}Gb", n,Math.Round(n / _1Mb, 0), Math.Round(n / _1Gb, 0));
      }

      string wmiquery = "SELECT Capacity FROM Win32_PhysicalMemory";
      var searcher = new System.Management.ManagementObjectSearcher(wmiquery);
      decimal capacity = 0L;
      Console.WriteLine($"\n{wmiquery}:");
      foreach (System.Management.ManagementObject wmiobject in searcher.Get())
      {
        decimal n = Convert.ToUInt64(wmiobject.Properties["Capacity"].Value);
        capacity += n;
        Console.WriteLine("{0:N0} bytes {1:N0}Mb {2:N0}Gb", n, Math.Round(n / _1Mb, 0), Math.Round(n / _1Gb, 0));
      }
      Console.WriteLine($"Total capacity: {capacity:N0} bytes {Math.Round(capacity / _1Mb, 0):N0}Mb {Math.Round(capacity / _1Gb, 0)}Gb");

      long memoryKb;
      bool result_code=GetPhysicallyInstalledSystemMemory(out memoryKb);
      double b = memoryKb * 1024D;
      Console.WriteLine($"\n(GetPhysicallyInstalledSystemMemory result code: {result_code}) {b:N0} bytes {Math.Round(b / _1Mb, 0):N0}Mb {Math.Round(b / _1Gb, 0)}Gb");

      //https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx
      var memory_status = new MEMORYSTATUSEX();
      result_code = GlobalMemoryStatusEx(memory_status);
      Console.WriteLine($"\n(GlobalMemoryStatusEx result code: {result_code})");
      foreach (var field in memory_status.GetType().GetFields())
      {
        Console.WriteLine($"{field.Name} = {field.GetValue(memory_status):N0}");
      }

      //https://msdn.microsoft.com/en-us/library/windows/desktop/ms683210(v=vs.85).aspx
      var performance_data = new PERFORMANCE_INFORMATION();
      uint input_size = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(PERFORMANCE_INFORMATION));
      result_code = GetPerformanceInfo(out performance_data, input_size);
      Console.WriteLine($"\n(Global GetPerformanceInfo result code: {result_code})");
      foreach (var field in performance_data.GetType().GetFields())
      {
        object xx = field.GetValue(performance_data);
        ulong v=xx is UIntPtr? ((UIntPtr)xx).ToUInt64():(uint)xx;
        Console.WriteLine($"{field.Name} = {v:N0}");
      }

      var this_process = System.Diagnostics.Process.GetCurrentProcess();
      counter_name = "Working Set Peak";
      var instanceName = "ConsoleApplication1";
      pc = new System.Diagnostics.PerformanceCounter("Process", counter_name, instanceName);
      decimal raw_value = pc.RawValue;
      Console.WriteLine("\nPerformanceCounter Process {0} {1}:\t{2:N0} bytes {3:N0}Mb {4:N0}Gb ({5:N0})", instanceName, counter_name, raw_value, Math.Round(raw_value / _1Mb, 0), Math.Round(raw_value / _1Gb, 0), this_process.PeakWorkingSet64);
      counter_name = "Working Set";
      instanceName = "ConsoleApplication1";
      pc = new System.Diagnostics.PerformanceCounter("Process", counter_name, instanceName);
      raw_value = pc.RawValue;
      Console.WriteLine("PerformanceCounter Process {0} {1}:\t\t{2:N0} bytes {3:N0}Mb {4:N0}Gb ({5:N0})", instanceName, counter_name, raw_value, Math.Round(raw_value / _1Mb, 0), Math.Round(raw_value / _1Gb, 0), this_process.WorkingSet64);
    }
        public static Dictionary<IMethod, Dictionary<string,List<KeyValuePair<INode,IMethodOrProperty>>>> externalMethodsAndProperties(this O2MappedAstData astData, string filter, string targetFolder, int numberOfItemsToProcess)
        {
        	var MimimumAvailableMemoryRequired = "".availableMemory()/4; //50;
        	"Starting externalMethodsAndProperties calculations (with min memory required set to: {0}".info(MimimumAvailableMemoryRequired);
        	if (targetFolder.valid().isFalse())
        		targetFolder = PublicDI.config.getTempFolderInTempDirectory("_AstEngine_ExternalMappings"); 
        	
        	var methodMappingHashesFile = targetFolder.pathCombine("_methodMappingHashes.txt");
        	        
        	var o2Timer = new O2Timer("Calculated externalMethodsAndProperties").start();
        	var iMethodMappings = new Dictionary<IMethod, Dictionary<string,List<KeyValuePair<INode,IMethodOrProperty>>>>(); 					
        	var iMethods = astData.iMethods();
        	var itemsToMap = iMethods.size();// - targetFolder.files().size();
			var itemsMapped = 0;
								
			foreach(var iMethod in iMethods)
			{
				// check avaialble memory
				var availableMemory = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes").NextValue();
				if (availableMemory < MimimumAvailableMemoryRequired)
				{
					"In externalMethodsAndProperties, There is not enough free memory to continue (MimimumAvailableMemoryRequired = {0}, availableMemory = {1}. Stopping mappings".error(MimimumAvailableMemoryRequired,availableMemory);
					"There are {0} iMethodMappings".debug(iMethodMappings.size());
					break;
				}
				//"Available Memory: {0}".debug(availableMemory);
				
				//convert method
				var fullName = iMethod.fullName();
                var md5Hash = fullName.safeFileName().md5Hash();
                var savedMethodMappingsFile = targetFolder.pathCombine(md5Hash) + ".xml";
				//var savedMethodMappingsFile = targetFolder.pathCombine(iMethod.fullName().safeFileName(100))+ ".xml";
				itemsMapped++;
				if (savedMethodMappingsFile.fileExists().isFalse()) // Skip if method mappings have already been calculated
				{
					//"Mapping :{0}".debug(iMethod.DotNetName);
					if (iMethod.Name.regEx(filter))	
					{
						var mappings = astData.externalMethodsAndProperties(iMethod);
						iMethodMappings.Add(iMethod, mappings);
						var savedMethodMappings = astData.saveMappings(mappings);
						if (savedMethodMappings.fileExists())
						{	
							Files.MoveFile(savedMethodMappings, savedMethodMappingsFile);
							methodMappingHashesFile.fileInsertAt(0,"{0}\t{1}".format(md5Hash, fullName).line());
						}
						
					}
						//savedMethodMappingsFile	
					if (itemsMapped % 10 ==0)		// every 10 methods show a log message		
					{
						"In externalMethodsAndProperties, mapped [{0}/{1}] to folder: {2}".info(itemsMapped, itemsToMap, targetFolder);
						if (itemsMapped % 100 ==0)	
							PublicDI.config.gcCollect();	// every 100 methods release some memory				
					}
					if (numberOfItemsToProcess > 0 && numberOfItemsToProcess < iMethodMappings.size())
					{
						"In externalMethodsAndProperties, max number of Items To Process reached ({0}), so stopping mappings]".info(numberOfItemsToProcess);
						"There are {0} iMethodMappings".debug(iMethodMappings.size());
						break;
					}												
				}
			}
			o2Timer.stop();
			return iMethodMappings;
		}