/// <summary>
 /// Re-creates the _counters list if the number
 /// of valid PerformanceCounters has changed.
 /// </summary>
 private void RefreshCounters()
 {
     PerformanceCounterCategory cat = new PerformanceCounterCategory("Network Interface");
      if (cat.GetInstanceNames().Length != _counters.Count)
      {
     _counters.Clear();
     foreach (string instance in cat.GetInstanceNames())
     {
        _counters.Add(new PerformanceCounter("Network Interface", _counterName, instance));
     }
      }
 }
Example #2
0
        public void WatchCpuAndMemory()
        {
            var pc = new PerformanceCounter("Processor Information", "% Processor Time");
            var cat = new PerformanceCounterCategory("Processor Information");
            var cpuInstances = cat.GetInstanceNames();
            var cpus = new Dictionary<string, CounterSample>();

            var memoryCounter = new PerformanceCounter("Memory", "Available MBytes");

            foreach (var s in cpuInstances)
            {
                pc.InstanceName = s;
                cpus.Add(s, pc.NextSample());
            }
            var t = DateTime.Now;
            while (t.AddMinutes(1) > DateTime.Now)
            {
                Trace.WriteLine(string.Format("Memory:{0}MB", memoryCounter.NextValue()));

                foreach (var s in cpuInstances)
                {
                    pc.InstanceName = s;
                    Trace.WriteLine(string.Format("CPU:{0} - {1:f}", s, Calculate(cpus[s], pc.NextSample())));
                    cpus[s] = pc.NextSample();
                }

                //Trace.Flush();
                System.Threading.Thread.Sleep(1000);
            }
        }
        public IEnumerable<string> GetInstances(string category)
        {
            var counterCategory = new PerformanceCounterCategory(category);
            var instances = counterCategory.GetInstanceNames();

            return instances;
        }
        public void Configure()
        {
            var counters = CounterList;

            counters.Add("Processor Load", "Processor", "% Processor Time", "_Total");
            counters.Add("Memory Usage", "Memory", "% Committed Bytes In Use");

            counters.Add("IIS Requests/sec", "Web Service", "Total Method Requests/sec", "_Total");
            //this one is very unreliable
            counters.Add("ASP.NET Request/Sec", "ASP.NET Applications", "Requests/Sec", "__Total__");

            counters.Add("ASP.NET Current Requests", "ASP.NET", "Requests Current");
            counters.Add("ASP.NET Queued Requests", "ASP.NET", "Requests Queued");
            counters.Add("ASP.NET Requests Wait Time", "ASP.NET", "Request Wait Time");

            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
            String[] instanceNames = category.GetInstanceNames();

            foreach (string name in instanceNames)
            {
                counters.Add("Net IO Total: " + name, "Network Interface", "Bytes Total/sec", name);
                counters.Add("Net IO Received: " + name, "Network Interface", "Bytes Received/sec", name);
                counters.Add("Net IO Sent: " + name, "Network Interface", "Bytes Sent/sec", name);
            }
        }
        private void TryToInitializeCounters()
        {
            if (!countersInitialized)
            {
                PerformanceCounterCategory category = new PerformanceCounterCategory(".NET CLR Networking 4.0.0.0");

                var instanceNames = category.GetInstanceNames().Where(i => i.Contains(string.Format("p{0}", pid)));

                if (instanceNames.Any())
                {
                    bytesSentPerformanceCounter = new PerformanceCounter();
                    bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
                    bytesSentPerformanceCounter.CounterName = "Bytes Sent";
                    bytesSentPerformanceCounter.InstanceName = instanceNames.First();
                    bytesSentPerformanceCounter.ReadOnly = true;

                    bytesReceivedPerformanceCounter = new PerformanceCounter();
                    bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
                    bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
                    bytesReceivedPerformanceCounter.InstanceName = instanceNames.First();
                    bytesReceivedPerformanceCounter.ReadOnly = true;

                    countersInitialized = true;
                }
            }
        }
		/// <summary>
		/// Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
		/// </summary>
		/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context that can be used to extract additional information about the environment from which this converter is invoked. This parameter or properties of this parameter can be null.</param>
		/// <returns>
		/// A <see cref="T:System.ComponentModel.TypeConverter.StandardValuesCollection"/> that holds a standard set of valid values, or null if the data type does not support a standard set of values.
		/// </returns>
		public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
		{
			INuGenCounter counter = (context == null) ? null : (context.Instance as INuGenCounter);

			string machineName = ".";
			string categoryName = string.Empty;

			if (counter != null)
			{
				machineName = counter.MachineName;
				categoryName = counter.CategoryName;
			}

			try
			{
				PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, machineName);
				string[] instances = category.GetInstanceNames();
				Array.Sort(instances, Comparer.Default);
				return new TypeConverter.StandardValuesCollection(instances);
			}
			catch
			{
			}

			return null;
		}
