/// <summary>
        /// Gets the or create counter category.
        /// </summary>
        /// <param name="categoryInfo">The category information.</param>
        /// <param name="counters">The counters.</param>
        /// <returns>PerformanceCounterCategory.</returns>
        private static PerformanceCounterCategory GetOrCreateCounterCategory(
            PerformanceCounterCategoryInfo categoryInfo, CounterCreationData[] counters)
        {
            var creationPending = true;
            var categoryExists = false;
            var categoryName = categoryInfo.CategoryName;
            var counterNames = new HashSet<string>(counters.Select(info => info.CounterName));
            PerformanceCounterCategory category = null;

            if (PerformanceCounterCategory.Exists(categoryName))
            {
                categoryExists = true;
                category = new PerformanceCounterCategory(categoryName);
                var counterList = category.GetCounters();
                if (category.CategoryType == categoryInfo.CategoryType && counterList.Length == counterNames.Count)
                {
                    creationPending = counterList.Any(x => !counterNames.Contains(x.CounterName));
                }
            }

            if (!creationPending) return category;

            if (categoryExists)
                PerformanceCounterCategory.Delete(categoryName);

            var counterCollection = new CounterCreationDataCollection(counters);

            category = PerformanceCounterCategory.Create(
                categoryInfo.CategoryName,
                categoryInfo.CategoryHelp,
                categoryInfo.CategoryType,
                counterCollection);

            return category;
        }
Example #2
0
        private void OptionsFormVisibleChanged(object sender, EventArgs e)
        {
            if (Visible == false)
            {
                return;
            }

            textBoxPhoneIp.Text = _options.PhoneIp;
            textBoxPhonePort.Text = _options.PhonePort.ToString();
            textBoxMyipHost.Text = _options.MyipHost;
            textBoxMyipPort.Text = _options.MyipPort.ToString();
            textBoxMyipUrl.Text = _options.MyipUrl;
            textBoxMyipInterval.Text = _options.MyipInterval.ToString();
            textBoxNpFile.Text = _options.NpFile;
            checkBoxSendNp.Checked = _options.SendNp;

            // set listBoxNetworkInterface
            listBoxNetworkInterface.Items.Clear();
            var instanceNames = new PerformanceCounterCategory("Network Interface").GetInstanceNames();
            listBoxNetworkInterface.Items.AddRange(instanceNames);
            if (instanceNames.Length > 0)
            {
                listBoxNetworkInterface.SelectedIndex = 0;
            }
            if (instanceNames.Length > _options.NetIndex)
            {
                listBoxNetworkInterface.SelectedIndex = _options.NetIndex;
            }
        }
        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);
            }
        }
        public IEnumerable<string> GetInstances(string category)
        {
            var counterCategory = new PerformanceCounterCategory(category);
            var instances = counterCategory.GetInstanceNames();

            return instances;
        }
Example #5
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
                }
            }
        }
        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;
        }
Example #7
0
 public PerfCounterMBean(string perfObjectName, string perfInstanceName, IEnumerable<string> perfCounterNames, bool useProcessInstanceName, bool useAllCounters)
 {
     _perfObjectName = perfObjectName;
      if (useProcessInstanceName)
      {
     Process p = Process.GetCurrentProcess();
     _perfInstanceName = p.ProcessName;
      }
      else
      {
     _perfInstanceName = perfInstanceName ?? "";
      }
      _category = new PerformanceCounterCategory(_perfObjectName);
      if (useAllCounters)
      {
     foreach (PerformanceCounter counter in _category.GetCounters(_perfInstanceName))
     {
        _counters[counter.CounterName] = counter;
     }
      }
      else if (perfCounterNames != null)
      {
     foreach (string counterName in perfCounterNames)
     {
        PerformanceCounter counter;
        counter = new PerformanceCounter(_perfObjectName, counterName, _perfInstanceName, true);
        _counters.Add(counterName, counter);
     }
      }
 }
        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;
                }
            }
        }
        public void Enabling_performance_counters_should_result_in_performance_counters_being_created()
        {
            //This will delete an recreate the categories.
            PerformanceCategoryCreator.CreateCategories();

            var outboundIntances = new PerformanceCounterCategory(OutboundPerfomanceCounters.CATEGORY).GetInstanceNames();
            var inboundIntances = new PerformanceCounterCategory(InboundPerfomanceCounters.CATEGORY).GetInstanceNames();
            Assert.Empty(outboundIntances);
            Assert.Empty(inboundIntances);

            var hostConfiguration = new RhinoQueuesHostConfiguration()
                .EnablePerformanceCounters()
                .Bus("rhino.queues://localhost/test_queue2", "test");

            container = new WindsorContainer();
            new RhinoServiceBusConfiguration()
                .UseConfiguration(hostConfiguration.ToBusConfiguration())
                .UseCastleWindsor(container)
                .Configure();
            bus = container.Resolve<IStartableServiceBus>();
            bus.Start();

            using (var tx = new TransactionScope())
            {
                bus.Send(bus.Endpoint, "test message.");
                tx.Complete();
            }

            outboundIntances = new PerformanceCounterCategory(OutboundPerfomanceCounters.CATEGORY).GetInstanceNames();
            inboundIntances = new PerformanceCounterCategory(InboundPerfomanceCounters.CATEGORY).GetInstanceNames();

            Assert.NotEmpty(outboundIntances.Where(name => name.Contains("test_queue2")));
            Assert.NotEmpty(inboundIntances.Where(name => name.Contains("test_queue2")));
        }
