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; }
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; } } }
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); } } }
/// <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; }
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()); }
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 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); } }
public MemoryPlugin(ApplicationConfiguration config) { using (Profiler.Step("Memory Init")) { _config = _config; var category = new PerformanceCounterCategory("Memory"); _counters = category.GetCounters(); } }
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; }
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()); }
/// <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 <see langword="null"/> .</param> /// <returns> /// A <see cref="T:System.ComponentModel.TypeConverter.StandardValuesCollection"/> that holds a standard set /// of valid values, or <see langword="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(); PerformanceCounter[] counters = null; if (instances.Length == 0) counters = category.GetCounters(); else counters = category.GetCounters(instances[0]); string[] names = new string[counters.Length]; for (int nameIndex = 0; nameIndex < counters.Length; nameIndex++) { names[nameIndex] = counters[nameIndex].CounterName; } Array.Sort(names, Comparer.Default); return new TypeConverter.StandardValuesCollection(names); } catch { } return null; }
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(); } }
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(); } }
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { PerformanceCounter counter = (context == null) ? null : (context.Instance as PerformanceCounter); string machineName = "."; string categoryName = string.Empty; if (counter != null) { machineName = counter.MachineName; categoryName = counter.CategoryName; } try { PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, machineName); string[] instanceNames = category.GetInstanceNames(); PerformanceCounter[] counters = null; if (instanceNames.Length == 0) { counters = category.GetCounters(); } else { counters = category.GetCounters(instanceNames[0]); } string[] array = new string[counters.Length]; for (int i = 0; i < counters.Length; i++) { array[i] = counters[i].CounterName; } Array.Sort(array, Comparer.Default); return new TypeConverter.StandardValuesCollection(array); } catch (Exception) { } return null; }
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_; }
private void ListInstances(PerformanceCounterCategory category, string instanceName) { richTextBox1.Text += string.Format(" {0}", instanceName); PerformanceCounter[] counters = category.GetCounters(instanceName); foreach (PerformanceCounter counter in counters) { richTextBox1.Text += string.Format(" {0}", counter.CounterName); } richTextBox1.Text += string.Format("\n\nWorkingSet: {0}", (Environment.WorkingSet / (1024*10))); }
private void TrackContextSwitches() { PerformanceCounterCategory allThreadsWithPerformanceCounters = new PerformanceCounterCategory("Thread"); PerformanceCounter[] performanceCountersForThisThread = null; // Iterate over all "Thread" category performance counters on system (includes numerous processes) foreach (string threadName in allThreadsWithPerformanceCounters.GetInstanceNames()) { // Obtain those performance counters for the OrleansHost if (threadName.Contains("OrleansHost") && threadName.EndsWith("/" + Thread.CurrentThread.ManagedThreadId)) { performanceCountersForThisThread = allThreadsWithPerformanceCounters.GetCounters(threadName); break; } } // In the case that the performance was not obtained correctly (this condition is null), we simply will not have stats for context switches if (performanceCountersForThisThread == null) return; // Look at all performance counters for this thread foreach (PerformanceCounter performanceCounter in performanceCountersForThisThread) { // Find performance counter for context switches if (performanceCounter.CounterName == CONTEXT_SWTICH_COUNTER_NAME) { // Use raw value for logging, should show total context switches FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_CONTEXT_SWITCHES, Name), () => (float)performanceCounter.RawValue, CounterStorage.LogOnly); } } }
private void LoadPerformanceCounters() { var worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; // // Enumerates the counters on a background thread // worker.DoWork += (sender, e) => { try { object[] args = e.Argument as object[]; string categoryName = args[0] as string; string instanceName = args[1] as string; var category = new PerformanceCounterCategory(categoryName); var counters = (instanceName == "<unnamed>" ? category.GetCounters() : category.GetCounters(instanceName)); foreach (var item in counters.OrderBy(c => c.CounterName)) { worker.ReportProgress(0, new PerformanceCounterListItem() { Text = item.CounterName, Help = item.CounterHelp }); } } catch {} }; // // Adds counters to list // worker.ProgressChanged += (sender, e) => { counterList.Items.Add(e.UserState); }; // // Cleans up UI // worker.RunWorkerCompleted += (sender, e) => { Cursor = Cursors.Default; if (counterList.Items.Count > 0) counterList.SelectedIndex = 0; }; Cursor = Cursors.WaitCursor; counterList.Items.Clear(); worker.RunWorkerAsync(new object[] { categoryComboBox.SelectedItem, instanceComboBox.SelectedItem }); }
private List<PerformanceCounter> getCounterlist(string counterName) { if (!counters.ContainsKey(counterName)) { List<System.Diagnostics.PerformanceCounter> counterlist = new List<PerformanceCounter>(); var counterData = DefaultPerfCounterRegEx.split(counterName); try { PerformanceCounterCategory mycat = new PerformanceCounterCategory(counterData.Category); var foo = PerformanceCounterCategory.GetCategories(); var foolist = new List<string>(); foreach (var f in foo) { foolist.Add(f.CategoryName); } foolist.Sort(); switch (mycat.CategoryType) { case PerformanceCounterCategoryType.SingleInstance: foreach (var counter in mycat.GetCounters()) { if (!counter.CounterName.Equals(counterData.Counter, StringComparison.InvariantCultureIgnoreCase)) continue; counterlist.Add(counter); counter.NextValue(); // Initialize performance counters in order to avoid them to return 0. } break; case PerformanceCounterCategoryType.MultiInstance: if (counterData.Instance == null || counterData.Instance.Equals("*")) { foreach (var instance in mycat.GetInstanceNames()) { foreach (var counter in mycat.GetCounters(instance)) { if (!counter.CounterName.Equals(counterData.Counter, StringComparison.InvariantCultureIgnoreCase)) continue; counterlist.Add(counter); counter.NextValue(); // Initialize performance counters in order to avoid them to return 0. } } } else { foreach (var counter in mycat.GetCounters(counterData.Instance)) { if (!counter.CounterName.Equals(counterData.Counter, StringComparison.InvariantCultureIgnoreCase)) continue; counterlist.Add(counter); counter.NextValue(); // Initialize performance counters in order to avoid them to return 0. } } break; default: break; } } catch (Exception e) { Log.Error(String.Format("Counter {0} will be ignored due to errors: {1}", counterName, e)); Log.Error(e); } finally { counters.Add(counterName, counterlist); } } return counters[counterName]; }
private IEnumerable<PerformanceCounter> GetPerformanceCounters(string categoryName, string counterName, string instanceName) { var response = new List<PerformanceCounter>(); try { if ((counterName.Contains("*") || (instanceName != null && instanceName.Contains("*")))) { var cat = new PerformanceCounterCategory(categoryName); string[] instances; if (instanceName.Contains("*")) { instances = cat.GetInstanceNames().Where(x => Match(x, instanceName)).ToArray(); //TODO: If this response gives no instances, this means that this counter should use null, for instance if (!instances.Any()) { instances = new[] { (string)null }; } } else { instances = new[] { instanceName }; } var counterNames = new[] { counterName }; if (counterName.Contains("*")) { foreach (var instance in instances) { if (string.IsNullOrEmpty(instance)) counterNames = cat.GetCounters().Where(x => Match(x.CounterName, counterName)).Select(x => x.CounterName).ToArray(); else counterNames = cat.GetCounters(instance).Where(x => Match(x.CounterName, counterName)).Select(x => x.CounterName).ToArray(); } } foreach(var counter in counterNames) { foreach (var instance in instances) { var processorCounter = new PerformanceCounter(categoryName, counter, instance); processorCounter.NextValue(); response.Add(processorCounter); } } } else { var processorCounter = new PerformanceCounter(categoryName, counterName, instanceName); processorCounter.NextValue(); response.Add(processorCounter); } } catch (Exception exception) { OnGetPerformanceCounters(exception, categoryName, counterName, instanceName); } return response; }
/// <summary> /// Stops with the specified kill_TimeOut. /// </summary> /// <param name="Kill_TimeOut">The kill_ time out.</param> public void Stop(int Kill_TimeOut) { // Process object used to kill the children of the main process System.Diagnostics.Process process; try { // ########################################################################################### // Kills all the children processes... // The process loop found on Stackoverflow posted by Jeremy Murray // http://stackoverflow.com/questions/394816/how-to-get-parent-process-in-net-in-managed-way // Thanks to him, this saved a lots of time for the dev... // ########################################################################################## var processCounters = new SortedDictionary<string, PerformanceCounter[]>(); var category = new PerformanceCounterCategory("Process"); childPidToParentPid = new Dictionary<int,int>(); var instanceNames = category.GetInstanceNames(); foreach (string t in instanceNames) { try { processCounters[t] = category.GetCounters(t); } catch (InvalidOperationException) { // Transient processes may no longer exist between // GetInstanceNames and when the counters are queried. } } foreach (var kvp in processCounters) { int childPid = -1; int parentPid = -1; foreach (var counter in kvp.Value) { if ("ID Process".CompareTo(counter.CounterName) == 0) { childPid = (int)(counter.NextValue()); } else if ("Creating Process ID".CompareTo(counter.CounterName) == 0) { parentPid = (int)(counter.NextValue()); } } if (childPid != -1 && parentPid != -1) { childPidToParentPid[childPid] = parentPid; } } //list all the computed dictionnary to find the Parent ID and kill it arrayID = new ArrayList(); populate(P_Service.Id.ToString()); foreach (var item in arrayID) { try { LogWrite(String.Format("Service {2} , item with ID {0} has for parent or more {1} - going to kill this process", item.ToString(), P_Service.Id.ToString(), ShinkenSrvName)); process = System.Diagnostics.Process.GetProcessById(Int32.Parse(item.ToString())); process.Kill(); } catch (Exception ex) { LogWrite("Exception thrown during the kill of children processes, message : " + ex.Message); } } } catch (Exception ex) { LogWrite("Exception thrown during the ending of processes, message : " + ex.Message); } // ########################################################################################### // END of the kill of the subprocesses // ########################################################################################## try { // ###################################################################### P_Service.Kill(); bool killresult = P_Service.WaitForExit(Kill_TimeOut); if (P_Service.HasExited && this.running) { LogWrite(String.Format("Service {0} has exited !", this.ShinkenSrvName)); } else StopRunning(); if (this.GetOutput) { // Stopping the Asynchronous log system P_Service.OutputDataReceived -= new DataReceivedEventHandler(SrvOutputHandler); } if (P_Service != null) P_Service.Close(); } catch (Exception ex) { LogWrite("Exception thrown during stop method of the service object, message : "+ex.Message); } }
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; } } } }
/// <summary> /// Ensures the counter. /// </summary> /// <param name="category">The category.</param> /// <param name="counterName">Name of the counter.</param> /// <param name="type">The type.</param> /// <param name="perf">The perf.</param> /// <returns></returns> private static PerformanceCounter EnsureCounter(string category, string counterName, PerformanceCounterType type, IDictionary<string, PerformanceCounter> perf) { PerformanceCounter counter = null; string counterkey = category + "||" + counterName; if (_disabledCounters.Contains(counterkey)) { Trace.WriteLine(string.Format("The counter {0} in category {1} could not be accessed and therefore disabled", counterName, category), typeof(PerformanceCounterBaseAttribute).FullName); return null; } if (perf != null && perf.ContainsKey(counterName)) counter = perf[counterName]; else { cacheLock.EnterWriteLock(); try { Dictionary<string, PerformanceCounter> counterDict; var creation = new CounterCreationDataCollection(); var counterKeys = new List<string>(); if (PerformanceCounterCategory.Exists(category)) { var pc = new PerformanceCounterCategory(category); PerformanceCounter[] counters; if (pc.CategoryType == PerformanceCounterCategoryType.MultiInstance) { string[] instances = pc.GetInstanceNames(); if (instances.Length > 0) { foreach (string instance in instances) { counters = pc.GetCounters(instance); LoopCounterCollection(creation, counters, counterKeys); } } else { counters = pc.GetCounters(); LoopCounterCollection(creation, counters, counterKeys); } } else { counters = pc.GetCounters(); LoopCounterCollection(creation, counters, counterKeys); } if (perf != null) { foreach (PerformanceCounter p in perf.Values) { p.Dispose(); } perf.Clear(); perf = null; } //PerformanceCounterCategory.Delete(category); } else { CheckAndAddCounter(creation, counterKeys, counterName, type); if (type == PerformanceCounterType.AverageTimer32) creation.Add(new CounterCreationData(counterName + "Base", string.Empty, PerformanceCounterType.AverageBase)); PerformanceCounterCategory.Create(category, string.Empty, PerformanceCounterCategoryType.MultiInstance, creation); } counterDict = new Dictionary<string, PerformanceCounter>(creation.Count); foreach (CounterCreationData ccd in creation) { counter = new PerformanceCounter(category, ccd.CounterName, AppDomain.CurrentDomain.FriendlyName, false); counterDict.Add(ccd.CounterName, counter); } if (counterDict.TryGetValue(counterName, out counter)) { counter = counterDict[counterName]; perf = counterDict; if (categoryDict.ContainsKey(category)) categoryDict[category] = counterDict; else categoryDict.Add(category, counterDict); } else { Trace.WriteLine("Counter does not exists in group. Counter will be disabled", typeof(PerformanceCounterBaseAttribute).FullName); lock (_disabledCounters) { if (!_disabledCounters.Contains(counterkey)) _disabledCounters.Add(counterkey); } counter = null; } } catch (System.Security.SecurityException sex) { Trace.WriteLine("Failed to create counter -> counter will be deactivated!" + sex, typeof(PerformanceCounterBaseAttribute).FullName); lock (_disabledCounters) { if (!_disabledCounters.Contains(counterkey)) _disabledCounters.Add(counterkey); } counter = null; } finally { cacheLock.ExitWriteLock(); } } return counter; }
public DataTable EnumeratePerformanceCounters() { DataTable dt = new DataTable(); DataRow dr = null; // define the table's schema dt.Columns.Add(new DataColumn("PerfCategoryName", typeof(string))); dt.Columns.Add(new DataColumn("PerfCounterName", typeof(string))); dt.Columns.Add(new DataColumn("PerfInstanceName", typeof(string))); dt.Columns.Add(new DataColumn("PerfCategoryDesc", typeof(string))); PerformanceCounterCategory[] perfCounterCats = PerformanceCounterCategory.GetCategories(); PerformanceCounterCategory perfCounterCat = null; PerformanceCounter[] perfCounters = null; // PerformanceCounterCategoryType - MultiInstance, SingleInstance, Unknown string catName = string.Empty; string catDesc = string.Empty; string counterName = string.Empty; string[] instanceNames = null; for (int count = 0; count < perfCounterCats.Length; count++) { catName = perfCounterCats[count].CategoryName; catDesc = perfCounterCats[count].CategoryHelp; perfCounterCat = new PerformanceCounterCategory(catName); instanceNames = perfCounterCat.GetInstanceNames(); if (instanceNames.Length > 0) { foreach (string instanceName in instanceNames) { try { if (perfCounterCat.InstanceExists(instanceName)) { perfCounters = perfCounterCat.GetCounters(instanceName); foreach (PerformanceCounter perfCounter in perfCounters) { counterName = perfCounter.CounterName; dr = dt.NewRow(); dr[0] = catName; dr[1] = counterName; dr[2] = instanceName; dr[3] = catDesc; dt.Rows.Add(dr); } } } catch (Exception ex) { System.Diagnostics.Trace.Write(ex.Message + ex.StackTrace, TRACE_CATEGORY); } } } else { foreach (PerformanceCounter perfCounter in perfCounterCat.GetCounters()) { counterName = perfCounter.CounterName; dr = dt.NewRow(); dr[0] = catName; dr[1] = counterName; dr[2] = BCCUIHelper.Constants.SC303_INSTANCE_NOT_FOUND; dr[3] = catDesc; dt.Rows.Add(dr); } } } return dt; }
private void buildCounters() { // for each 'counter' Plugin... foreach (ConfigSection section in _config.Root().Sections("Plugin", "counter")) { // for each Counter definition section... foreach (ConfigSection counter in section.Sections("Counter")) { // the Counter must have a name, and a Category must be specified if (counter.Name().Length > 0 && !counter.Option("Category").IsEmpty()) { string szSystemCategory = counter.Option("Category").FirstValue(); _counterCategoryMap.Add(counter.Name(), szSystemCategory); // pull the current counter category PerformanceCounterCategory pcCategory = new PerformanceCounterCategory(szSystemCategory); // get all of its instances string[] pcInstances = pcCategory.GetInstanceNames(); if (pcInstances.Length > 0) { // for each instance in this category... foreach (string szInstance in pcInstances) { // if an exclude is specified, all but that instance should be shown if (!counter.Option("ExcludeInstance").IsEmpty() && counter.Option("ExcludeInstance").Values().Contains(szInstance)) continue; // if an include is specified, only those instances should be shown if (!counter.Option("Instance").IsEmpty() && !counter.Option("Instance").Values().Contains(szInstance)) continue; // get all counters PerformanceCounter[] pcCounters = pcCategory.GetCounters(szInstance); // for each counter... foreach (PerformanceCounter pcCounter in pcCounters) { // only add this counter if it was explicitly added in the config if (!counter.Option("CounterName").Values().Contains(pcCounter.CounterName)) continue; pcCounter.InstanceName = szInstance; _counters.Add(new Counter(counter.Name(), pcCounter)); } } } else { // get all counters PerformanceCounter[] pcCounters = pcCategory.GetCounters(); // for each counter... foreach (PerformanceCounter pcCounter in pcCounters) { // only add this counter if it was explicitly added in the config if (!counter.Option("CounterName").Values().Contains(pcCounter.CounterName)) continue; _counters.Add(new Counter(counter.Name(), pcCounter)); } } } } } }
private bool CheckCounterExists() { if (string.IsNullOrEmpty(this.CounterName)) { Log.LogError("CounterName is required"); return false; } if (!PerformanceCounterCategory.Exists(this.CategoryName, this.MachineName)) { this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "Performance Counter Category not found: {0}", this.CategoryName)); return false; } PerformanceCounterCategory cat = new PerformanceCounterCategory(this.CategoryName, this.MachineName); PerformanceCounter[] counters = cat.GetCounters(); return counters.Any(c => c.CounterName == this.CounterName); }
private static void EnumerateCounters() { var categories = PerformanceCounterCategory.GetCategories().Select(c => c.CategoryName).OrderBy(s => s).ToArray(); var sb = new StringBuilder(); foreach (var category in categories) { var counterCategory = new PerformanceCounterCategory(category); foreach (var counterInstance in counterCategory.GetInstanceNames()) { try { foreach (var counter in counterCategory.GetCounters(counterInstance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName)); } } catch { // Drop it on the floor } } } Console.WriteLine(sb.ToString()); }
/// <summary> /// Dumps all counters in the category /// </summary> private static void DumpAllInCategory(string currentInstance, PerformanceCounterCategory category, bool initializeOnly) { if (category.CategoryName.IndexOf("remoting", StringComparison.OrdinalIgnoreCase) != -1) // not interesting { return; } PerformanceCounter[] counters; try { counters = category.GetCounters(currentInstance); } catch (InvalidOperationException) { // This is a system-wide category, ignore those return; } if (!initializeOnly) { Console.WriteLine("\n{0}{1}{0}", new String('=', 41 - category.CategoryName.Length / 2), category.CategoryName); } foreach (PerformanceCounter counter in counters) { DumpCounter(counter, initializeOnly); } if (!initializeOnly) { Console.WriteLine("{0}{0}", new String('=', 41)); } }
/// <summary> /// The constructor. Initializes remote performance counters. /// </summary> /// <param name="machineName">The machine name.</param> /// <param name="performanceCounterInstanceName">The performance counter instance name.</param> public CustomPerformanceCounterManager(string machineName, string performanceCounterInstanceName) { // Sanitize if (string.IsNullOrWhiteSpace(machineName)) { throw new ArgumentException("cannot be null, empty, or white space", "machineName"); } if (string.IsNullOrWhiteSpace(performanceCounterInstanceName)) { throw new ArgumentException("cannot be null, empty, or white space", "performanceCounterInstanceName"); } // Special case - "localhost" must be "." instead if (string.Equals(machineName, "localhost", StringComparison.OrdinalIgnoreCase)) { machineName = "."; } var performanceCounterCategory = new PerformanceCounterCategory(_performanceCounterCategoryName, machineName); var performanceCounters = performanceCounterCategory.GetCounters(performanceCounterInstanceName); // Add the counters foreach (var performanceCounter in performanceCounters) { _performanceCounters.Add(performanceCounter.CounterName, performanceCounter); if (string.Equals(performanceCounter.CounterName, "Number of Cached Objects", StringComparison.OrdinalIgnoreCase)) { NumberOfCachedObjects = performanceCounter; } else if (string.Equals(performanceCounter.CounterName, "Total Requests per Second", StringComparison.OrdinalIgnoreCase)) { TotalRequestsPerSecond = performanceCounter; } else if (string.Equals(performanceCounter.CounterName, "Cache Memory Usage %", StringComparison.OrdinalIgnoreCase)) { CacheMemoryUsagePercent = performanceCounter; } else if (string.Equals(performanceCounter.CounterName, "Cache Memory Usage Base %", StringComparison.OrdinalIgnoreCase)) { CacheMemoryUsageBasePercent = performanceCounter; } else if (string.Equals(performanceCounter.CounterName, "Cache Memory Usage MB", StringComparison.OrdinalIgnoreCase)) { CacheMemoryUsageMb = performanceCounter; } else if (string.Equals(performanceCounter.CounterName, "Adds per Second", StringComparison.OrdinalIgnoreCase)) { AddsPerSecond = performanceCounter; } else if (string.Equals(performanceCounter.CounterName, "Gets per Second", StringComparison.OrdinalIgnoreCase)) { GetsPerSecond = performanceCounter; } else if (string.Equals(performanceCounter.CounterName, "Removes per Second", StringComparison.OrdinalIgnoreCase)) { RemovesPerSecond = performanceCounter; } } }
static void Main(string[] args) { try { while (true) { ServerManager objSvrMgr = new ServerManager(); ApplicationPoolCollection objAppPoolCollectn = objSvrMgr.ApplicationPools; WorkerProcessCollection objW3WPCollectn = objSvrMgr.WorkerProcesses; foreach (ApplicationPool appPool in objAppPoolCollectn) { System.IO.File.AppendAllText(System.Environment.CurrentDirectory + "\\Logs.txt", "\n" + DateTime.Now.AddMinutes(630).ToString("yyyy-MMM-dd HH:mm:ss") + " Name => " + appPool.Name + "; State => " + appPool.State); Console.WriteLine("Name => " + appPool.Name + "; State => " + appPool.State); if (appPool.State == ObjectState.Stopped) { appPool.Start(); } } PerformanceCounterCategory a = new PerformanceCounterCategory("Process"); var w3wpInstances = a.GetInstanceNames().Where(delegate(string s) { return s.Contains("w3wp"); }); foreach (string instanceName in w3wpInstances) //(Process process in Process.GetProcessesByName("w3wp")) { try { PerformanceCounter obj = new PerformanceCounter("Process", "% Processor Time", instanceName); var c = a.GetCounters(instanceName); float p = obj.NextValue(); Thread.Sleep(1000); p = obj.NextValue(); if (Convert.ToInt32(Math.Ceiling(p)) == 90) { lstDT.Add(DateTime.Now.AddMinutes(630)); if (lstDT.Count >= 10) { CheckErrorRate(); } } System.IO.File.AppendAllText(System.Environment.CurrentDirectory + "\\Logs.txt", "\n" + DateTime.Now.AddMinutes(630).ToString("yyyy-MMM-dd HH:mm:ss") + " Instance name = " + instanceName + "; CPU Usage = " + p.ToString()); Console.WriteLine("\nInstance name = " + instanceName + "; CPU Usage = " + p.ToString()); } catch (Exception ex) { System.IO.File.AppendAllText(System.Environment.CurrentDirectory + "\\Logs.txt", "\n" + DateTime.Now.AddMinutes(630).ToString("yyyy-MMM-dd HH:mm:ss") + " Instance name = " + instanceName + "; Message = " + ex.Message + "; Trace = " + ex.StackTrace); Console.WriteLine("\nInstance name = " + instanceName + ex.Message + "; " + ex.StackTrace); } } System.IO.File.AppendAllText(System.Environment.CurrentDirectory + "\\Logs.txt", "\n"); Thread.Sleep(60000); } } catch (Exception ex) { System.IO.File.AppendAllText(System.Environment.CurrentDirectory + "\\Logs.txt", "\n" + DateTime.Now.AddMinutes(630).ToString("yyyy-MMM-dd HH:mm:ss") + " Message = " + ex.Message + "; Trace = " + ex.StackTrace); Console.WriteLine("\nMessage = " + ex.Message + "; Trace = " + ex.StackTrace); } Console.ReadLine(); }
private void GetPerfCounters() { PerformanceCounterCategory[] arrCategories = PerformanceCounterCategory.GetCategories(); ArrayList arrItems = new ArrayList(); PerformanceCounterCategory Category = null; for (int i=0; i < arrCategories.Length;i++) { if ( (!arrCategories[i].CategoryName.ToLower().StartsWith("memory")) && (!arrCategories[i].CategoryName.ToLower().StartsWith(".net clr memory")) ) continue; arrItems.Add(arrCategories[i].CategoryName); } foreach (string item in arrItems) { Category = new PerformanceCounterCategory(item, Environment.MachineName); PerformanceCounterCategory pcInfo = new PerformanceCounterCategory(Category.CategoryName, Environment.MachineName); string [] Names = pcInfo.GetInstanceNames(); PerformanceCounter[] Counters = null; try { foreach (string name in Names) { if ( (name == null) || name == string.Empty ) continue; Counters = pcInfo.GetCounters(name); PerformanceCounter CounterInfo = null; foreach (System.Diagnostics.PerformanceCounter myCounter in Counters) { CounterInfo = new PerformanceCounter(Category.CategoryName, myCounter.CounterName); if (CounterInfo == null) continue; Console.WriteLine("-- " +Category.CategoryName + " - " + myCounter.CounterName + ": " + myCounter.RawValue.ToString() ); } } } catch (System.Exception ex ) { Console.WriteLine("*** ERROR: "+ ex.Message); } } }