Example #7
0
        public NetworkIO()
        {
            _dict = new Dictionary<string, double>();
            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");

            var interfaces = GetNetworkInterfaces();
            var categoryList = category.GetInstanceNames();

            foreach (string name in categoryList)
            {
                var nicName = name.Replace('[', '(').Replace(']', ')');
                if (!interfaces.Select(t => t.Description).Contains(nicName) || nicName.ToLower().Contains("loopback"))
                    continue;
                try
                {
                    NetworkAdapter adapter = new NetworkAdapter(interfaces.First(t => t.Description.Contains(nicName)).Name);
                    adapter.NetworkBytesReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);
                    adapter.NetworkBytesSend = new PerformanceCounter("Network Interface", "Bytes Sent/sec", name);
                    _adappterList.Add(adapter);         // Add it to ArrayList adapter
                }
                catch
                {
                    //pass
                }
            }
        }
 private static void SetVariables(int eth = 0)
 {
     performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
     instance = performanceCounterCategory.GetInstanceNames()[eth]; // 1st NIC !
     performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
     performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);
 }
        public static List<PerformanceCounterCategoryModel> GetPerformanceCounterCategories()
        {
            var counterCategories = new List<PerformanceCounterCategoryModel>();

            PerformanceCounterCategory.GetCategories().ToList().ForEach((i) =>
                counterCategories.Add(new PerformanceCounterCategoryModel { Name = i.CategoryName })
                );

            counterCategories = counterCategories.OrderBy(x => x.Name).ToList();

            counterCategories.ForEach((i) => {
                try {
                    var cat = new PerformanceCounterCategory(i.Name);
                    var instances = cat.GetInstanceNames();

                    if(instances.Length > 0) {
                        foreach(var instance in instances) {
                            i.Instances.Add(instance);
                        }
                    }
                }
                catch {
                    // sometimes this freaks out when an instance can't be examined
                }
            });

            return counterCategories;
        }
        public static bool TryGetInstanceName(Process process, out string instanceName)
        {
            try
            {
                PerformanceCounterCategory processCategory = new PerformanceCounterCategory(CategoryName);
                string[] instanceNames = processCategory.GetInstanceNames();
                foreach (string name in instanceNames)
                {
                    if (name.StartsWith(process.ProcessName))
                    {
                        using (
                            PerformanceCounter processIdCounter = new PerformanceCounter(CategoryName, ProcessIdCounter,
                                name, true))
                        {
                            if (process.Id == (int) processIdCounter.RawValue)
                            {
                                instanceName = name;
                                return true;
                            }
                        }
                    }
                }

                instanceName = null;
                return false;
            }
            catch
            {
                instanceName = null;
                return false;
            }
        }