Example #10
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 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 #12
0
        private static void EnumerateCountersFor(string category)
        {
            var sb = new StringBuilder();
            var counterCategory = new PerformanceCounterCategory(category);

            if(counterCategory.CategoryType == PerformanceCounterCategoryType.SingleInstance)
            {
                foreach (var counter in counterCategory.GetCounters())
                {
                    sb.AppendLine(string.Format("{0}:{1}", category, counter.CounterName));
                }
            }
            else
            {
                foreach (var counterInstance in counterCategory.GetInstanceNames())
                {
                    foreach (var counter in counterCategory.GetCounters(counterInstance))
                    {
                        sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName));
                    }
                }
            }

            Console.WriteLine(sb.ToString());
        }
Example #13
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;
            }
        }
		/// <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;
		}
		static PerfCounters()
		{
			var p = Process.GetCurrentProcess();
			ProcessName = p.ProcessName;
			ProcessId = p.Id;

			CategoryProcess = new PerformanceCounterCategory("Process");

			ProcessorTime = new PerformanceCounter("Process", "% Processor Time", ProcessName);
			UserTime = new PerformanceCounter("Process", "% User Time", ProcessName);

			PrivateBytes = new PerformanceCounter("Process", "Private Bytes", ProcessName);
			VirtualBytes = new PerformanceCounter("Process", "Virtual Bytes", ProcessName);
			VirtualBytesPeak = new PerformanceCounter("Process", "Virtual Bytes Peak", ProcessName);
			WorkingSet = new PerformanceCounter("Process", "Working Set", ProcessName);
			WorkingSetPeak = new PerformanceCounter("Process", "Working Set Peak", ProcessName);
			HandleCount = new PerformanceCounter("Process", "Handle Count", ProcessName);

			CategoryNetClrMemory = new PerformanceCounterCategory(".NET CLR Memory");
			ClrBytesInAllHeaps = new PerformanceCounter(".NET CLR Memory", "# Bytes in all Heaps", ProcessName);
			ClrTimeInGC = new PerformanceCounter(".NET CLR Memory", "% Time in GC", ProcessName);
			ClrGen0Collections = new PerformanceCounter(".NET CLR Memory", "# Gen 0 Collections", p.ProcessName, true);
			ClrGen1Collections = new PerformanceCounter(".NET CLR Memory", "# Gen 1 Collections", p.ProcessName, true);
			ClrGen2Collections = new PerformanceCounter(".NET CLR Memory", "# Gen 1 Collections", p.ProcessName, true);
		}
 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 void Initialize()
        {
            if (Log.IsInfoEnabled)
            {
                Log.InfoFormat("Start to initialize {0} performance counters", CategoryName);
            }

            if (!IsUserAdmin())
            {
                Log.Info("User has no Admin rights. CustomAuthResultCounters initialization skipped");
                return;
            }

            try
            {
                PerformanceCounterCategory = GetOrCreateCategory(CategoryName, GetCounterCreationData());
            }
            catch (Exception e)
            {
                Log.WarnFormat("Exception happened during counters initialization. Excpetion {0}", e);
                return;
            }

            if (Log.IsInfoEnabled)
            {
                Log.InfoFormat("{0} performance counters successfully initialized", CategoryName);
            }
        }
