/// <summary> /// Installs the specified performance <paramref name="counters" />. /// </summary> /// <param name="counters">A list of counters to install.</param> /// <exception cref="ArgumentNullException"><paramref name="counters" /> is <c>null</c>.</exception> public static void Install(this IEnumerable <PerformanceCounterSettings> counters) { if (counters == null) { throw new ArgumentNullException(nameof(counters)); } // Group counters by category var countersByCategories = ( from counter in counters group counter by counter.Category into countersByCategory select countersByCategory ).ToDictionary(c => c.Key); // For each counters by category foreach (var countersByCategory in countersByCategories) { // Get group category var category = countersByCategory.Key; // Check if category exists if (PerformanceCounterCategory.Exists(category)) { // Check if all counters exists within the category if (countersByCategory.Value.All(counter => PerformanceCounterCategory.CounterExists(counter.Name, counter.Category))) { continue; } // Some or all counters does not exists within the category // Delete category PerformanceCounterCategory.Delete(category); } // Create new counters collection var counterData = new CounterCreationDataCollection(); foreach (var counterCreationData in countersByCategory.Value.Select(counterConfig => new CounterCreationData(counterConfig.Name, String.Empty, counterConfig.CounterType))) { counterData.Add(counterCreationData); } // Create category with counters PerformanceCounterCategory.Create(category, String.Empty, PerformanceCounterCategoryType.SingleInstance, counterData); } }
PerformanceCounter GetCounter(string category, string counter, PerformanceCounterType type = PerformanceCounterType.AverageCount64, string machine = ".", string instance = "_Total") { if (!PerformanceCounterCategory.Exists(category)) { // create category var counterInfos = new CounterCreationDataCollection(); var counterInfo = new CounterCreationData() { CounterType = type, CounterName = counter, }; counterInfos.Add(counterInfo); PerformanceCounterCategory .Create(category, category, counterInfos); // check creation var counters = new PerformanceCounterCategory(category, machine); if (!counters.CounterExists(counter)) Debug.Fail("Counter was not created"); if (!counters.InstanceExists(instance)) Debug.Fail("Instance not found"); } // get counter var perfCounter = new PerformanceCounter { CategoryName = category, CounterName = counter, MachineName = machine, ReadOnly = false, }; perfCounter.IncrementBy(10); return perfCounter; }
public static long? SafelyGetPerformanceCounter(string categoryName, string counterName, string processName) { try { if (PerformanceCounterCategory.Exists(categoryName) == false) return null; var category = new PerformanceCounterCategory(categoryName); var instances = category.GetInstanceNames(); var ravenInstance = instances.FirstOrDefault(x => x == processName); if (ravenInstance == null || !category.CounterExists(counterName)) { return null; } using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true)) { return counter.NextSample().RawValue; } } catch (Exception e) { //Don't log anything here, it's up to the calling code to decide what to do return null; } }
public long GetDatabaseTransactionVersionSizeInBytes() { if (getDatabaseTransactionVersionSizeInBytesErrorValue != 0) return getDatabaseTransactionVersionSizeInBytesErrorValue; try { const string categoryName = "Database ==> Instances"; if (PerformanceCounterCategory.Exists(categoryName) == false) return getDatabaseTransactionVersionSizeInBytesErrorValue = -1; var category = new PerformanceCounterCategory(categoryName); var instances = category.GetInstanceNames(); var ravenInstance = instances.FirstOrDefault(x => x.Contains(uniquePrefix)); const string counterName = "Version Buckets Allocated"; if (ravenInstance == null || !category.CounterExists(counterName)) { return getDatabaseTransactionVersionSizeInBytesErrorValue = -2; } using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true)) { var value = counter.NextValue(); return (long)(value * StorageConfigurator.GetVersionPageSize()); } } catch (Exception e) { if (reportedGetDatabaseTransactionCacheSizeInBytesError == false) { reportedGetDatabaseTransactionCacheSizeInBytesError = true; log.WarnException("Failed to get Version Buckets Allocated value, this error will only be reported once.", e); } return getDatabaseTransactionVersionSizeInBytesErrorValue = -3; } }
/// <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); }
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); }
static void AssertCategoryIsCorrect(PerformanceCounterCategory category, string categoryName) { Assert.IsNotNull(category); Assert.AreEqual(categoryName, category.CategoryName); Assert.AreEqual(PerformanceCounterCategoryType.MultiInstance, category.CategoryType); Assert.IsTrue( category.CounterExists(PerformanceCounterCallHandler.NumberOfCallsCounterName)); Assert.IsTrue( category.CounterExists(PerformanceCounterCallHandler.CallsPerSecondCounterName)); Assert.IsTrue( category.CounterExists(PerformanceCounterCallHandler.AverageCallDurationCounterName)); Assert.IsTrue( category.CounterExists( PerformanceCounterCallHandler.AverageCallDurationBaseCounterName)); Assert.IsTrue( category.CounterExists(PerformanceCounterCallHandler.TotalExceptionsCounterName)); Assert.IsTrue( category.CounterExists(PerformanceCounterCallHandler.ExceptionsPerSecondCounterName)); }
private void InitializeCounters() { switch (this.sharedDataRef.Status) { case PerformanceCounterCategoryStatus.Uninitialized: try { foreach (KeyValuePair<string, PerformanceCounterCategoryData> pair in this.sharedDataRef.Categories) { if (!PerformanceCounterCategory.Exists(pair.Key)) { Trace.TraceInformation("Creating performance counters for category '{0}'.", pair.Key); PerformanceCounterCategory.Create(pair.Key, "", pair.Value.CategoryType, pair.Value.Counters); } else { PerformanceCounterCategory category = new PerformanceCounterCategory(pair.Key); bool invalid = category.CategoryType != pair.Value.CategoryType; foreach (CounterCreationData counterData in pair.Value.Counters) { if (!category.CounterExists(counterData.CounterName)) { invalid = true; break; } PerformanceCounter counter = CreatePerformanceCounter(pair.Key, counterData.CounterName, pair.Value.CategoryType, true); if (counter.CounterType != counterData.CounterType) { invalid = true; break; } } if (invalid) { Trace.TraceInformation("Recreating performance counters for category '{0}'.", pair.Key); PerformanceCounterCategory.Delete(pair.Key); PerformanceCounterCategory.Create(pair.Key, "", pair.Value.CategoryType, pair.Value.Counters); } } } } catch (Exception e) { Trace.TraceError("Cannot initialize performance counter {0}.{1}: {2}", this.CategoryName, this.CounterName, e.Message); this.sharedDataRef.Status = PerformanceCounterCategoryStatus.Failed; return; } this.sharedDataRef.Status = PerformanceCounterCategoryStatus.Initialized; break; case PerformanceCounterCategoryStatus.Failed: return; } }
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); }