Example #11
0
        // Try to discover GUID from buggy Performance Monitor instance names.
        // Note: Discover drive GUID comparing free space is uggly, but MS gave me no choice.
        static LogicalDisk()
        {
            // =====         WMI         =====
            Win32_Volume[] vols = Win32_Volume.GetAllVolumes();
            // Free megabytes and volume GUID relation
            Dictionary<ulong, Guid> wmiFree = new Dictionary<ulong, Guid>(vols.Length);
            // Volume name and volume GUID relation
            Dictionary<string, Guid> wmiName = new Dictionary<string, Guid>(vols.Length);

            foreach (Win32_Volume v in vols) {
                if (v.Automount &&
                    v.DriveType == System.IO.DriveType.Fixed) {
                    if (v.IsMounted) {
                        wmiName.Add(v.Name.TrimEnd('\\'), v.DeviceGuid);
                    } else {
                        wmiFree.Add(v.FreeSpace / MB_MULT, v.DeviceGuid);
                    }
                }
            }
            perfMonGuid = new Dictionary<Guid, string>(wmiFree.Count + wmiName.Count);

            // ===== PERFORMANCE MONITOR ======
            PerformanceCounterCategory perfCat = new PerformanceCounterCategory(
                Localization.GetName(COUNTER_LOGICAL_DISK));
            // TODO: Find a faster way to get instance names.
            string[] instances = perfCat.GetInstanceNames();
            // Free megabytes and Performance Monitor instance name
            Dictionary<ulong, string> perfFree = new Dictionary<ulong, string>(instances.Length);

            foreach (string item in instances) {
                if (item == "_Total")
                    continue;

                Guid volId = Guid.Empty;
                if (wmiName.TryGetValue(item, out volId)) {
                    perfMonGuid.Add(volId, item);
                } else {
                    PerformanceCounter p = new PerformanceCounter(
                        Localization.GetName(COUNTER_LOGICAL_DISK),
                        Localization.GetName(COUNTER_FREE_MB),
                        item);
                    perfFree.Add((ulong)p.RawValue, item);
                    p.Close();
                    p.Dispose();
                }
            }

            ulong[] warray = new ulong[wmiFree.Count];
            ulong[] pmarray = new ulong[perfFree.Count];
            if (warray.Length != pmarray.Length)
                throw new NotSupportedException(MSG_EXCEPTION);
            wmiFree.Keys.CopyTo(warray, 0);
            perfFree.Keys.CopyTo(pmarray, 0);
            Array.Sort<ulong>(warray);
            Array.Sort<ulong>(pmarray);

            for (int i = 0; i < warray.Length; i++) {
                perfMonGuid.Add(wmiFree[warray[i]], perfFree[pmarray[i]]);
            }
        }
        /// <summary>
        /// Gets the partition label of the system partition (e.g. "C:")
        /// </summary>
        /// <returns>Returns null if the system partition cannot be identified or located</returns>
        public static string GetSystemPartitionLabel()
        {
            try
            {
                string systemPartition = Path.GetPathRoot(Environment.SystemDirectory);
                if (!string.IsNullOrEmpty(systemPartition))
                {
                    systemPartition = systemPartition.Replace(@"\", "");
                    var      perfCategory  = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");
                    string[] instanceNames = perfCategory.GetInstanceNames();

                    foreach (string name in instanceNames)
                    {
                        if (name.IndexOf(systemPartition) > 0)
                        {
                            return(name);
                        }
                    }
                }
                return(null);
            }
            catch
            {
                throw;
            }
        }
Example #13
0
        private void Initialize()
        {
            var category = new PerformanceCounterCategory(Category);           
            var instances = category.GetInstanceNames();

            foreach (var instanceName in instances)
            {
                _counters.Add(new PerformanceCounter(Category, CounterName, instanceName));
            }

            PerformanceCounterHelper.InitializeCounters(_counters.ToArray());
        }
Example #14
0
        public CpuPlugin(ApplicationConfiguration config)
        {
            using (Profiler.Step("CPU Init"))
            {
                _config = config;
                var category = new PerformanceCounterCategory("Processor");

                _counters = (from name in category.GetInstanceNames()
                             select category.GetCounters(name))
                            .SelectMany(x => x)
                            .ToArray();
            }
        }
Example #15
0
        public void SetupCounters()
        {
            cpuCounter = new PerformanceCounter();

            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
            string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
            performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
            performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);
        }
 public IEnumerable<string> GetCounterNames(string category)
 {
     var cat = new PerformanceCounterCategory(category);
     var instances = cat.CategoryType == PerformanceCounterCategoryType.SingleInstance ? new string[] { null } : cat.GetInstanceNames();
     foreach (var instance in instances)
     {
         var coutners = string.IsNullOrEmpty(instance) ? cat.GetCounters().Select(x => x.CounterName) : cat.GetCounters(instance).Select(x => x.CounterName);
         foreach (var counter in coutners)
         {
             yield return counter;
         }
     }
 }