Example #19
0
 public ICollection GetPerfCounters(string category)
 {
     var r = new ArrayList();
     var cat = new PerformanceCounterCategory(category);
     foreach (var counter in cat.GetCounters()) {
         r.Add(new DictionaryEntry(counter.CounterName, counter.NextValue()));
     }
     return r;
 }
        public void ShouldInstallFirstCategory()
        {
            PerformanceCountersInstaller installer = GetCommandLineConfiguredInstaller(firstCategory);
            DoCommitInstall(installer);

            PerformanceCounterCategory category = new PerformanceCounterCategory(firstCategory);

            AssertCategoryIsCorrect(category);
        }
 public static PerformanceCounterCategory GetPerformanceCounterCategory(string category, string machineName)
 {
     PerformanceCounterCategory cat;
     if (string.IsNullOrEmpty(machineName))
         cat = new PerformanceCounterCategory(category);
     else
         cat = new PerformanceCounterCategory(category, machineName);
     return cat;
 }
 public void DotNetClrDataCategory() {
     var category = new PerformanceCounterCategory(".NET CLR Data");
     Assert.IsNotNull(category);
     var counters = category.GetCounters();
     Assert.IsNotNull(counters);
     Assert.IsTrue(counters.Any());
     foreach(var counter in counters) {
         Console.WriteLine("Counter={0}, InstanceName={1}", counter.CounterName, counter.InstanceName);
     }
 }
Example #23
0
        public MemoryPlugin(ApplicationConfiguration config)
        {
            using (Profiler.Step("Memory Init"))
            {
                _config = _config;
                var category = new PerformanceCounterCategory("Memory");

                _counters = category.GetCounters();
            }
        }
Example #24
0
        private static void EnumerateCountersFor(string category, string instance)
        {
            var sb = new StringBuilder();
            var counterCategory = new PerformanceCounterCategory(category);
            foreach (var counter in counterCategory.GetCounters(instance))
            {
                sb.AppendLine(string.Format("{0}:{1}:{2}", instance, category, counter.CounterName));
            }

            Console.WriteLine(sb.ToString());
        }
Example #25
0
        public object DoCheck()
        {
            PerformanceCounterCategory category = new PerformanceCounterCategory("ASP.NET");
            IDictionary<string, object> values = new Dictionary<string, object>();

            foreach (PerformanceCounter counter in category.GetCounters())
            {
                values.Add(counter.CounterName, counter.NextValue());
            }
            return values;
        }
Example #26
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());
        }
 public static List<string> GetCountersForCategory(string category, string instance)
 {
     var cat = new PerformanceCounterCategory(category);
     var counters = string.IsNullOrEmpty(instance)
         ? cat.GetCounters()
         : cat.GetCounters(instance);
     var ret = new List<string>();
     foreach(var counter in counters) {
         ret.Add(counter.CounterName);
     }
     return ret;
 }
 /// <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));
     }
      }
 }
 static PerformanceSampler()
 {
     if (!PerformanceCounterCategory.Exists(PerformanceCounters.CategoryName))
     {
         logger.WarnFormat("The Performance Counters For Category {0} are not installed. Performance sampling will be disabled.", PerformanceCounters.CategoryName);
         _disablePerformanceSampling = true;
     }
     else
     {
         category = new PerformanceCounterCategory(PerformanceCounters.CategoryName);
     }
 }
 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 #31
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 #32
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 #33
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 #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 PerformanceCounterCategory(System.Diagnostics.PerformanceCounterCategory counterCategory)
 {
     this.CounterCategory = counterCategory;
 }
