diff --git a/src/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj b/src/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj
index 7bba32119263..99d0a09842b7 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj
+++ b/src/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj
@@ -168,7 +168,6 @@
-
diff --git a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterSampleCalculator.cs b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterSampleCalculator.cs
index e4a47a744893..6c7ad997818f 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterSampleCalculator.cs
+++ b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterSampleCalculator.cs
@@ -5,7 +5,6 @@
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
-using System.Security.Permissions;
using System.Globalization;
namespace System.Diagnostics
@@ -235,9 +234,8 @@ private static void LoadPerfCounterDll()
if (s_perfCounterDllLoaded)
return;
- new FileIOPermission(PermissionState.Unrestricted).Assert();
-
string installPath = SharedUtils.GetLatestBuildDllDirectory(".");
+
string perfcounterPath = Path.Combine(installPath, "perfcounter.dll");
if (Interop.Kernel32.LoadLibrary(perfcounterPath) == IntPtr.Zero)
{
diff --git a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs
index d1b784cfc350..1b148e6cde76 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs
+++ b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs
@@ -165,8 +165,6 @@ public string CounterHelp
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);
- permission.Demand();
Initialize();
if (_helpMsg == null)
@@ -212,9 +210,6 @@ public PerformanceCounterType CounterType
// This is the same thing that NextSample does, except that it doesn't try to get the actual counter
// value. If we wanted the counter value, we would need to have an instance name.
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);
- permission.Demand();
-
Initialize();
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName);
CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
@@ -369,8 +364,6 @@ public void Close()
///
public static void CloseSharedResources()
{
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, ".", "*");
- permission.Demand();
PerformanceCounterLib.CloseAllLibraries();
}
@@ -466,7 +459,6 @@ private void Initialize()
private void InitializeImpl()
{
bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(InstanceLockObject, ref tookLock);
@@ -483,10 +475,6 @@ private void InitializeImpl()
if (ReadOnly)
{
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);
-
- permission.Demand();
-
if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, _counterName))
throw new InvalidOperationException(SR.Format(SR.CounterExists, currentCategoryName, _counterName));
@@ -509,9 +497,6 @@ private void InitializeImpl()
}
else
{
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, currentMachineName, currentCategoryName);
- permission.Demand();
-
if (currentMachineName != "." && !string.Equals(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(SR.Format(SR.RemoteWriting));
@@ -556,9 +541,6 @@ public CounterSample NextSample()
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);
- permission.Demand();
-
Initialize();
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName);
CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
diff --git a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs
index 86b32217c26d..2b42d2ceb404 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs
+++ b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs
@@ -53,9 +53,6 @@ public PerformanceCounterCategory(string categoryName, string machineName)
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
- permission.Demand();
-
_categoryName = categoryName;
_machineName = machineName;
}
@@ -82,9 +79,6 @@ public string CategoryName
// checks depend on both pieces of info.
lock (this)
{
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, _machineName, value);
- permission.Demand();
-
_categoryName = value;
}
}
@@ -147,12 +141,6 @@ public string MachineName
// checks depend on both pieces of info.
lock (this)
{
- if (_categoryName != null)
- {
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, value, _categoryName);
- permission.Demand();
- }
-
_machineName = value;
}
}
@@ -197,9 +185,6 @@ public static bool CounterExists(string counterName, string categoryName, string
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
- permission.Demand();
-
return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName);
}
@@ -243,11 +228,7 @@ public static PerformanceCounterCategory Create(string categoryName, string cate
}
string machineName = ".";
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
- permission.Demand();
-
Mutex mutex = null;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutex(PerfMutexName, ref mutex);
@@ -401,13 +382,9 @@ public static void Delete(string categoryName)
CheckValidCategory(categoryName);
string machineName = ".";
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
- permission.Demand();
-
categoryName = categoryName.ToLower(CultureInfo.InvariantCulture);
Mutex mutex = null;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutex(PerfMutexName, ref mutex);
@@ -451,9 +428,6 @@ public static bool Exists(string categoryName, string machineName)
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
- permission.Demand();
-
if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
return true;
@@ -466,9 +440,6 @@ public static bool Exists(string categoryName, string machineName)
///
internal static string[] GetCounterInstances(string categoryName, string machineName)
{
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
- permission.Demand();
-
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);
if (categorySample._instanceNameTable.Count == 0)
return Array.Empty();
@@ -530,9 +501,6 @@ public static PerformanceCounterCategory[] GetCategories(string machineName)
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, "*");
- permission.Demand();
-
string[] categoryNames = PerformanceCounterLib.GetCategories(machineName);
PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryNames.Length];
for (int index = 0; index < categories.Length; index++)
diff --git a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs
index ec41fb9979bb..f9c6c51e6bcc 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs
+++ b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs
@@ -4,7 +4,6 @@
using System.Runtime.InteropServices;
using System.Globalization;
-using System.Security.Permissions;
using System.Security;
using System.Text;
using System.Threading;
@@ -210,19 +209,12 @@ private static string IniFilePath
{
if (s_iniFilePath == null)
{
- // Need to assert Environment permissions here
- // the environment check is not exposed as a public
- // method
- EnvironmentPermission environmentPermission = new EnvironmentPermission(PermissionState.Unrestricted);
- environmentPermission.Assert();
try
{
s_iniFilePath = Path.GetTempFileName();
}
finally
- {
- EnvironmentPermission.RevertAssert();
- }
+ { }
}
}
}
@@ -261,24 +253,14 @@ private static string SymbolFilePath
{
string tempPath;
- EnvironmentPermission environmentPermission = new EnvironmentPermission(PermissionState.Unrestricted);
- environmentPermission.Assert();
tempPath = Path.GetTempPath();
- EnvironmentPermission.RevertAssert();
- // We need both FileIOPermission EvironmentPermission
- PermissionSet ps = new PermissionSet(PermissionState.None);
- ps.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
- ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, tempPath));
- ps.Assert();
try
{
s_symbolFilePath = Path.GetTempFileName();
}
finally
- {
- PermissionSet.RevertAssert();
- }
+ { }
}
}
}
@@ -406,9 +388,6 @@ private bool CounterExists(string category, string counter, ref bool categoryExi
private static void CreateIniFile(string categoryName, string categoryHelp, CounterCreationDataCollection creationData, string[] languageIds)
{
- //SECREVIEW: PerformanceCounterPermission must have been demanded before
- FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
- permission.Assert();
try
{
StreamWriter iniWriter = new StreamWriter(IniFilePath, false, Encoding.Unicode);
@@ -501,9 +480,7 @@ private static void CreateIniFile(string categoryName, string categoryHelp, Coun
}
}
finally
- {
- FileIOPermission.RevertAssert();
- }
+ { }
}
private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered)
@@ -512,11 +489,6 @@ private static void CreateRegistryEntry(string categoryName, PerformanceCounterC
RegistryKey serviceKey = null;
RegistryKey linkageKey = null;
- //SECREVIEW: Whoever is able to call this function, must already
- // have demmanded PerformanceCounterPermission
- // we can therefore assert the RegistryPermission.
- RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
- registryPermission.Assert();
try
{
serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
@@ -565,16 +537,11 @@ private static void CreateRegistryEntry(string categoryName, PerformanceCounterC
if (serviceParentKey != null)
serviceParentKey.Close();
-
- RegistryPermission.RevertAssert();
}
}
private static void CreateSymbolFile(CounterCreationDataCollection creationData)
{
- //SECREVIEW: PerformanceCounterPermission must have been demanded before
- FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
- permission.Assert();
try
{
StreamWriter symbolWriter = new StreamWriter(SymbolFilePath);
@@ -604,20 +571,13 @@ private static void CreateSymbolFile(CounterCreationDataCollection creationData)
}
}
finally
- {
- FileIOPermission.RevertAssert();
- }
+ { }
}
private static void DeleteRegistryEntry(string categoryName)
{
RegistryKey serviceKey = null;
- //SECREVIEW: Whoever is able to call this function, must already
- // have demmanded PerformanceCounterPermission
- // we can therefore assert the RegistryPermission.
- RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
- registryPermission.Assert();
try
{
serviceKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
@@ -646,8 +606,6 @@ private static void DeleteRegistryEntry(string categoryName)
{
if (serviceKey != null)
serviceKey.Close();
-
- RegistryPermission.RevertAssert();
}
}
@@ -757,7 +715,6 @@ internal bool FindCustomCategory(string category, out PerformanceCounterCategory
key.Close();
if (baseKey != null)
baseKey.Close();
- PermissionSet.RevertAssert();
}
}
return false;
@@ -991,19 +948,10 @@ private string GetCounterHelp(string category, string counter, ref bool category
return help;
}
- internal string GetCounterName(int index)
- {
- if (NameTable.ContainsKey(index))
- return (string)NameTable[index];
-
- return "";
- }
-
private static string[] GetLanguageIds()
{
RegistryKey libraryParentKey = null;
string[] ids = Array.Empty();
- new RegistryPermission(PermissionState.Unrestricted).Assert();
try
{
libraryParentKey = Registry.LocalMachine.OpenSubKey(PerflibPath);
@@ -1015,8 +963,6 @@ private static string[] GetLanguageIds()
{
if (libraryParentKey != null)
libraryParentKey.Close();
-
- RegistryPermission.RevertAssert();
}
return ids;
@@ -1355,7 +1301,6 @@ internal byte[] GetData(string item)
int error = 0;
// no need to revert here since we'll fall off the end of the method
- new RegistryPermission(PermissionState.Unrestricted).Assert();
while (waitRetries > 0)
{
try
diff --git a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PrivilegedConfigurationManager.cs b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PrivilegedConfigurationManager.cs
index 63e04f244b54..8cad71ca6282 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PrivilegedConfigurationManager.cs
+++ b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PrivilegedConfigurationManager.cs
@@ -9,9 +9,7 @@ namespace System.Configuration {
using System.Collections.Specialized;
using System.Security;
- using System.Security.Permissions;
-
- [ConfigurationPermission(SecurityAction.Assert, Unrestricted=true)]
+
internal static class PrivilegedConfigurationManager {
internal static ConnectionStringSettingsCollection ConnectionStrings {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
diff --git a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs
index 54902ed3c38f..6d1e25a1a099 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs
+++ b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs
@@ -8,7 +8,6 @@
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Security.Permissions;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
@@ -533,7 +532,6 @@ private static unsafe void WaitAndEnterCriticalSection(int* spinLockPointer, out
// but of course that's only a probabilisitic statement.
// Must be able to assign to the out param.
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
@@ -637,8 +635,6 @@ private unsafe CategoryData GetCategoryData()
data.FileMappingName = DefaultFileMappingName;
data.MutexName = _categoryName;
- RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
- registryPermission.Assert();
RegistryKey categoryKey = null;
try
{
@@ -717,7 +713,6 @@ private unsafe CategoryData GetCategoryData()
{
if (categoryKey != null)
categoryKey.Close();
- RegistryPermission.RevertAssert();
}
}
}
@@ -760,7 +755,6 @@ private static void RemoveCategoryData(string categoryName)
Mutex mutex = null;
CounterEntry* counterPointer = null;
InstanceEntry* instancePointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
@@ -1068,7 +1062,6 @@ private unsafe bool FindInstance(int instanceNameHashCode, string instanceName,
if (activateUnusedInstances)
{
Mutex mutex = null;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
@@ -1211,7 +1204,6 @@ private unsafe void Verify(CategoryEntry* currentCategoryPointer)
return;
Mutex mutex = null;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
@@ -1409,7 +1401,6 @@ private unsafe void RemoveAllInstances()
InstanceEntry* instancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, s_instanceEntrySize));
Mutex mutex = null;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
@@ -1451,7 +1442,6 @@ internal unsafe void RemoveInstance(string instanceName, PerformanceCounterInsta
bool temp;
Mutex mutex = null;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
@@ -1516,7 +1506,6 @@ private unsafe void RemoveOneInstance(InstanceEntry* instancePointer, bool clear
{
bool sectionEntered = false;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (!_categoryData.UseUniqueSharedMemory)
diff --git a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedUtils.cs b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedUtils.cs
index 96d4622669c6..9ddb161e0413 100644
--- a/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedUtils.cs
+++ b/src/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedUtils.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Security.Permissions;
using System.Threading;
using System.Text;
using Microsoft.Win32;
@@ -113,7 +112,6 @@ private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex mutexOut)
{
bool ret;
- RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
finally
@@ -163,17 +161,6 @@ internal static string GetLatestBuildDllDirectory(string machineName)
RegistryKey baseKey = null;
RegistryKey complusReg = null;
- //This property is retrieved only when creationg a new category,
- // the calling code already demanded PerformanceCounterPermission.
- // Therefore the assert below is safe.
-
- //This property is retrieved only when creationg a new log,
- // the calling code already demanded EventLogPermission.
- // Therefore the assert below is safe.
-
- RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
- registryPermission.Assert();
-
try
{
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);
@@ -298,8 +285,6 @@ internal static string GetLatestBuildDllDirectory(string machineName)
if (baseKey != null)
baseKey.Close();
-
- RegistryPermission.RevertAssert();
}
return dllDir;
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/CounterCreationDataCollectionTests.cs b/src/System.Diagnostics.PerformanceCounter/tests/CounterCreationDataCollectionTests.cs
new file mode 100644
index 000000000000..a03c2a305219
--- /dev/null
+++ b/src/System.Diagnostics.PerformanceCounter/tests/CounterCreationDataCollectionTests.cs
@@ -0,0 +1,129 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Collections.Specialized;
+using Xunit;
+
+namespace System.Diagnostics.Tests
+{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
+ public static class CounterCreationDataCollectionTests
+ {
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_CreateCounterCreationDataCollection_Empty()
+ {
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection();
+ Assert.Equal(0, ccdc.Count);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_CreateCounterCreationDataCollection_CCDC()
+ {
+ CounterCreationData[] ccds = { new CounterCreationData("Simple1", "Simple Help", PerformanceCounterType.RawBase), new CounterCreationData("Simple2", "Simple Help", PerformanceCounterType.RawBase) };
+ CounterCreationDataCollection ccdc1 = new CounterCreationDataCollection(ccds);
+ CounterCreationDataCollection ccdc2 = new CounterCreationDataCollection(ccdc1);
+
+ Assert.Equal(2, ccdc2.Count);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_CreateCounterCreationDataCollection_Array()
+ {
+ CounterCreationData[] ccds = { new CounterCreationData("Simple1", "Simple Help", PerformanceCounterType.RawBase), new CounterCreationData("Simple2", "Simple Help", PerformanceCounterType.RawBase) };
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection(ccds);
+ Assert.Equal(2, ccdc.Count);
+ Assert.True(ccdc.Contains(ccds[0]));
+ Assert.Equal(0, ccdc.IndexOf(ccds[0]));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_CreateCounterCreationDataCollection_Invalid()
+ {
+ CounterCreationData[] ccds = null;
+ CounterCreationDataCollection ccdc = null;
+ Assert.Throws(() => new CounterCreationDataCollection(ccds));
+ Assert.Throws(() => new CounterCreationDataCollection(ccdc));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_SetIndex2()
+ {
+ CounterCreationData[] ccds = { new CounterCreationData("Simple1", "Simple Help", PerformanceCounterType.RawBase), new CounterCreationData("Simple2", "Simple Help", PerformanceCounterType.RawBase) };
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection(ccds);
+
+ CounterCreationData ccd = new CounterCreationData("Simple3", "Simple Help", PerformanceCounterType.RawBase);
+
+ ccdc[1] = ccd;
+
+ Assert.Equal(ccd, ccdc[1]);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_Remove()
+ {
+ CounterCreationData[] ccds = { new CounterCreationData("Simple1", "Simple Help", PerformanceCounterType.RawBase), new CounterCreationData("Simple2", "Simple Help", PerformanceCounterType.RawBase) };
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection(ccds);
+
+ ccdc.Remove(ccds[0]);
+ Assert.False(ccdc.Contains(ccds[0]));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_Insert()
+ {
+ CounterCreationData[] ccds = { new CounterCreationData("Simple1", "Simple Help", PerformanceCounterType.RawBase), new CounterCreationData("Simple2", "Simple Help", PerformanceCounterType.RawBase) };
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection(ccds);
+
+ CounterCreationData ccd = new CounterCreationData("Simple3", "Simple Help", PerformanceCounterType.RawBase);
+ ccdc.Insert(1, ccd);
+
+ Assert.True(ccdc.Contains(ccd));
+ Assert.Equal(1, ccdc.IndexOf(ccd));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationDataCollection_CopyTo()
+ {
+ CounterCreationData[] ccds = { new CounterCreationData("Simple1", "Simple Help", PerformanceCounterType.RawBase), new CounterCreationData("Simple2", "Simple Help", PerformanceCounterType.RawBase) };
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection(ccds);
+
+ CounterCreationData[] ccds2 = new CounterCreationData[2];
+
+ ccdc.CopyTo(ccds2, 0);
+
+ Assert.Equal(ccdc[0], ccds2[0]);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CreateCategory()
+ {
+ if (!PerformanceCounterCategory.Exists("AverageCounter64SampleCategory"))
+ {
+ CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();
+
+ // Add the counter.
+ CounterCreationData averageCount64 = new CounterCreationData();
+ averageCount64.CounterType = PerformanceCounterType.AverageCount64;
+ averageCount64.CounterName = "AverageCounter64Sample";
+ counterDataCollection.Add(averageCount64);
+
+ // Add the base counter.
+ CounterCreationData averageCount64Base = new CounterCreationData();
+ averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
+ averageCount64Base.CounterName = "AverageCounter64SampleBase";
+ counterDataCollection.Add(averageCount64Base);
+
+ // Create the category.
+ PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
+ "Demonstrates usage of the AverageCounter64 performance counter type.",
+ PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
+ }
+
+ Assert.True(PerformanceCounterCategory.Exists("AverageCounter64SampleCategory"));
+ PerformanceCounterCategory.Delete("AverageCounter64SampleCategory");
+ }
+ }
+}
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/CounterCreationDataTests.cs b/src/System.Diagnostics.PerformanceCounter/tests/CounterCreationDataTests.cs
new file mode 100644
index 000000000000..2531f6af19a1
--- /dev/null
+++ b/src/System.Diagnostics.PerformanceCounter/tests/CounterCreationDataTests.cs
@@ -0,0 +1,33 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using Xunit;
+
+namespace System.Diagnostics.Tests
+{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
+ public static class CounterCreationDataTests
+ {
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationData_CreateCounterCreationData_SimpleSimpleHelpRawBase()
+ {
+ CounterCreationData ccd = new CounterCreationData("Simple", "Simple Help", PerformanceCounterType.RawBase);
+
+ Assert.Equal("Simple", ccd.CounterName);
+ Assert.Equal("Simple Help", ccd.CounterHelp);
+ Assert.Equal(PerformanceCounterType.RawBase, ccd.CounterType);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterCreationData_SetCounterType_Invalud()
+ {
+ CounterCreationData ccd = new CounterCreationData("Simple", "Simple Help", PerformanceCounterType.RawBase);
+ Assert.Throws(() => ccd.CounterType = (PerformanceCounterType)Int32.MaxValue);
+ }
+ }
+}
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/CounterSampleCalculatorTests.cs b/src/System.Diagnostics.PerformanceCounter/tests/CounterSampleCalculatorTests.cs
new file mode 100644
index 000000000000..2f27b4530a4a
--- /dev/null
+++ b/src/System.Diagnostics.PerformanceCounter/tests/CounterSampleCalculatorTests.cs
@@ -0,0 +1,53 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Collections.Specialized;
+using Xunit;
+
+namespace System.Diagnostics.Tests
+{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
+ public static class CounterSampleCalculatorTests
+ {
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSampleCalculator_ElapsedTime()
+ {
+ var name = nameof(CounterSampleCalculator_ElapsedTime) + "_Counter";
+
+ PerformanceCounter counterSample = CreateCounter(name, PerformanceCounterType.ElapsedTime);
+
+ counterSample.RawValue = Stopwatch.GetTimestamp();
+ DateTime Start = DateTime.Now;
+ Helpers.RetryOnAllPlatforms(() => counterSample.NextValue());
+
+ System.Threading.Thread.Sleep(500);
+
+ var counterVal = Helpers.RetryOnAllPlatforms(() => counterSample.NextValue());
+ var dateTimeVal = DateTime.Now.Subtract(Start).TotalSeconds;
+ Helpers.DeleteCategory(name);
+ Assert.True(Math.Abs(dateTimeVal - counterVal) < .3);
+ }
+
+ public static PerformanceCounter CreateCounter(string name, PerformanceCounterType counterType)
+ {
+ var category = name + "_Category";
+ var instance = name + "_Instance";
+
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection();
+ CounterCreationData ccd = new CounterCreationData();
+ ccd.CounterType = counterType;
+ ccd.CounterName = name;
+ ccdc.Add(ccd);
+
+ Helpers.DeleteCategory(name);
+ PerformanceCounterCategory.Create(category, "description", PerformanceCounterCategoryType.SingleInstance, ccdc);
+
+ Assert.True(Helpers.PerformanceCounterCategoryCreated(category));
+
+ return new PerformanceCounter(category, name, false);
+ }
+ }
+}
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/CounterSampleTests.cs b/src/System.Diagnostics.PerformanceCounter/tests/CounterSampleTests.cs
new file mode 100644
index 000000000000..803e34822692
--- /dev/null
+++ b/src/System.Diagnostics.PerformanceCounter/tests/CounterSampleTests.cs
@@ -0,0 +1,97 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Collections.Specialized;
+using Xunit;
+
+namespace System.Diagnostics.Tests
+{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
+ public static class CounterSampleTests
+ {
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_Constructor_EmptyCounterSample()
+ {
+ CounterSample counterSample = new CounterSample();
+
+ Assert.Equal(0, counterSample.BaseValue);
+ Assert.Equal(0, counterSample.CounterFrequency);
+ Assert.Equal(PerformanceCounterType.NumberOfItemsHEX32, counterSample.CounterType);
+ Assert.Equal(0, counterSample.RawValue);
+ Assert.Equal(0, counterSample.SystemFrequency);
+ Assert.Equal(0, counterSample.TimeStamp);
+ Assert.Equal(0, counterSample.TimeStamp100nSec);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_Constructor_CounterSample()
+ {
+ long timeStamp = DateTime.Now.ToFileTime();
+ CounterSample counterSample = new CounterSample(1, 2, 3, 4, timeStamp, timeStamp, PerformanceCounterType.SampleFraction);
+
+ Assert.Equal(2, counterSample.BaseValue);
+ Assert.Equal(3, counterSample.CounterFrequency);
+ Assert.Equal(PerformanceCounterType.SampleFraction, counterSample.CounterType);
+ Assert.Equal(1, counterSample.RawValue);
+ Assert.Equal(4, counterSample.SystemFrequency);
+ Assert.Equal(timeStamp, counterSample.TimeStamp);
+ Assert.Equal(timeStamp, counterSample.TimeStamp100nSec);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_Calculate_CalculateCounterSample()
+ {
+ CounterSample counterSample = new CounterSample(5, 0, 0, 0, 0, 0, PerformanceCounterType.NumberOfItems32);
+
+ Assert.Equal(5, CounterSample.Calculate(counterSample));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_Calculate_CalculateCounterSampleCounterSample()
+ {
+ CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+ CounterSample counterSample2 = new CounterSample(15, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+
+ Assert.Equal(10, CounterSample.Calculate(counterSample1, counterSample2));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_Equal()
+ {
+ CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+ CounterSample counterSample2 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+
+ Assert.Equal(counterSample1, counterSample2);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_opInequality()
+ {
+ CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+ CounterSample counterSample2 = new CounterSample(15, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+
+ Assert.True(counterSample1 != counterSample2);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_opEquality()
+ {
+ CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+ CounterSample counterSample2 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+
+ Assert.True(counterSample1 == counterSample2);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void CounterSample_GetHashCode()
+ {
+ CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+ CounterSample counterSample2 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
+
+ Assert.Equal(counterSample1.GetHashCode(), counterSample2.GetHashCode());
+ }
+ }
+}
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/Helpers.cs b/src/System.Diagnostics.PerformanceCounter/tests/Helpers.cs
new file mode 100644
index 000000000000..ebb956727176
--- /dev/null
+++ b/src/System.Diagnostics.PerformanceCounter/tests/Helpers.cs
@@ -0,0 +1,75 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+using System.Threading;
+using Xunit;
+
+namespace System.Diagnostics.Tests
+{
+ internal class Helpers
+ {
+ public static bool IsElevatedAndCanWriteToPerfCounters { get => AdminHelpers.IsProcessElevated() && CanWriteToPerfCounters; }
+ public static bool CanWriteToPerfCounters { get => PlatformDetection.IsNotWindowsNanoServer; }
+
+ public static string CreateCategory(string name, PerformanceCounterCategoryType categoryType)
+ {
+ var category = name + "_Category";
+
+ // If the categry already exists, delete it, then create it.
+ DeleteCategory(name);
+ PerformanceCounterCategory.Create(category, "description", categoryType, name, "counter description");
+
+ Assert.True(PerformanceCounterCategoryCreated(category));
+ return category;
+ }
+
+ public static bool PerformanceCounterCategoryCreated(string category)
+ {
+ int tries = 0;
+ while (!PerformanceCounterCategory.Exists(category) && tries < 10)
+ {
+ System.Threading.Thread.Sleep(100);
+ tries++;
+ }
+
+ return PerformanceCounterCategory.Exists(category);
+ }
+
+ public static void DeleteCategory(string name)
+ {
+ var category = name + "_Category";
+ if (PerformanceCounterCategory.Exists(category))
+ {
+ PerformanceCounterCategory.Delete(category);
+ }
+ }
+
+ public static T RetryOnAllPlatforms(Func func)
+ {
+ T entry = default(T);
+ int retries = 20;
+ while (retries > 0)
+ {
+ try
+ {
+ entry = func();
+ retries = -1;
+ }
+ catch (InvalidOperationException)
+ {
+ Thread.Sleep(100);
+ retries--;
+ }
+ catch (ArgumentException)
+ {
+ Thread.Sleep(100);
+ retries--;
+ }
+ }
+
+ Assert.NotEqual(0, retries);
+ return entry;
+ }
+ }
+}
+
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/InstanceDataTests.cs b/src/System.Diagnostics.PerformanceCounter/tests/InstanceDataTests.cs
new file mode 100644
index 000000000000..3cc52fc32869
--- /dev/null
+++ b/src/System.Diagnostics.PerformanceCounter/tests/InstanceDataTests.cs
@@ -0,0 +1,139 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Collections.Specialized;
+using Xunit;
+
+namespace System.Diagnostics.Tests
+{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
+ public static class InstanceDataTests
+ {
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceData_CreateInstanceData_FromCounterSample()
+ {
+ long timestamp = DateTime.Now.ToFileTime();
+ CounterSample cs = new CounterSample(1, 2, 3, 4, timestamp, timestamp, PerformanceCounterType.SampleFraction);
+
+ InstanceData id = new InstanceData("foo", cs);
+ Assert.Equal(cs.RawValue, id.Sample.RawValue);
+ Assert.Equal(cs.CounterType, id.Sample.CounterType);
+ Assert.Equal(1, id.RawValue);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollection_GetItem_ExistingCounter()
+ {
+ InstanceDataCollection idc = GetInstanceDataCollection();
+
+ InstanceData[] ids = new InstanceData[idc.Count];
+ idc.CopyTo(ids, 0);
+
+ Assert.Equal("% User Time", idc.CounterName);
+
+ for (int i = 0; i < idc.Count; i++)
+ {
+ string instanceName = ids[i].InstanceName;
+ Assert.Equal(instanceName, idc[instanceName].InstanceName);
+ Assert.Equal(ids[i].RawValue, idc[instanceName].RawValue);
+ Assert.True(idc.Contains(instanceName));
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollection_NullTest()
+ {
+ InstanceDataCollection idc = GetInstanceDataCollection();
+
+ Assert.Throws(() => idc[null]);
+ Assert.Throws(() => idc.Contains(null));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollection_GetKeys()
+ {
+ InstanceDataCollection idc = GetInstanceDataCollection();
+
+ string[] keys = new string[idc.Count];
+ idc.Keys.CopyTo(keys, 0);
+
+ Assert.True(keys.Length > 0);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollection_GetValues()
+ {
+ InstanceDataCollection idc = GetInstanceDataCollection();
+
+ InstanceData[] values = new InstanceData[idc.Count];
+ idc.Values.CopyTo(values, 0);
+
+ Assert.True(values.Length > 0);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollectionCollection_GetItem_Invalid()
+ {
+ InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();
+
+ Assert.Throws(() => idcc[null]);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollectionCollection_GetKeys()
+ {
+ InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();
+
+ Assert.True(idcc.Keys.Count > 0);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollectionCollection_GetValues()
+ {
+ InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();
+
+ Assert.True(idcc.Values.Count > 0);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollectionCollection_Contains_Valid()
+ {
+ InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();
+
+ Assert.False(idcc.Contains("Not a real instance"));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollectionCollection_Contains_inValid()
+ {
+ InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();
+
+ Assert.Throws(() => idcc.Contains(null));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void InstanceDataCollectionCollection_CopyTo()
+ {
+ InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();
+
+ InstanceDataCollection[] idc = new InstanceDataCollection[idcc.Values.Count];
+ idcc.CopyTo(idc, 0);
+ Assert.True(idc.Length > 0);
+ }
+
+ public static InstanceDataCollectionCollection GetInstanceDataCollectionCollection()
+ {
+ PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor"));
+ return Helpers.RetryOnAllPlatforms(() => pcc.ReadCategory());
+ }
+
+ public static InstanceDataCollection GetInstanceDataCollection()
+ {
+ InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();
+ return idcc["% User Time"];
+ }
+ }
+}
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/PerformanceCounterCategoryTests.cs b/src/System.Diagnostics.PerformanceCounter/tests/PerformanceCounterCategoryTests.cs
new file mode 100644
index 000000000000..bc50fa079e39
--- /dev/null
+++ b/src/System.Diagnostics.PerformanceCounter/tests/PerformanceCounterCategoryTests.cs
@@ -0,0 +1,312 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Collections.Specialized;
+using Xunit;
+
+namespace System.Diagnostics.Tests
+{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
+ public static class PerformanceCounterCategoryTests
+ {
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CreatePerformanceCounterCategory_DefaultConstructor()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+ Assert.Equal(".", pcc.MachineName);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CreatePerformanceCounterCategory_NullTests()
+ {
+ Assert.Throws(() => new PerformanceCounterCategory(null, "."));
+ Assert.Throws(() => new PerformanceCounterCategory(string.Empty, "."));
+ Assert.Throws(() => new PerformanceCounterCategory("category", string.Empty));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_SetCategoryName_Valid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+ pcc.CategoryName = "Processor";
+ Assert.Equal("Processor", pcc.CategoryName);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_SetCategoryName_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.CategoryName = null);
+ Assert.Throws(() => pcc.CategoryName = string.Empty);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_SetMachineName_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.MachineName = string.Empty);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_SetMachineName_ValidCategoryNameNull()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ pcc.MachineName = "machineName";
+ Assert.Equal("machineName", pcc.MachineName);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_SetMachineName_ValidCategoryNameNotNull()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ pcc.CategoryName = "Processor";
+ pcc.MachineName = "machineName";
+ Assert.Equal("machineName", pcc.MachineName);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_GetCounterHelp_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.CategoryHelp);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CategoryType_MultiInstance()
+ {
+ var name = nameof(PerformanceCounterCategory_CategoryType_MultiInstance) + "_Counter";
+
+ var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance);
+
+ PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory(category));
+
+ Assert.Equal(PerformanceCounterCategoryType.MultiInstance, Helpers.RetryOnAllPlatforms(() => pcc.CategoryType));
+ PerformanceCounterCategory.Delete(category);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CategoryType_SingleInstance()
+ {
+ var name = nameof(PerformanceCounterCategory_CategoryType_SingleInstance) + "_Counter";
+
+ var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance);
+
+ PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory(category));
+
+ Assert.Equal(PerformanceCounterCategoryType.SingleInstance, Helpers.RetryOnAllPlatforms(() => pcc.CategoryType));
+ PerformanceCounterCategory.Delete(category);
+ }
+
+#pragma warning disable 0618 // obsolete warning
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_Create_Obsolete()
+ {
+ var name = nameof(PerformanceCounterCategory_Create_Obsolete) + "_Counter";
+ var category = name + "_Category";
+
+ Helpers.DeleteCategory(category);
+
+ PerformanceCounterCategory.Create(category, "category help", name, "counter help");
+
+ Assert.True(PerformanceCounterCategory.Exists(category));
+ PerformanceCounterCategory.Delete(category);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_Create_Obsolete_CCD()
+ {
+ var name = nameof(PerformanceCounterCategory_Create_Obsolete_CCD) + "_Counter";
+ var category = name + "_Category";
+
+ CounterCreationData ccd = new CounterCreationData(name, "counter help", PerformanceCounterType.NumberOfItems32);
+ CounterCreationDataCollection ccdc = new CounterCreationDataCollection();
+ ccdc.Add(ccd);
+
+ Helpers.DeleteCategory(category);
+
+ PerformanceCounterCategory.Create(category, "category help", ccdc);
+
+ Assert.True(PerformanceCounterCategory.Exists(category));
+ PerformanceCounterCategory.Delete(category);
+ }
+#pragma warning restore 0618
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_Create_Invalid()
+ {
+ Assert.Throws(() => PerformanceCounterCategory.Create(null, "Categoryhelp", PerformanceCounterCategoryType.SingleInstance, "counter name", "counter help"));
+ Assert.Throws(() => PerformanceCounterCategory.Create("category name", "Categoryhelp", PerformanceCounterCategoryType.SingleInstance, null, "counter help"));
+ Assert.Throws(() => PerformanceCounterCategory.Create("category name", "Category help", PerformanceCounterCategoryType.SingleInstance, null));
+ Assert.Throws(() => PerformanceCounterCategory.Create("Processor", "Category help", PerformanceCounterCategoryType.MultiInstance, "Interrupts/sec", "counter help"));
+
+ string maxCounter = new string('a', 32769);
+
+ Assert.Throws(() => PerformanceCounterCategory.Create("Category name", "Category help", PerformanceCounterCategoryType.SingleInstance, maxCounter, "counter help"));
+ Assert.Throws(() => PerformanceCounterCategory.Create(maxCounter, "Category help", PerformanceCounterCategoryType.SingleInstance, "Counter name", "counter help"));
+ Assert.Throws(() => PerformanceCounterCategory.Create("Category name", maxCounter, PerformanceCounterCategoryType.SingleInstance, "Counter name", "counter help"));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_GetCategories()
+ {
+ PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();
+
+ Assert.True(categories.Length > 0);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_GetCategories_StaticInvalid()
+ {
+ Assert.Throws(() => PerformanceCounterCategory.GetCategories(string.Empty));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CounterExists_InterruptsPerSec()
+ {
+ PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor"));
+
+ Assert.True(pcc.CounterExists("Interrupts/sec"));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CounterExists_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.CounterExists(null));
+ Assert.Throws(() => pcc.CounterExists("Interrupts/sec"));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CounterExists_StaticInterruptsPerSec()
+ {
+ Assert.True(PerformanceCounterCategory.CounterExists("Interrupts/sec", "Processor"));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_CounterExists_StaticInvalid()
+ {
+ Assert.Throws(() => PerformanceCounterCategory.CounterExists(null, "Processor"));
+ Assert.Throws(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", null));
+ Assert.Throws(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", string.Empty));
+ Assert.Throws(() => PerformanceCounterCategory.CounterExists("Interrupts/sec", "Processor", string.Empty));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_DeleteCategory_Invalid()
+ {
+ Assert.Throws(() => PerformanceCounterCategory.Delete("Processor"));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_DeleteCategory()
+ {
+ var name = nameof(PerformanceCounterCategory_DeleteCategory) + "_Counter";
+ var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance);
+
+ PerformanceCounterCategory.Delete(category);
+
+ Assert.False(PerformanceCounterCategory.Exists(category));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_Exists_Invalid()
+ {
+ Assert.Throws(() => PerformanceCounterCategory.Exists(null, "."));
+ Assert.Throws(() => PerformanceCounterCategory.Exists(string.Empty, "."));
+ Assert.Throws(() => PerformanceCounterCategory.Exists("Processor", string.Empty));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_GetCounters()
+ {
+ var name = nameof(PerformanceCounterCategory_GetCounters) + "_Counter";
+ var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance);
+
+ PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory(category));
+ PerformanceCounter[] counters = pcc.GetCounters();
+
+ Assert.True(counters.Length > 0);
+ PerformanceCounterCategory.Delete(category);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_GetCounters_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.GetCounters(null));
+ Assert.Throws(() => pcc.GetCounters(string.Empty));
+
+ pcc.CategoryName = "Processor";
+
+ Assert.Throws(() => pcc.GetCounters("Not An Instance"));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_GetInstanceNames_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.GetInstanceNames());
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_InstanceExists_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.InstanceExists(null));
+ Assert.Throws(() => pcc.InstanceExists(""));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_InstanceExists_Static()
+ {
+ PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor"));
+
+ string[] instances = pcc.GetInstanceNames();
+ Assert.True(instances.Length > 0);
+
+ foreach (string instance in instances)
+ {
+ Assert.True(PerformanceCounterCategory.InstanceExists(instance, "Processor"));
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_InstanceExists_StaticInvalid()
+ {
+ Assert.Throws(() => PerformanceCounterCategory.InstanceExists(null, "Processor", "."));
+ Assert.Throws(() => PerformanceCounterCategory.InstanceExists("", null, "."));
+ Assert.Throws(() => PerformanceCounterCategory.InstanceExists("", string.Empty, "."));
+ Assert.Throws(() => PerformanceCounterCategory.InstanceExists("", "Processor", string.Empty));
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_ReadCategory()
+ {
+ PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor"));
+
+ InstanceDataCollectionCollection idColCol = pcc.ReadCategory();
+
+ Assert.NotNull(idColCol);
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounterCategory_ReadCategory_Invalid()
+ {
+ PerformanceCounterCategory pcc = new PerformanceCounterCategory();
+
+ Assert.Throws(() => pcc.ReadCategory());
+ }
+ }
+}
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/PerformanceCounterTests.cs b/src/System.Diagnostics.PerformanceCounter/tests/PerformanceCounterTests.cs
index 1f7fcfc72f9f..00c8ac06e1bb 100644
--- a/src/System.Diagnostics.PerformanceCounter/tests/PerformanceCounterTests.cs
+++ b/src/System.Diagnostics.PerformanceCounter/tests/PerformanceCounterTests.cs
@@ -12,67 +12,289 @@ namespace System.Diagnostics.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters
public static class PerformanceCounterTests
{
- [ConditionalFact(typeof(AdminHelpers), nameof(AdminHelpers.IsProcessElevated))]
- public static void PerformanceCounterCategory_CreateCategory()
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_CreateCounter_EmptyCounter()
{
- if ( !PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") )
+ using (PerformanceCounter counterSample = new PerformanceCounter())
{
- CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();
+ Assert.Equal(".", counterSample.MachineName);
+ Assert.Equal(string.Empty, counterSample.CategoryName);
+ Assert.Equal(string.Empty, counterSample.CounterName);
+ Assert.Equal(string.Empty, counterSample.InstanceName);
+ Assert.True(counterSample.ReadOnly);
+ }
+ }
- // Add the counter.
- CounterCreationData averageCount64 = new CounterCreationData();
- averageCount64.CounterType = PerformanceCounterType.AverageCount64;
- averageCount64.CounterName = "AverageCounter64Sample";
- counterDataCollection.Add(averageCount64);
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_CreateCounter_Count0()
+ {
+ var name = nameof(PerformanceCounter_CreateCounter_Count0) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
+ {
+ counterSample.RawValue = 0;
- // Add the base counter.
- CounterCreationData averageCount64Base = new CounterCreationData();
- averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
- averageCount64Base.CounterName = "AverageCounter64SampleBase";
- counterDataCollection.Add(averageCount64Base);
+ Assert.Equal(0, counterSample.RawValue);
+ Helpers.DeleteCategory(name);
+ }
+ }
- // Create the category.
- PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
- "Demonstrates usage of the AverageCounter64 performance counter type.",
- PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_CreateCounter_ProcessorCounter()
+ {
+ using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
+ {
+ Assert.Equal(0, Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()));
+
+ Assert.True(counterSample.RawValue > 0);
}
+ }
- Assert.True(PerformanceCounterCategory.Exists("AverageCounter64SampleCategory"));
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_CreateCounter_MultiInstanceReadOnly()
+ {
+ var name = nameof(PerformanceCounter_CreateCounter_MultiInstanceReadOnly) + "_Counter";
+ var instance = name + "_Instance";
+
+ var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance);
+
+ using (PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name, instance)))
+ {
+ Assert.Equal(name, counterSample.CounterName);
+ Assert.Equal(category, counterSample.CategoryName);
+ Assert.Equal(instance, counterSample.InstanceName);
+ Assert.Equal("counter description", Helpers.RetryOnAllPlatforms(() => counterSample.CounterHelp));
+ Assert.True(counterSample.ReadOnly);
+ Helpers.DeleteCategory(name);
+ }
}
- [ConditionalFact(typeof(AdminHelpers), nameof(AdminHelpers.IsProcessElevated))]
- public static void PerformanceCounter_CreateCounter_Count0()
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_CreateCounter_SetReadOnly()
{
- var name = Guid.NewGuid().ToString("N") + "_Counter";
- var category = name + "_Category";
- if ( !PerformanceCounterCategory.Exists(category) )
+ var name = nameof(PerformanceCounter_CreateCounter_SetReadOnly) + "_Counter";
+
+ var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance);
+
+ using (PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name)))
{
- CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();
+ counterSample.ReadOnly = false;
- // Add the counter.
- CounterCreationData counter = new CounterCreationData();
- counter.CounterType = PerformanceCounterType.AverageCount64;
- counter.CounterName = name;
- counterDataCollection.Add(counter);
+ Assert.False(counterSample.ReadOnly);
+ }
+
+ Helpers.DeleteCategory(name);
+ }
- // Add the base counter.
- CounterCreationData counterBase = new CounterCreationData();
- counterBase.CounterType = PerformanceCounterType.AverageBase;
- counterBase.CounterName = name + "Base";
- counterDataCollection.Add(counterBase);
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_SetProperties_Null()
+ {
+ using (PerformanceCounter counterSample = new PerformanceCounter())
+ {
+ Assert.Throws(() => counterSample.CategoryName = null);
+ Assert.Throws(() => counterSample.CounterName = null);
+ Assert.Throws(() => counterSample.MachineName = null);
+ }
+ }
- // Create the category.
- PerformanceCounterCategory.Create(category,
- "description",
- PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_SetRawValue_ReadOnly()
+ {
+ using (PerformanceCounter counterSample = new PerformanceCounter())
+ {
+ Assert.Throws(() => counterSample.RawValue = 10);
}
+ }
- PerformanceCounter counterSample = new PerformanceCounter(category,
- name, false);
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_GetRawValue_EmptyCategoryName()
+ {
+ var name = nameof(PerformanceCounter_GetRawValue_EmptyCategoryName) + "_Counter";
+ using (PerformanceCounter counterSample = new PerformanceCounter())
+ {
+ counterSample.ReadOnly = false;
+ counterSample.CounterName = name;
+
+ Assert.Throws(() => counterSample.RawValue);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_GetRawValue_EmptyCounterName()
+ {
+ var name = nameof(PerformanceCounter_GetRawValue_EmptyCounterName) + "_Counter";
+ using (PerformanceCounter counterSample = new PerformanceCounter())
+ {
+ counterSample.ReadOnly = false;
+ counterSample.CategoryName = name + "_Category";
+
+ Assert.Throws(() => counterSample.RawValue);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_GetRawValue_CounterDoesNotExist()
+ {
+ var name = nameof(PerformanceCounter_GetRawValue_CounterDoesNotExist) + "_Counter";
+ using (PerformanceCounter counterSample = new PerformanceCounter())
+ {
+ counterSample.ReadOnly = false;
+ counterSample.CounterName = name;
+ counterSample.CategoryName = name + "_Category";
+
+ Assert.Throws(() => counterSample.RawValue);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_NextValue_ProcessorCounter()
+ {
+ using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
+ {
+ Helpers.RetryOnAllPlatforms(() => counterSample.NextValue());
+ System.Threading.Thread.Sleep(30);
+
+ Assert.True(Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()) > 0);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_BeginInit_ProcessorCounter()
+ {
+ using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
+ {
+ counterSample.BeginInit();
+
+ Assert.NotNull(counterSample);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_BeginInitEndInit_ProcessorCounter()
+ {
+ using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", "."))
+ {
+ counterSample.BeginInit();
+ counterSample.EndInit();
+
+ Assert.NotNull(counterSample);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_Decrement()
+ {
+ var name = nameof(PerformanceCounter_Decrement) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
+ {
+ counterSample.RawValue = 10;
+ Helpers.RetryOnAllPlatforms(() => counterSample.Decrement());
+
+ Assert.Equal(9, counterSample.RawValue);
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_Increment()
+ {
+ var name = nameof(PerformanceCounter_Increment) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
+ {
+ counterSample.RawValue = 10;
+ Helpers.RetryOnAllPlatforms(() => counterSample.Increment());
+
+ Assert.Equal(11, Helpers.RetryOnAllPlatforms(() => counterSample.NextSample().RawValue));
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_IncrementBy_IncrementBy2()
+ {
+ var name = nameof(PerformanceCounter_IncrementBy_IncrementBy2) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
+ {
+ counterSample.RawValue = 10;
+ Helpers.RetryOnAllPlatforms(() => counterSample.IncrementBy(2));
+
+ Assert.Equal(12, counterSample.RawValue);
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_IncrementBy_IncrementByReadOnly()
+ {
+ var name = nameof(PerformanceCounter_IncrementBy_IncrementByReadOnly) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance))
+ {
+ Assert.Throws(() => counterSample.IncrementBy(2));
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_Increment_IncrementReadOnly()
+ {
+ var name = nameof(PerformanceCounter_Increment_IncrementReadOnly) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance))
+ {
+ Assert.Throws(() => counterSample.Increment());
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_Decrement_DecrementReadOnly()
+ {
+ var name = nameof(PerformanceCounter_Decrement_DecrementReadOnly) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance))
+ {
+ Assert.Throws(() => counterSample.Decrement());
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_RemoveInstance()
+ {
+ var name = nameof(PerformanceCounter_RemoveInstance) + "_Counter";
+ using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance))
+ {
+ counterSample.RawValue = 100;
+ counterSample.RemoveInstance();
+ counterSample.Close();
+
+ Assert.NotNull(counterSample);
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
+ public static void PerformanceCounter_NextSample_MultiInstance()
+ {
+ var name = nameof(PerformanceCounter_NextSample_MultiInstance) + "_Counter";
+ var instance = name + "_Instance";
+
+ var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance);
+
+ using (PerformanceCounter counterSample = new PerformanceCounter(category, name, instance, false))
+ {
+ counterSample.RawValue = 10;
+ Helpers.RetryOnAllPlatforms(() => counterSample.Decrement());
+
+ Assert.Equal(9, counterSample.RawValue);
+ Helpers.DeleteCategory(name);
+ }
+ }
+
+ public static PerformanceCounter CreateCounterWithCategory(string name, bool readOnly, PerformanceCounterCategoryType categoryType )
+ {
+ var category = Helpers.CreateCategory(name, categoryType);
- counterSample.RawValue = 0;
+ PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name, readOnly));
- Assert.Equal(0, counterSample.RawValue);
+ return counterSample;
}
}
}
diff --git a/src/System.Diagnostics.PerformanceCounter/tests/System.Diagnostics.PerformanceCounter.Tests.csproj b/src/System.Diagnostics.PerformanceCounter/tests/System.Diagnostics.PerformanceCounter.Tests.csproj
index dcdb5ef17c9c..b070f8fe783d 100644
--- a/src/System.Diagnostics.PerformanceCounter/tests/System.Diagnostics.PerformanceCounter.Tests.csproj
+++ b/src/System.Diagnostics.PerformanceCounter/tests/System.Diagnostics.PerformanceCounter.Tests.csproj
@@ -10,6 +10,13 @@
+
+
+
+
+
+
+
Common\System\ShouldNotBeInvokedException.cs