Example #17
0
        public DriveIdleMonitor()
        {
            drivesMonitored = new List <string>();

            PerformanceCounterCategory cat = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");

            string[] instNames = cat.GetInstanceNames();

            if (instNames.Length - 1 > 0)
            {
                timers       = new DefaultTimer[instNames.Length - 1];
                diskIdleTime = new PerformanceCounter[instNames.Length - 1];
            }

            int i = 0;

            foreach (string inst in instNames)
            {
                if (inst.Equals("_Total"))
                {
                    continue;
                }

                timers[i]       = new DefaultTimer();
                diskIdleTime[i] = new PerformanceCounter("PhysicalDisk",
                                                         "% Idle Time", inst);
                diskIdleTime[i].NextValue();

                timers[i].Interval = 3000;
                timers[i].Tick    += new EventHandler(timer_Tick);
                timers[i].Tag      = inst;
                timers[i].start();

                char[] delimiterChars = { ' ' };

                string[] drives = inst.Split(delimiterChars);

                foreach (String drive in drives)
                {
                    int  val;
                    bool isInt = int.TryParse(drive, out val);

                    if (!isInt)
                    {
                        drivesMonitored.Add(drive);
                    }
                }

                i++;
            }
        }
Example #18
0
        public static void ShowNetworkTraffic()
        {
            var performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
            var instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
            var performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
            var performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);

            for (var i = 0; i < 10; i++)
            {
                Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue()/1024,
                    performanceCounterReceived.NextValue()/1024);
                Thread.Sleep(500);
            }
        }
Example #19
0
		/*
		 * Return the list of running mono vms owned by the current user. The 
		 * result includes the current vm too.
		 */
		public static List<VirtualMachine> GetVirtualMachines () {
			PerformanceCounterCategory p = new PerformanceCounterCategory (".NET CLR JIT");
			string[] machines = p.GetInstanceNames ();

			var res = new List<VirtualMachine> ();

			foreach (string s in machines) {
				// The names are in the form 'pid/name'
				int pos = s.IndexOf ('/');
				if (pos != -1)
					res.Add (new VirtualMachine (Int32.Parse (s.Substring (0, pos))));
			}
			return res;
		}
		void UpdateTreeView ()
		{
			var a = new PerformanceCounterCategory ("Mono Memory");

			procstore.Clear ();
			string thispid = Syscall.getpid ().ToString ();
			
			foreach (string p in a.GetInstanceNames ()){
				if (p.StartsWith (thispid, StringComparison.Ordinal))
					continue;
				
				procstore.AppendValues (p);
			}
		}
Example #21
0
        public InterfacePlugin()
        {
            using (Profiler.Step("Interface Init"))
            {
                var category = new PerformanceCounterCategory("Network Interface");

                // TODO: This is too slow. Need to define a default list of counters
                //       which can be overridden in the config file.
                _counters = (from name in category.GetInstanceNames()
                             select category.GetCounters(name))
                            .SelectMany(x => x)
                            .ToArray();
            }
        }
Example #22
0
 protected virtual void OnSetSelected(object sender, System.EventArgs e)
 {
     instances_store.Clear ();
     CounterSet cset = cfg.sets [counterset.Active];
     csetn = cset.Name;
     try {
         // we take just the first counter category into consideration
         // to retrieve an instance
         PerformanceCounterCategory cat = new PerformanceCounterCategory (cset.Counters [0]);
         foreach (string s in cat.GetInstanceNames ()) {
             instances_store.AppendValues (s);
         }
     } catch {
     }
 }
Example #23
0
		public SystemData()
		{
			PerformanceCounterCategory cat = new PerformanceCounterCategory("Network Interface");
			_instanceNames = cat.GetInstanceNames();

			_netRecvCounters = new PerformanceCounter[_instanceNames.Length];
			for (int i =0; i<_instanceNames.Length; i++)
				_netRecvCounters[i] = new PerformanceCounter();

			_netSentCounters = new PerformanceCounter[_instanceNames.Length];
			for (int i =0; i<_instanceNames.Length; i++)
				_netSentCounters[i] = new PerformanceCounter();

			_compactFormat = false;
		}
Example #24
0
 void AddMetric(string categoryName, string counterName, string instanceName = null)
 {
     PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName);
     if (category.CategoryType == PerformanceCounterCategoryType.MultiInstance && string.IsNullOrEmpty(instanceName))
     {
         foreach (string name in category.GetInstanceNames())
         {
             this.metrics.Add(new PerfMetric(new PerformanceCounter(categoryName, counterName, name)));
         }
     }
     else
     {
         this.metrics.Add(new PerfMetric(new PerformanceCounter(categoryName, counterName, instanceName)));
     }
 }