Example #37
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 #38
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;
                    }
                }
            }
        }
        public override void CopyFromComponent(IComponent component)
        {
            if (!(component is PerformanceCounter))
            {
                throw new ArgumentException(Res.GetString("NotAPerformanceCounter"));
            }
            PerformanceCounter counter = (PerformanceCounter)component;

            if ((counter.CategoryName == null) || (counter.CategoryName.Length == 0))
            {
                throw new ArgumentException(Res.GetString("IncompletePerformanceCounter"));
            }
            if (!this.CategoryName.Equals(counter.CategoryName) && !string.IsNullOrEmpty(this.CategoryName))
            {
                throw new ArgumentException(Res.GetString("NewCategory"));
            }
            PerformanceCounterType counterType = PerformanceCounterType.NumberOfItems32;
            string counterHelp = string.Empty;

            if (string.IsNullOrEmpty(this.CategoryName))
            {
                this.CategoryName = counter.CategoryName;
            }
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                string machineName = counter.MachineName;
                if (PerformanceCounterCategory.Exists(this.CategoryName, machineName))
                {
                    string      name = @"SYSTEM\CurrentControlSet\Services\" + this.CategoryName + @"\Performance";
                    RegistryKey key  = null;
                    try
                    {
                        if ((machineName == ".") || (string.Compare(machineName, SystemInformation.ComputerName, StringComparison.OrdinalIgnoreCase) == 0))
                        {
                            key = Registry.LocalMachine.OpenSubKey(name);
                        }
                        else
                        {
                            key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, @"\\" + machineName).OpenSubKey(name);
                        }
                        if (key == null)
                        {
                            throw new ArgumentException(Res.GetString("NotCustomPerformanceCategory"));
                        }
                        object obj2 = key.GetValue("Library");
                        if (((obj2 == null) || !(obj2 is string)) || (string.Compare((string)obj2, "netfxperf.dll", StringComparison.OrdinalIgnoreCase) != 0))
                        {
                            throw new ArgumentException(Res.GetString("NotCustomPerformanceCategory"));
                        }
                        PerformanceCounterCategory category = new PerformanceCounterCategory(this.CategoryName, machineName);
                        this.CategoryHelp = category.CategoryHelp;
                        if (category.CounterExists(counter.CounterName))
                        {
                            counterType = counter.CounterType;
                            counterHelp = counter.CounterHelp;
                        }
                        this.CategoryType = category.CategoryType;
                    }
                    finally
                    {
                        if (key != null)
                        {
                            key.Close();
                        }
                    }
                }
            }
            CounterCreationData data = new CounterCreationData(counter.CounterName, counterHelp, counterType);

            this.Counters.Add(data);
        }
Example #40
0
        /// <include file='doc\PerformanceCounterInstaller.uex' path='docs/doc[@for="PerformanceCounterInstaller.CopyFromComponent"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override void CopyFromComponent(IComponent component)
        {
            if (!(component is PerformanceCounter))
            {
                throw new ArgumentException(Res.GetString(Res.NotAPerformanceCounter));
            }

            PerformanceCounter counter = (PerformanceCounter)component;

            if (counter.CategoryName == null || counter.CategoryName.Length == 0)
            {
                throw new ArgumentException(Res.GetString(Res.IncompletePerformanceCounter));
            }

            if (Counters.Count > 0 && !CategoryName.Equals(counter.CategoryName))
            {
                throw new ArgumentException(Res.GetString(Res.NewCategory));
            }

            PerformanceCounterType counterType = PerformanceCounterType.NumberOfItems32;
            string counterHelp = string.Empty;

            if (CategoryName == null || string.Empty.Equals(CategoryName))
            {
                CategoryName = counter.CategoryName;
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    string machineName = counter.MachineName;

                    if (PerformanceCounterCategory.Exists(CategoryName, machineName))
                    {
                        string      keyPath = ServicePath + "\\" + CategoryName + "\\Performance";
                        RegistryKey key     = null;
                        try {
                            if (machineName == "." || String.Compare(machineName, SystemInformation.ComputerName, true, CultureInfo.InvariantCulture) == 0)
                            {
                                key = Registry.LocalMachine.OpenSubKey(keyPath);
                            }
                            else
                            {
                                RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + machineName);
                                key = baseKey.OpenSubKey(keyPath);
                            }

                            if (key == null)
                            {
                                throw new ArgumentException(Res.GetString(Res.NotCustomPerformanceCategory));
                            }

                            object systemDllName = key.GetValue("Library");
                            if (systemDllName == null || !(systemDllName is string) || String.Compare((string)systemDllName, PerfShimName, true, CultureInfo.InvariantCulture) != 0)
                            {
                                throw new ArgumentException(Res.GetString(Res.NotCustomPerformanceCategory));
                            }

                            PerformanceCounterCategory pcat = new PerformanceCounterCategory(CategoryName, machineName);
                            CategoryHelp = pcat.CategoryHelp;
                            if (pcat.CounterExists(counter.CounterName))
                            {
                                counterType = counter.CounterType;
                                counterHelp = counter.CounterHelp;
                            }
                        }
                        finally {
                            if (key != null)
                            {
                                key.Close();
                            }
                        }
                    }
                }
            }

            CounterCreationData data = new CounterCreationData(counter.CounterName, counterHelp, counterType);

            Counters.Add(data);
        }