Example #25
0
        public void GetDriveStats()
        {
            DriveInfo[] drives    = DriveInfo.GetDrives();
            var         cat       = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");
            var         instNames = cat.GetInstanceNames();

            PerformanceCounter diskCounter = new PerformanceCounter
            {
                CategoryName = "PhysicalDisk"
            };

            foreach (DriveInfo drive in drives)
            {
                //There are more attributes you can use.
                //Check the MSDN link for a complete example.

                if (drive.IsReady && drive.DriveType == DriveType.Fixed)
                {
                    BaseDisks disk = null;
                    if (this.Disks != null)
                    {
                        disk = this.Disks.Find(x => x.DiskLetter == drive.Name);
                    }

                    if (disk == null)
                    {
                        disk = new BaseDisks(this.ServerID);
                        this.Disks.Add(disk);
                    }

                    disk.DiskLetter    = drive.Name;
                    disk.FreeDiskSpace = ((drive.AvailableFreeSpace / 1024) / 1024);
                    disk.TotalDiskSize = ((drive.TotalSize / 1024) / 1024);

                    diskCounter.CounterName  = "Disk Read Bytes/sec";
                    diskCounter.InstanceName = instNames.Where(x => x.Contains(drive.Name[0])).First();
                    diskCounter.NextValue();
                    System.Threading.Thread.Sleep(500);
                    disk.ReadBytesPerSec = diskCounter.NextValue();

                    diskCounter.CounterName  = "Disk Write Bytes/sec";
                    diskCounter.InstanceName = instNames.Where(x => x.Contains(drive.Name[0])).First();
                    diskCounter.NextValue();
                    System.Threading.Thread.Sleep(500);
                    disk.WriteBytesPerSec = diskCounter.NextValue();
                }
            }
        }
Example #26
0
        public DriveIdleMonitor()
        {
            drivesMonitored = new List<string>();

            PerformanceCounterCategory cat = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");         
            string[] instNames = cat.GetInstanceNames();           

            if (instNames.Length - 1 > 0)
            {
                timers = new DefaultTimer[instNames.Length - 1];
                diskIdleTime = new PerformanceCounter[instNames.Length - 1];
            }

            int i = 0;

            foreach (string inst in instNames)
            {
                if (inst.Equals("_Total")) continue;

                timers[i] = new DefaultTimer();
                diskIdleTime[i] = new PerformanceCounter("PhysicalDisk",
                     "% Idle Time", inst);
                diskIdleTime[i].NextValue();

                timers[i].Interval = 3000;
                timers[i].Tick += new EventHandler(timer_Tick);
                timers[i].Tag = inst;
                timers[i].start();                

                char[] delimiterChars = {' '};
           
                string[] drives = inst.Split(delimiterChars);

                foreach(String drive in drives) {
                    
                    int val;
                    bool isInt = int.TryParse(drive, out val);

                    if (!isInt)
                    {
                        drivesMonitored.Add(drive);
                    }
                }

                i++;
            }        
            
        }
        public static bool IsProcessRunning(string processName)
        {
            bool found = false;

            // assumption of english
            PerformanceCounterCategory category = new PerformanceCounterCategory("Process");
            PerformanceCounterCategory[] availableCategories = PerformanceCounterCategory.GetCategories();
            string[] names = category.GetInstanceNames();
            foreach (string name in names)
            {
                if(processName == name + ".exe")
                    found = true;
            }

            return found;
        }
        public long GetMemoryUsage()
        {
            if (_hostProcess == null || _hostProcess.HasExited)
            {
                return -1;
            }

            var perfCounterCategory = new PerformanceCounterCategory("Process");
            var instanceName = (from name in perfCounterCategory.GetInstanceNames()
                let counter = new PerformanceCounter("Process", "ID Process", name, true)
                where (int) counter.RawValue == Id
                select name).FirstOrDefault();

            var memoryCounter = new PerformanceCounter("Process", "Working Set - Private", instanceName);
            return memoryCounter.RawValue;
        }
Example #29
0
        /// <summary>
        /// Enumerates network adapters installed on the computer.
        /// </summary>
        private void EnumerateNetworkAdapters()
        {
            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");

            foreach (string name in category.GetInstanceNames())
            {
                // This one exists on every computer.
                if (name == "MS TCP Loopback interface")
                    continue;
                // Create an instance of NetworkAdapter class, and create performance counters for it.
                NetworkAdapter adapter = new NetworkAdapter(name);
                adapter.dlCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);
                adapter.ulCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", name);
                this.adapters.Add(adapter);			// Add it to ArrayList adapter
            }
        }
Example #30
0
        public Dictionary<string, int> GetAllNics()
        {
            var performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
            var cn = performanceCounterCategory.GetInstanceNames();

            var nicDict = new Dictionary<string, int>();

            for (var i = 0; i < cn.Count(); i++)
            {
                if (!nicDict.ContainsKey(cn[i]))
                {
                    nicDict.Add(cn[i],i);
                }
            }

            return nicDict;
        }
        private static string GetProcessInstanceName(int pid)
        {
            var cat = new PerformanceCounterCategory("Process");

            var instances = cat.GetInstanceNames();
            foreach (var instance in instances)
            {
                using (var cnt = new PerformanceCounter("Process", "ID Process", instance, true))
                {
                    var val = (int)cnt.RawValue;
                    if (val == pid)
                        return instance;
                }
            }

            throw new Exception("Could not find performance counter for current process.");
        }
Example #32
0
 private PerformanceCounterCategory getDiskCounterHandler_()
 {
     if (diskCounterHandler_ == null)
     {
         diskCounterHandler_ = new PerformanceCounterCategory("logicaldisk", Environment.MachineName);
         Console.WriteLine("Created new disk counter handler");
         String[] instanceNames = diskCounterHandler_.GetInstanceNames();
         for (int i = 0; i < instanceNames.Length; i++)
             if (instanceNames[i].Contains(':'))
             {
                 diskCounters_ = diskCounterHandler_.GetCounters(instanceNames[i]);
                 Console.WriteLine("Selected logical disk: "+instanceNames[i]+", total counter count: "+diskCounters_.Length);
                 break;
             }
     }
     return diskCounterHandler_;
 }
Example #33
0
        public static void SetupDiskCounters(string Disk)
        {
            // Don't need to setup if don't need to.
            if (DiskActivityCounter != null)
                return;

            // Get Disk Instance of interest
            var cat = new System.Diagnostics.PerformanceCounterCategory("LogicalDisk");
            var names = cat.GetInstanceNames();

            string instance = names.FirstOrDefault(name => name.Contains(Disk, StringComparison.OrdinalIgnoreCase));
            if (instance == null)
                return;

            DiskActivityCounter = new PerformanceCounter("LogicalDisk", "% Disk Time", instance);
            DiskTransferCounter = new PerformanceCounter("LogicalDisk", "Disk Bytes/sec", instance);
        }
Example #34
0
        public StatDiskActivity()
        {
            sessionID        = DateTime.Now.Ticks;
            historyIndex     = -1;
            historyIndexHour = -1;
            historyIndexDay  = -1;

            var cat       = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");
            var instNames = cat.GetInstanceNames();

            foreach (var s in instNames)
            {
                if (s == "_Total")
                {
                    continue;
                }

                var item = new StatDiskActivityItem(s);
                _disks.Add(item);
            }

            _timer = new Timer(Update, null, 0, 1000);
            Update(null);
        }
Example #35
0
        public StorageMonitor()
        {
            // Disk Activity
            string category            = "PhysicalDisk";
            string activityCounterName = "% Disk Time";
            string readCounterName     = "Disk Read Bytes/sec";
            string writeCounterName    = "Disk Write Bytes/sec";
            // Check Drive types
            HashSet <char> fixedDrives = new HashSet <char>();
            {
                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (var drive in drives)
                {
                    if (drive.DriveType == DriveType.Fixed)
                    {
                        fixedDrives.Add(drive.Name[0]);
                    }
                }
            }
            //// Instances (Filter out non fixed drives)
            var           cat       = new System.Diagnostics.PerformanceCounterCategory(category);
            List <string> instNames = new List <string>();

            {
                List <string> instNames_tmp = new List <string>(cat.GetInstanceNames());
                instNames_tmp.Remove("_Total");
                instNames_tmp.Sort((x, y) => {
                    if ((x.Length >= 2 && y.Length >= 2) && (x[x.Length - 2] > y[y.Length - 2]))
                    {
                        return(1);
                    }
                    else
                    {
                        return(-1);
                    }
                });
                for (int i = 0; i < instNames_tmp.Count; i++)
                {
                    if (instNames_tmp[i].Length >= 3)
                    {
                        if (fixedDrives.Contains(instNames_tmp[i][instNames_tmp[i].Length - 2]))
                        {
                            instNames.Add(instNames_tmp[i]);
                        }
                    }
                }
            }
            //// Setup
            drives       = new Drive[instNames.Count];
            diskActivity = new PerformanceCounter[instNames.Count];
            diskRead     = new PerformanceCounter[instNames.Count];
            diskWrite    = new PerformanceCounter[instNames.Count];
            for (int i = 0; i < instNames.Count; i++)
            {
                drives[i].letter = instNames[i].Substring(instNames[i].Length - 2, 1).ToCharArray()[0];
                diskActivity[i]  = new PerformanceCounter(category, activityCounterName, instNames[i]);
                diskRead[i]      = new PerformanceCounter(category, readCounterName, instNames[i]);
                diskWrite[i]     = new PerformanceCounter(category, writeCounterName, instNames[i]);
            }
            // Release Memory
            fixedDrives.Clear(); cat = null;
            GC.Collect();
        }
Example #36
0
/*
 *      public static void createIfNotExists(string categoryName, string counterName, string instanceName, string machineName,
 *          string categoryHelp, string counterHelp)
 *      {
 *
 *          bool objectExists = false;
 *          PerformanceCounterCategory pcc;
 *          bool createCategory = false;
 *
 *          // Verify that the category name is not blank.
 *          if (categoryName.Length == 0)
 *          {
 *              throw new ArgumentException("Category name cannot be blank.");
 *          }
 *
 *          // Check whether the specified category exists.
 *          if (machineName.Length == 0)
 *          {
 *              objectExists = PerformanceCounterCategory.Exists(categoryName);
 *          }
 *          else
 *          {
 *              // Handle the exception that is thrown if the computer
 *              // cannot be found.
 *              try
 *              {
 *                  objectExists = PerformanceCounterCategory.Exists(categoryName, machineName);
 *              }
 *              catch (Exception ex)
 *              {
 *                  throw new Exception(String.Format("Error checking for existence of " +
 *                      "category \"{0}\" on computer \"{1}\":" + "\n" + ex.Message, categoryName, machineName));
 *              }
 *          }
 *
 *          // Tell the user whether the specified category exists.
 *          //Console.WriteLine("Category \"{0}\" " + (objectExists ? "exists on " : "does not exist on ") +
 *          //    (machineName.Length > 0 ? "computer \"{1}\"." : "this computer."), categoryName, machineName);
 *
 *          // If no counter name is given, the program cannot continue.
 *          if (counterName.Length == 0)
 *          {
 *              throw new ArgumentException("counterName name cannot be blank.");
 *          }
 *
 *          // A category can only be created on the local computer.
 *          if (!objectExists)
 *          {
 *              if (machineName.Length > 0)
 *              {
 *                  throw new Exception("A category can only be created on the local computer.");
 *              }
 *              else
 *              {
 *                  createCategory = true;
 *              }
 *          }
 *          else
 *          {
 *              // Check whether the specified counter exists.
 *              if (machineName.Length == 0)
 *              {
 *                  objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName);
 *              }
 *              else
 *              {
 *                  objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName);
 *              }
 *
 *              // Tell the user whether the counter exists.
 *             // Console.WriteLine("Counter \"{0}\" " + (objectExists ? "exists" : "does not exist") +
 *             //     " in category \"{1}\" on " + (machineName.Length > 0 ? "computer \"{2}\"." : "this computer."),
 *             //     counterName, categoryName, machineName);
 *
 *              // If the counter does not exist, consider creating it.
 *              if (!objectExists)
 *
 *              // If this is a remote computer,
 *              // exit because the category cannot be created.
 *              {
 *                  if (machineName.Length > 0)
 *                  {
 *                      throw new Exception("A category can only be created on the local computer.");
 *                  }
 *                  else
 *                  {
 *
 *                      // Ask whether the user wants to recreate the category.
 *                      Console.Write("Do you want to delete and recreate " +
 *                          "category \"{0}\" with your new counter? [Y/N]: ", categoryName);
 *                      string userReply = Console.ReadLine();
 *
 *                      // If yes, delete the category so it can be recreated later.
 *                      if (userReply.Trim().ToUpper() == "Y")
 *                      {
 *                          PerformanceCounterCategory.Delete(categoryName);
 *                          createCategory = true;
 *                      }
 *                      else
 *                      {
 *                          return;
 *                      }
 *
 *                  }
 *              }
 *          }
 *
 *          // Create the category if it was deleted or it never existed.
 *          if (createCategory)
 *          {
 *              pcc = PerformanceCounterCategory.Create(categoryName, categoryHelp, counterName, counterHelp);
 *
 *            //  Console.WriteLine("Category \"{0}\" with counter \"{1}\" created.", pcc.CategoryName, counterName);
 *
 *          }
 *          else if (instanceName.Length > 0)
 *          {
 *              if (machineName.Length == 0)
 *              {
 *                  objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName);
 *              }
 *              else
 *              {
 *                  objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName, machineName);
 *              }
 *
 *              // Tell the user whether the instance exists.
 *              //Console.WriteLine("Instance \"{0}\" " + (objectExists ? "exists" : "does not exist") +
 *              //    " in category \"{1}\" on " + (machineName.Length > 0 ? "computer \"{2}\"." : "this computer."),
 *              //    instanceName, categoryName, machineName);
 *          }
 *      }
 */


        public static void listCategories()
        {
            //Get all performance categories
            var cat       = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");
            var instNames = cat.GetInstanceNames();
        }
Example #37
0
        void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
        {
            perfobject.Items.Clear();
            string[] instanceNames;
            System.Collections.ArrayList counters = new System.Collections.ArrayList();
            if (comboBox1.SelectedIndex != -1)
            {
                bool IsFinded = false;
                System.Diagnostics.PerformanceCounterCategory mycat = new System.Diagnostics.PerformanceCounterCategory(comboBox1.SelectedItem.ToString());
                instanceNames = mycat.GetInstanceNames();
                int proccount = 0;
                for (int i = 0; i < instanceNames.Length; i++)
                {
                    string fortest  = instanceNames[i].ToLower();
                    int    lastdiez = fortest.LastIndexOf("#");
                    if (lastdiez != -1)
                    {
                        fortest = fortest.Remove(lastdiez, fortest.Length - lastdiez);
                    }
                    if (ProcessName.ToLower().Contains(fortest))
                    {
                        proccount++;
                        if (proccount >= 2)
                        {
                            break;
                        }
                    }
                }

                for (int i = 0; i < instanceNames.Length; i++)
                {
                    IsFinded = false;
                    System.Diagnostics.PerformanceCounterCategory mycattest = new System.Diagnostics.PerformanceCounterCategory(".NET CLR Memory");
                    System.Collections.ArrayList testcounters = new System.Collections.ArrayList();
                    testcounters.AddRange(mycattest.GetCounters(instanceNames[i]));

                    foreach (System.Diagnostics.PerformanceCounter tcounter in testcounters)
                    {
                        if (tcounter.CounterName == "Process ID")
                        {
                            if ((int)tcounter.RawValue == procid)
                            {
                                IsFinded = true;
                            }
                            else
                            {
                                IsFinded = false;
                            }
                        }
                    }


                    if (!IsFinded || proccount >= 2)
                    {
                        string fortest  = instanceNames[i];
                        int    lastdiez = fortest.LastIndexOf("#");
                        if (lastdiez != -1)
                        {
                            fortest = fortest.Remove(lastdiez, fortest.Length - lastdiez);
                        }
                        if (ProcessName.ToLower().Contains(fortest.ToLower()))
                        {
                            IsFinded = true;
                            string[]     prcdet   = new string[] { "" };
                            ListViewItem proctadd = new ListViewItem(prcdet);
                            perfobject.Items.Add(proctadd);
                            prcdet   = new string[] { instanceNames[i] };
                            proctadd = new ListViewItem(prcdet);
                            perfobject.Items.Add(proctadd);
                        }
                    }

                    if (IsFinded)
                    {
                        counters.AddRange(mycat.GetCounters(instanceNames[i]));
                        // Add the retrieved counters to the list.
                        foreach (System.Diagnostics.PerformanceCounter counter in counters)
                        {
                            string[]     prcdetails = new string[] { counter.CounterName, counter.RawValue.ToString() };
                            ListViewItem proc       = new ListViewItem(prcdetails);
                            perfobject.Items.Add(proc);
                        }
                    }
                    if (proccount < 2 && IsFinded)
                    {
                        break;
                    }
                }
            }
        }