internal const string NCrypt = "ncrypt.dll";
internal const string NtDll = "ntdll.dll";
internal const string OleAut32 = "oleaut32.dll";
+ internal const string PerfCounter = "perfcounter.dll";
internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll";
internal const string Secur32 = "secur32.dll";
internal const string Shell32 = "shell32.dll";
internal const string WinHttp = "winhttp.dll";
internal const string Ws2_32 = "ws2_32.dll";
internal const string Zlib = "clrcompression.dll";
- internal const string PerfCounter = "perfcounter.dll";
}
}
--- /dev/null
+// 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 Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Advapi32
+ {
+ [DllImport(Interop.Libraries.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true, BestFitMapping=false)]
+ internal static extern unsafe bool ConvertStringSecurityDescriptorToSecurityDescriptor(string StringSecurityDescriptor, int StringSDRevision, out SafeLocalMemHandle pSecurityDescriptor, IntPtr SecurityDescriptorSize);
+ }
+}
SafeLocalAllocHandle TokenInformation,
uint TokenInformationLength,
out uint ReturnLength);
+
+ [DllImport(Interop.Libraries.Advapi32, CharSet=CharSet.Auto, SetLastError=true)]
+ internal static extern bool GetTokenInformation (
+ IntPtr TokenHandle,
+ uint TokenInformationClass,
+ IntPtr TokenInformation,
+ uint TokenInformationLength,
+ out uint ReturnLength);
}
}
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
+using System;
+using System.Text;
internal partial class Interop
{
[DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, EntryPoint = "GetComputerNameW")]
private static extern unsafe int GetComputerName(char* lpBuffer, ref uint nSize);
+ [DllImport(Libraries.Kernel32, CharSet=CharSet.Auto, BestFitMapping=false)]
+ public static extern bool GetComputerName(StringBuilder lpBuffer, int[] nSize);
+
// maximum length of the NETBIOS name (not including NULL)
private const int MAX_COMPUTERNAME_LENGTH = 15;
--- /dev/null
+// 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.Runtime.InteropServices;
+
+using Microsoft.Win32.SafeHandles;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
+ public static extern IntPtr LoadLibrary(string libFilename);
+ }
+}
+
--- /dev/null
+// 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.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ // P/Invoke for the methods above. Don't call this from anywhere else.
+ [DllImport(Libraries.Kernel32, ExactSpelling=true, SetLastError=true, EntryPoint="WaitForSingleObject")]
+ internal static extern int WaitForSingleObjectDontCallThis(SafeWaitHandle handle, int timeout);
+ }
+}
--- /dev/null
+// 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.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class PerfCounters
+ {
+#pragma warning disable BCL0015 // Invalid Pinvoke call
+ [DllImport(Libraries.PerfCounter, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
+ public static unsafe extern int FormatFromRawValue(
+ uint dwCounterType,
+ uint dwFormat,
+ ref long pTimeBase,
+ Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER pRawValue1,
+ Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER pRawValue2,
+ Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE pFmtValue
+ );
+#pragma warning restore BCL0015
+ }
+}
SetHandle(existingHandle);
}
-
- [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true, BestFitMapping=false)]
- internal static extern unsafe bool ConvertStringSecurityDescriptorToSecurityDescriptor(string StringSecurityDescriptor, int StringSDRevision, out SafeLocalMemHandle pSecurityDescriptor, IntPtr SecurityDescriptorSize);
-
- [DllImport(ExternDll.Kernel32)]
- private static extern IntPtr LocalFree(IntPtr hMem);
-
override protected bool ReleaseHandle()
{
- return LocalFree(handle) == IntPtr.Zero;
+ return Interop.Kernel32.LocalFree(handle) == IntPtr.Zero;
}
-
}
}
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
-VisualStudioVersion = 15.0.26228.9
+VisualStudioVersion = 15.0.26923.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Diagnostics.PerformanceCounter", "ref\System.Diagnostics.PerformanceCounter.csproj", "{5BDC8641-E3EE-47B5-BE7B-2D2275402412}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Diagnostics.PerformanceCounter", "src\System.Diagnostics.PerformanceCounter.csproj", "{E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Diagnostics.PerformanceCounter", "src\System.Diagnostics.PerformanceCounter.csproj", "{F55047F8-E47B-46E3-B221-C23595AFE168}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
{5BDC8641-E3EE-47B5-BE7B-2D2275402412}.uap-Windows_NT-Debug|Any CPU.Build.0 = netcoreapp-Release|Any CPU
{5BDC8641-E3EE-47B5-BE7B-2D2275402412}.uap-Windows_NT-Release|Any CPU.ActiveCfg = netcoreapp-Release|Any CPU
{5BDC8641-E3EE-47B5-BE7B-2D2275402412}.uap-Windows_NT-Release|Any CPU.Build.0 = netcoreapp-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.Debug|Any CPU.ActiveCfg = uapaot-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.Debug|Any CPU.Build.0 = uapaot-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Unix-Debug|Any CPU.ActiveCfg = netcoreapp-Unix-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Unix-Debug|Any CPU.Build.0 = netcoreapp-Unix-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Unix-Release|Any CPU.ActiveCfg = netcoreapp-Unix-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Unix-Release|Any CPU.Build.0 = netcoreapp-Unix-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Windows_NT-Debug|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Windows_NT-Debug|Any CPU.Build.0 = netcoreapp-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Windows_NT-Release|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.netcoreapp-Windows_NT-Release|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.Release|Any CPU.ActiveCfg = uapaot-Windows_NT-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.Release|Any CPU.Build.0 = uapaot-Windows_NT-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uapaot-Windows_NT-Debug|Any CPU.ActiveCfg = uapaot-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uapaot-Windows_NT-Debug|Any CPU.Build.0 = uapaot-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uapaot-Windows_NT-Release|Any CPU.ActiveCfg = uapaot-Windows_NT-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uapaot-Windows_NT-Release|Any CPU.Build.0 = uapaot-Windows_NT-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uap-Windows_NT-Debug|Any CPU.ActiveCfg = uap-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uap-Windows_NT-Debug|Any CPU.Build.0 = uap-Windows_NT-Debug|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uap-Windows_NT-Release|Any CPU.ActiveCfg = uap-Windows_NT-Release|Any CPU
- {E7E8DE8A-9EC1-46A8-A6EE-727DB32DBEB8}.uap-Windows_NT-Release|Any CPU.Build.0 = uap-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.Debug|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Debug|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.Debug|Any CPU.Build.0 = netcoreapp-Windows_NT-Debug|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Unix-Debug|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Unix-Debug|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Unix-Release|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Unix-Release|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Windows_NT-Debug|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Debug|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Windows_NT-Debug|Any CPU.Build.0 = netcoreapp-Windows_NT-Debug|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Windows_NT-Release|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.netcoreapp-Windows_NT-Release|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.Release|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.Release|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uapaot-Windows_NT-Debug|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uapaot-Windows_NT-Debug|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uapaot-Windows_NT-Release|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uapaot-Windows_NT-Release|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uap-Windows_NT-Debug|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uap-Windows_NT-Debug|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uap-Windows_NT-Release|Any CPU.ActiveCfg = netcoreapp-Windows_NT-Release|Any CPU
+ {F55047F8-E47B-46E3-B221-C23595AFE168}.uap-Windows_NT-Release|Any CPU.Build.0 = netcoreapp-Windows_NT-Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
GlobalSection(NestedProjects) = preSolution
{5BDC8641-E3EE-47B5-BE7B-2D2275402412} = {2E666815-2EDB-464B-9DF6-380BF4789AD4}
EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {29572587-9F67-4F7B-9234-68BC2E1C28B1}
+ EndGlobalSection
EndGlobal
<PropertyGroup>
<BuildConfigurations>
netcoreapp-Windows_NT;
+ netstandard;
+ netfx;
</BuildConfigurations>
</PropertyGroup>
</Project>
+++ /dev/null
-// 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.Runtime.InteropServices;
-using System.Runtime.Versioning;
-using System;
-using System.Text;
-using System.Runtime;
-using System.Security;
-using System.Threading;
-
-namespace System.Diagnostics
-{
- internal partial class SafeNativeMethods
- {
- // file src\Services\Monitoring\system\Diagnosticts\SafeNativeMethods.cs
- [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
- public static extern IntPtr LoadLibrary(string libFilename);
-
- [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
- public static extern bool FreeLibrary(HandleRef hModule);
-
- [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto, BestFitMapping=false)]
- public static extern bool GetComputerName(StringBuilder lpBuffer, int[] nSize);
-
- public static unsafe int InterlockedCompareExchange(IntPtr pDestination, int exchange, int compare)
- {
- return Interlocked.CompareExchange(ref *(int *)pDestination.ToPointer(), exchange, compare);
- }
-
-#pragma warning disable BCL0015 // Invalid Pinvoke call
- [DllImport(ExternDll.PerfCounter, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
- public static unsafe extern int FormatFromRawValue(
- uint dwCounterType,
- uint dwFormat,
- ref long pTimeBase,
- Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER pRawValue1,
- Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER pRawValue2,
- Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE pFmtValue
- );
- }
-}
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
- <data name="NoAssociatedProcess" xml:space="preserve">
- <value>No process is associated with this object.</value>
- </data>
- <data name="ProcessIdRequired" xml:space="preserve">
- <value>Feature requires a process identifier.</value>
- </data>
- <data name="NotSupportedRemote" xml:space="preserve">
- <value>Feature is not supported for remote machines.</value>
- </data>
- <data name="NoProcessInfo" xml:space="preserve">
- <value>Process has exited, so the requested information is not available.</value>
- </data>
- <data name="WaitTillExit" xml:space="preserve">
- <value>Process must exit before requested information can be determined.</value>
- </data>
- <data name="NoProcessHandle" xml:space="preserve">
- <value>Process was not started by this object, so requested information cannot be determined.</value>
- </data>
- <data name="MissingProccess" xml:space="preserve">
- <value>Process with an Id of {0} is not running.</value>
- </data>
- <data name="BadMinWorkset" xml:space="preserve">
- <value>Minimum working set size is invalid. It must be less than or equal to the maximum working set size.</value>
- </data>
- <data name="BadMaxWorkset" xml:space="preserve">
- <value>Maximum working set size is invalid. It must be greater than or equal to the minimum working set size.</value>
- </data>
- <data name="ProcessHasExited" xml:space="preserve">
- <value>Cannot process request because the process ({0}) has exited.</value>
- </data>
- <data name="ProcessHasExitedNoId" xml:space="preserve">
- <value>Cannot process request because the process has exited.</value>
- </data>
- <data name="ThreadExited" xml:space="preserve">
- <value>The request cannot be processed because the thread ({0}) has exited.</value>
- </data>
- <data name="CantGetProcessId" xml:space="preserve">
- <value>Cannot retrieve process identifier from the process handle.</value>
- </data>
- <data name="ProcessDisabled" xml:space="preserve">
- <value>Process performance counter is disabled, so the requested operation cannot be performed.</value>
- </data>
- <data name="WaitReasonUnavailable" xml:space="preserve">
- <value>WaitReason is only available if the ThreadState is Wait.</value>
- </data>
- <data name="NotSupportedRemoteThread" xml:space="preserve">
- <value>Feature is not supported for threads on remote computers.</value>
- </data>
- <data name="CouldntConnectToRemoteMachine" xml:space="preserve">
- <value>Couldn't connect to remote machine.</value>
- </data>
- <data name="CouldntGetProcessInfos" xml:space="preserve">
- <value>Couldn't get process information from performance counter.</value>
- </data>
- <data name="InputIdleUnkownError" xml:space="preserve">
- <value>WaitForInputIdle failed. This could be because the process does not have a graphical interface.</value>
- </data>
- <data name="FileNameMissing" xml:space="preserve">
- <value>Cannot start process because a file name has not been provided.</value>
- </data>
- <data name="EnumProcessModuleFailed" xml:space="preserve">
- <value>Unable to enumerate the process modules.</value>
- </data>
- <data name="EnumProcessModuleFailedDueToWow" xml:space="preserve">
- <value>A 32 bit processes cannot access modules of a 64 bit process.</value>
- </data>
- <data name="NoAsyncOperation" xml:space="preserve">
- <value>No async read operation is in progress on the stream.</value>
- </data>
- <data name="InvalidApplication" xml:space="preserve">
- <value>The specified executable is not a valid application for this OS platform.</value>
- </data>
- <data name="StandardOutputEncodingNotAllowed" xml:space="preserve">
- <value>StandardOutputEncoding is only supported when standard output is redirected.</value>
- </data>
- <data name="StandardErrorEncodingNotAllowed" xml:space="preserve">
- <value>StandardErrorEncoding is only supported when standard error is redirected.</value>
- </data>
- <data name="CantGetStandardOut" xml:space="preserve">
- <value>StandardOut has not been redirected or the process hasn't started yet.</value>
- </data>
- <data name="CantGetStandardIn" xml:space="preserve">
- <value>StandardIn has not been redirected.</value>
- </data>
- <data name="CantGetStandardError" xml:space="preserve">
- <value>StandardError has not been redirected.</value>
- </data>
- <data name="CantMixSyncAsyncOperation" xml:space="preserve">
- <value>Cannot mix synchronous and asynchronous operation on process stream.</value>
- </data>
- <data name="CantRedirectStreams" xml:space="preserve">
- <value>The Process object must have the UseShellExecute property set to false in order to redirect IO streams.</value>
- </data>
- <data name="DirectoryNotValidAsInput" xml:space="preserve">
- <value>The FileName property should not be a directory unless UseShellExecute is set.</value>
- </data>
- <data name="PendingAsyncOperation" xml:space="preserve">
- <value>An async read operation has already been started on the stream.</value>
- </data>
<data name="InvalidParameter" xml:space="preserve">
<value>Invalid value '{1}' for parameter '{0}'.</value>
</data>
<data name="CounterDataCorrupt" xml:space="preserve">
<value>Cannot load Performance Counter data because an unexpected registry key value type was read from '{0}'.</value>
</data>
- <data name="CantGetProcessStartInfo" xml:space="preserve">
- <value>Process was not started by this object, so requested information cannot be determined.</value>
- </data>
- <data name="CantSetProcessStartInfo" xml:space="preserve">
- <value>Process is already associated with a real process, so the requested operation cannot be performed.</value>
- </data>
- <data name="CantGetAllPids" xml:space="preserve">
- <value>Could not get all running Process IDs.</value>
- </data>
- <data name="NegativePidNotSupported" xml:space="preserve">
- <value>Process IDs cannot be negative.</value>
- </data>
- <data name="ProcessorAffinityNotSupported" xml:space="preserve">
- <value>Processor affinity for processes or threads is not supported on this platform.</value>
- </data>
- <data name="ProcessStartIdentityNotSupported" xml:space="preserve">
- <value>Starting a process with a different identity is not supported on this platform.</value>
- </data>
- <data name="RUsageFailure" xml:space="preserve">
- <value>Failed to set or retrieve rusage information. See the error code for OS-specific error information.</value>
- </data>
- <data name="MinimumWorkingSetNotSupported" xml:space="preserve">
- <value>Setting the minimum working set is not supported on this platform.</value>
- </data>
- <data name="OsxExternalProcessWorkingSetNotSupported" xml:space="preserve">
- <value>Getting or setting the working set limits on other processes is not supported on this platform.</value>
- </data>
- <data name="ThreadPriorityNotSupported" xml:space="preserve">
- <value>Getting or setting the thread priority is not supported on this platform.</value>
- </data>
- <data name="ProcessInformationUnavailable" xml:space="preserve">
- <value>Unable to retrieve the specified information about the process or thread. It may have exited or may be privileged.</value>
- </data>
- <data name="RemoteMachinesNotSupported" xml:space="preserve">
- <value>Access to processes on remote machines is not supported on this platform.</value>
- </data>
- <data name="CantSetDuplicatePassword" xml:space="preserve">
- <value>ProcessStartInfo.Password and ProcessStartInfo.PasswordInClearText cannot both be set. Use only one of them.</value>
- </data>
- <data name="ArgumentNull_Array" xml:space="preserve">
- <value>Array cannot be null.</value>
- </data>
- <data name="ArgumentOutOfRange_IndexCountBuffer" xml:space="preserve">
- <value>Index and count must refer to a location within the buffer.</value>
- </data>
- <data name="ArgumentOutOfRange_IndexCount" xml:space="preserve">
- <value>Index and count must refer to a location within the string.</value>
- </data>
- <data name="ArgumentOutOfRange_Index" xml:space="preserve">
- <value>Index was out of range. Must be non-negative and less than the size of the collection.</value>
- </data>
- <data name="Argument_EncodingConversionOverflowBytes" xml:space="preserve">
- <value>The output byte buffer is too small to contain the encoded data, encoding '{0}' fallback '{1}'.</value>
- </data>
- <data name="Argument_EncodingConversionOverflowChars" xml:space="preserve">
- <value>The output char buffer is too small to contain the decoded characters, encoding '{0}' fallback '{1}'.</value>
- </data>
- <data name="ArgumentOutOfRange_GetByteCountOverflow" xml:space="preserve">
- <value>Too many characters. The resulting number of bytes is larger than what can be returned as an int.</value>
- </data>
- <data name="ArgumentOutOfRange_GetCharCountOverflow" xml:space="preserve">
- <value>Too many bytes. The resulting number of chars is larger than what can be returned as an int.</value>
- </data>
- <data name="Argument_InvalidCharSequenceNoIndex" xml:space="preserve">
- <value>String contains invalid Unicode code points.</value>
- </data>
- <data name="ArgumentOutOfRange_NeedNonNegNum" xml:space="preserve">
- <value>Non-negative number required.</value>
- </data>
- <data name="CantStartAsUser" xml:space="preserve">
- <value>The Process object must have the UseShellExecute property set to false in order to start a process as a user.</value>
- </data>
- <data name="CantUseEnvVars" xml:space="preserve">
- <value>The Process object must have the UseShellExecute property set to false in order to use environment variables.</value>
- </data>
- <data name="UseShellExecuteNotSupported" xml:space="preserve">
- <value>UseShellExecute is not supported on this platform.</value>
- </data>
- <data name="GetProcessInfoNotSupported" xml:space="preserve">
- <value>Retrieving information about local processes is not supported on this platform.</value>
- </data>
<data name="InstanceNameTooLong" xml:space="preserve">
<value>Instance names used for writing to custom counters must be 127 characters or less.</value>
</data>
<data name="CounterExists" xml:space="preserve">
<value>Could not locate Performance Counter with specified category name '{0}', counter name '{1}'.</value>
</data>
- <data name="RegKeyMissingShort" xml:space="preserve">
- <value>Cannot open registry key {0} on computer {1}.</value>
- </data>
<data name="SetSecurityDescriptorFailed" xml:space="preserve">
<value>Cannot initialize security descriptor initialized.</value>
</data>
+ <data name="RegKeyMissingShort" xml:space="preserve">
+ <value>Cannot open registry key {0} on computer {1}.</value>
+ </data>
<data name="CantGetMappingSize" xml:space="preserve">
<value>Cannot calculate the size of the file view.</value>
</data>
<data name="CantReadCategory" xml:space="preserve">
<value>Cannot read Category {0}.</value>
</data>
- <data name="Reference_to_nonexistent_listener" xml:space="preserve">
- <value>Listener '{0}' does not exist in the sharedListeners section.</value>
- </data>
- <data name="Only_specify_one" xml:space="preserve">
- <value>'switchValue' and 'switchName' cannot both be specified on source '{0}'.</value>
- </data>
- <data name="Reference_listener_cant_have_properties" xml:space="preserve">
- <value>A listener with no type name specified references the sharedListeners section and cannot have any attributes other than 'Name'. Listener: '{0}'.</value>
- </data>
- <data name="Could_not_create_listener" xml:space="preserve">
- <value>Couldn't create listener '{0}'.</value>
- </data>
- <data name="EmptyTypeName_NotAllowed" xml:space="preserve">
- <value>switchType needs to be a valid class name. It can't be empty.</value>
- </data>
- <data name="Could_not_find_type" xml:space="preserve">
- <value>Couldn't find type for class {0}.</value>
- </data>
- <data name="Incorrect_base_type" xml:space="preserve">
- <value>The specified type, '{0}' is not derived from the appropriate base type, '{1}'.</value>
- </data>
- <data name="TL_InitializeData_NotSpecified" xml:space="preserve">
- <value>initializeData needs to be valid for this TraceListener.</value>
- </data>
- <data name="Could_not_get_constructor" xml:space="preserve">
- <value>Couldn't find constructor for class {0}.</value>
- </data>
- <data name="Could_not_create_type_instance" xml:space="preserve">
- <value>Could not create {0}.</value>
- </data>
- <data name="AttributeNotSupported" xml:space="preserve">
- <value>'{0}' is not a valid configuration attribute for type '{1}'.</value>
+ <data name="PlatformNotSupported_PerCounters" xml:space="preserve">
+ <value>Performance Counters are not supported on this platform</value>
</data>
</root>
<AssemblyName>System.Diagnostics.PerformanceCounter</AssemblyName>
<DefineConstants Condition="'$(TargetGroup)' != 'uap'">$(DefineConstants);FEATURE_REGISTRY</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetsWindows)' != 'true'">SR.PlatformNotSupported_PerfCounters</GeneratePlatformNotSupportedAssemblyMessage>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetsFreeBSD)' == 'true' OR '$(TargetsUnknownUnix)' == 'true' ">
<!-- Suppress unused field warnings when using PlatformNotSupportedException stubs -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="System\Diagnostics\PerformanceCounter.cs" />
+ <Compile Include="System\Diagnostics\PerformanceCounter.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System\Diagnostics\PerformanceCounterCategory.cs" />
<Compile Include="System\Diagnostics\PerformanceCounterCategoryType.cs" />
<Compile Include="System\Diagnostics\PerformanceCounterInstanceLifetime.cs" />
<Compile Include="System\Diagnostics\SystemDiagnosticsSection.cs" />
<Compile Include="System\Diagnostics\PerfCounterSection.cs" />
<Compile Include="misc\EnvironmentHelpers.cs" />
- <Compile Include="Interop\SafeNativeMethods.cs" />
- <Compile Include="Microsoft\Win32\SafeHandles\SafeLocalMemHandle.cs" />
- <!--<Compile Include="misc\ExternDll.cs" />-->
<Compile Include="System\Diagnostics\ProcessWaitHandle.Windows.cs" />
+ <Compile Include="$(CommonPath)\Interop\Windows\perfcounter\Interop.FormatFromRawValue.cs">
+ <Link>Common\Interop\Windows\perfcounter\Interop.FormatFromRawValue.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.PerformanceCounterOptions.cs">
<Link>Common\Interop\Windows\kernel32\Interop.PerformanceCounterOptions.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetProcessTimes.cs">
<Link>Common\Interop\Windows\kernel32\Interop.GetProcessTimes.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.LoadLibrary.cs">
+ <Link>Common\Interop\Windows\kernel32\Interop.LoadLibrary.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.FreeLibrary.cs">
+ <Link>Common\Interop\Windows\kernel32\Interop.FreeLibrary.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFileMapping.cs">
<Link>Common\Interop\Windows\kernel32\Interop.CreateFileMapping.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.OpenProcess.cs">
<Link>Common\Interop\Windows\kernel32\Interop.OpenProcess.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.WaitForSingleObjectDontCallThis.cs">
+ <Link>Common\Interop\Windows\kernel32\Interop.WaitForSingleObjectDontCallThis.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\Interop.Libraries.cs">
<Link>Common\Interop\Windows\Interop.Libraries.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Microsoft\Win32\SafeHandles\SafeLocalAllocHandle.cs">
<Link>Common\Microsoft\Win32\SafeHandles\SafeLocalAllocHandle.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Microsoft\Win32\SafeHandles\SafeLocalMemHandle.cs">
+ <Link>Common\Microsoft\Win32\SafeHandles\SafeLocalMemHandle.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.LocalAlloc.cs">
<Link>Common\Interop\Windows\kernel32\Interop.LocalAlloc.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetCurrentProcess_SafeProcessHandle.cs">
<Link>Common\Interop\Windows\kernel32\Interop.GetCurrentProcess.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetComputerName.cs">
+ <Link>Common\Interop\Windows\kernel32\Interop.GetComputerName.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.DuplicateHandle_SafeProcessHandle.cs">
<Link>Common\Interop\Windows\kernel32\Interop.DuplicateHandle.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\advapi32\Interop.ConvertStringSecurityDescriptorToSecurityDescriptor.cs">
+ <Link>Common\Interop\Windows\advapi32\Interop.ConvertStringSecurityDescriptorToSecurityDescriptor.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\advapi32\Interop.PERF_INFO.cs">
<Link>Common\Interop\Windows\advapi32\Interop.PERF_INFO.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\advapi32\Interop.GetTokenInformation.cs">
+ <Link>Common\Interop\Windows\advapi32\Interop.GetTokenInformation.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetCurrentProcessId.cs">
<Link>Common\Interop\Windows\kernel32\Interop.GetCurrentProcessId.cs</Link>
</Compile>
</Compile>
</ItemGroup>
<ItemGroup>
- <Reference Condition="'$(TargetGroup)' != 'uap'" Include="Microsoft.Win32.Registry" />
+ <Reference Include="Microsoft.Win32.Registry" />
<Reference Include="Microsoft.Win32.Primitives" />
<Reference Include="System.Collections" />
<Reference Include="System.Collections.NonGeneric" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
-
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
+using System.ComponentModel;
- using System.Diagnostics;
-
- using System;
- using System.ComponentModel;
-
+namespace System.Diagnostics
+{
/// <summary>
/// A struct defining the counter type, name and help string for a custom counter.
/// </summary>
- public class CounterCreationData {
- private PerformanceCounterType counterType = PerformanceCounterType.NumberOfItems32;
- private string counterName = String.Empty;
- private string counterHelp = String.Empty;
+ public class CounterCreationData
+ {
+ private PerformanceCounterType _counterType = PerformanceCounterType.NumberOfItems32;
+ private string _counterName = string.Empty;
+ private string _counterHelp = string.Empty;
- public CounterCreationData() {
+ public CounterCreationData()
+ {
}
-
- public CounterCreationData(string counterName, string counterHelp, PerformanceCounterType counterType) {
+
+ public CounterCreationData(string counterName, string counterHelp, PerformanceCounterType counterType)
+ {
CounterType = counterType;
CounterName = counterName;
CounterHelp = counterHelp;
}
- public PerformanceCounterType CounterType {
- get {
- return counterType;
+ public PerformanceCounterType CounterType
+ {
+ get
+ {
+ return _counterType;
}
- set {
- if (!Enum.IsDefined(typeof(PerformanceCounterType), value))
+ set
+ {
+ if (!Enum.IsDefined(typeof(PerformanceCounterType), value))
throw new InvalidEnumArgumentException("value", (int)value, typeof(PerformanceCounterType));
-
- counterType = value;
+
+ _counterType = value;
}
}
- public string CounterName {
- get {
- return counterName;
+ public string CounterName
+ {
+ get
+ {
+ return _counterName;
}
- set {
+ set
+ {
PerformanceCounterCategory.CheckValidCounter(value);
- counterName = value;
+ _counterName = value;
}
}
- public string CounterHelp {
- get {
- return counterHelp;
+ public string CounterHelp
+ {
+ get
+ {
+ return _counterHelp;
}
- set {
+ set
+ {
PerformanceCounterCategory.CheckValidHelp(value);
- counterHelp = value;
+ _counterHelp = value;
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System;
- using System.ComponentModel;
- using System.Collections;
-
- [Serializable()]
- public class CounterCreationDataCollection : CollectionBase {
- public CounterCreationDataCollection() {
+using System;
+using System.Collections;
+
+namespace System.Diagnostics
+{
+ public class CounterCreationDataCollection : CollectionBase
+ {
+ public CounterCreationDataCollection()
+ {
+ }
+
+ public CounterCreationDataCollection(CounterCreationDataCollection value)
+ {
+ AddRange(value);
}
- public CounterCreationDataCollection(CounterCreationDataCollection value) {
- this.AddRange(value);
- }
-
- public CounterCreationDataCollection(CounterCreationData[] value) {
- this.AddRange(value);
+ public CounterCreationDataCollection(CounterCreationData[] value)
+ {
+ AddRange(value);
}
-
- public CounterCreationData this[int index] {
- get {
+
+ public CounterCreationData this[int index]
+ {
+ get
+ {
return ((CounterCreationData)(List[index]));
}
- set {
+ set
+ {
List[index] = value;
}
}
-
- public int Add(CounterCreationData value) {
+
+ public int Add(CounterCreationData value)
+ {
return List.Add(value);
}
- public void AddRange(CounterCreationData[] value) {
- if (value == null) {
+ public void AddRange(CounterCreationData[] value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException("value");
}
- for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) {
- this.Add(value[i]);
+ for (int i = 0; ((i) < (value.Length)); i = ((i) + (1)))
+ {
+ Add(value[i]);
}
}
- public void AddRange(CounterCreationDataCollection value) {
- if (value == null) {
+ public void AddRange(CounterCreationDataCollection value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException("value");
}
int currentCount = value.Count;
- for (int i = 0; i < currentCount; i = ((i) + (1))) {
- this.Add(value[i]);
+ for (int i = 0; i < currentCount; i = ((i) + (1)))
+ {
+ Add(value[i]);
}
}
-
- public bool Contains(CounterCreationData value) {
+
+ public bool Contains(CounterCreationData value)
+ {
return List.Contains(value);
}
-
- public void CopyTo(CounterCreationData[] array, int index) {
+
+ public void CopyTo(CounterCreationData[] array, int index)
+ {
List.CopyTo(array, index);
}
-
- public int IndexOf(CounterCreationData value) {
+
+ public int IndexOf(CounterCreationData value)
+ {
return List.IndexOf(value);
}
-
- public void Insert(int index, CounterCreationData value) {
+
+ public void Insert(int index, CounterCreationData value)
+ {
List.Insert(index, value);
}
-
- public virtual void Remove(CounterCreationData value) {
+
+ public virtual void Remove(CounterCreationData value)
+ {
List.Remove(value);
- }
+ }
- protected override void OnValidate(object value) {
+ protected override void OnValidate(object value)
+ {
if (value == null)
throw new ArgumentNullException("value");
-
+
CounterCreationData dataToAdd = value as CounterCreationData;
- if (dataToAdd == null)
+ if (dataToAdd == null)
throw new ArgumentException(SR.Format(SR.MustAddCounterCreationData));
}
-
- }
+
+ }
}
-
+
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
-
- using System.Diagnostics;
-
- using System;
-
+namespace System.Diagnostics
+{
/// <summary>
/// A struct holding the raw data for a performance counter.
/// </summary>
- public struct CounterSample {
- private long rawValue;
- private long baseValue;
- private long timeStamp;
- private long counterFrequency;
- private PerformanceCounterType counterType;
- private long timeStamp100nSec;
- private long systemFrequency;
- private long counterTimeStamp;
-
+ public struct CounterSample
+ {
+ private long _rawValue;
+ private long _baseValue;
+ private long _timeStamp;
+ private long _counterFrequency;
+ private PerformanceCounterType _counterType;
+ private long _timeStamp100nSec;
+ private long _systemFrequency;
+ private long _counterTimeStamp;
+
public static CounterSample Empty = new CounterSample(0, 0, 0, 0, 0, 0, PerformanceCounterType.NumberOfItems32);
- public CounterSample(long rawValue, long baseValue, long counterFrequency, long systemFrequency, long timeStamp, long timeStamp100nSec, PerformanceCounterType counterType) {
- this.rawValue = rawValue;
- this.baseValue = baseValue;
- this.timeStamp = timeStamp;
- this.counterFrequency = counterFrequency;
- this.counterType = counterType;
- this.timeStamp100nSec = timeStamp100nSec;
- this.systemFrequency = systemFrequency;
- this.counterTimeStamp = 0;
- }
-
- public CounterSample(long rawValue, long baseValue, long counterFrequency, long systemFrequency, long timeStamp, long timeStamp100nSec, PerformanceCounterType counterType, long counterTimeStamp) {
- this.rawValue = rawValue;
- this.baseValue = baseValue;
- this.timeStamp = timeStamp;
- this.counterFrequency = counterFrequency;
- this.counterType = counterType;
- this.timeStamp100nSec = timeStamp100nSec;
- this.systemFrequency = systemFrequency;
- this.counterTimeStamp = counterTimeStamp;
- }
-
+ public CounterSample(long rawValue, long baseValue, long counterFrequency, long systemFrequency, long timeStamp, long timeStamp100nSec, PerformanceCounterType counterType)
+ {
+ _rawValue = rawValue;
+ _baseValue = baseValue;
+ _timeStamp = timeStamp;
+ _counterFrequency = counterFrequency;
+ _counterType = counterType;
+ _timeStamp100nSec = timeStamp100nSec;
+ _systemFrequency = systemFrequency;
+ _counterTimeStamp = 0;
+ }
+
+ public CounterSample(long rawValue, long baseValue, long counterFrequency, long systemFrequency, long timeStamp, long timeStamp100nSec, PerformanceCounterType counterType, long counterTimeStamp)
+ {
+ _rawValue = rawValue;
+ _baseValue = baseValue;
+ _timeStamp = timeStamp;
+ _counterFrequency = counterFrequency;
+ _counterType = counterType;
+ _timeStamp100nSec = timeStamp100nSec;
+ _systemFrequency = systemFrequency;
+ _counterTimeStamp = counterTimeStamp;
+ }
+
/// <summary>
/// Raw value of the counter.
/// </summary>
- public long RawValue {
- get {
- return this.rawValue;
+ public long RawValue
+ {
+ get
+ {
+ return _rawValue;
}
}
- internal ulong UnsignedRawValue {
- get {
- return (ulong)this.rawValue;
+ internal ulong UnsignedRawValue
+ {
+ get
+ {
+ return (ulong)_rawValue;
}
}
-
+
/// <summary>
/// Optional base raw value for the counter (only used if multiple counter based).
/// </summary>
- public long BaseValue {
- get {
- return this.baseValue;
+ public long BaseValue
+ {
+ get
+ {
+ return _baseValue;
}
}
-
+
/// <summary>
/// Raw system frequency
/// </summary>
- public long SystemFrequency {
- get {
- return this.systemFrequency;
+ public long SystemFrequency
+ {
+ get
+ {
+ return _systemFrequency;
}
}
/// <summary>
/// Raw counter frequency
/// </summary>
- public long CounterFrequency {
- get {
- return this.counterFrequency;
+ public long CounterFrequency
+ {
+ get
+ {
+ return _counterFrequency;
}
}
/// <summary>
/// Raw counter frequency
/// </summary>
- public long CounterTimeStamp {
- get {
- return this.counterTimeStamp;
+ public long CounterTimeStamp
+ {
+ get
+ {
+ return _counterTimeStamp;
}
}
-
+
/// <summary>
/// Raw timestamp
/// </summary>
- public long TimeStamp {
- get {
- return this.timeStamp;
+ public long TimeStamp
+ {
+ get
+ {
+ return _timeStamp;
}
}
/// <summary>
/// Raw high fidelity timestamp
/// </summary>
- public long TimeStamp100nSec {
- get {
- return this.timeStamp100nSec;
+ public long TimeStamp100nSec
+ {
+ get
+ {
+ return _timeStamp100nSec;
}
}
-
+
/// <summary>
/// Counter type
/// </summary>
- public PerformanceCounterType CounterType {
- get {
- return this.counterType;
+ public PerformanceCounterType CounterType
+ {
+ get
+ {
+ return _counterType;
}
}
/// <summary>
/// Static functions to calculate the performance value off the sample
/// </summary>
- public static float Calculate(CounterSample counterSample) {
+ public static float Calculate(CounterSample counterSample)
+ {
return CounterSampleCalculator.ComputeCounterValue(counterSample);
}
/// <summary>
/// Static functions to calculate the performance value off the samples
/// </summary>
- public static float Calculate(CounterSample counterSample, CounterSample nextCounterSample) {
+ public static float Calculate(CounterSample counterSample, CounterSample nextCounterSample)
+ {
return CounterSampleCalculator.ComputeCounterValue(counterSample, nextCounterSample);
}
- public override bool Equals(Object o) {
- return ( o is CounterSample) && Equals((CounterSample)o);
+ public override bool Equals(Object o)
+ {
+ return (o is CounterSample) && Equals((CounterSample)o);
}
-
- public bool Equals(CounterSample sample) {
- return (rawValue == sample.rawValue) &&
- (baseValue == sample.baseValue) &&
- (timeStamp == sample.timeStamp) &&
- (counterFrequency == sample.counterFrequency) &&
- (counterType == sample.counterType) &&
- (timeStamp100nSec == sample.timeStamp100nSec) &&
- (systemFrequency == sample.systemFrequency) &&
- (counterTimeStamp == sample.counterTimeStamp);
+
+ public bool Equals(CounterSample sample)
+ {
+ return (_rawValue == sample._rawValue) &&
+ (_baseValue == sample._baseValue) &&
+ (_timeStamp == sample._timeStamp) &&
+ (_counterFrequency == sample._counterFrequency) &&
+ (_counterType == sample._counterType) &&
+ (_timeStamp100nSec == sample._timeStamp100nSec) &&
+ (_systemFrequency == sample._systemFrequency) &&
+ (_counterTimeStamp == sample._counterTimeStamp);
}
- public override int GetHashCode() {
- return rawValue.GetHashCode();
+ public override int GetHashCode()
+ {
+ return _rawValue.GetHashCode();
}
- public static bool operator ==(CounterSample a, CounterSample b) {
+ public static bool operator ==(CounterSample a, CounterSample b)
+ {
return a.Equals(b);
- }
+ }
- public static bool operator !=(CounterSample a, CounterSample b) {
+ public static bool operator !=(CounterSample a, CounterSample b)
+ {
return !(a.Equals(b));
}
-
+
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System.Threading;
- using System;
- using System.ComponentModel;
- using Microsoft.Win32;
- using System.Text;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
- using System.Globalization;
- using System.Runtime.Versioning;
-
+using System.ComponentModel;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Security.Permissions;
+using System.Globalization;
+
+namespace System.Diagnostics
+{
/// <summary>
/// Set of utility functions for interpreting the counter data
/// NOTE: most of this code was taken and ported from counters.c (PerfMon source code)
/// </summary>
- public static class CounterSampleCalculator {
- static volatile bool perfCounterDllLoaded = false;
-
+ public static class CounterSampleCalculator
+ {
+ static volatile bool s_perfCounterDllLoaded = false;
+
/// <summary>
/// Converts 100NS elapsed time to fractional seconds
/// </summary>
/// <internalonly/>
- private static float GetElapsedTime(CounterSample oldSample, CounterSample newSample) {
+ private static float GetElapsedTime(CounterSample oldSample, CounterSample newSample)
+ {
float eSeconds;
float eDifference;
- if (newSample.RawValue == 0) {
+ if (newSample.RawValue == 0)
+ {
// no data [start time = 0] so return 0
return 0.0f;
- }
- else {
+ }
+ else
+ {
float eFreq;
eFreq = (float)(ulong)oldSample.CounterFrequency;
if (oldSample.UnsignedRawValue >= (ulong)newSample.CounterTimeStamp || eFreq <= 0.0f)
return 0.0f;
-
+
// otherwise compute difference between current time and start time
eDifference = (float)((ulong)newSample.CounterTimeStamp - oldSample.UnsignedRawValue);
-
+
// convert to fractional seconds using object counter
eSeconds = eDifference / eFreq;
return eSeconds;
- }
+ }
}
/// <summary>
/// Computes the calculated value given a raw counter sample.
/// </summary>
- public static float ComputeCounterValue(CounterSample newSample) {
+ public static float ComputeCounterValue(CounterSample newSample)
+ {
return ComputeCounterValue(CounterSample.Empty, newSample);
}
/// <summary>
/// Computes the calculated value given a raw counter sample.
/// </summary>
- public static float ComputeCounterValue(CounterSample oldSample, CounterSample newSample) {
- int newCounterType = (int) newSample.CounterType;
- if (oldSample.SystemFrequency == 0) {
+ public static float ComputeCounterValue(CounterSample oldSample, CounterSample newSample)
+ {
+ int newCounterType = (int)newSample.CounterType;
+ if (oldSample.SystemFrequency == 0)
+ {
if ((newCounterType != Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) &&
(newCounterType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_RAWCOUNT) &&
(newCounterType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_RAWCOUNT_HEX) &&
(newCounterType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT) &&
(newCounterType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT_HEX) &&
- (newCounterType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_BASE)) {
+ (newCounterType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_BASE))
+ {
// Since oldSample has a system frequency of 0, this means the newSample is the first sample
// on a two sample calculation. Since we can't do anything with it, return 0.
return 0.0f;
}
}
- else if (oldSample.CounterType != newSample.CounterType) {
+ else if (oldSample.CounterType != newSample.CounterType)
+ {
throw new InvalidOperationException(SR.Format(SR.MismatchedCounterTypes));
}
- if (newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_ELAPSED_TIME)
+ if (newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_ELAPSED_TIME)
return (float)GetElapsedTime(oldSample, newSample);
-
+
Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER newPdhValue = new Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER();
Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER oldPdhValue = new Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER();
LoadPerfCounterDll();
- Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE pdhFormattedValue= new Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE();
+ Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE pdhFormattedValue = new Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_COUNTERVALUE();
long timeBase = newSample.SystemFrequency;
- int result = SafeNativeMethods.FormatFromRawValue((uint) newCounterType, Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_DOUBLE | Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_NOSCALE | Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_NOCAP100,
+ int result = Interop.PerfCounters.FormatFromRawValue((uint)newCounterType, Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_DOUBLE | Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_NOSCALE | Interop.Kernel32.PerformanceCounterOptions.PDH_FMT_NOCAP100,
ref timeBase, newPdhValue, oldPdhValue, pdhFormattedValue);
-
- if (result != Interop.Errors.ERROR_SUCCESS) {
+
+ if (result != Interop.Errors.ERROR_SUCCESS)
+ {
// If the numbers go negative, just return 0. This better matches the old behavior.
if (result == Interop.Kernel32.PerformanceCounterOptions.PDH_CALC_NEGATIVE_VALUE || result == Interop.Kernel32.PerformanceCounterOptions.PDH_CALC_NEGATIVE_DENOMINATOR || result == Interop.Kernel32.PerformanceCounterOptions.PDH_NO_DATA)
return 0;
else
throw new Win32Exception(result, SR.Format(SR.PerfCounterPdhError, result.ToString("x", CultureInfo.InvariantCulture)));
}
-
- return (float) pdhFormattedValue.data;
-
+
+ return (float)pdhFormattedValue.data;
+
}
// This method figures out which values are supposed to go into which structures so that PDH can do the
// calculation for us. This was ported from Window's cutils.c
- private static void FillInValues(CounterSample oldSample, CounterSample newSample, Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER oldPdhValue, Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER newPdhValue) {
- int newCounterType = (int) newSample.CounterType;
+ private static void FillInValues(CounterSample oldSample, CounterSample newSample, Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER oldPdhValue, Interop.Kernel32.PerformanceCounterOptions.PDH_RAW_COUNTER newPdhValue)
+ {
+ int newCounterType = (int)newSample.CounterType;
- switch (newCounterType) {
+ switch (newCounterType)
+ {
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_COUNTER:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_QUEUELEN_TYPE:
case Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_COUNTER:
case Interop.Kernel32.PerformanceCounterOptions.PERF_OBJ_TIME_TIMER:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_OBJ_TIME_QUEUELEN_TYPE:
- newPdhValue.FirstValue = newSample.RawValue;
+ newPdhValue.FirstValue = newSample.RawValue;
newPdhValue.SecondValue = newSample.TimeStamp;
- oldPdhValue.FirstValue = oldSample.RawValue;
+ oldPdhValue.FirstValue = oldSample.RawValue;
oldPdhValue.SecondValue = oldSample.TimeStamp;
break;
-
+
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_100NS_QUEUELEN_TYPE:
- newPdhValue.FirstValue = newSample.RawValue;
+ newPdhValue.FirstValue = newSample.RawValue;
newPdhValue.SecondValue = newSample.TimeStamp100nSec;
- oldPdhValue.FirstValue = oldSample.RawValue;
+ oldPdhValue.FirstValue = oldSample.RawValue;
oldPdhValue.SecondValue = oldSample.TimeStamp100nSec;
break;
-
+
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_TIMER:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_TIMER_INV:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_BULK_COUNT:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_QUEUELEN_TYPE:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV:
- newPdhValue.FirstValue = newSample.RawValue;
+ newPdhValue.FirstValue = newSample.RawValue;
newPdhValue.SecondValue = newSample.TimeStamp;
- oldPdhValue.FirstValue = oldSample.RawValue;
+ oldPdhValue.FirstValue = oldSample.RawValue;
oldPdhValue.SecondValue = oldSample.TimeStamp;
- if (newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER || newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) {
+ if (newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER || newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV)
+ {
// this is to make PDH work like PERFMON for
// this counter type
- newPdhValue.FirstValue *= (uint) newSample.CounterFrequency;
- if (oldSample.CounterFrequency != 0) {
- oldPdhValue.FirstValue *= (uint) oldSample.CounterFrequency;
+ newPdhValue.FirstValue *= (uint)newSample.CounterFrequency;
+ if (oldSample.CounterFrequency != 0)
+ {
+ oldPdhValue.FirstValue *= (uint)oldSample.CounterFrequency;
}
}
- if ((newCounterType & Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER) == Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER) {
- newPdhValue.MultiCount = (int) newSample.BaseValue;
- oldPdhValue.MultiCount = (int) oldSample.BaseValue;
+ if ((newCounterType & Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER) == Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER)
+ {
+ newPdhValue.MultiCount = (int)newSample.BaseValue;
+ oldPdhValue.MultiCount = (int)oldSample.BaseValue;
}
-
-
+
+
break;
//
// These counters do not use any time reference
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT_HEX:
case Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_DELTA:
- newPdhValue.FirstValue = newSample.RawValue;
+ newPdhValue.FirstValue = newSample.RawValue;
newPdhValue.SecondValue = 0;
- oldPdhValue.FirstValue = oldSample.RawValue;
+ oldPdhValue.FirstValue = oldSample.RawValue;
oldPdhValue.SecondValue = 0;
break;
//
case Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_TIMER_INV:
case Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER:
case Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV:
- newPdhValue.FirstValue = newSample.RawValue;
+ newPdhValue.FirstValue = newSample.RawValue;
newPdhValue.SecondValue = newSample.TimeStamp100nSec;
- oldPdhValue.FirstValue = oldSample.RawValue;
+ oldPdhValue.FirstValue = oldSample.RawValue;
oldPdhValue.SecondValue = oldSample.TimeStamp100nSec;
- if ((newCounterType & Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER) == Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER) {
- newPdhValue.MultiCount = (int) newSample.BaseValue;
- oldPdhValue.MultiCount = (int) oldSample.BaseValue;
+ if ((newCounterType & Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER) == Interop.Kernel32.PerformanceCounterOptions.PERF_MULTI_COUNTER)
+ {
+ newPdhValue.MultiCount = (int)newSample.BaseValue;
+ oldPdhValue.MultiCount = (int)oldSample.BaseValue;
}
break;
//
oldPdhValue.FirstValue = oldSample.RawValue;
oldPdhValue.SecondValue = oldSample.BaseValue;
break;
-
+
default:
// an unidentified counter was returned so
- newPdhValue.FirstValue = 0;
+ newPdhValue.FirstValue = 0;
newPdhValue.SecondValue = 0;
- oldPdhValue.FirstValue = 0;
+ oldPdhValue.FirstValue = 0;
oldPdhValue.SecondValue = 0;
break;
}
}
- private static void LoadPerfCounterDll() {
- if (perfCounterDllLoaded)
+ private static void LoadPerfCounterDll()
+ {
+ if (s_perfCounterDllLoaded)
return;
new FileIOPermission(PermissionState.Unrestricted).Assert();
string installPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
string perfcounterPath = Path.Combine(installPath, "perfcounter.dll");
- if (SafeNativeMethods.LoadLibrary(perfcounterPath) == IntPtr.Zero) {
- throw new Win32Exception( Marshal.GetLastWin32Error() );
+ if (Interop.Kernel32.LoadLibrary(perfcounterPath) == IntPtr.Zero)
+ {
+ throw new Win32Exception(Marshal.GetLastWin32Error());
}
- perfCounterDllLoaded = true;
- }
+ s_perfCounterDllLoaded = true;
+ }
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Configuration;
- using System.Threading;
- using System.Runtime.Versioning;
-
- internal enum InitState {
+using System.Reflection;
+using System.Configuration;
+
+namespace System.Diagnostics
+{
+ internal enum InitState
+ {
NotInitialized,
Initializing,
Initialized
}
- internal static class DiagnosticsConfiguration {
- private static volatile SystemDiagnosticsSection configSection;
- private static volatile InitState initState = InitState.NotInitialized;
+ internal static class DiagnosticsConfiguration
+ {
+ private static volatile SystemDiagnosticsSection s_configSection;
+ private static volatile InitState s_initState = InitState.NotInitialized;
#if !FEATURE_PAL // perfcounter
- internal static int PerformanceCountersFileMappingSize {
- get {
- for (int retryCount = 0; !CanInitialize() && retryCount <= 5; ++retryCount) {
+ internal static int PerformanceCountersFileMappingSize
+ {
+ get
+ {
+ for (int retryCount = 0; !CanInitialize() && retryCount <= 5; ++retryCount)
+ {
if (retryCount == 5)
return SharedPerformanceCounter.DefaultCountersFileMappingSize;
-
+
System.Threading.Thread.Sleep(200);
- }
-
+ }
+
Initialize();
- SystemDiagnosticsSection configSectionSav = configSection;
- if (configSectionSav != null && configSectionSav.PerfCounters != null) {
+ SystemDiagnosticsSection configSectionSav = s_configSection;
+ if (configSectionSav != null && configSectionSav.PerfCounters != null)
+ {
int size = configSectionSav.PerfCounters.FileMappingSize;
if (size < SharedPerformanceCounter.MinCountersFileMappingSize)
size = SharedPerformanceCounter.MinCountersFileMappingSize;
-
+
if (size > SharedPerformanceCounter.MaxCountersFileMappingSize)
size = SharedPerformanceCounter.MaxCountersFileMappingSize;
return size;
- }
+ }
else
return SharedPerformanceCounter.DefaultCountersFileMappingSize;
- }
+ }
}
#endif // !FEATURE_PAL
- internal static string ConfigFilePath {
- get {
+ internal static string ConfigFilePath
+ {
+ get
+ {
Initialize();
- SystemDiagnosticsSection configSectionSav = configSection;
- if (configSectionSav != null)
+ SystemDiagnosticsSection configSectionSav = s_configSection;
+ if (configSectionSav != null)
return configSectionSav.ElementInformation.Source;
else
return string.Empty; // the default
}
}
- private static SystemDiagnosticsSection GetConfigSection() {
- SystemDiagnosticsSection configSection = (SystemDiagnosticsSection) ConfigurationManager.GetSection("system.diagnostics");
+ private static SystemDiagnosticsSection GetConfigSection()
+ {
+ SystemDiagnosticsSection configSection = (SystemDiagnosticsSection)ConfigurationManager.GetSection("system.diagnostics");
return configSection;
}
- internal static bool CanInitialize() {
- bool setConfigurationSystemInProgress = (bool)(typeof(ConfigurationManager).GetProperty("SetConfigurationSystemInProgress", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null));
- return (initState != InitState.Initializing) &&
+ internal static bool CanInitialize()
+ {
+ bool setConfigurationSystemInProgress = (bool)(typeof(ConfigurationManager).GetProperty("SetConfigurationSystemInProgress", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null));
+ return (s_initState != InitState.Initializing) &&
!setConfigurationSystemInProgress;
}
-
- internal static void Initialize() {
+
+ internal static void Initialize()
+ {
// Initialize() is also called by other components outside of Trace (such as PerformanceCounter)
// as a result using one lock for this critical section and another for Trace API critical sections
// (such as Trace.WriteLine) could potentially lead to deadlock between 2 threads that are
// executing these critical sections (and consequently obtaining the 2 locks) in the reverse order.
// Using the same lock for DiagnosticsConfiguration as well as TraceInternal avoids this issue.
// Sequential locks on TraceInternal.critSec by the same thread is a non issue for this critical section.
- lock (TraceInternal.critSec) {
+ lock (TraceInternal.critSec)
+ {
// because some of the code used to load config also uses diagnostics
// we can't block them while we initialize from config. Therefore we just
// return immediately and they just use the default values.
- bool setConfigurationSystemInProgress = (bool)(typeof(ConfigurationManager).GetProperty("SetConfigurationSystemInProgress", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null));
- if ( initState != InitState.NotInitialized ||
- setConfigurationSystemInProgress) {
+ bool setConfigurationSystemInProgress = (bool)(typeof(ConfigurationManager).GetProperty("SetConfigurationSystemInProgress", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null));
+ if (s_initState != InitState.NotInitialized ||
+ setConfigurationSystemInProgress)
+ {
return;
}
- initState = InitState.Initializing; // used for preventing recursion
- try {
- configSection = GetConfigSection();
+ s_initState = InitState.Initializing; // used for preventing recursion
+ try
+ {
+ s_configSection = GetConfigSection();
}
- finally {
- initState = InitState.Initialized;
+ finally
+ {
+ s_initState = InitState.Initialized;
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System.Runtime.InteropServices;
-
- using System.Diagnostics;
- using System;
-
+using System.Runtime.InteropServices;
+namespace System.Diagnostics
+{
/// <internalonly/>
[ComImport, Guid("73386977-D6FD-11D2-BED5-00C04F79E3AE"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
- public interface ICollectData {
+ public interface ICollectData
+ {
- [return: MarshalAs(UnmanagedType.I4 )]
- void CollectData(
- [In, MarshalAs(UnmanagedType.I4 )]
- int id,
- [In, MarshalAs(UnmanagedType.SysInt )]
- IntPtr valueName,
- [In, MarshalAs(UnmanagedType.SysInt )]
- IntPtr data,
- [In, MarshalAs(UnmanagedType.I4 )]
- int totalBytes,
+ [return: MarshalAs(UnmanagedType.I4)]
+ void CollectData(
+ [In, MarshalAs(UnmanagedType.I4 )]
+ int id,
+ [In, MarshalAs(UnmanagedType.SysInt )]
+ IntPtr valueName,
+ [In, MarshalAs(UnmanagedType.SysInt )]
+ IntPtr data,
+ [In, MarshalAs(UnmanagedType.I4 )]
+ int totalBytes,
[Out, MarshalAs(UnmanagedType.SysInt)]
- out IntPtr res);
-
- void CloseData();
-
+ out IntPtr res);
+ void CloseData();
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
-
- using System.Diagnostics;
-
- using System;
- using System.Collections;
-
+namespace System.Diagnostics
+{
/// <summary>
/// A holder of instance data.
/// </summary>
- public class InstanceData {
- private string instanceName;
- private CounterSample sample;
-
- public InstanceData(string instanceName, CounterSample sample) {
- this.instanceName = instanceName;
- this.sample = sample;
+ public class InstanceData
+ {
+ private string _instanceName;
+ private CounterSample _sample;
+
+ public InstanceData(string instanceName, CounterSample sample)
+ {
+ _instanceName = instanceName;
+ _sample = sample;
}
- public string InstanceName {
- get {
- return instanceName;
+ public string InstanceName
+ {
+ get
+ {
+ return _instanceName;
}
}
- public CounterSample Sample {
- get {
- return sample;
+ public CounterSample Sample
+ {
+ get
+ {
+ return _sample;
}
}
- public long RawValue {
- get {
- return sample.RawValue;
+ public long RawValue
+ {
+ get
+ {
+ return _sample.RawValue;
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System;
- using System.Diagnostics;
- using System.Collections;
- using System.Globalization;
-
+using System;
+using System.Collections;
+using System.Globalization;
+
+namespace System.Diagnostics
+{
/// <summary>
/// A collection containing all the instance data for a counter. This collection is contained in the
/// <see cref='System.Diagnostics.InstanceDataCollectionCollection'/> when using the
/// <see cref='System.Diagnostics.PerformanceCounterCategory.ReadCategory'/> method.
/// </summary>
- public class InstanceDataCollection : DictionaryBase {
- private string counterName;
+ public class InstanceDataCollection : DictionaryBase
+ {
+ private string _counterName;
[Obsolete("This constructor has been deprecated. Please use System.Diagnostics.InstanceDataCollectionCollection.get_Item to get an instance of this collection instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public InstanceDataCollection(string counterName) {
+ public InstanceDataCollection(string counterName)
+ {
if (counterName == null)
throw new ArgumentNullException("counterName");
- this.counterName = counterName;
+ _counterName = counterName;
}
- public string CounterName {
- get {
- return counterName;
+ public string CounterName
+ {
+ get
+ {
+ return _counterName;
}
}
- public ICollection Keys {
+ public ICollection Keys
+ {
get { return Dictionary.Keys; }
}
- public ICollection Values {
- get {
+ public ICollection Values
+ {
+ get
+ {
return Dictionary.Values;
}
}
- public InstanceData this[string instanceName] {
- get {
+ public InstanceData this[string instanceName]
+ {
+ get
+ {
if (instanceName == null)
throw new ArgumentNullException("instanceName");
if (instanceName.Length == 0)
instanceName = PerformanceCounterLib.SingleInstanceName;
-
+
object objectName = instanceName.ToLower(CultureInfo.InvariantCulture);
- return (InstanceData) Dictionary[objectName];
+ return (InstanceData)Dictionary[objectName];
}
}
- internal void Add(string instanceName, InstanceData value) {
- object objectName = instanceName.ToLower(CultureInfo.InvariantCulture);
+ internal void Add(string instanceName, InstanceData value)
+ {
+ object objectName = instanceName.ToLower(CultureInfo.InvariantCulture);
Dictionary.Add(objectName, value);
}
- public bool Contains(string instanceName) {
+ public bool Contains(string instanceName)
+ {
if (instanceName == null)
- throw new ArgumentNullException("instanceName");
-
+ throw new ArgumentNullException("instanceName");
+
object objectName = instanceName.ToLower(CultureInfo.InvariantCulture);
return Dictionary.Contains(objectName);
}
-
- public void CopyTo(InstanceData[] instances, int index) {
+
+ public void CopyTo(InstanceData[] instances, int index)
+ {
Dictionary.Values.CopyTo((Array)instances, index);
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
+using System.Collections;
+using System.Globalization;
- using System.Diagnostics;
- using System;
- using System.Collections;
- using System.Globalization;
-
+namespace System.Diagnostics
+{
/// <summary>
/// The collection returned from the <see cref='System.Diagnostics.PerformanceCounterCategory.ReadCategory'/> method.
/// that contains all the counter and instance data.
/// object contains the performance data for all counters for that instance. In other words the data is
/// indexed by counter name and then by instance name.
/// </summary>
- public class InstanceDataCollectionCollection : DictionaryBase {
+ public class InstanceDataCollectionCollection : DictionaryBase
+ {
+
-
[Obsolete("This constructor has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.ReadCategory() to get an instance of this collection instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public InstanceDataCollectionCollection() : base() {}
-
- public InstanceDataCollection this[string counterName] {
- get {
+ public InstanceDataCollectionCollection() : base() { }
+
+ public InstanceDataCollection this[string counterName]
+ {
+ get
+ {
if (counterName == null)
throw new ArgumentNullException("counterName");
-
+
object objectName = counterName.ToLower(CultureInfo.InvariantCulture);
- return (InstanceDataCollection) Dictionary[objectName];
+ return (InstanceDataCollection)Dictionary[objectName];
}
}
- public ICollection Keys {
+ public ICollection Keys
+ {
get { return Dictionary.Keys; }
}
- public ICollection Values {
- get {
+ public ICollection Values
+ {
+ get
+ {
return Dictionary.Values;
}
}
- internal void Add(string counterName, InstanceDataCollection value) {
- object objectName = counterName.ToLower(CultureInfo.InvariantCulture);
+ internal void Add(string counterName, InstanceDataCollection value)
+ {
+ object objectName = counterName.ToLower(CultureInfo.InvariantCulture);
Dictionary.Add(objectName, value);
}
- public bool Contains(string counterName) {
+ public bool Contains(string counterName)
+ {
if (counterName == null)
- throw new ArgumentNullException("counterName");
-
+ throw new ArgumentNullException("counterName");
+
object objectName = counterName.ToLower(CultureInfo.InvariantCulture);
return Dictionary.Contains(objectName);
}
-
- public void CopyTo(InstanceDataCollection[] counters, int index) {
+
+ public void CopyTo(InstanceDataCollection[] counters, int index)
+ {
Dictionary.Values.CopyTo((Array)counters, index);
}
}
using System.Configuration;
-namespace System.Diagnostics {
- internal class PerfCounterSection : ConfigurationElement {
- private static readonly ConfigurationPropertyCollection _properties;
- private static readonly ConfigurationProperty _propFileMappingSize = new ConfigurationProperty("filemappingsize", typeof(int), 524288, ConfigurationPropertyOptions.None);
+namespace System.Diagnostics
+{
+ internal class PerfCounterSection : ConfigurationElement
+ {
+ private static readonly ConfigurationPropertyCollection s_properties;
+ private static readonly ConfigurationProperty s_propFileMappingSize = new ConfigurationProperty("filemappingsize", typeof(int), 524288, ConfigurationPropertyOptions.None);
- static PerfCounterSection(){
- _properties = new ConfigurationPropertyCollection();
- _properties.Add(_propFileMappingSize);
+ static PerfCounterSection()
+ {
+ s_properties = new ConfigurationPropertyCollection();
+ s_properties.Add(s_propFileMappingSize);
}
[ConfigurationProperty("filemappingsize", DefaultValue = 524288)]
- public int FileMappingSize {
- get {
- return (int) this[_propFileMappingSize];
+ public int FileMappingSize
+ {
+ get
+ {
+ return (int)this[s_propFileMappingSize];
}
}
- protected override ConfigurationPropertyCollection Properties {
- get {
- return _properties;
+ protected override ConfigurationPropertyCollection Properties
+ {
+ get
+ {
+ return s_properties;
}
}
}
// 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.Runtime.Serialization.Formatters;
-using System.Runtime.InteropServices;
using System.ComponentModel;
-using System.Diagnostics;
-using System;
-using System.Collections;
using System.Globalization;
-using System.Security;
-using System.Security.Permissions;
using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
using System.Threading;
-
-namespace System.Diagnostics {
+namespace System.Diagnostics
+{
/// <summary>
/// Performance Counter component.
/// This class provides support for NT Performance counters.
/// This class is a part of a larger framework, that includes the perf dll object and
/// perf service.
/// </summary>
- public sealed class PerformanceCounter : Component, ISupportInitialize {
- private string machineName;
- private string categoryName;
- private string counterName;
- private string instanceName;
- private PerformanceCounterInstanceLifetime instanceLifetime = PerformanceCounterInstanceLifetime.Global;
-
- private bool isReadOnly;
- private bool initialized = false;
- private string helpMsg = null;
- private int counterType = -1;
+ public sealed class PerformanceCounter : Component, ISupportInitialize
+ {
+ private string _machineName;
+ private string _categoryName;
+ private string _counterName;
+ private string _instanceName;
+ private PerformanceCounterInstanceLifetime _instanceLifetime = PerformanceCounterInstanceLifetime.Global;
+
+ private bool _isReadOnly;
+ private bool _initialized = false;
+ private string _helpMsg = null;
+ private int _counterType = -1;
// Cached old sample
- private CounterSample oldSample = CounterSample.Empty;
+ private CounterSample _oldSample = CounterSample.Empty;
// Cached IP Shared Performanco counter
- private SharedPerformanceCounter sharedCounter;
+ private SharedPerformanceCounter _sharedCounter;
[ObsoleteAttribute("This field has been deprecated and is not used. Use machine.config or an application configuration file to set the size of the PerformanceCounter file mapping.")]
public static int DefaultFileMappingSize = 524288;
- private Object m_InstanceLockObject;
- private Object InstanceLockObject {
- get {
- if (m_InstanceLockObject == null) {
+ private Object _instanceLockObject;
+ private Object InstanceLockObject
+ {
+ get
+ {
+ if (_instanceLockObject == null)
+ {
Object o = new Object();
- Interlocked.CompareExchange(ref m_InstanceLockObject, o, null);
+ Interlocked.CompareExchange(ref _instanceLockObject, o, null);
}
- return m_InstanceLockObject;
+ return _instanceLockObject;
}
}
/// <summary>
/// The defaut constructor. Creates the perf counter object
/// </summary>
- public PerformanceCounter() {
- machineName = ".";
- categoryName = String.Empty;
- counterName = String.Empty;
- instanceName = String.Empty;
- this.isReadOnly = true;
+ public PerformanceCounter()
+ {
+ _machineName = ".";
+ _categoryName = string.Empty;
+ _counterName = string.Empty;
+ _instanceName = string.Empty;
+ _isReadOnly = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the Performance Counter Object
/// </summary>
- public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName) {
- this.MachineName = machineName;
- this.CategoryName = categoryName;
- this.CounterName = counterName;
- this.InstanceName = instanceName;
- this.isReadOnly = true;
+ public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName)
+ {
+ MachineName = machineName;
+ CategoryName = categoryName;
+ CounterName = counterName;
+ InstanceName = instanceName;
+ _isReadOnly = true;
Initialize();
GC.SuppressFinalize(this);
}
- internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit) {
- this.MachineName = machineName;
- this.CategoryName = categoryName;
- this.CounterName = counterName;
- this.InstanceName = instanceName;
- this.isReadOnly = true;
- this.initialized = true;
+ internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit)
+ {
+ MachineName = machineName;
+ CategoryName = categoryName;
+ CounterName = counterName;
+ InstanceName = instanceName;
+ _isReadOnly = true;
+ _initialized = true;
GC.SuppressFinalize(this);
}
/// Creates the Performance Counter Object on local machine.
/// </summary>
public PerformanceCounter(string categoryName, string counterName, string instanceName) :
- this(categoryName, counterName, instanceName, true) {
+ this(categoryName, counterName, instanceName, true)
+ {
}
/// <summary>
/// Creates the Performance Counter Object on local machine.
/// </summary>
- public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly) {
- if(!readOnly) {
+ public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly)
+ {
+ if (!readOnly)
+ {
VerifyWriteableCounterAllowed();
}
- this.MachineName = ".";
- this.CategoryName = categoryName;
- this.CounterName = counterName;
- this.InstanceName = instanceName;
- this.isReadOnly = readOnly;
+ MachineName = ".";
+ CategoryName = categoryName;
+ CounterName = counterName;
+ InstanceName = instanceName;
+ _isReadOnly = readOnly;
Initialize();
GC.SuppressFinalize(this);
}
/// Creates the Performance Counter Object, assumes that it's a single instance
/// </summary>
public PerformanceCounter(string categoryName, string counterName) :
- this(categoryName, counterName, true) {
+ this(categoryName, counterName, true)
+ {
}
/// <summary>
/// Creates the Performance Counter Object, assumes that it's a single instance
/// </summary>
public PerformanceCounter(string categoryName, string counterName, bool readOnly) :
- this(categoryName, counterName, "", readOnly) {
+ this(categoryName, counterName, "", readOnly)
+ {
}
/// <summary>
/// Returns the performance category name for this performance counter
/// </summary>
- public string CategoryName {
- get {
- return categoryName;
+ public string CategoryName
+ {
+ get
+ {
+ return _categoryName;
}
- set {
+ set
+ {
if (value == null)
throw new ArgumentNullException("value");
- if (categoryName == null || String.Compare(categoryName, value, StringComparison.OrdinalIgnoreCase) != 0) {
- categoryName = value;
+ if (_categoryName == null || string.Compare(_categoryName, value, StringComparison.OrdinalIgnoreCase) != 0)
+ {
+ _categoryName = value;
Close();
}
}
/// <summary>
/// Returns the description message for this performance counter
/// </summary>
- public string CounterHelp {
- get {
- string currentCategoryName = categoryName;
- string currentMachineName = machineName;
-
+ public string CounterHelp
+ {
+ get
+ {
+ string currentCategoryName = _categoryName;
+ string currentMachineName = _machineName;
+
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);
permission.Demand();
Initialize();
- if (helpMsg == null)
- helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, this.counterName);
+ if (_helpMsg == null)
+ _helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName);
- return helpMsg;
+ return _helpMsg;
}
}
/// <summary>
/// Sets/returns the performance counter name for this performance counter
/// </summary>
- public string CounterName {
- get {
- return counterName;
+ public string CounterName
+ {
+ get
+ {
+ return _counterName;
}
- set {
+ set
+ {
if (value == null)
throw new ArgumentNullException("value");
- if (counterName == null || String.Compare(counterName, value, StringComparison.OrdinalIgnoreCase) != 0) {
- counterName = value;
+ if (_counterName == null || string.Compare(_counterName, value, StringComparison.OrdinalIgnoreCase) != 0)
+ {
+ _counterName = value;
Close();
}
}
/// <summary>
/// Sets/Returns the counter type for this performance counter
/// </summary>
- public PerformanceCounterType CounterType {
- get {
- if (counterType == -1) {
- string currentCategoryName = categoryName;
- string currentMachineName = machineName;
-
+ public PerformanceCounterType CounterType
+ {
+ get
+ {
+ if (_counterType == -1)
+ {
+ string currentCategoryName = _categoryName;
+ string currentMachineName = _machineName;
+
// 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(this.counterName);
- this.counterType = counterSample.CounterType;
+ CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
+ _counterType = counterSample._counterType;
}
- return(PerformanceCounterType) counterType;
+ return (PerformanceCounterType)_counterType;
}
}
- public PerformanceCounterInstanceLifetime InstanceLifetime {
- get { return instanceLifetime; }
- set {
+ public PerformanceCounterInstanceLifetime InstanceLifetime
+ {
+ get { return _instanceLifetime; }
+ set
+ {
if (value > PerformanceCounterInstanceLifetime.Process || value < PerformanceCounterInstanceLifetime.Global)
throw new ArgumentOutOfRangeException("value");
- if (initialized)
+ if (_initialized)
throw new InvalidOperationException(SR.Format(SR.CantSetLifetimeAfterInitialized));
-
- instanceLifetime = value;
+
+ _instanceLifetime = value;
}
}
-
+
/// <summary>
/// Sets/returns an instance name for this performance counter
/// </summary>
- public string InstanceName {
- get {
- return instanceName;
+ public string InstanceName
+ {
+ get
+ {
+ return _instanceName;
}
- set {
- if (value == null && instanceName == null)
+ set
+ {
+ if (value == null && _instanceName == null)
return;
- if ((value == null && instanceName != null) ||
- (value != null && instanceName == null) ||
- String.Compare(instanceName, value, StringComparison.OrdinalIgnoreCase) != 0) {
- instanceName = value;
+ if ((value == null && _instanceName != null) ||
+ (value != null && _instanceName == null) ||
+ string.Compare(_instanceName, value, StringComparison.OrdinalIgnoreCase) != 0)
+ {
+ _instanceName = value;
Close();
}
}
/// <summary>
/// Returns true if counter is read only (system counter, foreign extensible counter or remote counter)
/// </summary>
- public bool ReadOnly {
- get {
- return isReadOnly;
+ public bool ReadOnly
+ {
+ get
+ {
+ return _isReadOnly;
}
- set {
- if (value != this.isReadOnly) {
- if(value == false) {
+ set
+ {
+ if (value != _isReadOnly)
+ {
+ if (value == false)
+ {
VerifyWriteableCounterAllowed();
}
- this.isReadOnly = value;
+ _isReadOnly = value;
Close();
}
}
/// <summary>
/// Set/returns the machine name for this performance counter
/// </summary>
- public string MachineName {
- get {
- return machineName;
+ public string MachineName
+ {
+ get
+ {
+ return _machineName;
}
- set {
+ set
+ {
if (!SyntaxCheck.CheckMachineName(value))
throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", value));
- if (machineName != value) {
- machineName = value;
+ if (_machineName != value)
+ {
+ _machineName = value;
Close();
}
}
/// the raw value is sufficient. Note that this only works for custom counters created using
/// this component, non-custom counters will throw an exception if this property is accessed.
/// </summary>
- public long RawValue {
- get {
- if (ReadOnly) {
+ public long RawValue
+ {
+ get
+ {
+ if (ReadOnly)
+ {
//No need to initialize or Demand, since NextSample already does.
return NextSample().RawValue;
}
- else {
+ else
+ {
Initialize();
- return this.sharedCounter.Value;
+ return _sharedCounter.Value;
}
}
- set {
+ set
+ {
if (ReadOnly)
ThrowReadOnly();
Initialize();
- this.sharedCounter.Value = value;
+ _sharedCounter.Value = value;
}
}
/// <summary>
/// </summary>
- public void BeginInit() {
- this.Close();
+ public void BeginInit()
+ {
+ Close();
}
/// <summary>
/// Frees all the resources allocated by this counter
/// </summary>
- public void Close() {
- this.helpMsg = null;
- this.oldSample = CounterSample.Empty;
- this.sharedCounter = null;
- this.initialized = false;
- this.counterType = -1;
+ public void Close()
+ {
+ _helpMsg = null;
+ _oldSample = CounterSample.Empty;
+ _sharedCounter = null;
+ _initialized = false;
+ _counterType = -1;
}
/// <summary>
/// counters, frees File Mapping used by extensible counters,
/// unloads dll's used to read counters.
/// </summary>
- public static void CloseSharedResources() {
+ public static void CloseSharedResources()
+ {
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, ".", "*");
permission.Demand();
PerformanceCounterLib.CloseAllLibraries();
/// <internalonly/>
/// <summary>
/// </summary>
- protected override void Dispose(bool disposing) {
+ protected override void Dispose(bool disposing)
+ {
// safe to call while finalizing or disposing
//
- if (disposing) {
+ if (disposing)
+ {
//Dispose managed and unmanaged resources
Close();
}
/// <summary>
/// Decrements counter by one using an efficient atomic operation.
/// </summary>
- public long Decrement() {
+ public long Decrement()
+ {
if (ReadOnly)
ThrowReadOnly();
Initialize();
- return this.sharedCounter.Decrement();
+ return _sharedCounter.Decrement();
}
/// <summary>
/// </summary>
- public void EndInit() {
+ public void EndInit()
+ {
Initialize();
}
/// the operation in case of multiple writers. This method should be used with caution because of the negative
/// impact on performance due to creation of the mutex.
/// </summary>
- public long IncrementBy(long value) {
- if (isReadOnly)
+ public long IncrementBy(long value)
+ {
+ if (_isReadOnly)
ThrowReadOnly();
Initialize();
- return this.sharedCounter.IncrementBy(value);
+ return _sharedCounter.IncrementBy(value);
}
/// <summary>
/// Increments counter by one using an efficient atomic operation.
/// </summary>
- public long Increment() {
- if (isReadOnly)
+ public long Increment()
+ {
+ if (_isReadOnly)
ThrowReadOnly();
Initialize();
- return this.sharedCounter.Increment();
+ return _sharedCounter.Increment();
}
- private void ThrowReadOnly() {
+ private void ThrowReadOnly()
+ {
throw new InvalidOperationException(SR.Format(SR.ReadOnlyCounter));
}
-
- private static void VerifyWriteableCounterAllowed() {
- if(EnvironmentHelpers.IsAppContainerProcess) {
+
+ private static void VerifyWriteableCounterAllowed()
+ {
+ if (EnvironmentHelpers.IsAppContainerProcess)
+ {
throw new NotSupportedException(SR.Format(SR.PCNotSupportedUnderAppContainer));
}
}
- private void Initialize() {
+ private void Initialize()
+ {
// Keep this method small so the JIT will inline it.
- if (!initialized && !DesignMode) {
+ if (!_initialized && !DesignMode)
+ {
InitializeImpl();
}
}
/// <summary>
/// Intializes required resources
/// </summary>
- private void InitializeImpl() {
+ private void InitializeImpl()
+ {
bool tookLock = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
Monitor.Enter(InstanceLockObject, ref tookLock);
- if (!initialized) {
- string currentCategoryName = categoryName;
- string currentMachineName = machineName;
+ if (!_initialized)
+ {
+ string currentCategoryName = _categoryName;
+ string currentMachineName = _machineName;
- if (currentCategoryName == String.Empty)
+ if (currentCategoryName == string.Empty)
throw new InvalidOperationException(SR.Format(SR.CategoryNameMissing));
- if (this.counterName == String.Empty)
+ if (_counterName == string.Empty)
throw new InvalidOperationException(SR.Format(SR.CounterNameMissing));
- if (this.ReadOnly) {
+ 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));
+ if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, _counterName))
+ throw new InvalidOperationException(SR.Format(SR.CounterExists, currentCategoryName, _counterName));
PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
- if (categoryType == PerformanceCounterCategoryType.MultiInstance) {
- if (String.IsNullOrEmpty(instanceName))
+ if (categoryType == PerformanceCounterCategoryType.MultiInstance)
+ {
+ if (string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
- } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) {
- if (!String.IsNullOrEmpty(instanceName))
+ }
+ else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
+ {
+ if (!string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
}
- if (instanceLifetime != PerformanceCounterInstanceLifetime.Global)
+ if (_instanceLifetime != PerformanceCounterInstanceLifetime.Global)
throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessonReadOnly));
- this.initialized = true;
- } else {
+ _initialized = true;
+ }
+ else
+ {
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, currentMachineName, currentCategoryName);
permission.Demand();
- if (currentMachineName != "." && String.Compare(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0)
+ if (currentMachineName != "." && string.Compare(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0)
throw new InvalidOperationException(SR.Format(SR.RemoteWriting));
SharedUtils.CheckNtEnvironment();
// check category type
PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
- if (categoryType == PerformanceCounterCategoryType.MultiInstance) {
- if (String.IsNullOrEmpty(instanceName))
+ if (categoryType == PerformanceCounterCategoryType.MultiInstance)
+ {
+ if (string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
- } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) {
- if (!String.IsNullOrEmpty(instanceName))
+ }
+ else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
+ {
+ if (!string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
}
- if (String.IsNullOrEmpty(instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
+ if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessforSingleInstance));
- this.sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), counterName.ToLower(CultureInfo.InvariantCulture), instanceName.ToLower(CultureInfo.InvariantCulture), instanceLifetime);
- this.initialized = true;
+ _sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), _counterName.ToLower(CultureInfo.InvariantCulture), _instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
+ _initialized = true;
}
}
- } finally {
+ }
+ finally
+ {
if (tookLock)
Monitor.Exit(InstanceLockObject);
}
}
- // Will cause an update, raw value
+ // Will cause an update, raw value
/// <summary>
/// Obtains a counter sample and returns the raw value for it.
/// </summary>
- public CounterSample NextSample() {
- string currentCategoryName = categoryName;
- string currentMachineName = machineName;
-
+ 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(this.counterName);
- this.counterType = counterSample.CounterType;
- if (!categorySample.IsMultiInstance) {
- if (instanceName != null && instanceName.Length != 0)
- throw new InvalidOperationException(SR.Format(SR.InstanceNameProhibited, this.instanceName));
+ CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
+ _counterType = counterSample._counterType;
+ if (!categorySample._isMultiInstance)
+ {
+ if (_instanceName != null && _instanceName.Length != 0)
+ throw new InvalidOperationException(SR.Format(SR.InstanceNameProhibited, _instanceName));
return counterSample.GetSingleValue();
}
- else {
- if (instanceName == null || instanceName.Length == 0)
+ else
+ {
+ if (_instanceName == null || _instanceName.Length == 0)
throw new InvalidOperationException(SR.Format(SR.InstanceNameRequired));
- return counterSample.GetInstanceValue(this.instanceName);
+ return counterSample.GetInstanceValue(_instanceName);
}
}
/// NOTE: For counters whose calculated value depend upon 2 counter reads,
/// the very first read will return 0.0.
/// </summary>
- public float NextValue() {
+ public float NextValue()
+ {
//No need to initialize or Demand, since NextSample already does.
CounterSample newSample = NextSample();
float retVal = 0.0f;
- retVal = CounterSample.Calculate(oldSample, newSample);
- oldSample = newSample;
+ retVal = CounterSample.Calculate(_oldSample, newSample);
+ _oldSample = newSample;
return retVal;
}
/// <summary>
/// Removes this counter instance from the shared memory
/// </summary>
- public void RemoveInstance() {
- if (isReadOnly)
+ public void RemoveInstance()
+ {
+ if (_isReadOnly)
throw new InvalidOperationException(SR.Format(SR.ReadOnlyRemoveInstance));
Initialize();
- sharedCounter.RemoveInstance(this.instanceName.ToLower(CultureInfo.InvariantCulture), instanceLifetime);
+ _sharedCounter.RemoveInstance(_instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System.Runtime.Serialization.Formatters;
- using System.ComponentModel;
- using System.Diagnostics;
- using System;
- using System.Threading;
- using System.Security;
- using System.Security.Permissions;
- using System.Collections;
- using Microsoft.Win32;
- using System.Globalization;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
-
+using System.ComponentModel;
+using System;
+using System.Threading;
+using System.Collections;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+
+namespace System.Diagnostics
+{
/// <summary>
/// A Performance counter category object.
/// </summary>
- public sealed class PerformanceCounterCategory {
- private string categoryName;
- private string categoryHelp;
- private string machineName;
- internal const int MaxCategoryNameLength = 80;
+ public sealed class PerformanceCounterCategory
+ {
+ private string _categoryName;
+ private string _categoryHelp;
+ private string _machineName;
+ internal const int MaxCategoryNameLength = 80;
internal const int MaxCounterNameLength = 32767;
internal const int MaxHelpLength = 32767;
- private const string perfMutexName = "netfxperf.1.0";
+ private const string PerfMutexName = "netfxperf.1.0";
- public PerformanceCounterCategory() {
- machineName = ".";
+ public PerformanceCounterCategory()
+ {
+ _machineName = ".";
}
/// <summary>
/// Uses the local machine.
/// </summary>
public PerformanceCounterCategory(string categoryName)
- : this(categoryName, ".") {
+ : this(categoryName, ".")
+ {
}
/// <summary>
/// Creates a PerformanceCounterCategory object for given category.
/// Uses the given machine name.
/// </summary>
- public PerformanceCounterCategory(string categoryName, string machineName) {
+ public PerformanceCounterCategory(string categoryName, string machineName)
+ {
if (categoryName == null)
throw new ArgumentNullException("categoryName");
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
permission.Demand();
- this.categoryName = categoryName;
- this.machineName = machineName;
- }
+ _categoryName = categoryName;
+ _machineName = machineName;
+ }
/// <summary>
/// Gets/sets the Category name
/// </summary>
- public string CategoryName {
- get {
- return categoryName;
+ public string CategoryName
+ {
+ get
+ {
+ return _categoryName;
}
- set {
+ set
+ {
if (value == null)
throw new ArgumentNullException("value");
// there lock prevents a race between setting CategoryName and MachineName, since this permission
// checks depend on both pieces of info.
- lock (this) {
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, value);
+ lock (this)
+ {
+ PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, _machineName, value);
permission.Demand();
- this.categoryName = value;
+ _categoryName = value;
}
}
}
/// <summary>
/// Gets/sets the Category help
/// </summary>
- public string CategoryHelp {
- get {
- if (this.categoryName == null)
+ public string CategoryHelp
+ {
+ get
+ {
+ if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
- if (categoryHelp == null)
- categoryHelp = PerformanceCounterLib.GetCategoryHelp(this.machineName, this.categoryName);
+ if (_categoryHelp == null)
+ _categoryHelp = PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName);
- return categoryHelp;
+ return _categoryHelp;
}
}
- public PerformanceCounterCategoryType CategoryType{
- get {
- CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);
+ public PerformanceCounterCategoryType CategoryType
+ {
+ get
+ {
+ CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName);
// If we get MultiInstance, we can be confident it is correct. If it is single instance, though
// we need to check if is a custom category and if the IsMultiInstance value is set in the registry.
// If not we return Unknown
- if (categorySample.IsMultiInstance)
+ if (categorySample._isMultiInstance)
return PerformanceCounterCategoryType.MultiInstance;
- else {
- if (PerformanceCounterLib.IsCustomCategory(".", categoryName))
- return PerformanceCounterLib.GetCategoryType(".", categoryName);
+ else
+ {
+ if (PerformanceCounterLib.IsCustomCategory(".", _categoryName))
+ return PerformanceCounterLib.GetCategoryType(".", _categoryName);
else
return PerformanceCounterCategoryType.SingleInstance;
}
}
}
-
+
/// <summary>
/// Gets/sets the Machine name
/// </summary>
- public string MachineName {
- get {
- return machineName;
+ public string MachineName
+ {
+ get
+ {
+ return _machineName;
}
- set {
+ set
+ {
if (!SyntaxCheck.CheckMachineName(value))
throw new ArgumentException(SR.Format(SR.InvalidProperty, "MachineName", value));
// there lock prevents a race between setting CategoryName and MachineName, since this permission
// checks depend on both pieces of info.
- lock (this) {
- if (categoryName != null) {
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, value, categoryName);
+ lock (this)
+ {
+ if (_categoryName != null)
+ {
+ PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, value, _categoryName);
permission.Demand();
}
- machineName = value;
+ _machineName = value;
}
}
}
/// <summary>
/// Returns true if the counter is registered for this category
/// </summary>
- public bool CounterExists(string counterName) {
+ public bool CounterExists(string counterName)
+ {
if (counterName == null)
throw new ArgumentNullException("counterName");
- if (this.categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ if (_categoryName == null)
+ throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
- return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName);
+ return PerformanceCounterLib.CounterExists(_machineName, _categoryName, counterName);
}
/// <summary>
/// Returns true if the counter is registered for this category on the current machine.
/// </summary>
- public static bool CounterExists(string counterName, string categoryName) {
+ public static bool CounterExists(string counterName, string categoryName)
+ {
return CounterExists(counterName, categoryName, ".");
}
/// <summary>
/// Returns true if the counter is registered for this category on a particular machine.
/// </summary>
- public static bool CounterExists(string counterName, string categoryName, string machineName) {
+ public static bool CounterExists(string counterName, string categoryName, string machineName)
+ {
if (counterName == null)
throw new ArgumentNullException("counterName");
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName));
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
+ PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
permission.Demand();
return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName);
- }
+ }
/// <summary>
/// Registers one extensible performance category of type NumberOfItems32 with the system
/// </summary>
[Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp) {
+ public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp)
+ {
CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32);
- return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, new CounterCreationDataCollection(new CounterCreationData [] {customData}));
+ return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, new CounterCreationDataCollection(new CounterCreationData[] { customData }));
}
- public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) {
+ public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp)
+ {
CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32);
- return Create(categoryName, categoryHelp, categoryType, new CounterCreationDataCollection(new CounterCreationData [] {customData}));
+ return Create(categoryName, categoryHelp, categoryType, new CounterCreationDataCollection(new CounterCreationData[] { customData }));
}
/// <summary>
/// Registers the extensible performance category with the system on the local machine
/// </summary>
[Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData) {
+ public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData)
+ {
return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, counterData);
}
- public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) {
+ public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData)
+ {
if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
throw new ArgumentOutOfRangeException("categoryType");
if (counterData == null)
throw new ArgumentNullException("counterData");
CheckValidCategory(categoryName);
- if (categoryHelp != null) {
+ if (categoryHelp != null)
+ {
// null categoryHelp is a valid option - it gets set to "Help Not Available" later on.
CheckValidHelp(categoryHelp);
}
string machineName = ".";
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
+ PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
permission.Demand();
SharedUtils.CheckNtEnvironment();
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- SharedUtils.EnterMutex(perfMutexName, ref mutex);
- if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName , categoryName))
+ try
+ {
+ SharedUtils.EnterMutex(PerfMutexName, ref mutex);
+ if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName))
throw new InvalidOperationException(SR.Format(SR.PerformanceCategoryExists, categoryName));
CheckValidCounterLayout(counterData);
PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData);
return new PerformanceCounterCategory(categoryName, machineName);
}
- finally {
- if (mutex != null) {
+ finally
+ {
+ if (mutex != null)
+ {
mutex.ReleaseMutex();
mutex.Close();
}
}
// there is an idential copy of CheckValidCategory in PerformnaceCounterInstaller
- internal static void CheckValidCategory(string categoryName) {
+ internal static void CheckValidCategory(string categoryName)
+ {
if (categoryName == null)
throw new ArgumentNullException("categoryName");
throw new ArgumentException(SR.Format(SR.CategoryNameTooLong));
}
- internal static void CheckValidCounter(string counterName) {
+ internal static void CheckValidCounter(string counterName)
+ {
if (counterName == null)
throw new ArgumentNullException("counterName");
}
// there is an idential copy of CheckValidId in PerformnaceCounterInstaller
- internal static bool CheckValidId(string id, int maxLength) {
+ internal static bool CheckValidId(string id, int maxLength)
+ {
if (id.Length == 0 || id.Length > maxLength)
return false;
- for (int index = 0; index < id.Length; ++index) {
+ for (int index = 0; index < id.Length; ++index)
+ {
char current = id[index];
- if ((index == 0 || index == (id.Length -1)) && current == ' ')
+ if ((index == 0 || index == (id.Length - 1)) && current == ' ')
return false;
if (current == '\"')
return true;
}
- internal static void CheckValidHelp(string help) {
+ internal static void CheckValidHelp(string help)
+ {
if (help == null)
throw new ArgumentNullException("help");
if (help.Length > MaxHelpLength)
throw new ArgumentException(SR.Format(SR.PerfInvalidHelp, 0, MaxHelpLength));
}
- internal static void CheckValidCounterLayout(CounterCreationDataCollection counterData) {
+ internal static void CheckValidCounterLayout(CounterCreationDataCollection counterData)
+ {
// Ensure that there are no duplicate counter names being created
Hashtable h = new Hashtable();
- for (int i = 0; i < counterData.Count; i++) {
- if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0) {
+ for (int i = 0; i < counterData.Count; i++)
+ {
+ if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0)
+ {
throw new ArgumentException(SR.Format(SR.InvalidCounterName));
}
-
+
int currentSampleType = (int)counterData[i].CounterType;
- if ( (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) ||
- (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) ||
- (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) ||
- (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) ||
- (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) ||
- (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) ||
- (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) ||
- (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER)) {
-
+ if ((currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) ||
+ (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) ||
+ (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) ||
+ (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) ||
+ (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) ||
+ (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) ||
+ (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) ||
+ (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER))
+ {
+
if (counterData.Count <= (i + 1))
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
- else {
+ else
+ {
currentSampleType = (int)counterData[i + 1].CounterType;
-
-
+
+
if (!PerformanceCounterLib.IsBaseCounter(currentSampleType))
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
}
}
- else if (PerformanceCounterLib.IsBaseCounter(currentSampleType)) {
+ else if (PerformanceCounterLib.IsBaseCounter(currentSampleType))
+ {
if (i == 0)
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
- else {
+ else
+ {
currentSampleType = (int)counterData[i - 1].CounterType;
-
+
if (
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) &&
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) &&
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) &&
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) &&
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) &&
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) &&
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) &&
- (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER))
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) &&
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) &&
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) &&
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) &&
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) &&
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) &&
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) &&
+ (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER))
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
}
-
+
}
-
- if (h.ContainsKey(counterData[i].CounterName)) {
+
+ if (h.ContainsKey(counterData[i].CounterName))
+ {
throw new ArgumentException(SR.Format(SR.DuplicateCounterName, counterData[i].CounterName));
}
- else {
- h.Add(counterData[i].CounterName, String.Empty);
-
+ else
+ {
+ h.Add(counterData[i].CounterName, string.Empty);
+
// Ensure that all counter help strings aren't null or empty
- if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0) {
+ if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0)
+ {
counterData[i].CounterHelp = counterData[i].CounterName;
}
}
}
- }
+ }
/// <summary>
/// Removes the counter (category) from the system
/// </summary>
- public static void Delete(string categoryName) {
+ public static void Delete(string categoryName)
+ {
CheckValidCategory(categoryName);
string machineName = ".";
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
+ PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
permission.Demand();
SharedUtils.CheckNtEnvironment();
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- SharedUtils.EnterMutex(perfMutexName, ref mutex);
+ try
+ {
+ SharedUtils.EnterMutex(PerfMutexName, ref mutex);
if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
throw new InvalidOperationException(SR.Format(SR.CantDeleteCategory));
SharedPerformanceCounter.RemoveAllInstances(categoryName);
-
+
PerformanceCounterLib.UnregisterCategory(categoryName);
PerformanceCounterLib.CloseAllLibraries();
}
- finally {
- if (mutex != null) {
+ finally
+ {
+ if (mutex != null)
+ {
mutex.ReleaseMutex();
mutex.Close();
}
/// <summary>
/// Returns true if the category is registered on the current machine.
/// </summary>
- public static bool Exists(string categoryName) {
+ public static bool Exists(string categoryName)
+ {
return Exists(categoryName, ".");
}
/// <summary>
/// Returns true if the category is registered in the machine.
/// </summary>
- public static bool Exists(string categoryName, string machineName) {
+ public static bool Exists(string categoryName, string machineName)
+ {
if (categoryName == null)
throw new ArgumentNullException("categoryName");
throw new ArgumentException(SR.Format(SR.InvalidParameter, "categoryName", categoryName));
if (!SyntaxCheck.CheckMachineName(machineName))
- throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName));
+ throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName));
- PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
+ PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
permission.Demand();
- if (PerformanceCounterLib.IsCustomCategory(machineName , categoryName))
+ if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
return true;
- return PerformanceCounterLib.CategoryExists(machineName , categoryName);
+ return PerformanceCounterLib.CategoryExists(machineName, categoryName);
}
/// <summary>
/// Returns the instance names for a given category
/// </summary>
/// <internalonly/>
- internal static string[] GetCounterInstances(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)
+ if (categorySample._instanceNameTable.Count == 0)
return new string[0];
- string[] instanceNames = new string[categorySample.InstanceNameTable.Count];
- categorySample.InstanceNameTable.Keys.CopyTo(instanceNames, 0);
+ string[] instanceNames = new string[categorySample._instanceNameTable.Count];
+ categorySample._instanceNameTable.Keys.CopyTo(instanceNames, 0);
if (instanceNames.Length == 1 && instanceNames[0].CompareTo(PerformanceCounterLib.SingleInstanceName) == 0)
return new string[0];
/// <summary>
/// Returns an array of counters in this category. The counter must have only one instance.
/// </summary>
- public PerformanceCounter[] GetCounters() {
+ public PerformanceCounter[] GetCounters()
+ {
if (GetInstanceNames().Length != 0)
throw new ArgumentException(SR.Format(SR.InstanceNameRequired));
return GetCounters("");
/// <summary>
/// Returns an array of counters in this category for the given instance.
/// </summary>
- public PerformanceCounter[] GetCounters(string instanceName) {
+ public PerformanceCounter[] GetCounters(string instanceName)
+ {
if (instanceName == null)
throw new ArgumentNullException("instanceName");
- if (this.categoryName == null)
+ if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
if (instanceName.Length != 0 && !InstanceExists(instanceName))
- throw new InvalidOperationException(SR.Format(SR.MissingInstance, instanceName, categoryName));
+ throw new InvalidOperationException(SR.Format(SR.MissingInstance, instanceName, _categoryName));
- string[] counterNames = PerformanceCounterLib.GetCounters(machineName, categoryName);
+ string[] counterNames = PerformanceCounterLib.GetCounters(_machineName, _categoryName);
PerformanceCounter[] counters = new PerformanceCounter[counterNames.Length];
for (int index = 0; index < counters.Length; index++)
- counters[index] = new PerformanceCounter(categoryName, counterNames[index], instanceName, machineName, true);
+ counters[index] = new PerformanceCounter(_categoryName, counterNames[index], instanceName, _machineName, true);
return counters;
}
/// <summary>
/// Returns an array of performance counter categories for the current machine.
/// </summary>
- public static PerformanceCounterCategory[] GetCategories() {
+ public static PerformanceCounterCategory[] GetCategories()
+ {
return GetCategories(".");
}
/// <summary>
/// Returns an array of performance counter categories for a particular machine.
/// </summary>
- public static PerformanceCounterCategory[] GetCategories(string machineName) {
+ public static PerformanceCounterCategory[] GetCategories(string machineName)
+ {
if (!SyntaxCheck.CheckMachineName(machineName))
- throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName));
+ throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName));
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, "*");
permission.Demand();
/// <summary>
/// Returns an array of instances for this category
/// </summary>
- public string[] GetInstanceNames() {
- if (this.categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ public string[] GetInstanceNames()
+ {
+ if (_categoryName == null)
+ throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
- return GetCounterInstances(categoryName, machineName);
+ return GetCounterInstances(_categoryName, _machineName);
}
/// <summary>
/// Returns true if the instance already exists for this category.
/// </summary>
- public bool InstanceExists(string instanceName) {
+ public bool InstanceExists(string instanceName)
+ {
if (instanceName == null)
throw new ArgumentNullException("instanceName");
- if (this.categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ if (_categoryName == null)
+ throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
- CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);
- return categorySample.InstanceNameTable.ContainsKey(instanceName);
+ CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName);
+ return categorySample._instanceNameTable.ContainsKey(instanceName);
}
/// <summary>
/// Returns true if the instance already exists for the category specified.
/// </summary>
- public static bool InstanceExists(string instanceName, string categoryName) {
+ public static bool InstanceExists(string instanceName, string categoryName)
+ {
return InstanceExists(instanceName, categoryName, ".");
}
/// <summary>
/// Returns true if the instance already exists for this category and machine specified.
/// </summary>
- public static bool InstanceExists(string instanceName, string categoryName, string machineName) {
+ public static bool InstanceExists(string instanceName, string categoryName, string machineName)
+ {
if (instanceName == null)
throw new ArgumentNullException("instanceName");
/// Reads all the counter and instance data of this performance category. Note that reading the entire category
/// at once can be as efficient as reading a single counter because of the way the system provides the data.
/// </summary>
- public InstanceDataCollectionCollection ReadCategory() {
- if (this.categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ public InstanceDataCollectionCollection ReadCategory()
+ {
+ if (_categoryName == null)
+ throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
- CategorySample categorySample = PerformanceCounterLib.GetCategorySample(this.machineName, this.categoryName);
+ CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName);
return categorySample.ReadCategory();
}
}
[Flags]
- internal enum PerformanceCounterCategoryOptions {
+ internal enum PerformanceCounterCategoryOptions
+ {
EnableReuse = 0x1,
UseUniqueSharedMemory = 0x2,
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- public enum PerformanceCounterCategoryType {
+namespace System.Diagnostics
+{
+ public enum PerformanceCounterCategoryType
+ {
Unknown = -1,
SingleInstance = 0,
MultiInstance = 1
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- public enum PerformanceCounterInstanceLifetime {
+namespace System.Diagnostics
+{
+ public enum PerformanceCounterInstanceLifetime
+ {
Global = 0,
Process = 1
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System.Runtime.InteropServices;
- using System.Globalization;
- using System.Security.Permissions;
- using System.Security;
- using System.Text;
- using System.Threading;
- using System.Reflection;
- using System.Collections;
- using System.ComponentModel;
- using System.Collections.Specialized;
- using Microsoft.Win32;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
-
- internal class PerformanceCounterLib {
+using System.Runtime.InteropServices;
+using System.Globalization;
+using System.Security.Permissions;
+using System.Security;
+using System.Text;
+using System.Threading;
+using System.Collections;
+using System.ComponentModel;
+using Microsoft.Win32;
+using System.IO;
+
+namespace System.Diagnostics
+{
+ internal class PerformanceCounterLib
+ {
internal const string PerfShimName = "netfxperf.dll";
- private const string PerfShimFullNameSuffix = @"\netfxperf.dll";
- private const string PerfShimPathExp = @"%systemroot%\system32\netfxperf.dll";
+ private const string PerfShimFullNameSuffix = @"\netfxperf.dll";
+ private const string PerfShimPathExp = @"%systemroot%\system32\netfxperf.dll";
internal const string OpenEntryPoint = "OpenPerformanceData";
internal const string CollectEntryPoint = "CollectPerformanceData";
internal const string CloseEntryPoint = "ClosePerformanceData";
private const string PerflibPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib";
internal const string ServicePath = "SYSTEM\\CurrentControlSet\\Services";
- private const string categorySymbolPrefix = "OBJECT_";
- private const string conterSymbolPrefix = "DEVICE_COUNTER_";
- private const string helpSufix = "_HELP";
- private const string nameSufix = "_NAME";
- private const string textDefinition = "[text]";
- private const string infoDefinition = "[info]";
- private const string languageDefinition = "[languages]";
- private const string objectDefinition = "[objects]";
- private const string driverNameKeyword = "drivername";
- private const string symbolFileKeyword = "symbolfile";
- private const string defineKeyword = "#define";
- private const string languageKeyword = "language";
+ private const string CategorySymbolPrefix = "OBJECT_";
+ private const string ConterSymbolPrefix = "DEVICE_COUNTER_";
+ private const string HelpSufix = "_HELP";
+ private const string NameSufix = "_NAME";
+ private const string TextDefinition = "[text]";
+ private const string InfoDefinition = "[info]";
+ private const string LanguageDefinition = "[languages]";
+ private const string ObjectDefinition = "[objects]";
+ private const string DriverNameKeyword = "drivername";
+ private const string SymbolFileKeyword = "symbolfile";
+ private const string DefineKeyword = "#define";
+ private const string LanguageKeyword = "language";
private const string DllName = "netfxperf.dll";
private const int EnglishLCID = 0x009;
- private static volatile string computerName;
- private static volatile string iniFilePath;
- private static volatile string symbolFilePath;
-
- private PerformanceMonitor performanceMonitor;
- private string machineName;
- private string perfLcid;
-
- private Hashtable customCategoryTable;
- private static volatile Hashtable libraryTable;
- private Hashtable categoryTable;
- private Hashtable nameTable;
- private Hashtable helpTable;
- private readonly object CategoryTableLock = new Object();
- private readonly object NameTableLock = new Object();
- private readonly object HelpTableLock = new Object();
-
- private static Object s_InternalSyncObject;
- private static Object InternalSyncObject {
- get {
- if (s_InternalSyncObject == null) {
+ private static volatile string s_computerName;
+ private static volatile string s_iniFilePath;
+ private static volatile string s_symbolFilePath;
+
+ private PerformanceMonitor _performanceMonitor;
+ private string _machineName;
+ private string _perfLcid;
+
+ private Hashtable _customCategoryTable;
+ private static volatile Hashtable s_libraryTable;
+ private Hashtable _categoryTable;
+ private Hashtable _nameTable;
+ private Hashtable _helpTable;
+ private readonly object _categoryTableLock = new Object();
+ private readonly object _nameTableLock = new Object();
+ private readonly object _helpTableLock = new Object();
+
+ private static Object s_internalSyncObject;
+ private static Object InternalSyncObject
+ {
+ get
+ {
+ if (s_internalSyncObject == null)
+ {
Object o = new Object();
- Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
+ Interlocked.CompareExchange(ref s_internalSyncObject, o, null);
}
- return s_InternalSyncObject;
+ return s_internalSyncObject;
}
}
- internal PerformanceCounterLib(string machineName, string lcid) {
- this.machineName = machineName;
- this.perfLcid = lcid;
+ internal PerformanceCounterLib(string machineName, string lcid)
+ {
+ _machineName = machineName;
+ _perfLcid = lcid;
}
/// <internalonly/>
- internal static string ComputerName {
- get {
- if (computerName == null) {
- lock (InternalSyncObject) {
- if (computerName == null) {
+ internal static string ComputerName
+ {
+ get
+ {
+ if (s_computerName == null)
+ {
+ lock (InternalSyncObject)
+ {
+ if (s_computerName == null)
+ {
StringBuilder sb = new StringBuilder(256);
- SafeNativeMethods.GetComputerName(sb, new int[] {sb.Capacity});
- computerName = sb.ToString();
+ Interop.Kernel32.GetComputerName(sb, new int[] { sb.Capacity });
+ s_computerName = sb.ToString();
}
}
}
- return computerName;
+ return s_computerName;
}
}
- private unsafe Hashtable CategoryTable {
- get {
- if (this.categoryTable == null) {
- lock (this.CategoryTableLock) {
- if (this.categoryTable == null) {
- byte[] perfData = GetPerformanceData("Global");
-
- fixed (byte* perfDataPtr = perfData) {
- IntPtr dataRef = new IntPtr( (void*) perfDataPtr);
+ private unsafe Hashtable CategoryTable
+ {
+ get
+ {
+ if (_categoryTable == null)
+ {
+ lock (_categoryTableLock)
+ {
+ if (_categoryTable == null)
+ {
+ byte[] perfData = GetPerformanceData("Global");
+
+ fixed (byte* perfDataPtr = perfData)
+ {
+ IntPtr dataRef = new IntPtr((void*)perfDataPtr);
Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataRef, dataBlock);
dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength);
// of the perf data. (ASURT 137097)
long endPerfData = (long)(new IntPtr((void*)perfDataPtr)) + dataBlock.TotalByteLength;
Hashtable tempCategoryTable = new Hashtable(categoryNumber, StringComparer.OrdinalIgnoreCase);
- for (int index = 0; index < categoryNumber && ((long) dataRef < endPerfData); index++) {
+ for (int index = 0; index < categoryNumber && ((long)dataRef < endPerfData); index++)
+ {
Interop.Advapi32.PERF_OBJECT_TYPE perfObject = new Interop.Advapi32.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(dataRef, perfObject);
CategoryEntry newCategoryEntry = new CategoryEntry(perfObject);
- IntPtr nextRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength);
+ IntPtr nextRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength);
dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength);
int index3 = 0;
int previousCounterIndex = -1;
//Need to filter out counters that are repeated, some providers might
//return several adyacent copies of the same counter.
- for (int index2 = 0; index2 < newCategoryEntry.CounterIndexes.Length; ++ index2) {
+ for (int index2 = 0; index2 < newCategoryEntry.CounterIndexes.Length; ++index2)
+ {
Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter = new Interop.Advapi32.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(dataRef, perfCounter);
- if (perfCounter.CounterNameTitleIndex != previousCounterIndex) {
- newCategoryEntry.CounterIndexes[index3] = perfCounter.CounterNameTitleIndex;
+ if (perfCounter.CounterNameTitleIndex != previousCounterIndex)
+ {
+ newCategoryEntry.CounterIndexes[index3] = perfCounter.CounterNameTitleIndex;
newCategoryEntry.HelpIndexes[index3] = perfCounter.CounterHelpTitleIndex;
previousCounterIndex = perfCounter.CounterNameTitleIndex;
- ++ index3;
+ ++index3;
}
dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength);
}
//Lets adjust the entry counter arrays in case there were repeated copies
- if (index3 < newCategoryEntry.CounterIndexes.Length) {
+ if (index3 < newCategoryEntry.CounterIndexes.Length)
+ {
int[] adjustedCounterIndexes = new int[index3];
int[] adjustedHelpIndexes = new int[index3];
Array.Copy(newCategoryEntry.CounterIndexes, adjustedCounterIndexes, index3);
newCategoryEntry.HelpIndexes = adjustedHelpIndexes;
}
- string categoryName = (string)this.NameTable[newCategoryEntry.NameIndex];
+ string categoryName = (string)NameTable[newCategoryEntry.NameIndex];
if (categoryName != null)
tempCategoryTable[categoryName] = newCategoryEntry;
dataRef = nextRef;
}
- this.categoryTable = tempCategoryTable;
+ _categoryTable = tempCategoryTable;
}
}
}
}
- return this.categoryTable;
+ return _categoryTable;
}
}
- internal Hashtable HelpTable {
- get {
- if (this.helpTable == null) {
- lock(this.HelpTableLock) {
- if (this.helpTable == null)
- this.helpTable = GetStringTable(true);
+ internal Hashtable HelpTable
+ {
+ get
+ {
+ if (_helpTable == null)
+ {
+ lock (_helpTableLock)
+ {
+ if (_helpTable == null)
+ _helpTable = GetStringTable(true);
}
}
- return this.helpTable;
+ return _helpTable;
}
}
// Returns a temp file name
- private static string IniFilePath {
- get {
- if (iniFilePath == null) {
- lock (InternalSyncObject) {
- if (iniFilePath == null) {
+ private static string IniFilePath
+ {
+ get
+ {
+ if (s_iniFilePath == null)
+ {
+ lock (InternalSyncObject)
+ {
+ 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 {
- iniFilePath = Path.GetTempFileName();
+ try
+ {
+ s_iniFilePath = Path.GetTempFileName();
}
- finally {
- EnvironmentPermission.RevertAssert();
+ finally
+ {
+ EnvironmentPermission.RevertAssert();
}
}
}
}
- return iniFilePath;
+ return s_iniFilePath;
}
}
- internal Hashtable NameTable {
- get {
- if (this.nameTable == null) {
- lock(this.NameTableLock) {
- if (this.nameTable == null)
- this.nameTable = GetStringTable(false);
+ internal Hashtable NameTable
+ {
+ get
+ {
+ if (_nameTable == null)
+ {
+ lock (_nameTableLock)
+ {
+ if (_nameTable == null)
+ _nameTable = GetStringTable(false);
}
}
- return this.nameTable;
+ return _nameTable;
}
}
// Returns a temp file name
- private static string SymbolFilePath {
- get {
- if (symbolFilePath == null) {
- lock (InternalSyncObject) {
- if (symbolFilePath == null) {
+ private static string SymbolFilePath
+ {
+ get
+ {
+ if (s_symbolFilePath == null)
+ {
+ lock (InternalSyncObject)
+ {
+ if (s_symbolFilePath == null)
+ {
string tempPath;
-
+
EnvironmentPermission environmentPermission = new EnvironmentPermission(PermissionState.Unrestricted);
environmentPermission.Assert();
tempPath = Path.GetTempPath();
ps.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, tempPath));
ps.Assert();
- try {
- symbolFilePath = Path.GetTempFileName();
+ try
+ {
+ s_symbolFilePath = Path.GetTempFileName();
}
- finally {
- PermissionSet.RevertAssert();
+ finally
+ {
+ PermissionSet.RevertAssert();
}
}
}
}
- return symbolFilePath;
+ return s_symbolFilePath;
}
}
- internal static bool CategoryExists(string machine, string category) {
+ internal static bool CategoryExists(string machine, string category)
+ {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
- if (library.CategoryExists(category))
+ if (library.CategoryExists(category))
return true;
- if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
if (library.CategoryExists(category))
return true;
return false;
}
- internal bool CategoryExists(string category) {
+ internal bool CategoryExists(string category)
+ {
return CategoryTable.ContainsKey(category);
}
- internal static void CloseAllLibraries() {
- if (libraryTable != null) {
- foreach (PerformanceCounterLib library in libraryTable.Values)
+ internal static void CloseAllLibraries()
+ {
+ if (s_libraryTable != null)
+ {
+ foreach (PerformanceCounterLib library in s_libraryTable.Values)
library.Close();
- libraryTable = null;
+ s_libraryTable = null;
}
}
- internal static void CloseAllTables() {
- if (libraryTable != null) {
- foreach (PerformanceCounterLib library in libraryTable.Values)
+ internal static void CloseAllTables()
+ {
+ if (s_libraryTable != null)
+ {
+ foreach (PerformanceCounterLib library in s_libraryTable.Values)
library.CloseTables();
}
}
- internal void CloseTables() {
- this.nameTable = null;
- this.helpTable = null;
- this.categoryTable = null;
- this.customCategoryTable = null;
+ internal void CloseTables()
+ {
+ _nameTable = null;
+ _helpTable = null;
+ _categoryTable = null;
+ _customCategoryTable = null;
}
- internal void Close() {
- if (this.performanceMonitor != null) {
- this.performanceMonitor.Close();
- this.performanceMonitor = null;
+ internal void Close()
+ {
+ if (_performanceMonitor != null)
+ {
+ _performanceMonitor.Close();
+ _performanceMonitor = null;
}
CloseTables();
}
- internal static bool CounterExists(string machine, string category, string counter) {
+ internal static bool CounterExists(string machine, string category, string counter)
+ {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
bool categoryExists = false;
bool counterExists = library.CounterExists(category, counter, ref categoryExists);
- if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
counterExists = library.CounterExists(category, counter, ref categoryExists);
if (counterExists)
}
}
- if (!categoryExists) {
+ if (!categoryExists)
+ {
// Consider adding diagnostic logic here, may be we can dump the nameTable...
throw new InvalidOperationException(SR.Format(SR.MissingCategory));
}
return counterExists;
}
- private bool CounterExists(string category, string counter, ref bool categoryExists) {
+ private bool CounterExists(string category, string counter, ref bool categoryExists)
+ {
categoryExists = false;
if (!CategoryTable.ContainsKey(category))
return false;
else
categoryExists = true;
- CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
- for (int index = 0; index < entry.CounterIndexes.Length; ++ index) {
+ CategoryEntry entry = (CategoryEntry)CategoryTable[category];
+ for (int index = 0; index < entry.CounterIndexes.Length; ++index)
+ {
int counterIndex = entry.CounterIndexes[index];
- string counterName = (string)this.NameTable[counterIndex];
+ string counterName = (string)NameTable[counterIndex];
if (counterName == null)
- counterName = String.Empty;
+ counterName = string.Empty;
- if (String.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0)
+ if (string.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
return false;
}
- private static void CreateIniFile(string categoryName, string categoryHelp, CounterCreationDataCollection creationData, string[] languageIds) {
+ 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 {
+ try
+ {
StreamWriter iniWriter = new StreamWriter(IniFilePath, false, Encoding.Unicode);
- try {
+ try
+ {
//NT4 won't be able to parse Unicode ini files without this
//extra white space.
iniWriter.WriteLine("");
- iniWriter.WriteLine(infoDefinition);
- iniWriter.Write(driverNameKeyword);
+ iniWriter.WriteLine(InfoDefinition);
+ iniWriter.Write(DriverNameKeyword);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
- iniWriter.Write(symbolFileKeyword);
+ iniWriter.Write(SymbolFileKeyword);
iniWriter.Write("=");
iniWriter.WriteLine(Path.GetFileName(SymbolFilePath));
iniWriter.WriteLine("");
- iniWriter.WriteLine(languageDefinition);
- foreach (string languageId in languageIds) {
+ iniWriter.WriteLine(LanguageDefinition);
+ foreach (string languageId in languageIds)
+ {
iniWriter.Write(languageId);
iniWriter.Write("=");
- iniWriter.Write(languageKeyword);
+ iniWriter.Write(LanguageKeyword);
iniWriter.WriteLine(languageId);
}
iniWriter.WriteLine("");
- iniWriter.WriteLine(objectDefinition);
- foreach (string languageId in languageIds) {
- iniWriter.Write(categorySymbolPrefix);
+ iniWriter.WriteLine(ObjectDefinition);
+ foreach (string languageId in languageIds)
+ {
+ iniWriter.Write(CategorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
- iniWriter.Write(nameSufix);
+ iniWriter.Write(NameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
}
iniWriter.WriteLine("");
- iniWriter.WriteLine(textDefinition);
- foreach (string languageId in languageIds) {
- iniWriter.Write(categorySymbolPrefix);
+ iniWriter.WriteLine(TextDefinition);
+ foreach (string languageId in languageIds)
+ {
+ iniWriter.Write(CategorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
- iniWriter.Write(nameSufix);
+ iniWriter.Write(NameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
- iniWriter.Write(categorySymbolPrefix);
+ iniWriter.Write(CategorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
- iniWriter.Write(helpSufix);
+ iniWriter.Write(HelpSufix);
iniWriter.Write("=");
- if (categoryHelp == null || categoryHelp == String.Empty)
+ if (categoryHelp == null || categoryHelp == string.Empty)
iniWriter.WriteLine(SR.Format(SR.HelpNotAvailable));
else
iniWriter.WriteLine(categoryHelp);
int counterIndex = 0;
- foreach (CounterCreationData counterData in creationData) {
+ foreach (CounterCreationData counterData in creationData)
+ {
++counterIndex;
iniWriter.WriteLine("");
- iniWriter.Write(conterSymbolPrefix);
+ iniWriter.Write(ConterSymbolPrefix);
iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
iniWriter.Write("_");
iniWriter.Write(languageId);
- iniWriter.Write(nameSufix);
+ iniWriter.Write(NameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(counterData.CounterName);
- iniWriter.Write(conterSymbolPrefix);
+ iniWriter.Write(ConterSymbolPrefix);
iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
iniWriter.Write("_");
iniWriter.Write(languageId);
- iniWriter.Write(helpSufix);
+ iniWriter.Write(HelpSufix);
iniWriter.Write("=");
- Debug.Assert(!String.IsNullOrEmpty(counterData.CounterHelp), "CounterHelp should have been fixed up by the caller");
+ Debug.Assert(!string.IsNullOrEmpty(counterData.CounterHelp), "CounterHelp should have been fixed up by the caller");
iniWriter.WriteLine(counterData.CounterHelp);
}
}
iniWriter.WriteLine("");
}
- finally {
+ finally
+ {
iniWriter.Close();
}
}
- finally {
+ finally
+ {
FileIOPermission.RevertAssert();
}
}
- private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered) {
+ private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered)
+ {
RegistryKey serviceParentKey = null;
RegistryKey serviceKey = null;
RegistryKey linkageKey = null;
// we can therefore assert the RegistryPermission.
RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
registryPermission.Assert();
- try {
+ try
+ {
serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true);
if (serviceKey == null)
serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance");
- serviceKey.SetValue("Open","OpenPerformanceData");
+ serviceKey.SetValue("Open", "OpenPerformanceData");
serviceKey.SetValue("Collect", "CollectPerformanceData");
- serviceKey.SetValue("Close","ClosePerformanceData");
+ serviceKey.SetValue("Close", "ClosePerformanceData");
serviceKey.SetValue("Library", DllName);
- serviceKey.SetValue("IsMultiInstance", (int) categoryType, RegistryValueKind.DWord);
+ serviceKey.SetValue("IsMultiInstance", (int)categoryType, RegistryValueKind.DWord);
serviceKey.SetValue("CategoryOptions", 0x3, RegistryValueKind.DWord);
- string [] counters = new string[creationData.Count];
- string [] counterTypes = new string[creationData.Count];
- for (int i = 0; i < creationData.Count; i++) {
+ string[] counters = new string[creationData.Count];
+ string[] counterTypes = new string[creationData.Count];
+ for (int i = 0; i < creationData.Count; i++)
+ {
counters[i] = creationData[i].CounterName;
- counterTypes[i] = ((int) creationData[i].CounterType).ToString(CultureInfo.InvariantCulture);
+ counterTypes[i] = ((int)creationData[i].CounterType).ToString(CultureInfo.InvariantCulture);
}
- linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage" , true);
+ linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage", true);
if (linkageKey == null)
- linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage" );
+ linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage");
- linkageKey.SetValue("Export", new string[]{categoryName});
+ linkageKey.SetValue("Export", new string[] { categoryName });
- serviceKey.SetValue("Counter Types", (object) counterTypes);
- serviceKey.SetValue("Counter Names", (object) counters);
+ serviceKey.SetValue("Counter Types", (object)counterTypes);
+ serviceKey.SetValue("Counter Names", (object)counters);
object firstID = serviceKey.GetValue("First Counter");
if (firstID != null)
- iniRegistered = true;
+ iniRegistered = true;
else
- iniRegistered = false;
+ iniRegistered = false;
}
- finally {
+ finally
+ {
if (serviceKey != null)
serviceKey.Close();
}
}
- private static void CreateSymbolFile(CounterCreationDataCollection creationData) {
+ private static void CreateSymbolFile(CounterCreationDataCollection creationData)
+ {
//SECREVIEW: PerformanceCounterPermission must have been demanded before
FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
permission.Assert();
- try {
+ try
+ {
StreamWriter symbolWriter = new StreamWriter(SymbolFilePath);
- try {
- symbolWriter.Write(defineKeyword);
+ try
+ {
+ symbolWriter.Write(DefineKeyword);
symbolWriter.Write(" ");
- symbolWriter.Write(categorySymbolPrefix);
+ symbolWriter.Write(CategorySymbolPrefix);
symbolWriter.WriteLine("1 0;");
- for (int counterIndex = 1; counterIndex <= creationData.Count; ++ counterIndex) {
- symbolWriter.Write(defineKeyword);
+ for (int counterIndex = 1; counterIndex <= creationData.Count; ++counterIndex)
+ {
+ symbolWriter.Write(DefineKeyword);
symbolWriter.Write(" ");
- symbolWriter.Write(conterSymbolPrefix);
+ symbolWriter.Write(ConterSymbolPrefix);
symbolWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
symbolWriter.Write(" ");
symbolWriter.Write((counterIndex * 2).ToString(CultureInfo.InvariantCulture));
symbolWriter.WriteLine("");
}
- finally {
+ finally
+ {
symbolWriter.Close();
}
}
- finally {
+ finally
+ {
FileIOPermission.RevertAssert();
}
}
- private static void DeleteRegistryEntry(string categoryName) {
+ private static void DeleteRegistryEntry(string categoryName)
+ {
RegistryKey serviceKey = null;
//SECREVIEW: Whoever is able to call this function, must already
// we can therefore assert the RegistryPermission.
RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
registryPermission.Assert();
- try {
+ try
+ {
serviceKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
bool deleteCategoryKey = false;
- using (RegistryKey categoryKey = serviceKey.OpenSubKey(categoryName, true)) {
- if (categoryKey != null) {
- if (categoryKey.GetValueNames().Length == 0) {
+ using (RegistryKey categoryKey = serviceKey.OpenSubKey(categoryName, true))
+ {
+ if (categoryKey != null)
+ {
+ if (categoryKey.GetValueNames().Length == 0)
+ {
deleteCategoryKey = true;
}
- else {
+ else
+ {
categoryKey.DeleteSubKeyTree("Linkage");
categoryKey.DeleteSubKeyTree("Performance");
}
}
if (deleteCategoryKey)
serviceKey.DeleteSubKeyTree(categoryName);
-
+
}
- finally {
+ finally
+ {
if (serviceKey != null)
serviceKey.Close();
}
}
- private static void DeleteTemporaryFiles() {
- try {
+ private static void DeleteTemporaryFiles()
+ {
+ try
+ {
File.Delete(IniFilePath);
}
- catch {
+ catch
+ {
}
- try {
+ try
+ {
File.Delete(SymbolFilePath);
}
- catch {
+ catch
+ {
}
}
// 1) is a custom category
// 2) is a multi instance custom category
// The return value is whether the category is a custom category or not.
- internal bool FindCustomCategory(string category, out PerformanceCounterCategoryType categoryType) {
+ internal bool FindCustomCategory(string category, out PerformanceCounterCategoryType categoryType)
+ {
RegistryKey key = null;
RegistryKey baseKey = null;
categoryType = PerformanceCounterCategoryType.Unknown;
-
- if (this.customCategoryTable == null) {
- Interlocked.CompareExchange(ref this.customCategoryTable, new Hashtable(StringComparer.OrdinalIgnoreCase), null);
+
+ if (_customCategoryTable == null)
+ {
+ Interlocked.CompareExchange(ref _customCategoryTable, new Hashtable(StringComparer.OrdinalIgnoreCase), null);
}
- if (this.customCategoryTable.ContainsKey(category)) {
- categoryType= (PerformanceCounterCategoryType) this.customCategoryTable[category];
+ if (_customCategoryTable.ContainsKey(category))
+ {
+ categoryType = (PerformanceCounterCategoryType)_customCategoryTable[category];
return true;
}
- else {
- //SECREVIEW: Whoever is able to call this function, must already
- // have demanded PerformanceCounterPermission
- // we can therefore assert the RegistryPermission.
- PermissionSet ps = new PermissionSet(PermissionState.None);
- ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
- ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
- ps.Assert();
- try {
+ else
+ {
+ try
+ {
string keyPath = ServicePath + "\\" + category + "\\Performance";
- if (machineName == "." || String.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0) {
+ if (_machineName == "." || string.Compare(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0)
+ {
key = Registry.LocalMachine.OpenSubKey(keyPath);
}
- else {
- baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + this.machineName);
- if (baseKey != null) {
- try {
+ else
+ {
+ baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + _machineName);
+ if (baseKey != null)
+ {
+ try
+ {
key = baseKey.OpenSubKey(keyPath);
- } catch (SecurityException) {
+ }
+ catch (SecurityException)
+ {
// we may not have permission to read the registry key on the remote machine. The security exception
// is thrown when RegOpenKeyEx returns ERROR_ACCESS_DENIED or ERROR_BAD_IMPERSONATION_LEVEL
//
// In this case we return an 'Unknown' category type and 'false' to indicate the category is *not* custom.
//
categoryType = PerformanceCounterCategoryType.Unknown;
- this.customCategoryTable[category] = categoryType;
+ _customCategoryTable[category] = categoryType;
return false;
}
}
}
- if (key != null) {
+ if (key != null)
+ {
object systemDllName = key.GetValue("Library", null, RegistryValueOptions.DoNotExpandEnvironmentNames);
- if (systemDllName != null && systemDllName is string
- && (String.Compare((string)systemDllName, PerformanceCounterLib.PerfShimName, StringComparison.OrdinalIgnoreCase) == 0
- || ((string)systemDllName).EndsWith(PerformanceCounterLib.PerfShimFullNameSuffix, StringComparison.OrdinalIgnoreCase))) {
-
+ if (systemDllName != null && systemDllName is string
+ && (string.Compare((string)systemDllName, PerformanceCounterLib.PerfShimName, StringComparison.OrdinalIgnoreCase) == 0
+ || ((string)systemDllName).EndsWith(PerformanceCounterLib.PerfShimFullNameSuffix, StringComparison.OrdinalIgnoreCase)))
+ {
+
object isMultiInstanceObject = key.GetValue("IsMultiInstance");
- if (isMultiInstanceObject != null) {
- categoryType = (PerformanceCounterCategoryType) isMultiInstanceObject;
+ if (isMultiInstanceObject != null)
+ {
+ categoryType = (PerformanceCounterCategoryType)isMultiInstanceObject;
if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
categoryType = PerformanceCounterCategoryType.Unknown;
}
else
categoryType = PerformanceCounterCategoryType.Unknown;
-
+
object objectID = key.GetValue("First Counter");
- if (objectID != null) {
+ if (objectID != null)
+ {
int firstID = (int)objectID;
- this.customCategoryTable[category] = categoryType;
+ _customCategoryTable[category] = categoryType;
return true;
}
}
}
}
- finally {
- if (key != null) key.Close();
- if (baseKey != null) baseKey.Close();
+ finally
+ {
+ if (key != null)
+ key.Close();
+ if (baseKey != null)
+ baseKey.Close();
PermissionSet.RevertAssert();
}
}
return false;
}
- internal static string[] GetCategories(string machineName) {
+ internal static string[] GetCategories(string machineName)
+ {
PerformanceCounterLib library;
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machineName, culture);
string[] categories = library.GetCategories();
- if (categories.Length != 0 )
+ if (categories.Length != 0)
return categories;
culture = culture.Parent;
}
return library.GetCategories();
}
- internal string[] GetCategories() {
+ internal string[] GetCategories()
+ {
ICollection keys = CategoryTable.Keys;
string[] categories = new string[keys.Count];
keys.CopyTo(categories, 0);
return categories;
}
- internal static string GetCategoryHelp(string machine, string category) {
+ internal static string GetCategoryHelp(string machine, string category)
+ {
PerformanceCounterLib library;
string help;
//First check the current culture for the category. This will allow
//PerformanceCounterCategory.CategoryHelp to return localized strings.
- if(CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
-
- while (culture != CultureInfo.InvariantCulture) {
+
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
help = library.GetCategoryHelp(category);
if (help != null)
return help;
}
- private string GetCategoryHelp(string category) {
- CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
+ private string GetCategoryHelp(string category)
+ {
+ CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
- return (string)this.HelpTable[entry.HelpIndex];
+ return (string)HelpTable[entry.HelpIndex];
}
- internal static CategorySample GetCategorySample(string machine, string category) {
+ internal static CategorySample GetCategorySample(string machine, string category)
+ {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
CategorySample sample = library.GetCategorySample(category);
- if (sample == null && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (sample == null && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
sample = library.GetCategorySample(category);
if (sample != null)
return sample;
}
- private CategorySample GetCategorySample(string category) {
- CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
+ private CategorySample GetCategorySample(string category)
+ {
+ CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
return sample;
}
- internal static string[] GetCounters(string machine, string category) {
+ internal static string[] GetCounters(string machine, string category)
+ {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
bool categoryExists = false;
string[] counters = library.GetCounters(category, ref categoryExists);
- if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
counters = library.GetCounters(category, ref categoryExists);
if (categoryExists)
culture = culture.Parent;
}
}
-
+
if (!categoryExists)
throw new InvalidOperationException(SR.Format(SR.MissingCategory));
return counters;
}
- private string[] GetCounters(string category, ref bool categoryExists) {
+ private string[] GetCounters(string category, ref bool categoryExists)
+ {
categoryExists = false;
- CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
+ CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
else
int index2 = 0;
string[] counters = new string[entry.CounterIndexes.Length];
- for (int index = 0; index < counters.Length; ++ index) {
+ for (int index = 0; index < counters.Length; ++index)
+ {
int counterIndex = entry.CounterIndexes[index];
- string counterName = (string)this.NameTable[counterIndex];
- if (counterName != null && counterName != String.Empty) {
+ string counterName = (string)NameTable[counterIndex];
+ if (counterName != null && counterName != string.Empty)
+ {
counters[index2] = counterName;
++index2;
}
}
//Lets adjust the array in case there were null entries
- if (index2 < counters.Length) {
+ if (index2 < counters.Length)
+ {
string[] adjustedCounters = new string[index2];
Array.Copy(counters, adjustedCounters, index2);
counters = adjustedCounters;
return counters;
}
- internal static string GetCounterHelp(string machine, string category, string counter) {
+ internal static string GetCounterHelp(string machine, string category, string counter)
+ {
PerformanceCounterLib library;
bool categoryExists = false;
string help;
//First check the current culture for the counter. This will allow
//PerformanceCounter.CounterHelp to return localized strings.
- if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
help = library.GetCounterHelp(category, counter, ref categoryExists);
if (categoryExists)
return help;
}
- private string GetCounterHelp(string category, string counter, ref bool categoryExists) {
+ private string GetCounterHelp(string category, string counter, ref bool categoryExists)
+ {
categoryExists = false;
- CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
+ CategoryEntry entry = (CategoryEntry)CategoryTable[category];
if (entry == null)
return null;
else
categoryExists = true;
int helpIndex = -1;
- for (int index = 0; index < entry.CounterIndexes.Length; ++ index) {
+ for (int index = 0; index < entry.CounterIndexes.Length; ++index)
+ {
int counterIndex = entry.CounterIndexes[index];
- string counterName = (string)this.NameTable[counterIndex];
+ string counterName = (string)NameTable[counterIndex];
if (counterName == null)
- counterName = String.Empty;
+ counterName = string.Empty;
- if (String.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0) {
+ if (string.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0)
+ {
helpIndex = entry.HelpIndexes[index];
break;
}
if (helpIndex == -1)
throw new InvalidOperationException(SR.Format(SR.MissingCounter, counter));
- string help = (string)this.HelpTable[helpIndex];
+ string help = (string)HelpTable[helpIndex];
if (help == null)
- return String.Empty;
+ return string.Empty;
else
return help;
}
- internal string GetCounterName(int index) {
- if (this.NameTable.ContainsKey(index))
- return (string)this.NameTable[index];
+ internal string GetCounterName(int index)
+ {
+ if (NameTable.ContainsKey(index))
+ return (string)NameTable[index];
return "";
}
- private static string[] GetLanguageIds() {
+ private static string[] GetLanguageIds()
+ {
RegistryKey libraryParentKey = null;
string[] ids = new string[0];
new RegistryPermission(PermissionState.Unrestricted).Assert();
- try {
+ try
+ {
libraryParentKey = Registry.LocalMachine.OpenSubKey(PerflibPath);
if (libraryParentKey != null)
ids = libraryParentKey.GetSubKeyNames();
}
- finally {
+ finally
+ {
if (libraryParentKey != null)
libraryParentKey.Close();
return ids;
}
- internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) {
+ internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
+ {
SharedUtils.CheckEnvironment();
string lcidString = culture.LCID.ToString("X3", CultureInfo.InvariantCulture);
else
machineName = machineName.ToLower(CultureInfo.InvariantCulture);
- if (PerformanceCounterLib.libraryTable == null) {
- lock (InternalSyncObject) {
- if (PerformanceCounterLib.libraryTable == null)
- PerformanceCounterLib.libraryTable = new Hashtable();
+ if (PerformanceCounterLib.s_libraryTable == null)
+ {
+ lock (InternalSyncObject)
+ {
+ if (PerformanceCounterLib.s_libraryTable == null)
+ PerformanceCounterLib.s_libraryTable = new Hashtable();
}
}
string libraryKey = machineName + ":" + lcidString;
- if (PerformanceCounterLib.libraryTable.Contains(libraryKey))
- return (PerformanceCounterLib)PerformanceCounterLib.libraryTable[libraryKey];
- else {
+ if (PerformanceCounterLib.s_libraryTable.Contains(libraryKey))
+ return (PerformanceCounterLib)PerformanceCounterLib.s_libraryTable[libraryKey];
+ else
+ {
PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString);
- PerformanceCounterLib.libraryTable[libraryKey] = library;
+ PerformanceCounterLib.s_libraryTable[libraryKey] = library;
return library;
}
}
- internal byte[] GetPerformanceData(string item) {
- if (this.performanceMonitor == null) {
- lock (InternalSyncObject) {
- if (this.performanceMonitor == null)
- this.performanceMonitor = new PerformanceMonitor(this.machineName);
+ internal byte[] GetPerformanceData(string item)
+ {
+ if (_performanceMonitor == null)
+ {
+ lock (InternalSyncObject)
+ {
+ if (_performanceMonitor == null)
+ _performanceMonitor = new PerformanceMonitor(_machineName);
}
}
- return this.performanceMonitor.GetData(item);
+ return _performanceMonitor.GetData(item);
}
- private Hashtable GetStringTable(bool isHelp) {
+ private Hashtable GetStringTable(bool isHelp)
+ {
Hashtable stringTable;
RegistryKey libraryKey;
- PermissionSet ps = new PermissionSet(PermissionState.None);
- ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
- ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
- ps.Assert();
-
- if (String.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0)
+ if (string.Compare(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0)
libraryKey = Registry.PerformanceData;
- else {
- libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, this.machineName);
+ else
+ {
+ libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName);
}
- try {
+ try
+ {
string[] names = null;
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// make it more reliable because getting null back once doesn't necessarily mean
// that the data is corrupted, most of the time we would get the data just fine
// in subsequent tries.
- while (waitRetries > 0) {
- try {
+ while (waitRetries > 0)
+ {
+ try
+ {
if (!isHelp)
- names = (string[])libraryKey.GetValue("Counter " + perfLcid);
+ names = (string[])libraryKey.GetValue("Counter " + _perfLcid);
else
- names = (string[])libraryKey.GetValue("Explain " + perfLcid);
+ names = (string[])libraryKey.GetValue("Explain " + _perfLcid);
- if ((names == null) || (names.Length == 0)) {
+ if ((names == null) || (names.Length == 0))
+ {
--waitRetries;
if (waitSleep == 0)
waitSleep = 10;
- else {
+ else
+ {
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
else
break;
}
- catch (IOException) {
+ catch (IOException)
+ {
// RegistryKey throws if it can't find the value. We want to return an empty table
// and throw a different exception higher up the stack.
names = null;
break;
}
- catch (InvalidCastException) {
+ catch (InvalidCastException)
+ {
// Unable to cast object of type 'System.Byte[]' to type 'System.String[]'.
// this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ
names = null;
if (names == null)
stringTable = new Hashtable();
- else {
- stringTable = new Hashtable(names.Length/2);
-
- for (int index = 0; index < (names.Length/2); ++ index) {
- string nameString = names[(index *2) + 1];
+ else
+ {
+ stringTable = new Hashtable(names.Length / 2);
+
+ for (int index = 0; index < (names.Length / 2); ++index)
+ {
+ string nameString = names[(index * 2) + 1];
if (nameString == null)
- nameString = String.Empty;
-
+ nameString = string.Empty;
+
int key;
- if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) {
- if (isHelp) {
+ if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key))
+ {
+ if (isHelp)
+ {
// Category Help Table
throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2]));
}
- else {
+ else
+ {
// Counter Name Table
throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2]));
}
}
}
}
- finally {
+ finally
+ {
libraryKey.Close();
}
return stringTable;
}
-
- internal static bool IsCustomCategory(string machine, string category) {
+
+ internal static bool IsCustomCategory(string machine, string category)
+ {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
- if (library.IsCustomCategory(category))
+ if (library.IsCustomCategory(category))
return true;
- if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
if (library.IsCustomCategory(category))
return true;
return false;
}
- internal static bool IsBaseCounter(int type) {
+ internal static bool IsBaseCounter(int type)
+ {
return (type == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BASE ||
type == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_BASE ||
- type == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_BASE ||
- type == Interop.Kernel32.PerformanceCounterOptions.PERF_LARGE_RAW_BASE ||
+ type == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_BASE ||
+ type == Interop.Kernel32.PerformanceCounterOptions.PERF_LARGE_RAW_BASE ||
type == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_BASE);
}
-
- private bool IsCustomCategory(string category) {
+
+ private bool IsCustomCategory(string category)
+ {
PerformanceCounterCategoryType categoryType;
-
+
return FindCustomCategory(category, out categoryType);
}
- internal static PerformanceCounterCategoryType GetCategoryType(string machine, string category) {
+ internal static PerformanceCounterCategoryType GetCategoryType(string machine, string category)
+ {
PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
-
+
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
- if (!library.FindCustomCategory(category, out categoryType)) {
- if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
+ if (!library.FindCustomCategory(category, out categoryType))
+ {
+ if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID)
+ {
CultureInfo culture = CultureInfo.CurrentCulture;
- while (culture != CultureInfo.InvariantCulture) {
+ while (culture != CultureInfo.InvariantCulture)
+ {
library = GetPerformanceCounterLib(machine, culture);
if (library.FindCustomCategory(category, out categoryType))
return categoryType;
return categoryType;
}
- internal static void RegisterCategory(string categoryName, PerformanceCounterCategoryType categoryType, string categoryHelp, CounterCreationDataCollection creationData) {
- try {
+ internal static void RegisterCategory(string categoryName, PerformanceCounterCategoryType categoryType, string categoryHelp, CounterCreationDataCollection creationData)
+ {
+ try
+ {
bool iniRegistered = false;
CreateRegistryEntry(categoryName, categoryType, creationData, ref iniRegistered);
- if (!iniRegistered) {
+ if (!iniRegistered)
+ {
string[] languageIds = GetLanguageIds();
CreateIniFile(categoryName, categoryHelp, creationData, languageIds);
CreateSymbolFile(creationData);
CloseAllTables();
CloseAllLibraries();
}
- finally {
+ finally
+ {
DeleteTemporaryFiles();
}
}
- private static void RegisterFiles(string arg0, bool unregister) {
+ private static void RegisterFiles(string arg0, bool unregister)
+ {
Process p;
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.UseShellExecute = false;
processStartInfo.FileName = Environment.SystemDirectory + "\\lodctr.exe";
int res = 0;
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
- try {
+ try
+ {
processStartInfo.Arguments = "\"" + arg0 + "\"";
p = Process.Start(processStartInfo);
p.WaitForExit();
res = p.ExitCode;
}
- finally {
- SecurityPermission.RevertAssert();
+ finally
+ {
}
-
- if (res == Interop.Errors.ERROR_ACCESS_DENIED) {
+
+ if (res == Interop.Errors.ERROR_ACCESS_DENIED)
+ {
throw new UnauthorizedAccessException(SR.Format(SR.CantChangeCategoryRegistration, arg0));
}
throw SharedUtils.CreateSafeWin32Exception(res);
}
- internal static void UnregisterCategory(string categoryName) {
+ internal static void UnregisterCategory(string categoryName)
+ {
RegisterFiles(categoryName, true);
DeleteRegistryEntry(categoryName);
CloseAllTables();
}
}
- internal class PerformanceMonitor {
+ internal class PerformanceMonitor
+ {
private RegistryKey perfDataKey = null;
private string machineName;
- internal PerformanceMonitor(string machineName) {
+ internal PerformanceMonitor(string machineName)
+ {
this.machineName = machineName;
Init();
}
- private void Init() {
- try {
- if (machineName != "." && String.Compare(machineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0) {
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
+ private void Init()
+ {
+ try
+ {
+ if (machineName != "." && string.Compare(machineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0)
+ {
perfDataKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, machineName);
}
else
perfDataKey = Registry.PerformanceData;
}
- catch (UnauthorizedAccessException) {
+ catch (UnauthorizedAccessException)
+ {
// we need to do this for compatibility with v1.1 and v1.0.
throw new Win32Exception(Interop.Errors.ERROR_ACCESS_DENIED);
}
- catch (IOException e) {
+ catch (IOException e)
+ {
// we need to do this for compatibility with v1.1 and v1.0.
throw new Win32Exception(Marshal.GetHRForException(e));
}
}
- internal void Close() {
- if( perfDataKey != null)
+ internal void Close()
+ {
+ if (perfDataKey != null)
perfDataKey.Close();
perfDataKey = null;
// we wait may not be sufficient if the Win32 code keeps running into this deadlock again
// and again. A condition very rare but possible in theory. We would get back to the user
// in this case with InvalidOperationException after the wait time expires.
- internal byte[] GetData(string item) {
+ internal byte[] GetData(string item)
+ {
int waitRetries = 17; //2^16*10ms == approximately 10mins
int waitSleep = 0;
byte[] data = null;
// no need to revert here since we'll fall off the end of the method
new RegistryPermission(PermissionState.Unrestricted).Assert();
- while (waitRetries > 0) {
- try {
- data = (byte[]) perfDataKey.GetValue(item);
+ while (waitRetries > 0)
+ {
+ try
+ {
+ data = (byte[])perfDataKey.GetValue(item);
return data;
}
- catch (IOException e) {
+ catch (IOException e)
+ {
error = Marshal.GetHRForException(e);
- switch (error) {
+ switch (error)
+ {
case Interop.Advapi32.RPCStatus.RPC_S_CALL_FAILED:
case Interop.Errors.ERROR_INVALID_HANDLE:
case Interop.Advapi32.RPCStatus.RPC_S_SERVER_UNAVAILABLE:
case Interop.Errors.ERROR_LOCK_FAILED:
case Interop.Errors.ERROR_BUSY:
--waitRetries;
- if (waitSleep == 0) {
+ if (waitSleep == 0)
+ {
waitSleep = 10;
}
- else {
+ else
+ {
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
throw SharedUtils.CreateSafeWin32Exception(error);
}
}
- catch (InvalidCastException e) {
+ catch (InvalidCastException e)
+ {
throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, perfDataKey.ToString()), e);
}
}
}
- internal class CategoryEntry {
+ internal class CategoryEntry
+ {
internal int NameIndex;
internal int HelpIndex;
internal int[] CounterIndexes;
internal int[] HelpIndexes;
- internal CategoryEntry(Interop.Advapi32.PERF_OBJECT_TYPE perfObject) {
- this.NameIndex = perfObject.ObjectNameTitleIndex;
- this.HelpIndex = perfObject.ObjectHelpTitleIndex;
- this.CounterIndexes = new int[perfObject.NumCounters];
- this.HelpIndexes = new int[perfObject.NumCounters];
+ internal CategoryEntry(Interop.Advapi32.PERF_OBJECT_TYPE perfObject)
+ {
+ NameIndex = perfObject.ObjectNameTitleIndex;
+ HelpIndex = perfObject.ObjectHelpTitleIndex;
+ CounterIndexes = new int[perfObject.NumCounters];
+ HelpIndexes = new int[perfObject.NumCounters];
}
}
- internal class CategorySample {
- internal readonly long SystemFrequency;
- internal readonly long TimeStamp;
- internal readonly long TimeStamp100nSec;
- internal readonly long CounterFrequency;
- internal readonly long CounterTimeStamp;
- internal Hashtable CounterTable;
- internal Hashtable InstanceNameTable;
- internal bool IsMultiInstance;
- private CategoryEntry entry;
- private PerformanceCounterLib library;
-
- internal unsafe CategorySample(byte[] data, CategoryEntry entry, PerformanceCounterLib library) {
- this.entry = entry;
- this.library = library;
+ internal class CategorySample
+ {
+ internal readonly long _systemFrequency;
+ internal readonly long _timeStamp;
+ internal readonly long _timeStamp100nSec;
+ internal readonly long _counterFrequency;
+ internal readonly long _counterTimeStamp;
+ internal Hashtable _counterTable;
+ internal Hashtable _instanceNameTable;
+ internal bool _isMultiInstance;
+ private CategoryEntry _entry;
+ private PerformanceCounterLib _library;
+
+ internal unsafe CategorySample(byte[] data, CategoryEntry entry, PerformanceCounterLib library)
+ {
+ _entry = entry;
+ _library = library;
int categoryIndex = entry.NameIndex;
Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK();
- fixed (byte* dataPtr = data) {
- IntPtr dataRef = new IntPtr((void*) dataPtr);
+ fixed (byte* dataPtr = data)
+ {
+ IntPtr dataRef = new IntPtr((void*)dataPtr);
Marshal.PtrToStructure(dataRef, dataBlock);
- this.SystemFrequency = dataBlock.PerfFreq;
- this.TimeStamp = dataBlock.PerfTime;
- this.TimeStamp100nSec = dataBlock.PerfTime100nSec;
+ _systemFrequency = dataBlock.PerfFreq;
+ _timeStamp = dataBlock.PerfTime;
+ _timeStamp100nSec = dataBlock.PerfTime100nSec;
dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength);
int numPerfObjects = dataBlock.NumObjectTypes;
- if (numPerfObjects == 0) {
- this.CounterTable = new Hashtable();
- this.InstanceNameTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
+ if (numPerfObjects == 0)
+ {
+ _counterTable = new Hashtable();
+ _instanceNameTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
return;
}
//several of them.
Interop.Advapi32.PERF_OBJECT_TYPE perfObject = null;
bool foundCategory = false;
- for (int index = 0; index < numPerfObjects; index++) {
+ for (int index = 0; index < numPerfObjects; index++)
+ {
perfObject = new Interop.Advapi32.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(dataRef, perfObject);
- if (perfObject.ObjectNameTitleIndex == categoryIndex) {
+ if (perfObject.ObjectNameTitleIndex == categoryIndex)
+ {
foundCategory = true;
break;
}
if (!foundCategory)
throw new InvalidOperationException(SR.Format(SR.CantReadCategoryIndex, categoryIndex.ToString(CultureInfo.CurrentCulture)));
- this.CounterFrequency = perfObject.PerfFreq;
- this.CounterTimeStamp = perfObject.PerfTime;
+ _counterFrequency = perfObject.PerfFreq;
+ _counterTimeStamp = perfObject.PerfTime;
int counterNumber = perfObject.NumCounters;
int instanceNumber = perfObject.NumInstances;
if (instanceNumber == -1)
- IsMultiInstance = false;
+ _isMultiInstance = false;
else
- IsMultiInstance = true;
-
+ _isMultiInstance = true;
+
// Move pointer forward to end of PERF_OBJECT_TYPE
dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength);
CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber];
- this.CounterTable = new Hashtable(counterNumber);
- for (int index = 0; index < samples.Length; ++ index) {
+ _counterTable = new Hashtable(counterNumber);
+ for (int index = 0; index < samples.Length; ++index)
+ {
Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter = new Interop.Advapi32.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(dataRef, perfCounter);
samples[index] = new CounterDefinitionSample(perfCounter, this, instanceNumber);
dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength);
- int currentSampleType = samples[index].CounterType;
- if (!PerformanceCounterLib.IsBaseCounter(currentSampleType)) {
+ int currentSampleType = samples[index]._counterType;
+ if (!PerformanceCounterLib.IsBaseCounter(currentSampleType))
+ {
// We'll put only non-base counters in the table.
if (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_NODATA)
- this.CounterTable[samples[index].NameIndex] = samples[index];
+ _counterTable[samples[index]._nameIndex] = samples[index];
}
- else {
+ else
+ {
// it's a base counter, try to hook it up to the main counter.
Debug.Assert(index > 0, "Index > 0 because base counters should never be at index 0");
if (index > 0)
- samples[index-1].BaseCounterDefinitionSample = samples[index];
+ samples[index - 1]._baseCounterDefinitionSample = samples[index];
}
}
// now set up the InstanceNameTable.
- if (!IsMultiInstance) {
- this.InstanceNameTable = new Hashtable(1, StringComparer.OrdinalIgnoreCase);
- this.InstanceNameTable[PerformanceCounterLib.SingleInstanceName] = 0;
+ if (!_isMultiInstance)
+ {
+ _instanceNameTable = new Hashtable(1, StringComparer.OrdinalIgnoreCase);
+ _instanceNameTable[PerformanceCounterLib.SingleInstanceName] = 0;
- for (int index = 0; index < samples.Length; ++ index) {
+ for (int index = 0; index < samples.Length; ++index)
+ {
samples[index].SetInstanceValue(0, dataRef);
}
}
- else {
+ else
+ {
string[] parentInstanceNames = null;
- this.InstanceNameTable = new Hashtable(instanceNumber, StringComparer.OrdinalIgnoreCase);
- for (int i = 0; i < instanceNumber; i++) {
+ _instanceNameTable = new Hashtable(instanceNumber, StringComparer.OrdinalIgnoreCase);
+ for (int i = 0; i < instanceNumber; i++)
+ {
Interop.Advapi32.PERF_INSTANCE_DEFINITION perfInstance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION();
Marshal.PtrToStructure(dataRef, perfInstance);
if (perfInstance.ParentObjectTitleIndex > 0 && parentInstanceNames == null)
//generate a unique name.
string newInstanceName = instanceName;
int newInstanceNumber = 1;
- while (true) {
- if (!this.InstanceNameTable.ContainsKey(newInstanceName)) {
- this.InstanceNameTable[newInstanceName] = i;
+ while (true)
+ {
+ if (!_instanceNameTable.ContainsKey(newInstanceName))
+ {
+ _instanceNameTable[newInstanceName] = i;
break;
}
- else {
- newInstanceName = instanceName + "#" + newInstanceNumber.ToString(CultureInfo.InvariantCulture);
- ++ newInstanceNumber;
+ else
+ {
+ newInstanceName = instanceName + "#" + newInstanceNumber.ToString(CultureInfo.InvariantCulture);
+ ++newInstanceNumber;
}
}
dataRef = (IntPtr)((long)dataRef + perfInstance.ByteLength);
- for (int index = 0; index < samples.Length; ++ index)
+ for (int index = 0; index < samples.Length; ++index)
samples[index].SetInstanceValue(i, dataRef);
dataRef = (IntPtr)((long)dataRef + Marshal.ReadInt32(dataRef));
}
}
- internal unsafe string[] GetInstanceNamesFromIndex(int categoryIndex) {
- byte[] data = library.GetPerformanceData(categoryIndex.ToString(CultureInfo.InvariantCulture));
- fixed (byte* dataPtr = data) {
- IntPtr dataRef = new IntPtr((void*) dataPtr);
+ internal unsafe string[] GetInstanceNamesFromIndex(int categoryIndex)
+ {
+ byte[] data = _library.GetPerformanceData(categoryIndex.ToString(CultureInfo.InvariantCulture));
+ fixed (byte* dataPtr = data)
+ {
+ IntPtr dataRef = new IntPtr((void*)dataPtr);
Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataRef, dataBlock);
Interop.Advapi32.PERF_OBJECT_TYPE perfObject = null;
bool foundCategory = false;
- for (int index = 0; index < numPerfObjects; index++) {
+ for (int index = 0; index < numPerfObjects; index++)
+ {
perfObject = new Interop.Advapi32.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(dataRef, perfObject);
- if (perfObject.ObjectNameTitleIndex == categoryIndex) {
+ if (perfObject.ObjectNameTitleIndex == categoryIndex)
+ {
foundCategory = true;
break;
}
return new string[0];
CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber];
- for (int index = 0; index < samples.Length; ++ index) {
+ for (int index = 0; index < samples.Length; ++index)
+ {
Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter = new Interop.Advapi32.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(dataRef, perfCounter);
dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength);
}
string[] instanceNames = new string[instanceNumber];
- for (int i = 0; i < instanceNumber; i++) {
+ for (int i = 0; i < instanceNumber; i++)
+ {
Interop.Advapi32.PERF_INSTANCE_DEFINITION perfInstance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION();
Marshal.PtrToStructure(dataRef, perfInstance);
- instanceNames[i] = Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset));
+ instanceNames[i] = Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset));
dataRef = (IntPtr)((long)dataRef + perfInstance.ByteLength);
dataRef = (IntPtr)((long)dataRef + Marshal.ReadInt32(dataRef));
}
}
}
- internal CounterDefinitionSample GetCounterDefinitionSample(string counter) {
- for (int index = 0; index < this.entry.CounterIndexes.Length; ++ index) {
- int counterIndex = entry.CounterIndexes[index];
- string counterName = (string)this.library.NameTable[counterIndex];
- if (counterName != null) {
- if (String.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0) {
- CounterDefinitionSample sample = (CounterDefinitionSample)this.CounterTable[counterIndex];
- if (sample == null) {
+ internal CounterDefinitionSample GetCounterDefinitionSample(string counter)
+ {
+ for (int index = 0; index < _entry.CounterIndexes.Length; ++index)
+ {
+ int counterIndex = _entry.CounterIndexes[index];
+ string counterName = (string)_library.NameTable[counterIndex];
+ if (counterName != null)
+ {
+ if (string.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0)
+ {
+ CounterDefinitionSample sample = (CounterDefinitionSample)_counterTable[counterIndex];
+ if (sample == null)
+ {
//This is a base counter and has not been added to the table
- foreach (CounterDefinitionSample multiSample in this.CounterTable.Values) {
- if (multiSample.BaseCounterDefinitionSample != null &&
- multiSample.BaseCounterDefinitionSample.NameIndex == counterIndex)
- return multiSample.BaseCounterDefinitionSample;
+ foreach (CounterDefinitionSample multiSample in _counterTable.Values)
+ {
+ if (multiSample._baseCounterDefinitionSample != null &&
+ multiSample._baseCounterDefinitionSample._nameIndex == counterIndex)
+ return multiSample._baseCounterDefinitionSample;
}
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
throw new InvalidOperationException(SR.Format(SR.CantReadCounter, counter));
}
- internal InstanceDataCollectionCollection ReadCategory() {
+ internal InstanceDataCollectionCollection ReadCategory()
+ {
#pragma warning disable 618
InstanceDataCollectionCollection data = new InstanceDataCollectionCollection();
#pragma warning restore 618
- for (int index = 0; index < this.entry.CounterIndexes.Length; ++ index) {
- int counterIndex = entry.CounterIndexes[index];
-
- string name = (string)library.NameTable[counterIndex];
- if (name != null && name != String.Empty) {
- CounterDefinitionSample sample = (CounterDefinitionSample)this.CounterTable[counterIndex];
+ for (int index = 0; index < _entry.CounterIndexes.Length; ++index)
+ {
+ int counterIndex = _entry.CounterIndexes[index];
+
+ string name = (string)_library.NameTable[counterIndex];
+ if (name != null && name != string.Empty)
+ {
+ CounterDefinitionSample sample = (CounterDefinitionSample)_counterTable[counterIndex];
if (sample != null)
//If the current index refers to a counter base,
//the sample will be null
}
}
- internal class CounterDefinitionSample {
- internal readonly int NameIndex;
- internal readonly int CounterType;
- internal CounterDefinitionSample BaseCounterDefinitionSample;
-
- private readonly int size;
- private readonly int offset;
- private long[] instanceValues;
- private CategorySample categorySample;
-
- internal CounterDefinitionSample(Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter, CategorySample categorySample, int instanceNumber) {
- this.NameIndex = perfCounter.CounterNameTitleIndex;
- this.CounterType = perfCounter.CounterType;
- this.offset = perfCounter.CounterOffset;
- this.size = perfCounter.CounterSize;
- if (instanceNumber == -1) {
- this.instanceValues = new long[1];
+ internal class CounterDefinitionSample
+ {
+ internal readonly int _nameIndex;
+ internal readonly int _counterType;
+ internal CounterDefinitionSample _baseCounterDefinitionSample;
+
+ private readonly int _size;
+ private readonly int _offset;
+ private long[] _instanceValues;
+ private CategorySample _categorySample;
+
+ internal CounterDefinitionSample(Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter, CategorySample categorySample, int instanceNumber)
+ {
+ _nameIndex = perfCounter.CounterNameTitleIndex;
+ _counterType = perfCounter.CounterType;
+ _offset = perfCounter.CounterOffset;
+ _size = perfCounter.CounterSize;
+ if (instanceNumber == -1)
+ {
+ _instanceValues = new long[1];
}
else
- this.instanceValues = new long[instanceNumber];
+ _instanceValues = new long[instanceNumber];
- this.categorySample = categorySample;
+ _categorySample = categorySample;
}
- private long ReadValue(IntPtr pointer) {
- if (this.size == 4) {
- return (long)(uint)Marshal.ReadInt32((IntPtr)((long)pointer + this.offset));
+ private long ReadValue(IntPtr pointer)
+ {
+ if (_size == 4)
+ {
+ return (long)(uint)Marshal.ReadInt32((IntPtr)((long)pointer + _offset));
}
- else if (this.size == 8) {
- return (long)Marshal.ReadInt64((IntPtr)((long)pointer + this.offset));
+ else if (_size == 8)
+ {
+ return (long)Marshal.ReadInt64((IntPtr)((long)pointer + _offset));
}
return -1;
}
- internal CounterSample GetInstanceValue(string instanceName) {
+ internal CounterSample GetInstanceValue(string instanceName)
+ {
- if (!categorySample.InstanceNameTable.ContainsKey(instanceName)) {
+ if (!_categorySample._instanceNameTable.ContainsKey(instanceName))
+ {
// Our native dll truncates instance names to 128 characters. If we can't find the instance
// with the full name, try truncating to 128 characters.
if (instanceName.Length > SharedPerformanceCounter.InstanceNameMaxLength)
instanceName = instanceName.Substring(0, SharedPerformanceCounter.InstanceNameMaxLength);
-
- if (!categorySample.InstanceNameTable.ContainsKey(instanceName))
+
+ if (!_categorySample._instanceNameTable.ContainsKey(instanceName))
throw new InvalidOperationException(SR.Format(SR.CantReadInstance, instanceName));
}
- int index = (int)categorySample.InstanceNameTable[instanceName];
- long rawValue = this.instanceValues[index];
+ int index = (int)_categorySample._instanceNameTable[instanceName];
+ long rawValue = _instanceValues[index];
long baseValue = 0;
- if (this.BaseCounterDefinitionSample != null) {
- CategorySample baseCategorySample = this.BaseCounterDefinitionSample.categorySample;
- int baseIndex = (int)baseCategorySample.InstanceNameTable[instanceName];
- baseValue = this.BaseCounterDefinitionSample.instanceValues[baseIndex];
+ if (_baseCounterDefinitionSample != null)
+ {
+ CategorySample baseCategorySample = _baseCounterDefinitionSample._categorySample;
+ int baseIndex = (int)baseCategorySample._instanceNameTable[instanceName];
+ baseValue = _baseCounterDefinitionSample._instanceValues[baseIndex];
}
return new CounterSample(rawValue,
baseValue,
- categorySample.CounterFrequency,
- categorySample.SystemFrequency,
- categorySample.TimeStamp,
- categorySample.TimeStamp100nSec,
- (PerformanceCounterType)this.CounterType,
- categorySample.CounterTimeStamp);
+ _categorySample._counterFrequency,
+ _categorySample._systemFrequency,
+ _categorySample._timeStamp,
+ _categorySample._timeStamp100nSec,
+ (PerformanceCounterType)_counterType,
+ _categorySample._counterTimeStamp);
}
- internal InstanceDataCollection ReadInstanceData(string counterName) {
+ internal InstanceDataCollection ReadInstanceData(string counterName)
+ {
#pragma warning disable 618
InstanceDataCollection data = new InstanceDataCollection(counterName);
#pragma warning restore 618
- string[] keys = new string[categorySample.InstanceNameTable.Count];
- categorySample.InstanceNameTable.Keys.CopyTo(keys, 0);
- int[] indexes = new int[categorySample.InstanceNameTable.Count];
- categorySample.InstanceNameTable.Values.CopyTo(indexes, 0);
- for (int index = 0; index < keys.Length; ++ index) {
+ string[] keys = new string[_categorySample._instanceNameTable.Count];
+ _categorySample._instanceNameTable.Keys.CopyTo(keys, 0);
+ int[] indexes = new int[_categorySample._instanceNameTable.Count];
+ _categorySample._instanceNameTable.Values.CopyTo(indexes, 0);
+ for (int index = 0; index < keys.Length; ++index)
+ {
long baseValue = 0;
- if (this.BaseCounterDefinitionSample != null) {
- CategorySample baseCategorySample = this.BaseCounterDefinitionSample.categorySample;
- int baseIndex = (int)baseCategorySample.InstanceNameTable[keys[index]];
- baseValue = this.BaseCounterDefinitionSample.instanceValues[baseIndex];
+ if (_baseCounterDefinitionSample != null)
+ {
+ CategorySample baseCategorySample = _baseCounterDefinitionSample._categorySample;
+ int baseIndex = (int)baseCategorySample._instanceNameTable[keys[index]];
+ baseValue = _baseCounterDefinitionSample._instanceValues[baseIndex];
}
- CounterSample sample = new CounterSample(this.instanceValues[indexes[index]],
+ CounterSample sample = new CounterSample(_instanceValues[indexes[index]],
baseValue,
- categorySample.CounterFrequency,
- categorySample.SystemFrequency,
- categorySample.TimeStamp,
- categorySample.TimeStamp100nSec,
- (PerformanceCounterType)this.CounterType,
- categorySample.CounterTimeStamp);
+ _categorySample._counterFrequency,
+ _categorySample._systemFrequency,
+ _categorySample._timeStamp,
+ _categorySample._timeStamp100nSec,
+ (PerformanceCounterType)_counterType,
+ _categorySample._counterTimeStamp);
data.Add(keys[index], new InstanceData(keys[index], sample));
}
return data;
}
- internal CounterSample GetSingleValue() {
- long rawValue = this.instanceValues[0];
+ internal CounterSample GetSingleValue()
+ {
+ long rawValue = _instanceValues[0];
long baseValue = 0;
- if (this.BaseCounterDefinitionSample != null)
- baseValue = this.BaseCounterDefinitionSample.instanceValues[0];
+ if (_baseCounterDefinitionSample != null)
+ baseValue = _baseCounterDefinitionSample._instanceValues[0];
return new CounterSample(rawValue,
baseValue,
- categorySample.CounterFrequency,
- categorySample.SystemFrequency,
- categorySample.TimeStamp,
- categorySample.TimeStamp100nSec,
- (PerformanceCounterType)this.CounterType,
- categorySample.CounterTimeStamp);
+ _categorySample._counterFrequency,
+ _categorySample._systemFrequency,
+ _categorySample._timeStamp,
+ _categorySample._timeStamp100nSec,
+ (PerformanceCounterType)_counterType,
+ _categorySample._counterTimeStamp);
}
- internal void SetInstanceValue(int index, IntPtr dataRef) {
+ internal void SetInstanceValue(int index, IntPtr dataRef)
+ {
long rawValue = ReadValue(dataRef);
- this.instanceValues[index] = rawValue;
+ _instanceValues[index] = rawValue;
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System.Runtime.InteropServices;
- using System;
- using System.Security.Permissions;
- using System.Security;
- using Microsoft.Win32;
+using System;
+namespace System.Diagnostics
+{
// All of this code was ported to native and this implementation is no longer used. It is not meant to be accessed directly.
// This code was no longer maintained, and it accessed the same shared memory that the new code accessed. To be certain there
// are no security holes and no serious bugs, we have removed all of the real code.
-
-
+
+
/// <internalonly/>
public sealed class PerformanceCounterManager : ICollectData
{
[
Obsolete("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. http://go.microsoft.com/fwlink/?linkid=14202")
]
- public PerformanceCounterManager() {
+ public PerformanceCounterManager()
+ {
}
-
+
/// <internalonly/>
[
Obsolete("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. http://go.microsoft.com/fwlink/?linkid=14202")
]
- void ICollectData.CollectData(int callIdx, IntPtr valueNamePtr, IntPtr dataPtr, int totalBytes, out IntPtr res) {
+ void ICollectData.CollectData(int callIdx, IntPtr valueNamePtr, IntPtr dataPtr, int totalBytes, out IntPtr res)
+ {
res = (IntPtr)(-1);
}
[
Obsolete("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. http://go.microsoft.com/fwlink/?linkid=14202")
]
- void ICollectData.CloseData() {
+ void ICollectData.CloseData()
+ {
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System;
- using System.ComponentModel;
- using Microsoft.Win32;
-
-
+namespace System.Diagnostics
+{
/// <summary>
/// Enum of friendly names to counter types (maps directory to the native types)
/// </summary>
- public enum PerformanceCounterType {
- NumberOfItems32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_RAWCOUNT,
- NumberOfItems64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT,
- NumberOfItemsHEX32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_RAWCOUNT_HEX,
- NumberOfItemsHEX64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT_HEX,
+ public enum PerformanceCounterType
+ {
+ NumberOfItems32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_RAWCOUNT,
+ NumberOfItems64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT,
+ NumberOfItemsHEX32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_RAWCOUNT_HEX,
+ NumberOfItemsHEX64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_RAWCOUNT_HEX,
RateOfCountsPerSecond32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_COUNTER,
RateOfCountsPerSecond64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_BULK_COUNT,
- CountPerTimeInterval32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_QUEUELEN_TYPE,
- CountPerTimeInterval64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_QUEUELEN_TYPE,
- RawFraction = Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION,
- RawBase = Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_BASE,
-
- AverageTimer32 = Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER,
- AverageBase = Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BASE,
- AverageCount64 = Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK,
-
- SampleFraction = Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION,
- SampleCounter = Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_COUNTER,
- SampleBase = Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_BASE,
-
- CounterTimer = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_TIMER,
- CounterTimerInverse = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_TIMER_INV,
- Timer100Ns = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_TIMER,
- Timer100NsInverse = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_TIMER_INV,
- ElapsedTime = Interop.Kernel32.PerformanceCounterOptions.PERF_ELAPSED_TIME,
- CounterMultiTimer = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER,
- CounterMultiTimerInverse= Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV,
- CounterMultiTimer100Ns = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER,
- CounterMultiTimer100NsInverse = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV,
- CounterMultiBase = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_BASE,
+ CountPerTimeInterval32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_QUEUELEN_TYPE,
+ CountPerTimeInterval64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_QUEUELEN_TYPE,
+ RawFraction = Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION,
+ RawBase = Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_BASE,
+
+ AverageTimer32 = Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER,
+ AverageBase = Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BASE,
+ AverageCount64 = Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK,
+
+ SampleFraction = Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION,
+ SampleCounter = Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_COUNTER,
+ SampleBase = Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_BASE,
+
+ CounterTimer = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_TIMER,
+ CounterTimerInverse = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_TIMER_INV,
+ Timer100Ns = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_TIMER,
+ Timer100NsInverse = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_TIMER_INV,
+ ElapsedTime = Interop.Kernel32.PerformanceCounterOptions.PERF_ELAPSED_TIME,
+ CounterMultiTimer = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER,
+ CounterMultiTimerInverse = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV,
+ CounterMultiTimer100Ns = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER,
+ CounterMultiTimer100NsInverse = Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV,
+ CounterMultiBase = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_BASE,
- CounterDelta32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_DELTA,
- CounterDelta64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_DELTA
+ CounterDelta32 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_DELTA,
+ CounterDelta64 = Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_LARGE_DELTA
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System;
- using System.Text;
- using System.Threading;
- using System.Collections;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
- using System.Security;
- using Microsoft.Win32;
- using Microsoft.Win32.SafeHandles;
- using System.Globalization;
- using System.Security.Principal;
- using System.Security.AccessControl;
- using System.Collections.Generic;
- using System.Runtime.Versioning;
-
- internal sealed class SharedPerformanceCounter {
+using System;
+using System.Text;
+using System.Threading;
+using System.Collections;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security.Permissions;
+using Microsoft.Win32;
+using Microsoft.Win32.SafeHandles;
+
+namespace System.Diagnostics
+{
+ internal sealed class SharedPerformanceCounter
+ {
private const int MaxSpinCount = 5000;
internal const int DefaultCountersFileMappingSize = 524288;
internal const int MaxCountersFileMappingSize = 33554432;
internal const int InstanceNameSlotSize = 256;
internal const string SingleInstanceName = "systemdiagnosticssharedsingleinstance";
internal const string DefaultFileMappingName = "netfxcustomperfcounters.1.0";
- internal static readonly int SingleInstanceHashCode = GetWstrHashCode(SingleInstanceName);
- private static Hashtable categoryDataTable = new Hashtable(StringComparer.Ordinal);
- private static readonly int CategoryEntrySize = Marshal.SizeOf(typeof(CategoryEntry));
- private static readonly int InstanceEntrySize = Marshal.SizeOf(typeof(InstanceEntry));
- private static readonly int CounterEntrySize = Marshal.SizeOf(typeof(CounterEntry));
- private static readonly int ProcessLifetimeEntrySize = Marshal.SizeOf(typeof(ProcessLifetimeEntry));
-
- private static long LastInstanceLifetimeSweepTick;
- private const long InstanceLifetimeSweepWindow = 30*10000000; //ticks
- private static volatile ProcessData procData;
-
- private static ProcessData ProcessData {
- get {
- if (procData == null) {
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
- try {
+ internal static readonly int s_singleInstanceHashCode = GetWstrHashCode(SingleInstanceName);
+ private static Hashtable s_categoryDataTable = new Hashtable(StringComparer.Ordinal);
+ private static readonly int s_categoryEntrySize = Marshal.SizeOf(typeof(CategoryEntry));
+ private static readonly int s_instanceEntrySize = Marshal.SizeOf(typeof(InstanceEntry));
+ private static readonly int s_counterEntrySize = Marshal.SizeOf(typeof(CounterEntry));
+ private static readonly int s_processLifetimeEntrySize = Marshal.SizeOf(typeof(ProcessLifetimeEntry));
+
+ private static long s_lastInstanceLifetimeSweepTick;
+ private const long InstanceLifetimeSweepWindow = 30 * 10000000; //ticks
+ private static volatile ProcessData s_procData;
+
+ private static ProcessData ProcessData
+ {
+ get
+ {
+ if (s_procData == null)
+ {
+ try
+ {
int pid = (int)Interop.Kernel32.GetCurrentProcessId();
- long startTime = -1;
-
+ long startTime = -1;
+
// Though we have asserted the required CAS permissions above, we may
// still fail to query the process information if the user does not
// have the necessary process access rights or privileges.
// This might be the case if the current process was started by a
// different user (primary token) than the current user
// (impersonation token) that has less privilege/ACL rights.
- using (SafeProcessHandle procHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, pid)) {
- if (!procHandle.IsInvalid) {
+ using (SafeProcessHandle procHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, pid))
+ {
+ if (!procHandle.IsInvalid)
+ {
long temp;
Interop.Kernel32.GetProcessTimes(procHandle, out startTime, out temp, out temp, out temp);
}
}
- procData = new ProcessData(pid, startTime);
+ s_procData = new ProcessData(pid, startTime);
}
- finally {
- SecurityPermission.RevertAssert();
+ finally
+ {
}
}
- return procData;
+ return s_procData;
}
}
// However, using an offset of 4 means that our CounterEntry.Value is potentially misaligned. This is why we have SetValue
// and other methods which split CounterEntry.Value into two ints. With separate shared memory blocks per
// category, we can fix this and always use an inital offset of 8.
- internal int InitialOffset = 4;
-
- private CategoryData categoryData;
- private long baseAddress;
- private unsafe CounterEntry* counterEntryPointer;
- private string categoryName;
- private int categoryNameHashCode;
- private int thisInstanceOffset = -1;
+ internal int _initialOffset = 4;
- internal SharedPerformanceCounter(string catName, string counterName, string instanceName) :
- this (catName, counterName, instanceName, PerformanceCounterInstanceLifetime.Global) { }
+ private CategoryData _categoryData;
+ private long _baseAddress;
+ private unsafe CounterEntry* _counterEntryPointer;
+ private string _categoryName;
+ private int _categoryNameHashCode;
+ private int _thisInstanceOffset = -1;
- internal unsafe SharedPerformanceCounter(string catName, string counterName, string instanceName, PerformanceCounterInstanceLifetime lifetime) {
- this.categoryName = catName;
- this.categoryNameHashCode = GetWstrHashCode(categoryName);
+ internal SharedPerformanceCounter(string catName, string counterName, string instanceName) :
+ this(catName, counterName, instanceName, PerformanceCounterInstanceLifetime.Global)
+ { }
- categoryData = GetCategoryData();
+ internal unsafe SharedPerformanceCounter(string catName, string counterName, string instanceName, PerformanceCounterInstanceLifetime lifetime)
+ {
+ _categoryName = catName;
+ _categoryNameHashCode = GetWstrHashCode(_categoryName);
+
+ _categoryData = GetCategoryData();
// Check that the instance name isn't too long if we're using the new shared memory.
// We allocate InstanceNameSlotSize bytes in the shared memory
- if (categoryData.UseUniqueSharedMemory) {
+ if (_categoryData.UseUniqueSharedMemory)
+ {
if (instanceName != null && instanceName.Length > InstanceNameMaxLength)
throw new InvalidOperationException(SR.Format(SR.InstanceNameTooLong));
}
- else {
+ else
+ {
if (lifetime != PerformanceCounterInstanceLifetime.Global)
throw new InvalidOperationException(SR.Format(SR.ProcessLifetimeNotValidInGlobal));
}
- if (counterName != null && instanceName != null) {
- if (!categoryData.CounterNames.Contains(counterName))
+ if (counterName != null && instanceName != null)
+ {
+ if (!_categoryData.CounterNames.Contains(counterName))
Debug.Assert(false, "Counter " + counterName + " does not exist in category " + catName);
else
- this.counterEntryPointer = GetCounter(counterName, instanceName, categoryData.EnableReuse, lifetime);
+ _counterEntryPointer = GetCounter(counterName, instanceName, _categoryData.EnableReuse, lifetime);
}
}
- private FileMapping FileView {
- get {
- return categoryData.FileMapping;
+ private FileMapping FileView
+ {
+ get
+ {
+ return _categoryData.FileMapping;
}
}
- internal unsafe long Value {
- get {
- if (counterEntryPointer == null)
+ internal unsafe long Value
+ {
+ get
+ {
+ if (_counterEntryPointer == null)
return 0;
- return GetValue(this.counterEntryPointer);
+ return GetValue(_counterEntryPointer);
}
- set {
- if (counterEntryPointer == null)
+ set
+ {
+ if (_counterEntryPointer == null)
return;
- SetValue(this.counterEntryPointer, value);
+ SetValue(_counterEntryPointer, value);
}
}
- private unsafe int CalculateAndAllocateMemory(int totalSize, out int alignmentAdjustment) {
- int newOffset;
+ private unsafe int CalculateAndAllocateMemory(int totalSize, out int alignmentAdjustment)
+ {
+ int newOffset;
int oldOffset;
alignmentAdjustment = 0;
- Debug.Assert(!categoryData.UseUniqueSharedMemory, "We should never be calling CalculateAndAllocateMemory in the unique shared memory");
+ Debug.Assert(!_categoryData.UseUniqueSharedMemory, "We should never be calling CalculateAndAllocateMemory in the unique shared memory");
- do {
- oldOffset = *((int *) baseAddress);
+ do
+ {
+ oldOffset = *((int*)_baseAddress);
// we need to verify the oldOffset before we start using it. Otherwise someone could change
// it to something bogus and we would write outside of the shared memory.
ResolveOffset(oldOffset, 0);
-
+
newOffset = CalculateMemory(oldOffset, totalSize, out alignmentAdjustment);
// In the default shared mem we need to make sure that the end address is also aligned. This is because
// in v1.1/v1.0 we just assumed that the next free offset was always properly aligned.
- int endAddressMod8 = (int) (baseAddress + newOffset) & 0x7;
+ int endAddressMod8 = (int)(_baseAddress + newOffset) & 0x7;
int endAlignmentAdjustment = (8 - endAddressMod8) & 0x7;
newOffset += endAlignmentAdjustment;
-
- } while (SafeNativeMethods.InterlockedCompareExchange((IntPtr)baseAddress, newOffset, oldOffset) != oldOffset);
-
+
+ } while (Interlocked.CompareExchange(ref *(int*)((IntPtr)_baseAddress).ToPointer(), newOffset, oldOffset) != oldOffset);
+
return oldOffset;
- }
+ }
- private int CalculateMemory(int oldOffset, int totalSize, out int alignmentAdjustment) {
+ private int CalculateMemory(int oldOffset, int totalSize, out int alignmentAdjustment)
+ {
int newOffset = CalculateMemoryNoBoundsCheck(oldOffset, totalSize, out alignmentAdjustment);
-
- if (newOffset > FileView.FileMappingSize || newOffset < 0) {
+
+ if (newOffset > FileView._fileMappingSize || newOffset < 0)
+ {
throw new InvalidOperationException(SR.Format(SR.CountersOOM));
}
return newOffset;
}
- private int CalculateMemoryNoBoundsCheck(int oldOffset, int totalSize, out int alignmentAdjustment) {
+ private int CalculateMemoryNoBoundsCheck(int oldOffset, int totalSize, out int alignmentAdjustment)
+ {
int currentTotalSize = totalSize;
-
+
Thread.MemoryBarrier();
-
+
// make sure the start address is 8 byte aligned
- int startAddressMod8 = (int) (baseAddress + oldOffset) & 0x7;
+ int startAddressMod8 = (int)(_baseAddress + oldOffset) & 0x7;
alignmentAdjustment = (8 - startAddressMod8) & 0x7;
currentTotalSize = currentTotalSize + alignmentAdjustment;
-
+
int newOffset = oldOffset + currentTotalSize;
-
+
return newOffset;
}
-
- private unsafe int CreateCategory(CategoryEntry* lastCategoryPointer,
- int instanceNameHashCode, string instanceName,
- PerformanceCounterInstanceLifetime lifetime) {
+
+ private unsafe int CreateCategory(CategoryEntry* lastCategoryPointer,
+ int instanceNameHashCode, string instanceName,
+ PerformanceCounterInstanceLifetime lifetime)
+ {
int categoryNameLength;
int instanceNameLength;
int alignmentAdjustment;
int newOffset = 0;
int totalSize;
- categoryNameLength = (categoryName.Length + 1) * 2;
- totalSize = CategoryEntrySize + InstanceEntrySize + (CounterEntrySize * categoryData.CounterNames.Count) + categoryNameLength;
- for (int i=0; i<categoryData.CounterNames.Count; i++) {
- totalSize += (((string)categoryData.CounterNames[i]).Length + 1) * 2;
+ categoryNameLength = (_categoryName.Length + 1) * 2;
+ totalSize = s_categoryEntrySize + s_instanceEntrySize + (s_counterEntrySize * _categoryData.CounterNames.Count) + categoryNameLength;
+ for (int i = 0; i < _categoryData.CounterNames.Count; i++)
+ {
+ totalSize += (((string)_categoryData.CounterNames[i]).Length + 1) * 2;
}
- if (categoryData.UseUniqueSharedMemory) {
+ if (_categoryData.UseUniqueSharedMemory)
+ {
instanceNameLength = InstanceNameSlotSize;
- totalSize += ProcessLifetimeEntrySize + instanceNameLength;
+ totalSize += s_processLifetimeEntrySize + instanceNameLength;
// If we're in a separate shared memory, we need to do a two stage update of the free memory pointer.
// First we calculate our alignment adjustment and where the new free offset is. Then we
// existing ones and update the next free offset. Our process could get killed in between those two,
// leaving the memory in an inconsistent state. We use the "IsConsistent" flag to help determine
// when that has happened.
- freeMemoryOffset = *((int *) baseAddress);
+ freeMemoryOffset = *((int*)_baseAddress);
newOffset = CalculateMemory(freeMemoryOffset, totalSize, out alignmentAdjustment);
- if (freeMemoryOffset == InitialOffset)
+ if (freeMemoryOffset == _initialOffset)
lastCategoryPointer->IsConsistent = 0;
}
- else {
- instanceNameLength = (instanceName.Length +1) * 2;
+ else
+ {
+ instanceNameLength = (instanceName.Length + 1) * 2;
totalSize += instanceNameLength;
freeMemoryOffset = CalculateAndAllocateMemory(totalSize, out alignmentAdjustment);
}
long nextPtr = ResolveOffset(freeMemoryOffset, totalSize + alignmentAdjustment);
-
+
CategoryEntry* newCategoryEntryPointer;
InstanceEntry* newInstanceEntryPointer;
// We need to decide where to put the padding returned in alignmentAdjustment. There are several things that
// on 64 bit platforms we can use interlocked operations on the Value field. alignmentAdjustment guarantees 8 byte
// alignemnt, so we use that for both. If we're creating the very first category, however, we can't move that
// CategoryEntry. In this case we put the alignmentAdjustment before the InstanceEntry.
- if (freeMemoryOffset == InitialOffset) {
- newCategoryEntryPointer = (CategoryEntry*) nextPtr;
- nextPtr += CategoryEntrySize + alignmentAdjustment;
- newInstanceEntryPointer = (InstanceEntry*) nextPtr;
+ if (freeMemoryOffset == _initialOffset)
+ {
+ newCategoryEntryPointer = (CategoryEntry*)nextPtr;
+ nextPtr += s_categoryEntrySize + alignmentAdjustment;
+ newInstanceEntryPointer = (InstanceEntry*)nextPtr;
}
- else {
+ else
+ {
nextPtr += alignmentAdjustment;
- newCategoryEntryPointer = (CategoryEntry*) nextPtr;
- nextPtr += CategoryEntrySize;
- newInstanceEntryPointer = (InstanceEntry*) nextPtr;
+ newCategoryEntryPointer = (CategoryEntry*)nextPtr;
+ nextPtr += s_categoryEntrySize;
+ newInstanceEntryPointer = (InstanceEntry*)nextPtr;
}
- nextPtr += InstanceEntrySize;
+ nextPtr += s_instanceEntrySize;
// create the first CounterEntry and reserve space for all of the rest. We won't
// finish creating them until the end
- CounterEntry* newCounterEntryPointer = (CounterEntry*) nextPtr;
- nextPtr += CounterEntrySize * categoryData.CounterNames.Count;
-
- if (categoryData.UseUniqueSharedMemory) {
- ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*) nextPtr;
- nextPtr += ProcessLifetimeEntrySize;
-
- newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - baseAddress);
+ CounterEntry* newCounterEntryPointer = (CounterEntry*)nextPtr;
+ nextPtr += s_counterEntrySize * _categoryData.CounterNames.Count;
+
+ if (_categoryData.UseUniqueSharedMemory)
+ {
+ ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*)nextPtr;
+ nextPtr += s_processLifetimeEntrySize;
+
+ newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - _baseAddress);
PopulateLifetimeEntry(newLifetimeEntry, lifetime);
}
- newCategoryEntryPointer->CategoryNameHashCode = categoryNameHashCode;
+ newCategoryEntryPointer->CategoryNameHashCode = _categoryNameHashCode;
newCategoryEntryPointer->NextCategoryOffset = 0;
- newCategoryEntryPointer->FirstInstanceOffset = (int)((long)newInstanceEntryPointer - baseAddress);
- newCategoryEntryPointer->CategoryNameOffset = (int) (nextPtr - baseAddress);
- SafeMarshalCopy(categoryName, (IntPtr)nextPtr);
+ newCategoryEntryPointer->FirstInstanceOffset = (int)((long)newInstanceEntryPointer - _baseAddress);
+ newCategoryEntryPointer->CategoryNameOffset = (int)(nextPtr - _baseAddress);
+ SafeMarshalCopy(_categoryName, (IntPtr)nextPtr);
nextPtr += categoryNameLength;
newInstanceEntryPointer->InstanceNameHashCode = instanceNameHashCode;
newInstanceEntryPointer->NextInstanceOffset = 0;
- newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
+ newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
newInstanceEntryPointer->RefCount = 1;
- newInstanceEntryPointer->InstanceNameOffset = (int) (nextPtr - baseAddress);
+ newInstanceEntryPointer->InstanceNameOffset = (int)(nextPtr - _baseAddress);
SafeMarshalCopy(instanceName, (IntPtr)nextPtr);
nextPtr += instanceNameLength;
- string counterName = (string) categoryData.CounterNames[0];
+ string counterName = (string)_categoryData.CounterNames[0];
newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
SetValue(newCounterEntryPointer, 0);
- newCounterEntryPointer->CounterNameOffset = (int) (nextPtr - baseAddress);
+ newCounterEntryPointer->CounterNameOffset = (int)(nextPtr - _baseAddress);
SafeMarshalCopy(counterName, (IntPtr)nextPtr);
nextPtr += (counterName.Length + 1) * 2;
-
+
CounterEntry* previousCounterEntryPointer;
- for (int i=1; i<categoryData.CounterNames.Count; i++) {
+ for (int i = 1; i < _categoryData.CounterNames.Count; i++)
+ {
previousCounterEntryPointer = newCounterEntryPointer;
- counterName = (string) categoryData.CounterNames[i];
-
+ counterName = (string)_categoryData.CounterNames[i];
+
newCounterEntryPointer++;
newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
SetValue(newCounterEntryPointer, 0);
- newCounterEntryPointer->CounterNameOffset = (int) (nextPtr - baseAddress);
+ newCounterEntryPointer->CounterNameOffset = (int)(nextPtr - _baseAddress);
SafeMarshalCopy(counterName, (IntPtr)nextPtr);
nextPtr += (counterName.Length + 1) * 2;
- previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
+ previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
}
-
- Debug.Assert(nextPtr - baseAddress == freeMemoryOffset + totalSize + alignmentAdjustment, "We should have used all of the space we requested at this point");
-
- int offset = (int) ((long) newCategoryEntryPointer - baseAddress);
+
+ Debug.Assert(nextPtr - _baseAddress == freeMemoryOffset + totalSize + alignmentAdjustment, "We should have used all of the space we requested at this point");
+
+ int offset = (int)((long)newCategoryEntryPointer - _baseAddress);
lastCategoryPointer->IsConsistent = 0;
// If not the first category node, link it.
- if (offset != InitialOffset)
+ if (offset != _initialOffset)
lastCategoryPointer->NextCategoryOffset = offset;
- if (categoryData.UseUniqueSharedMemory) {
- *((int*) baseAddress) = newOffset;
+ if (_categoryData.UseUniqueSharedMemory)
+ {
+ *((int*)_baseAddress) = newOffset;
lastCategoryPointer->IsConsistent = 1;
}
return offset;
}
- private unsafe int CreateInstance(CategoryEntry* categoryPointer,
- int instanceNameHashCode, string instanceName,
- PerformanceCounterInstanceLifetime lifetime) {
+ private unsafe int CreateInstance(CategoryEntry* categoryPointer,
+ int instanceNameHashCode, string instanceName,
+ PerformanceCounterInstanceLifetime lifetime)
+ {
int instanceNameLength;
- int totalSize = InstanceEntrySize + (CounterEntrySize * categoryData.CounterNames.Count);
+ int totalSize = s_instanceEntrySize + (s_counterEntrySize * _categoryData.CounterNames.Count);
int alignmentAdjustment;
int freeMemoryOffset;
int newOffset = 0;
- if (categoryData.UseUniqueSharedMemory) {
+ if (_categoryData.UseUniqueSharedMemory)
+ {
instanceNameLength = InstanceNameSlotSize;
- totalSize += ProcessLifetimeEntrySize + instanceNameLength;
+ totalSize += s_processLifetimeEntrySize + instanceNameLength;
// If we're in a separate shared memory, we need to do a two stage update of the free memory pointer.
// First we calculate our alignment adjustment and where the new free offset is. Then we
// existing ones and update the next free offset. Our process could get killed in between those two,
// leaving the memory in an inconsistent state. We use the "IsConsistent" flag to help determine
// when that has happened.
- freeMemoryOffset = *((int *) baseAddress);
+ freeMemoryOffset = *((int*)_baseAddress);
newOffset = CalculateMemory(freeMemoryOffset, totalSize, out alignmentAdjustment);
}
- else {
- instanceNameLength = (instanceName.Length +1) * 2;
+ else
+ {
+ instanceNameLength = (instanceName.Length + 1) * 2;
totalSize += instanceNameLength;
// add in the counter names for the global shared mem.
- for (int i=0; i<categoryData.CounterNames.Count; i++) {
- totalSize += (((string)categoryData.CounterNames[i]).Length + 1) * 2;
+ for (int i = 0; i < _categoryData.CounterNames.Count; i++)
+ {
+ totalSize += (((string)_categoryData.CounterNames[i]).Length + 1) * 2;
}
freeMemoryOffset = CalculateAndAllocateMemory(totalSize, out alignmentAdjustment);
}
long nextPtr = ResolveOffset(freeMemoryOffset, totalSize); // don't add alignmentAdjustment since it's already
// been added to freeMemoryOffset
- InstanceEntry* newInstanceEntryPointer = (InstanceEntry*) nextPtr;
- nextPtr += InstanceEntrySize;
+ InstanceEntry* newInstanceEntryPointer = (InstanceEntry*)nextPtr;
+ nextPtr += s_instanceEntrySize;
// create the first CounterEntry and reserve space for all of the rest. We won't
// finish creating them until the end
- CounterEntry* newCounterEntryPointer = (CounterEntry*) nextPtr;
- nextPtr += CounterEntrySize * categoryData.CounterNames.Count;
-
- if (categoryData.UseUniqueSharedMemory) {
- ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*) nextPtr;
- nextPtr += ProcessLifetimeEntrySize;
-
- newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - baseAddress);
+ CounterEntry* newCounterEntryPointer = (CounterEntry*)nextPtr;
+ nextPtr += s_counterEntrySize * _categoryData.CounterNames.Count;
+
+ if (_categoryData.UseUniqueSharedMemory)
+ {
+ ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*)nextPtr;
+ nextPtr += s_processLifetimeEntrySize;
+
+ newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - _baseAddress);
PopulateLifetimeEntry(newLifetimeEntry, lifetime);
}
// set up the InstanceEntry
newInstanceEntryPointer->InstanceNameHashCode = instanceNameHashCode;
newInstanceEntryPointer->NextInstanceOffset = 0;
- newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
+ newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
newInstanceEntryPointer->RefCount = 1;
- newInstanceEntryPointer->InstanceNameOffset = (int) (nextPtr - baseAddress);
+ newInstanceEntryPointer->InstanceNameOffset = (int)(nextPtr - _baseAddress);
SafeMarshalCopy(instanceName, (IntPtr)nextPtr);
nextPtr += instanceNameLength;
- if (categoryData.UseUniqueSharedMemory) {
+ if (_categoryData.UseUniqueSharedMemory)
+ {
// in the unique shared mem we'll assume that the CounterEntries of the first instance
// are all created. Then we can just refer to the old counter name rather than copying in a new one.
- InstanceEntry* firstInstanceInCategoryPointer = (InstanceEntry*) ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize);
- CounterEntry* firstCounterInCategoryPointer = (CounterEntry*) ResolveOffset(firstInstanceInCategoryPointer->FirstCounterOffset, CounterEntrySize);
+ InstanceEntry* firstInstanceInCategoryPointer = (InstanceEntry*)ResolveOffset(categoryPointer->FirstInstanceOffset, s_instanceEntrySize);
+ CounterEntry* firstCounterInCategoryPointer = (CounterEntry*)ResolveOffset(firstInstanceInCategoryPointer->FirstCounterOffset, s_counterEntrySize);
newCounterEntryPointer->CounterNameHashCode = firstCounterInCategoryPointer->CounterNameHashCode;
SetValue(newCounterEntryPointer, 0);
newCounterEntryPointer->CounterNameOffset = firstCounterInCategoryPointer->CounterNameOffset;
// now create the rest of the CounterEntrys
CounterEntry* previousCounterEntryPointer;
- for (int i=1; i<categoryData.CounterNames.Count; i++) {
+ for (int i = 1; i < _categoryData.CounterNames.Count; i++)
+ {
previousCounterEntryPointer = newCounterEntryPointer;
-
+
newCounterEntryPointer++;
Debug.Assert(firstCounterInCategoryPointer->NextCounterOffset != 0, "The unique shared memory should have all of its counters created by the time we hit CreateInstance");
- firstCounterInCategoryPointer = (CounterEntry*) ResolveOffset(firstCounterInCategoryPointer->NextCounterOffset, CounterEntrySize);
+ firstCounterInCategoryPointer = (CounterEntry*)ResolveOffset(firstCounterInCategoryPointer->NextCounterOffset, s_counterEntrySize);
newCounterEntryPointer->CounterNameHashCode = firstCounterInCategoryPointer->CounterNameHashCode;
SetValue(newCounterEntryPointer, 0);
newCounterEntryPointer->CounterNameOffset = firstCounterInCategoryPointer->CounterNameOffset;
- previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
+ previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
}
}
- else {
+ else
+ {
// now create the rest of the CounterEntrys
CounterEntry* previousCounterEntryPointer = null;
- for (int i=0; i<categoryData.CounterNames.Count; i++) {
- string counterName = (string) categoryData.CounterNames[i];
+ for (int i = 0; i < _categoryData.CounterNames.Count; i++)
+ {
+ string counterName = (string)_categoryData.CounterNames[i];
newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
- newCounterEntryPointer->CounterNameOffset = (int) (nextPtr - baseAddress);
+ newCounterEntryPointer->CounterNameOffset = (int)(nextPtr - _baseAddress);
SafeMarshalCopy(counterName, (IntPtr)nextPtr);
nextPtr += (counterName.Length + 1) * 2;
SetValue(newCounterEntryPointer, 0);
if (i != 0)
- previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
+ previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
previousCounterEntryPointer = newCounterEntryPointer;
newCounterEntryPointer++;
}
}
-
- Debug.Assert(nextPtr - baseAddress == freeMemoryOffset + totalSize, "We should have used all of the space we requested at this point");
- int offset = (int) ((long) newInstanceEntryPointer - baseAddress);
+ Debug.Assert(nextPtr - _baseAddress == freeMemoryOffset + totalSize, "We should have used all of the space we requested at this point");
+
+ int offset = (int)((long)newInstanceEntryPointer - _baseAddress);
categoryPointer->IsConsistent = 0;
-
+
// prepend the new instance rather than append, helps with perf of hooking up subsequent counters
newInstanceEntryPointer->NextInstanceOffset = categoryPointer->FirstInstanceOffset;
categoryPointer->FirstInstanceOffset = offset;
- if (categoryData.UseUniqueSharedMemory) {
- *((int*) baseAddress) = newOffset;
+ if (_categoryData.UseUniqueSharedMemory)
+ {
+ *((int*)_baseAddress) = newOffset;
categoryPointer->IsConsistent = 1;
}
return freeMemoryOffset;
}
- private unsafe int CreateCounter(CounterEntry* lastCounterPointer,
- int counterNameHashCode, string counterName) {
+ private unsafe int CreateCounter(CounterEntry* lastCounterPointer,
+ int counterNameHashCode, string counterName)
+ {
int counterNameLength = (counterName.Length + 1) * 2;
int totalSize = sizeof(CounterEntry) + counterNameLength;
int alignmentAdjustment;
int freeMemoryOffset;
- Debug.Assert(!categoryData.UseUniqueSharedMemory, "We should never be calling CreateCounter in the unique shared memory");
+ Debug.Assert(!_categoryData.UseUniqueSharedMemory, "We should never be calling CreateCounter in the unique shared memory");
freeMemoryOffset = CalculateAndAllocateMemory(totalSize, out alignmentAdjustment);
freeMemoryOffset += alignmentAdjustment;
long nextPtr = ResolveOffset(freeMemoryOffset, totalSize);
- CounterEntry* newCounterEntryPointer = (CounterEntry*) nextPtr;
+ CounterEntry* newCounterEntryPointer = (CounterEntry*)nextPtr;
nextPtr += sizeof(CounterEntry);
- newCounterEntryPointer->CounterNameOffset = (int) (nextPtr - baseAddress);
+ newCounterEntryPointer->CounterNameOffset = (int)(nextPtr - _baseAddress);
newCounterEntryPointer->CounterNameHashCode = counterNameHashCode;
newCounterEntryPointer->NextCounterOffset = 0;
SetValue(newCounterEntryPointer, 0);
SafeMarshalCopy(counterName, (IntPtr)nextPtr);
- Debug.Assert(nextPtr + counterNameLength - baseAddress == freeMemoryOffset + totalSize, "We should have used all of the space we requested at this point");
+ Debug.Assert(nextPtr + counterNameLength - _baseAddress == freeMemoryOffset + totalSize, "We should have used all of the space we requested at this point");
- lastCounterPointer->NextCounterOffset = (int) ((long) newCounterEntryPointer - baseAddress);
+ lastCounterPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - _baseAddress);
return freeMemoryOffset;
}
- private unsafe static void PopulateLifetimeEntry(ProcessLifetimeEntry *lifetimeEntry, PerformanceCounterInstanceLifetime lifetime) {
+ private unsafe static void PopulateLifetimeEntry(ProcessLifetimeEntry* lifetimeEntry, PerformanceCounterInstanceLifetime lifetime)
+ {
- if (lifetime == PerformanceCounterInstanceLifetime.Process) {
+ if (lifetime == PerformanceCounterInstanceLifetime.Process)
+ {
- lifetimeEntry->LifetimeType = (int) PerformanceCounterInstanceLifetime.Process;
+ lifetimeEntry->LifetimeType = (int)PerformanceCounterInstanceLifetime.Process;
lifetimeEntry->ProcessId = ProcessData.ProcessId;
lifetimeEntry->StartupTime = ProcessData.StartupTime;
}
- else {
+ else
+ {
lifetimeEntry->ProcessId = 0;
lifetimeEntry->StartupTime = 0;
}
}
- private static unsafe void WaitAndEnterCriticalSection(int* spinLockPointer, out bool taken) {
+ private static unsafe void WaitAndEnterCriticalSection(int* spinLockPointer, out bool taken)
+ {
WaitForCriticalSection(spinLockPointer);
-
+
// Note - we are taking a lock here, but it probably isn't
// worthwhile to use Thread.BeginCriticalRegion & EndCriticalRegion.
// These only really help the CLR escalate from a thread abort
// Must be able to assign to the out param.
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
}
- finally {
+ finally
+ {
int r = Interlocked.CompareExchange(ref *spinLockPointer, 1, 0);
taken = (r == 0);
}
}
- private static unsafe void WaitForCriticalSection(int* spinLockPointer) {
+ private static unsafe void WaitForCriticalSection(int* spinLockPointer)
+ {
int spinCount = MaxSpinCount;
- for (; spinCount > 0 && *spinLockPointer != 0; spinCount--) {
+ for (; spinCount > 0 && *spinLockPointer != 0; spinCount--)
+ {
// We suspect there are scenarios where the finalizer thread
// will call this method. The finalizer thread runs with
// a higher priority than the other code. Using SpinWait
*spinLockPointer = 0;
}
- private static unsafe void ExitCriticalSection(int* spinLockPointer) {
+ private static unsafe void ExitCriticalSection(int* spinLockPointer)
+ {
*spinLockPointer = 0;
}
internal static int GetWstrHashCode(string wstr)
{
uint hash = 5381;
- for(uint i=0; i < wstr.Length; i++)
- hash = ((hash << 5) + hash) ^ wstr[(int) i];
+ for (uint i = 0; i < wstr.Length; i++)
+ hash = ((hash << 5) + hash) ^ wstr[(int)i];
return (int)hash;
}
// Calculate the length of a string in the shared memory. If we reach the end of the shared memory
// before we see a null terminator, we throw.
- private unsafe int GetStringLength(char* startChar) {
+ private unsafe int GetStringLength(char* startChar)
+ {
char* currentChar = startChar;
- ulong endAddress = (ulong) (baseAddress + FileView.FileMappingSize);
+ ulong endAddress = (ulong)(_baseAddress + FileView._fileMappingSize);
- while((ulong) currentChar < (endAddress - 2)) {
+ while ((ulong)currentChar < (endAddress - 2))
+ {
if (*currentChar == 0)
- return (int) (currentChar - startChar);
-
+ return (int)(currentChar - startChar);
+
currentChar++;
}
// Compare a managed string to a string located at a given offset. If we walk past the end of the
// shared memory, we throw.
- private unsafe bool StringEquals(string stringA, int offset) {
- char* currentChar = (char*) ResolveOffset(offset, 0);
- ulong endAddress = (ulong) (baseAddress + FileView.FileMappingSize);
-
+ private unsafe bool StringEquals(string stringA, int offset)
+ {
+ char* currentChar = (char*)ResolveOffset(offset, 0);
+ ulong endAddress = (ulong)(_baseAddress + FileView._fileMappingSize);
+
int i;
- for (i=0; i<stringA.Length; i++) {
- if ((ulong) (currentChar+i) > (endAddress - 2))
+ for (i = 0; i < stringA.Length; i++)
+ {
+ if ((ulong)(currentChar + i) > (endAddress - 2))
throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
if (stringA[i] != currentChar[i])
}
// now check for the null termination.
- if ((ulong) (currentChar+i) > (endAddress - 2))
+ if ((ulong)(currentChar + i) > (endAddress - 2))
throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
return (currentChar[i] == 0);
}
-
-
- private unsafe CategoryData GetCategoryData() {
- CategoryData data = (CategoryData) categoryDataTable[categoryName];
-
- if (data == null) {
- lock(categoryDataTable) {
- data = (CategoryData) categoryDataTable[categoryName];
- if (data == null) {
+
+
+ private unsafe CategoryData GetCategoryData()
+ {
+ CategoryData data = (CategoryData)s_categoryDataTable[_categoryName];
+
+ if (data == null)
+ {
+ lock (s_categoryDataTable)
+ {
+ data = (CategoryData)s_categoryDataTable[_categoryName];
+ if (data == null)
+ {
data = new CategoryData();
data.FileMappingName = DefaultFileMappingName;
- data.MutexName = categoryName;
+ data.MutexName = _categoryName;
RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
registryPermission.Assert();
RegistryKey categoryKey = null;
- try {
- categoryKey = Registry.LocalMachine.OpenSubKey(PerformanceCounterLib.ServicePath + "\\" + categoryName + "\\Performance");
+ try
+ {
+ categoryKey = Registry.LocalMachine.OpenSubKey(PerformanceCounterLib.ServicePath + "\\" + _categoryName + "\\Performance");
// first read the options
Object optionsObject = categoryKey.GetValue("CategoryOptions");
- if (optionsObject != null) {
- int options = (int) optionsObject;
- data.EnableReuse = (((PerformanceCounterCategoryOptions) options & PerformanceCounterCategoryOptions.EnableReuse) != 0);
-
- if (((PerformanceCounterCategoryOptions) options & PerformanceCounterCategoryOptions.UseUniqueSharedMemory) != 0) {
+ if (optionsObject != null)
+ {
+ int options = (int)optionsObject;
+ data.EnableReuse = (((PerformanceCounterCategoryOptions)options & PerformanceCounterCategoryOptions.EnableReuse) != 0);
+
+ if (((PerformanceCounterCategoryOptions)options & PerformanceCounterCategoryOptions.UseUniqueSharedMemory) != 0)
+ {
data.UseUniqueSharedMemory = true;
- InitialOffset = 8;
- data.FileMappingName = DefaultFileMappingName + categoryName;
+ _initialOffset = 8;
+ data.FileMappingName = DefaultFileMappingName + _categoryName;
}
}
int fileMappingSize;
object fileMappingSizeObject = categoryKey.GetValue("FileMappingSize");
- if (fileMappingSizeObject != null && data.UseUniqueSharedMemory) {
+ if (fileMappingSizeObject != null && data.UseUniqueSharedMemory)
+ {
// we only use this reg value in the unique shared memory case.
- fileMappingSize = (int) fileMappingSizeObject;
+ fileMappingSize = (int)fileMappingSizeObject;
if (fileMappingSize < MinCountersFileMappingSize)
fileMappingSize = MinCountersFileMappingSize;
-
+
if (fileMappingSize > MaxCountersFileMappingSize)
fileMappingSize = MaxCountersFileMappingSize;
}
- else {
- fileMappingSize = GetFileMappingSizeFromConfig();
+ else
+ {
+ fileMappingSize = GetFileMappingSizeFromConfig();
if (data.UseUniqueSharedMemory)
fileMappingSize = fileMappingSize >> 2; // if we have a custom filemapping, only make it 25% as large.
}
// now read the counter names
object counterNamesObject = categoryKey.GetValue("Counter Names");
byte[] counterNamesBytes = counterNamesObject as byte[];
-
- if (counterNamesBytes != null) {
+
+ if (counterNamesBytes != null)
+ {
ArrayList names = new ArrayList();
- fixed (byte* counterNamesPtr = counterNamesBytes) {
+ fixed (byte* counterNamesPtr = counterNamesBytes)
+ {
int start = 0;
- for (int i=0; i<counterNamesBytes.Length-1; i+=2) {
- if (counterNamesBytes[i] == 0 && counterNamesBytes[i+1] == 0 && start != i) {
- string counter = new String((sbyte*)counterNamesPtr, start, i-start, Encoding.Unicode);
+ for (int i = 0; i < counterNamesBytes.Length - 1; i += 2)
+ {
+ if (counterNamesBytes[i] == 0 && counterNamesBytes[i + 1] == 0 && start != i)
+ {
+ string counter = new String((sbyte*)counterNamesPtr, start, i - start, Encoding.Unicode);
names.Add(counter.ToLowerInvariant());
- start = i+2;
+ start = i + 2;
}
}
}
data.CounterNames = names;
}
- else {
- string[] counterNames = (string[]) counterNamesObject;
- for (int i=0; i<counterNames.Length; i++)
+ else
+ {
+ string[] counterNames = (string[])counterNamesObject;
+ for (int i = 0; i < counterNames.Length; i++)
counterNames[i] = counterNames[i].ToLowerInvariant();
data.CounterNames = new ArrayList(counterNames);
}
// figure out the shared memory name
- if (SharedUtils.CurrentEnvironment == SharedUtils.W2kEnvironment) {
- data.FileMappingName = "Global\\" + data.FileMappingName;
- data.MutexName = "Global\\" + categoryName;
+ if (SharedUtils.CurrentEnvironment == SharedUtils.W2kEnvironment)
+ {
+ data.FileMappingName = "Global\\" + data.FileMappingName;
+ data.MutexName = "Global\\" + _categoryName;
}
- data.FileMapping = new FileMapping(data.FileMappingName, fileMappingSize, InitialOffset);
- categoryDataTable[categoryName] = data;
+ data.FileMapping = new FileMapping(data.FileMappingName, fileMappingSize, _initialOffset);
+ s_categoryDataTable[_categoryName] = data;
}
- finally {
+ finally
+ {
if (categoryKey != null)
categoryKey.Close();
RegistryPermission.RevertAssert();
}
}
}
- baseAddress = (long) data.FileMapping.FileViewAddress;
+ _baseAddress = (long)data.FileMapping.FileViewAddress;
if (data.UseUniqueSharedMemory)
- InitialOffset = 8;
-
+ _initialOffset = 8;
+
return data;
}
[MethodImpl(MethodImplOptions.NoInlining)]
- private static int GetFileMappingSizeFromConfig() {
+ private static int GetFileMappingSizeFromConfig()
+ {
return DiagnosticsConfiguration.PerformanceCountersFileMappingSize;
}
- private static void RemoveCategoryData(string categoryName) {
- lock (categoryDataTable) {
- categoryDataTable.Remove(categoryName);
+ private static void RemoveCategoryData(string categoryName)
+ {
+ lock (s_categoryDataTable)
+ {
+ s_categoryDataTable.Remove(categoryName);
}
}
- private unsafe CounterEntry* GetCounter(string counterName, string instanceName, bool enableReuse, PerformanceCounterInstanceLifetime lifetime) {
+ private unsafe CounterEntry* GetCounter(string counterName, string instanceName, bool enableReuse, PerformanceCounterInstanceLifetime lifetime)
+ {
int counterNameHashCode = GetWstrHashCode(counterName);
int instanceNameHashCode;
if (instanceName != null && instanceName.Length != 0)
instanceNameHashCode = GetWstrHashCode(instanceName);
- else {
- instanceNameHashCode = SingleInstanceHashCode;
+ else
+ {
+ instanceNameHashCode = s_singleInstanceHashCode;
instanceName = SingleInstanceName;
}
CounterEntry* counterPointer = null;
InstanceEntry* instancePointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex);
+ try
+ {
+ SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
CategoryEntry* categoryPointer;
bool counterFound = false;
- while (!FindCategory(&categoryPointer)) {
+ while (!FindCategory(&categoryPointer))
+ {
// don't bother locking again if we're using a separate shared memory.
bool sectionEntered;
- if (categoryData.UseUniqueSharedMemory)
+ if (_categoryData.UseUniqueSharedMemory)
sectionEntered = true;
else
WaitAndEnterCriticalSection(&(categoryPointer->SpinLock), out sectionEntered);
int newCategoryOffset;
- if (sectionEntered) {
- try {
+ if (sectionEntered)
+ {
+ try
+ {
newCategoryOffset = CreateCategory(categoryPointer, instanceNameHashCode, instanceName, lifetime);
}
- finally {
- if (!categoryData.UseUniqueSharedMemory)
+ finally
+ {
+ if (!_categoryData.UseUniqueSharedMemory)
ExitCriticalSection(&(categoryPointer->SpinLock));
}
- categoryPointer = (CategoryEntry*)(ResolveOffset(newCategoryOffset, CategoryEntrySize));
- instancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize));
+ categoryPointer = (CategoryEntry*)(ResolveOffset(newCategoryOffset, s_categoryEntrySize));
+ instancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, s_instanceEntrySize));
counterFound = FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer);
Debug.Assert(counterFound, "All counters should be created, so we should always find the counter");
return counterPointer;
}
bool foundFreeInstance;
- while (!FindInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, true, lifetime, out foundFreeInstance)) {
+ while (!FindInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, true, lifetime, out foundFreeInstance))
+ {
InstanceEntry* lockInstancePointer = instancePointer;
-
+
// don't bother locking again if we're using a separate shared memory.
bool sectionEntered;
- if (categoryData.UseUniqueSharedMemory)
+ if (_categoryData.UseUniqueSharedMemory)
sectionEntered = true;
else
WaitAndEnterCriticalSection(&(lockInstancePointer->SpinLock), out sectionEntered);
-
- if (sectionEntered) {
- try {
+
+ if (sectionEntered)
+ {
+ try
+ {
bool reused = false;
- if (enableReuse && foundFreeInstance) {
+ if (enableReuse && foundFreeInstance)
+ {
reused = TryReuseInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, lifetime, lockInstancePointer);
// at this point we might have reused an instance that came from v1.1/v1.0. We can't assume it will have the counter
// we're looking for.
}
- if (!reused) {
+ if (!reused)
+ {
int newInstanceOffset = CreateInstance(categoryPointer, instanceNameHashCode, instanceName, lifetime);
- instancePointer = (InstanceEntry*)(ResolveOffset(newInstanceOffset, InstanceEntrySize));
+ instancePointer = (InstanceEntry*)(ResolveOffset(newInstanceOffset, s_instanceEntrySize));
counterFound = FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer);
Debug.Assert(counterFound, "All counters should be created, so we should always find the counter");
return counterPointer;
}
}
- finally {
- if (!categoryData.UseUniqueSharedMemory)
+ finally
+ {
+ if (!_categoryData.UseUniqueSharedMemory)
ExitCriticalSection(&(lockInstancePointer->SpinLock));
}
}
}
- if (categoryData.UseUniqueSharedMemory) {
+ if (_categoryData.UseUniqueSharedMemory)
+ {
counterFound = FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer);
Debug.Assert(counterFound, "All counters should be created, so we should always find the counter");
return counterPointer;
}
- else {
- while (!FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer)) {
+ else
+ {
+ while (!FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer))
+ {
bool sectionEntered;
WaitAndEnterCriticalSection(&(counterPointer->SpinLock), out sectionEntered);
-
- if (sectionEntered) {
- try {
- int newCounterOffset = CreateCounter(counterPointer, counterNameHashCode, counterName);
- return (CounterEntry*) (ResolveOffset(newCounterOffset, CounterEntrySize));
+
+ if (sectionEntered)
+ {
+ try
+ {
+ int newCounterOffset = CreateCounter(counterPointer, counterNameHashCode, counterName);
+ return (CounterEntry*)(ResolveOffset(newCounterOffset, s_counterEntrySize));
}
- finally {
+ finally
+ {
ExitCriticalSection(&(counterPointer->SpinLock));
}
}
}
-
+
return counterPointer;
}
}
- finally {
+ finally
+ {
// cache this instance for reuse
- try {
- if (counterPointer != null && instancePointer != null) {
- this.thisInstanceOffset = ResolveAddress((long)instancePointer, InstanceEntrySize);
+ try
+ {
+ if (counterPointer != null && instancePointer != null)
+ {
+ _thisInstanceOffset = ResolveAddress((long)instancePointer, s_instanceEntrySize);
}
}
- catch (InvalidOperationException) {
- this.thisInstanceOffset = -1;
+ catch (InvalidOperationException)
+ {
+ _thisInstanceOffset = -1;
}
- if (mutex != null) {
+ if (mutex != null)
+ {
mutex.ReleaseMutex();
mutex.Close();
}
// * when the function returns false the returnCategoryPointerReference is set to the last CategoryEntry
// in the linked list
//
- private unsafe bool FindCategory(CategoryEntry** returnCategoryPointerReference) {
- CategoryEntry* firstCategoryPointer = (CategoryEntry*)(ResolveOffset(InitialOffset, CategoryEntrySize));
+ private unsafe bool FindCategory(CategoryEntry** returnCategoryPointerReference)
+ {
+ CategoryEntry* firstCategoryPointer = (CategoryEntry*)(ResolveOffset(_initialOffset, s_categoryEntrySize));
CategoryEntry* currentCategoryPointer = firstCategoryPointer;
CategoryEntry* previousCategoryPointer = firstCategoryPointer;
- for(;;) {
+ for (; ; )
+ {
if (currentCategoryPointer->IsConsistent == 0)
Verify(currentCategoryPointer);
-
- if (currentCategoryPointer->CategoryNameHashCode == categoryNameHashCode) {
- if (StringEquals(categoryName, currentCategoryPointer->CategoryNameOffset)) {
+
+ if (currentCategoryPointer->CategoryNameHashCode == _categoryNameHashCode)
+ {
+ if (StringEquals(_categoryName, currentCategoryPointer->CategoryNameOffset))
+ {
*returnCategoryPointerReference = currentCategoryPointer;
return true;
}
previousCategoryPointer = currentCategoryPointer;
if (currentCategoryPointer->NextCategoryOffset != 0)
- currentCategoryPointer = (CategoryEntry*)(ResolveOffset(currentCategoryPointer->NextCategoryOffset, CategoryEntrySize));
- else {
+ currentCategoryPointer = (CategoryEntry*)(ResolveOffset(currentCategoryPointer->NextCategoryOffset, s_categoryEntrySize));
+ else
+ {
*returnCategoryPointerReference = previousCategoryPointer;
return false;
}
}
}
- private unsafe bool FindCounter(int counterNameHashCode, string counterName, InstanceEntry* instancePointer, CounterEntry** returnCounterPointerReference) {
- CounterEntry* currentCounterPointer = (CounterEntry*)(ResolveOffset(instancePointer->FirstCounterOffset, CounterEntrySize));
+ private unsafe bool FindCounter(int counterNameHashCode, string counterName, InstanceEntry* instancePointer, CounterEntry** returnCounterPointerReference)
+ {
+ CounterEntry* currentCounterPointer = (CounterEntry*)(ResolveOffset(instancePointer->FirstCounterOffset, s_counterEntrySize));
CounterEntry* previousCounterPointer = currentCounterPointer;
- for(;;) {
- if (currentCounterPointer->CounterNameHashCode == counterNameHashCode) {
- if (StringEquals(counterName, currentCounterPointer->CounterNameOffset)) {
+ for (; ; )
+ {
+ if (currentCounterPointer->CounterNameHashCode == counterNameHashCode)
+ {
+ if (StringEquals(counterName, currentCounterPointer->CounterNameOffset))
+ {
*returnCounterPointerReference = currentCounterPointer;
return true;
}
previousCounterPointer = currentCounterPointer;
if (currentCounterPointer->NextCounterOffset != 0)
- currentCounterPointer = (CounterEntry*)(ResolveOffset(currentCounterPointer->NextCounterOffset, CounterEntrySize));
- else {
+ currentCounterPointer = (CounterEntry*)(ResolveOffset(currentCounterPointer->NextCounterOffset, s_counterEntrySize));
+ else
+ {
*returnCounterPointerReference = previousCounterPointer;
return false;
}
}
}
- private unsafe bool FindInstance(int instanceNameHashCode, string instanceName,
- CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference,
- bool activateUnusedInstances, PerformanceCounterInstanceLifetime lifetime,
- out bool foundFreeInstance) {
+ private unsafe bool FindInstance(int instanceNameHashCode, string instanceName,
+ CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference,
+ bool activateUnusedInstances, PerformanceCounterInstanceLifetime lifetime,
+ out bool foundFreeInstance)
+ {
- InstanceEntry* currentInstancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize));
+ InstanceEntry* currentInstancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, s_instanceEntrySize));
InstanceEntry* previousInstancePointer = currentInstancePointer;
foundFreeInstance = false;
// Look at the first instance to determine if this is single or multi instance.
- if (currentInstancePointer->InstanceNameHashCode == SingleInstanceHashCode) {
- if (StringEquals(SingleInstanceName, currentInstancePointer->InstanceNameOffset)){
+ if (currentInstancePointer->InstanceNameHashCode == s_singleInstanceHashCode)
+ {
+ if (StringEquals(SingleInstanceName, currentInstancePointer->InstanceNameOffset))
+ {
if (instanceName != SingleInstanceName)
- throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, categoryName));
+ throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, _categoryName));
}
- else {
+ else
+ {
if (instanceName == SingleInstanceName)
- throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, categoryName));
+ throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, _categoryName));
}
}
- else {
+ else
+ {
if (instanceName == SingleInstanceName)
- throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, categoryName));
+ throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, _categoryName));
}
//
// verify lifetime of instances if activateUnusedInstances is specified and certain time
// has elapsed since last sweep or we are running out of shared memory.
bool verifyLifeTime = activateUnusedInstances;
- if (activateUnusedInstances) {
-
- int totalSize = InstanceEntrySize + ProcessLifetimeEntrySize + InstanceNameSlotSize + (CounterEntrySize * categoryData.CounterNames.Count);
- int freeMemoryOffset = *((int *) baseAddress);
+ if (activateUnusedInstances)
+ {
+
+ int totalSize = s_instanceEntrySize + s_processLifetimeEntrySize + InstanceNameSlotSize + (s_counterEntrySize * _categoryData.CounterNames.Count);
+ int freeMemoryOffset = *((int*)_baseAddress);
int alignmentAdjustment;
int newOffset = CalculateMemoryNoBoundsCheck(freeMemoryOffset, totalSize, out alignmentAdjustment);
- if (!(newOffset > FileView.FileMappingSize || newOffset < 0)) {
- long tickDelta = (DateTime.Now.Ticks - Volatile.Read(ref LastInstanceLifetimeSweepTick));
- if (tickDelta < InstanceLifetimeSweepWindow)
- verifyLifeTime = false;
+ if (!(newOffset > FileView._fileMappingSize || newOffset < 0))
+ {
+ long tickDelta = (DateTime.Now.Ticks - Volatile.Read(ref s_lastInstanceLifetimeSweepTick));
+ if (tickDelta < InstanceLifetimeSweepWindow)
+ verifyLifeTime = false;
}
}
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
- try {
- for(;;) {
+ try
+ {
+ for (; ; )
+ {
bool verifiedLifetimeOfThisInstance = false;
- if (verifyLifeTime && (currentInstancePointer->RefCount != 0)) {
+ if (verifyLifeTime && (currentInstancePointer->RefCount != 0))
+ {
verifiedLifetimeOfThisInstance = true;
VerifyLifetime(currentInstancePointer);
}
-
- if (currentInstancePointer->InstanceNameHashCode == instanceNameHashCode) {
- if (StringEquals(instanceName, currentInstancePointer->InstanceNameOffset)){
+
+ if (currentInstancePointer->InstanceNameHashCode == instanceNameHashCode)
+ {
+ if (StringEquals(instanceName, currentInstancePointer->InstanceNameOffset))
+ {
// we found a matching instance.
*returnInstancePointerReference = currentInstancePointer;
-
- CounterEntry* firstCounter = (CounterEntry*) ResolveOffset(currentInstancePointer->FirstCounterOffset, CounterEntrySize);
+
+ CounterEntry* firstCounter = (CounterEntry*)ResolveOffset(currentInstancePointer->FirstCounterOffset, s_counterEntrySize);
ProcessLifetimeEntry* lifetimeEntry;
- if (categoryData.UseUniqueSharedMemory)
- lifetimeEntry = (ProcessLifetimeEntry*) ResolveOffset(firstCounter->LifetimeOffset, ProcessLifetimeEntrySize);
+ if (_categoryData.UseUniqueSharedMemory)
+ lifetimeEntry = (ProcessLifetimeEntry*)ResolveOffset(firstCounter->LifetimeOffset, s_processLifetimeEntrySize);
else
lifetimeEntry = null;
-
+
// ensure that we have verified the lifetime of the matched instance
- if (!verifiedLifetimeOfThisInstance && currentInstancePointer->RefCount != 0)
+ if (!verifiedLifetimeOfThisInstance && currentInstancePointer->RefCount != 0)
VerifyLifetime(currentInstancePointer);
-
- if (currentInstancePointer->RefCount != 0) {
- if (lifetimeEntry != null && lifetimeEntry->ProcessId != 0) {
+
+ if (currentInstancePointer->RefCount != 0)
+ {
+ if (lifetimeEntry != null && lifetimeEntry->ProcessId != 0)
+ {
if (lifetime != PerformanceCounterInstanceLifetime.Process)
throw new InvalidOperationException(SR.Format(SR.CantConvertProcessToGlobal));
-
+
// make sure only one process is using this instance.
if (ProcessData.ProcessId != lifetimeEntry->ProcessId)
throw new InvalidOperationException(SR.Format(SR.InstanceAlreadyExists, instanceName));
- // compare start time of the process, account for ACL issues in querying process information
- if ((lifetimeEntry->StartupTime != -1) && (ProcessData.StartupTime != -1)) {
+ // compare start time of the process, account for ACL issues in querying process information
+ if ((lifetimeEntry->StartupTime != -1) && (ProcessData.StartupTime != -1))
+ {
if (ProcessData.StartupTime != lifetimeEntry->StartupTime)
throw new InvalidOperationException(SR.Format(SR.InstanceAlreadyExists, instanceName));
}
}
- else {
+ else
+ {
if (lifetime == PerformanceCounterInstanceLifetime.Process)
throw new InvalidOperationException(SR.Format(SR.CantConvertGlobalToProcess));
}
return true;
}
-
- if (activateUnusedInstances) {
+
+ if (activateUnusedInstances)
+ {
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex);
+ try
+ {
+ SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
ClearCounterValues(currentInstancePointer);
if (lifetimeEntry != null)
PopulateLifetimeEntry(lifetimeEntry, lifetime);
-
+
currentInstancePointer->RefCount = 1;
return true;
}
- finally {
- if (mutex != null) {
+ finally
+ {
+ if (mutex != null)
+ {
mutex.ReleaseMutex();
mutex.Close();
}
return false;
}
}
-
- if (currentInstancePointer->RefCount == 0) {
+
+ if (currentInstancePointer->RefCount == 0)
+ {
foundFreeInstance = true;
}
-
+
previousInstancePointer = currentInstancePointer;
if (currentInstancePointer->NextInstanceOffset != 0)
- currentInstancePointer = (InstanceEntry*)(ResolveOffset(currentInstancePointer->NextInstanceOffset, InstanceEntrySize));
- else {
+ currentInstancePointer = (InstanceEntry*)(ResolveOffset(currentInstancePointer->NextInstanceOffset, s_instanceEntrySize));
+ else
+ {
*returnInstancePointerReference = previousInstancePointer;
return false;
}
}
}
- finally {
- SecurityPermission.RevertAssert();
-
- if (verifyLifeTime)
- Volatile.Write(ref LastInstanceLifetimeSweepTick, DateTime.Now.Ticks);
+ finally
+ {
+ if (verifyLifeTime)
+ Volatile.Write(ref s_lastInstanceLifetimeSweepTick, DateTime.Now.Ticks);
}
}
- private unsafe bool TryReuseInstance(int instanceNameHashCode, string instanceName,
- CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference,
+ private unsafe bool TryReuseInstance(int instanceNameHashCode, string instanceName,
+ CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference,
PerformanceCounterInstanceLifetime lifetime,
- InstanceEntry* lockInstancePointer) {
+ InstanceEntry* lockInstancePointer)
+ {
//
// 2nd pass find a free instance slot
//
- InstanceEntry* currentInstancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize));
+ InstanceEntry* currentInstancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, s_instanceEntrySize));
InstanceEntry* previousInstancePointer = currentInstancePointer;
- for (;;) {
- if (currentInstancePointer->RefCount == 0) {
+ for (; ; )
+ {
+ if (currentInstancePointer->RefCount == 0)
+ {
bool hasFit;
long instanceNamePtr; // we need cache this to avoid race conditions.
-
- if (categoryData.UseUniqueSharedMemory) {
+
+ if (_categoryData.UseUniqueSharedMemory)
+ {
instanceNamePtr = ResolveOffset(currentInstancePointer->InstanceNameOffset, InstanceNameSlotSize);
// In the separate shared memory case we should always have enough space for instances. The
// name slot size is fixed.
Debug.Assert(((instanceName.Length + 1) * 2) <= InstanceNameSlotSize, "The instance name length should always fit in our slot size");
hasFit = true;
}
- else {
+ else
+ {
// we don't know the string length yet.
instanceNamePtr = ResolveOffset(currentInstancePointer->InstanceNameOffset, 0);
// In the global shared memory, we require names to be exactly the same length in order
// to reuse them. This way we don't end up leaking any space and we don't need to
// depend on the layout of the memory to calculate the space we have.
- int length = GetStringLength((char*) instanceNamePtr);
+ int length = GetStringLength((char*)instanceNamePtr);
hasFit = (length == instanceName.Length);
}
- bool noSpinLock = (lockInstancePointer == currentInstancePointer) || categoryData.UseUniqueSharedMemory;
+ bool noSpinLock = (lockInstancePointer == currentInstancePointer) || _categoryData.UseUniqueSharedMemory;
// Instance name fit
- if (hasFit) {
+ if (hasFit)
+ {
// don't bother locking again if we're using a separate shared memory.
bool sectionEntered;
if (noSpinLock)
else
WaitAndEnterCriticalSection(&(currentInstancePointer->SpinLock), out sectionEntered);
- if (sectionEntered) {
- try {
+ if (sectionEntered)
+ {
+ try
+ {
// Make copy with zero-term
SafeMarshalCopy(instanceName, (IntPtr)instanceNamePtr);
currentInstancePointer->InstanceNameHashCode = instanceNameHashCode;
// clear the counter values.
ClearCounterValues(*returnInstancePointerReference);
- if (categoryData.UseUniqueSharedMemory) {
- CounterEntry* counterPointer = (CounterEntry*)ResolveOffset(currentInstancePointer->FirstCounterOffset, CounterEntrySize);
- ProcessLifetimeEntry* lifetimeEntry = (ProcessLifetimeEntry*) ResolveOffset(counterPointer->LifetimeOffset, ProcessLifetimeEntrySize);
+ if (_categoryData.UseUniqueSharedMemory)
+ {
+ CounterEntry* counterPointer = (CounterEntry*)ResolveOffset(currentInstancePointer->FirstCounterOffset, s_counterEntrySize);
+ ProcessLifetimeEntry* lifetimeEntry = (ProcessLifetimeEntry*)ResolveOffset(counterPointer->LifetimeOffset, s_processLifetimeEntrySize);
PopulateLifetimeEntry(lifetimeEntry, lifetime);
}
-
+
(*returnInstancePointerReference)->RefCount = 1;
return true;
}
- finally {
+ finally
+ {
if (!noSpinLock)
ExitCriticalSection(&(currentInstancePointer->SpinLock));
}
}
}
- }
-
+ }
+
previousInstancePointer = currentInstancePointer;
if (currentInstancePointer->NextInstanceOffset != 0)
- currentInstancePointer = (InstanceEntry*)(ResolveOffset(currentInstancePointer->NextInstanceOffset, InstanceEntrySize));
+ currentInstancePointer = (InstanceEntry*)(ResolveOffset(currentInstancePointer->NextInstanceOffset, s_instanceEntrySize));
else
{
*returnInstancePointerReference = previousInstancePointer;
}
}
- private unsafe void Verify(CategoryEntry* currentCategoryPointer) {
- if (!categoryData.UseUniqueSharedMemory)
+ private unsafe void Verify(CategoryEntry* currentCategoryPointer)
+ {
+ if (!_categoryData.UseUniqueSharedMemory)
return;
-
+
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex);
+ try
+ {
+ SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
VerifyCategory(currentCategoryPointer);
}
- finally {
- if (mutex != null) {
+ finally
+ {
+ if (mutex != null)
+ {
mutex.ReleaseMutex();
mutex.Close();
}
}
- }
+ }
- private unsafe void VerifyCategory(CategoryEntry* currentCategoryPointer) {
- int freeOffset = *((int*)baseAddress);
+ private unsafe void VerifyCategory(CategoryEntry* currentCategoryPointer)
+ {
+ int freeOffset = *((int*)_baseAddress);
ResolveOffset(freeOffset, 0); // verify next free offset
// begin by verifying the head node's offset
- int currentOffset = ResolveAddress((long)currentCategoryPointer, CategoryEntrySize);
- if (currentOffset >= freeOffset) {
+ int currentOffset = ResolveAddress((long)currentCategoryPointer, s_categoryEntrySize);
+ if (currentOffset >= freeOffset)
+ {
// zero out the bad head node entry
- currentCategoryPointer->SpinLock = 0;
+ currentCategoryPointer->SpinLock = 0;
currentCategoryPointer->CategoryNameHashCode = 0;
- currentCategoryPointer->CategoryNameOffset = 0;
- currentCategoryPointer->FirstInstanceOffset = 0;
- currentCategoryPointer->NextCategoryOffset = 0;
- currentCategoryPointer->IsConsistent = 0;
+ currentCategoryPointer->CategoryNameOffset = 0;
+ currentCategoryPointer->FirstInstanceOffset = 0;
+ currentCategoryPointer->NextCategoryOffset = 0;
+ currentCategoryPointer->IsConsistent = 0;
return;
}
if (currentCategoryPointer->NextCategoryOffset > freeOffset)
currentCategoryPointer->NextCategoryOffset = 0;
else if (currentCategoryPointer->NextCategoryOffset != 0)
- VerifyCategory((CategoryEntry*) ResolveOffset(currentCategoryPointer->NextCategoryOffset, CategoryEntrySize));
+ VerifyCategory((CategoryEntry*)ResolveOffset(currentCategoryPointer->NextCategoryOffset, s_categoryEntrySize));
- if (currentCategoryPointer->FirstInstanceOffset != 0) {
+ if (currentCategoryPointer->FirstInstanceOffset != 0)
+ {
// In V3, we started prepending the new instances rather than appending (as in V2) for performance.
// Check whether the recently added instance at the head of the list is committed. If not, rewire
// the head of the list to point to the next instance
- if (currentCategoryPointer->FirstInstanceOffset > freeOffset) {
- InstanceEntry* currentInstancePointer = (InstanceEntry*) ResolveOffset(currentCategoryPointer->FirstInstanceOffset, InstanceEntrySize);
- currentCategoryPointer->FirstInstanceOffset = currentInstancePointer->NextInstanceOffset;
+ if (currentCategoryPointer->FirstInstanceOffset > freeOffset)
+ {
+ InstanceEntry* currentInstancePointer = (InstanceEntry*)ResolveOffset(currentCategoryPointer->FirstInstanceOffset, s_instanceEntrySize);
+ currentCategoryPointer->FirstInstanceOffset = currentInstancePointer->NextInstanceOffset;
if (currentCategoryPointer->FirstInstanceOffset > freeOffset)
currentCategoryPointer->FirstInstanceOffset = 0;
}
// the head of the list is a valid committed offset and if so we should traverse to the end of the
// list and do the consistency check for the tail instance. In theory, the inconsistent instance
// should either be the head node or the tail node but not the middle node.
- if (currentCategoryPointer->FirstInstanceOffset != 0) {
+ if (currentCategoryPointer->FirstInstanceOffset != 0)
+ {
Debug.Assert(currentCategoryPointer->FirstInstanceOffset <= freeOffset, "The head of the list is inconsistent - possible mismatch of V2 & V3 instances?");
- VerifyInstance((InstanceEntry*) ResolveOffset(currentCategoryPointer->FirstInstanceOffset, InstanceEntrySize));
+ VerifyInstance((InstanceEntry*)ResolveOffset(currentCategoryPointer->FirstInstanceOffset, s_instanceEntrySize));
}
}
-
+
currentCategoryPointer->IsConsistent = 1;
}
-
- private unsafe void VerifyInstance(InstanceEntry* currentInstancePointer) {
- int freeOffset = *((int*)baseAddress);
+
+ private unsafe void VerifyInstance(InstanceEntry* currentInstancePointer)
+ {
+ int freeOffset = *((int*)_baseAddress);
ResolveOffset(freeOffset, 0); // verify next free offset
if (currentInstancePointer->NextInstanceOffset > freeOffset)
currentInstancePointer->NextInstanceOffset = 0;
else if (currentInstancePointer->NextInstanceOffset != 0)
- VerifyInstance((InstanceEntry*) ResolveOffset(currentInstancePointer->NextInstanceOffset, InstanceEntrySize));
+ VerifyInstance((InstanceEntry*)ResolveOffset(currentInstancePointer->NextInstanceOffset, s_instanceEntrySize));
}
- private unsafe void VerifyLifetime(InstanceEntry* currentInstancePointer) {
+ private unsafe void VerifyLifetime(InstanceEntry* currentInstancePointer)
+ {
Debug.Assert(currentInstancePointer->RefCount != 0, "RefCount must be 1 for instances passed to VerifyLifetime");
- CounterEntry* counter = (CounterEntry*) ResolveOffset(currentInstancePointer->FirstCounterOffset, CounterEntrySize);
- if (counter->LifetimeOffset != 0) {
- ProcessLifetimeEntry* lifetime = (ProcessLifetimeEntry*) ResolveOffset(counter->LifetimeOffset, ProcessLifetimeEntrySize);
- if (lifetime->LifetimeType == (int) PerformanceCounterInstanceLifetime.Process) {
+ CounterEntry* counter = (CounterEntry*)ResolveOffset(currentInstancePointer->FirstCounterOffset, s_counterEntrySize);
+ if (counter->LifetimeOffset != 0)
+ {
+ ProcessLifetimeEntry* lifetime = (ProcessLifetimeEntry*)ResolveOffset(counter->LifetimeOffset, s_processLifetimeEntrySize);
+ if (lifetime->LifetimeType == (int)PerformanceCounterInstanceLifetime.Process)
+ {
int pid = lifetime->ProcessId;
long startTime = lifetime->StartupTime;
- if (pid != 0) {
+ if (pid != 0)
+ {
// Optimize for this process
- if (pid == ProcessData.ProcessId) {
- if ((ProcessData.StartupTime != -1) && (startTime != -1) && (ProcessData.StartupTime != startTime)) {
+ if (pid == ProcessData.ProcessId)
+ {
+ if ((ProcessData.StartupTime != -1) && (startTime != -1) && (ProcessData.StartupTime != startTime))
+ {
// Process id got recycled. Reclaim this instance.
currentInstancePointer->RefCount = 0;
return;
}
}
- else {
+ else
+ {
long processStartTime;
- using (SafeProcessHandle procHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, pid)) {
+ using (SafeProcessHandle procHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, pid))
+ {
int error = Marshal.GetLastWin32Error();
- if ((error == Interop.Errors.ERROR_INVALID_PARAMETER) && procHandle.IsInvalid) {
+ if ((error == Interop.Errors.ERROR_INVALID_PARAMETER) && procHandle.IsInvalid)
+ {
// The process is dead. Reclaim this instance. Note that we only clear the refcount here.
// If we tried to clear the pid and startup time as well, we would have a race where
// we could clear the pid/startup time but not the refcount.
// Defer cleaning the instance when we had previously encountered errors in
// recording process start time (i.e, when startTime == -1) until after the
// process id is not valid (which will be caught in the if check above)
- if (!procHandle.IsInvalid && startTime != -1) {
+ if (!procHandle.IsInvalid && startTime != -1)
+ {
long temp;
- if (Interop.Kernel32.GetProcessTimes(procHandle, out processStartTime, out temp, out temp, out temp)) {
- if (processStartTime != startTime) {
+ if (Interop.Kernel32.GetProcessTimes(procHandle, out processStartTime, out temp, out temp, out temp))
+ {
+ if (processStartTime != startTime)
+ {
// The process is dead but a new one is using the same pid. Reclaim this instance.
currentInstancePointer->RefCount = 0;
return;
// Check to see if the process handle has been signaled by the kernel. If this is the case then it's safe
// to reclaim the instance as the process is in the process of exiting.
- using (SafeProcessHandle procHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false, pid)) {
- if (!procHandle.IsInvalid) {
- using (ProcessWaitHandle wh = new ProcessWaitHandle(procHandle)) {
- if (wh.WaitOne(0, false)) {
+ using (SafeProcessHandle procHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false, pid))
+ {
+ if (!procHandle.IsInvalid)
+ {
+ using (ProcessWaitHandle wh = new ProcessWaitHandle(procHandle))
+ {
+ if (wh.WaitOne(0, false))
+ {
// Process has exited
currentInstancePointer->RefCount = 0;
return;
}
}
}
-
+
}
}
}
- internal unsafe long IncrementBy(long value) {
- if (counterEntryPointer == null)
+ internal unsafe long IncrementBy(long value)
+ {
+ if (_counterEntryPointer == null)
return 0;
- CounterEntry* counterEntry = this.counterEntryPointer;
+ CounterEntry* counterEntry = _counterEntryPointer;
return AddToValue(counterEntry, value);
}
- internal unsafe long Increment() {
- if (counterEntryPointer == null)
+ internal unsafe long Increment()
+ {
+ if (_counterEntryPointer == null)
return 0;
- return IncrementUnaligned(this.counterEntryPointer);
+ return IncrementUnaligned(_counterEntryPointer);
}
- internal unsafe long Decrement() {
- if (counterEntryPointer == null)
+ internal unsafe long Decrement()
+ {
+ if (_counterEntryPointer == null)
return 0;
- return DecrementUnaligned(this.counterEntryPointer);
+ return DecrementUnaligned(_counterEntryPointer);
}
- internal unsafe static void RemoveAllInstances(string categoryName) {
+ internal unsafe static void RemoveAllInstances(string categoryName)
+ {
SharedPerformanceCounter spc = new SharedPerformanceCounter(categoryName, null, null);
spc.RemoveAllInstances();
RemoveCategoryData(categoryName);
}
- private unsafe void RemoveAllInstances() {
+ private unsafe void RemoveAllInstances()
+ {
CategoryEntry* categoryPointer;
if (!FindCategory(&categoryPointer))
return;
- InstanceEntry* instancePointer = (InstanceEntry *)(ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize));
+ InstanceEntry* instancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, s_instanceEntrySize));
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex);
- for(;;) {
+ try
+ {
+ SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
+ for (; ; )
+ {
RemoveOneInstance(instancePointer, true);
-
+
if (instancePointer->NextInstanceOffset != 0)
- instancePointer = (InstanceEntry*)(ResolveOffset(instancePointer->NextInstanceOffset, InstanceEntrySize));
- else {
+ instancePointer = (InstanceEntry*)(ResolveOffset(instancePointer->NextInstanceOffset, s_instanceEntrySize));
+ else
+ {
break;
}
}
}
- finally {
- if (mutex != null) {
+ finally
+ {
+ if (mutex != null)
+ {
mutex.ReleaseMutex();
mutex.Close();
}
}
}
- internal unsafe void RemoveInstance(string instanceName, PerformanceCounterInstanceLifetime instanceLifetime) {
- if (instanceName == null || instanceName.Length == 0)
+ internal unsafe void RemoveInstance(string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
+ {
+ if (instanceName == null || instanceName.Length == 0)
return;
int instanceNameHashCode = GetWstrHashCode(instanceName);
-
+
CategoryEntry* categoryPointer;
- if (!FindCategory(&categoryPointer))
+ if (!FindCategory(&categoryPointer))
return;
-
+
InstanceEntry* instancePointer = null;
bool validatedCachedInstancePointer = false;
bool temp;
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex);
-
- if (this.thisInstanceOffset != -1) {
- try {
+ try
+ {
+ SharedUtils.EnterMutexWithoutGlobal(_categoryData.MutexName, ref mutex);
+
+ if (_thisInstanceOffset != -1)
+ {
+ try
+ {
// validate whether the cached instance pointer is pointing at the right instance
- instancePointer = (InstanceEntry*)(ResolveOffset(this.thisInstanceOffset, InstanceEntrySize));
- if (instancePointer->InstanceNameHashCode == instanceNameHashCode) {
- if (StringEquals(instanceName, instancePointer->InstanceNameOffset)){
+ instancePointer = (InstanceEntry*)(ResolveOffset(_thisInstanceOffset, s_instanceEntrySize));
+ if (instancePointer->InstanceNameHashCode == instanceNameHashCode)
+ {
+ if (StringEquals(instanceName, instancePointer->InstanceNameOffset))
+ {
validatedCachedInstancePointer = true;
// this is probably overkill
- CounterEntry* firstCounter = (CounterEntry*) ResolveOffset(instancePointer->FirstCounterOffset, CounterEntrySize);
+ CounterEntry* firstCounter = (CounterEntry*)ResolveOffset(instancePointer->FirstCounterOffset, s_counterEntrySize);
ProcessLifetimeEntry* lifetimeEntry;
- if (categoryData.UseUniqueSharedMemory) {
- lifetimeEntry = (ProcessLifetimeEntry*) ResolveOffset(firstCounter->LifetimeOffset, ProcessLifetimeEntrySize);
- if (lifetimeEntry != null
- && lifetimeEntry->LifetimeType == (int)PerformanceCounterInstanceLifetime.Process
- && lifetimeEntry->ProcessId != 0) {
+ if (_categoryData.UseUniqueSharedMemory)
+ {
+ lifetimeEntry = (ProcessLifetimeEntry*)ResolveOffset(firstCounter->LifetimeOffset, s_processLifetimeEntrySize);
+ if (lifetimeEntry != null
+ && lifetimeEntry->LifetimeType == (int)PerformanceCounterInstanceLifetime.Process
+ && lifetimeEntry->ProcessId != 0)
+ {
validatedCachedInstancePointer &= (instanceLifetime == PerformanceCounterInstanceLifetime.Process);
validatedCachedInstancePointer &= (ProcessData.ProcessId == lifetimeEntry->ProcessId);
- if ((lifetimeEntry->StartupTime != -1) && (ProcessData.StartupTime != -1))
+ if ((lifetimeEntry->StartupTime != -1) && (ProcessData.StartupTime != -1))
validatedCachedInstancePointer &= (ProcessData.StartupTime == lifetimeEntry->StartupTime);
}
- else
+ else
validatedCachedInstancePointer &= (instanceLifetime != PerformanceCounterInstanceLifetime.Process);
}
}
}
}
- catch (InvalidOperationException) {
+ catch (InvalidOperationException)
+ {
validatedCachedInstancePointer = false;
}
- if (!validatedCachedInstancePointer)
- this.thisInstanceOffset = -1;
+ if (!validatedCachedInstancePointer)
+ _thisInstanceOffset = -1;
}
-
- if (!validatedCachedInstancePointer && !FindInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, false, instanceLifetime, out temp))
- return ;
+
+ if (!validatedCachedInstancePointer && !FindInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, false, instanceLifetime, out temp))
+ return;
if (instancePointer != null)
RemoveOneInstance(instancePointer, false);
}
- finally {
- if (mutex != null) {
+ finally
+ {
+ if (mutex != null)
+ {
mutex.ReleaseMutex();
mutex.Close();
}
}
}
- private unsafe void RemoveOneInstance(InstanceEntry* instancePointer, bool clearValue) {
+ private unsafe void RemoveOneInstance(InstanceEntry* instancePointer, bool clearValue)
+ {
bool sectionEntered = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- if (!categoryData.UseUniqueSharedMemory) {
- while (!sectionEntered) {
+ try
+ {
+ if (!_categoryData.UseUniqueSharedMemory)
+ {
+ while (!sectionEntered)
+ {
WaitAndEnterCriticalSection(&(instancePointer->SpinLock), out sectionEntered);
}
}
-
+
instancePointer->RefCount = 0;
if (clearValue)
ClearCounterValues(instancePointer);
}
- finally {
+ finally
+ {
if (sectionEntered)
ExitCriticalSection(&(instancePointer->SpinLock));
}
}
- private unsafe void ClearCounterValues(InstanceEntry* instancePointer) {
+ private unsafe void ClearCounterValues(InstanceEntry* instancePointer)
+ {
//Clear counter instance values
CounterEntry* currentCounterPointer = null;
-
+
if (instancePointer->FirstCounterOffset != 0)
- currentCounterPointer = (CounterEntry*)(ResolveOffset(instancePointer->FirstCounterOffset, CounterEntrySize));
+ currentCounterPointer = (CounterEntry*)(ResolveOffset(instancePointer->FirstCounterOffset, s_counterEntrySize));
- while(currentCounterPointer != null) {
+ while (currentCounterPointer != null)
+ {
SetValue(currentCounterPointer, 0);
-
+
if (currentCounterPointer->NextCounterOffset != 0)
- currentCounterPointer = (CounterEntry*)(ResolveOffset(currentCounterPointer->NextCounterOffset, CounterEntrySize));
+ currentCounterPointer = (CounterEntry*)(ResolveOffset(currentCounterPointer->NextCounterOffset, s_counterEntrySize));
else
currentCounterPointer = null;
}
}
- private static unsafe long AddToValue(CounterEntry* counterEntry, long addend) {
+ private static unsafe long AddToValue(CounterEntry* counterEntry, long addend)
+ {
// Called while holding a lock - shouldn't have to worry about
// reading misaligned data & getting old vs. new parts of an Int64.
- if (IsMisaligned(counterEntry)) {
+ if (IsMisaligned(counterEntry))
+ {
ulong newvalue;
- CounterEntryMisaligned* entry = (CounterEntryMisaligned*) counterEntry;
- newvalue = (uint)entry->Value_hi;
+ CounterEntryMisaligned* entry = (CounterEntryMisaligned*)counterEntry;
+ newvalue = (uint)entry->Value_hi;
newvalue <<= 32;
newvalue |= (uint)entry->Value_lo;
- newvalue = (ulong) ((long) newvalue + addend);
+ newvalue = (ulong)((long)newvalue + addend);
- entry->Value_hi = (int) (newvalue >> 32);
- entry->Value_lo = (int) (newvalue & 0xffffffff);
+ entry->Value_hi = (int)(newvalue >> 32);
+ entry->Value_lo = (int)(newvalue & 0xffffffff);
- return (long) newvalue;
+ return (long)newvalue;
}
- else
+ else
return Interlocked.Add(ref counterEntry->Value, addend);
}
- private static unsafe long DecrementUnaligned(CounterEntry* counterEntry) {
- if (IsMisaligned(counterEntry))
+ private static unsafe long DecrementUnaligned(CounterEntry* counterEntry)
+ {
+ if (IsMisaligned(counterEntry))
return AddToValue(counterEntry, -1);
else
return Interlocked.Decrement(ref counterEntry->Value);
}
- private static unsafe long GetValue(CounterEntry* counterEntry) {
- if (IsMisaligned(counterEntry)) {
+ private static unsafe long GetValue(CounterEntry* counterEntry)
+ {
+ if (IsMisaligned(counterEntry))
+ {
ulong value;
- CounterEntryMisaligned* entry = (CounterEntryMisaligned*) counterEntry;
- value = (uint)entry->Value_hi;
+ CounterEntryMisaligned* entry = (CounterEntryMisaligned*)counterEntry;
+ value = (uint)entry->Value_hi;
value <<= 32;
value |= (uint)entry->Value_lo;
- return (long) value;
+ return (long)value;
}
else
return counterEntry->Value;
}
- private static unsafe long IncrementUnaligned(CounterEntry* counterEntry) {
- if (IsMisaligned(counterEntry))
+ private static unsafe long IncrementUnaligned(CounterEntry* counterEntry)
+ {
+ if (IsMisaligned(counterEntry))
return AddToValue(counterEntry, 1);
else
return Interlocked.Increment(ref counterEntry->Value);
}
- private static unsafe void SetValue(CounterEntry* counterEntry, long value) {
- if (IsMisaligned(counterEntry)) {
- CounterEntryMisaligned* entry = (CounterEntryMisaligned*) counterEntry;
- entry->Value_lo = (int) (value & 0xffffffff);
- entry->Value_hi = (int) (value >> 32);
+ private static unsafe void SetValue(CounterEntry* counterEntry, long value)
+ {
+ if (IsMisaligned(counterEntry))
+ {
+ CounterEntryMisaligned* entry = (CounterEntryMisaligned*)counterEntry;
+ entry->Value_lo = (int)(value & 0xffffffff);
+ entry->Value_hi = (int)(value >> 32);
}
else
counterEntry->Value = value;
}
- private static unsafe bool IsMisaligned(CounterEntry* counterEntry) {
- return (( (Int64)counterEntry & 0x7) != 0);
+ private static unsafe bool IsMisaligned(CounterEntry* counterEntry)
+ {
+ return (((Int64)counterEntry & 0x7) != 0);
}
- private long ResolveOffset(int offset, int sizeToRead) {
+ private long ResolveOffset(int offset, int sizeToRead)
+ {
//It is very important to check the integrity of the shared memory
//everytime a new address is resolved.
- if (offset > (FileView.FileMappingSize - sizeToRead) || offset < 0)
+ if (offset > (FileView._fileMappingSize - sizeToRead) || offset < 0)
throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
- long address = baseAddress + offset;
+ long address = _baseAddress + offset;
return address;
}
- private int ResolveAddress(long address, int sizeToRead) {
- int offset = (int)(address - baseAddress);
+ private int ResolveAddress(long address, int sizeToRead)
+ {
+ int offset = (int)(address - _baseAddress);
//It is very important to check the integrity of the shared memory
//everytime a new address is resolved.
- if (offset > (FileView.FileMappingSize - sizeToRead) || offset < 0)
+ if (offset > (FileView._fileMappingSize - sizeToRead) || offset < 0)
throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
return offset;
}
- private class FileMapping {
- internal int FileMappingSize;
- private SafeMemoryMappedViewHandle fileViewAddress = null;
- private SafeMemoryMappedFileHandle fileMappingHandle = null;
+ private class FileMapping
+ {
+ internal int _fileMappingSize;
+ private SafeMemoryMappedViewHandle _fileViewAddress = null;
+ private SafeMemoryMappedFileHandle _fileMappingHandle = null;
//The version of the file mapping name is independent from the
//assembly version.
-
- public FileMapping(string fileMappingName, int fileMappingSize, int initialOffset) {
- this.Initialize(fileMappingName, fileMappingSize, initialOffset);
+
+ public FileMapping(string fileMappingName, int fileMappingSize, int initialOffset)
+ {
+ Initialize(fileMappingName, fileMappingSize, initialOffset);
}
- internal IntPtr FileViewAddress {
- get {
- if (fileViewAddress.IsInvalid)
- throw new InvalidOperationException(SR.Format(SR.SharedMemoryGhosted));
+ internal IntPtr FileViewAddress
+ {
+ get
+ {
+ if (_fileViewAddress.IsInvalid)
+ throw new InvalidOperationException(SR.Format(SR.SharedMemoryGhosted));
- return fileViewAddress.DangerousGetHandle();
+ return _fileViewAddress.DangerousGetHandle();
}
}
- private unsafe void Initialize(string fileMappingName, int fileMappingSize, int initialOffset) {
+ private unsafe void Initialize(string fileMappingName, int fileMappingSize, int initialOffset)
+ {
string mappingName = fileMappingName;
SharedUtils.CheckEnvironment();
SafeLocalMemHandle securityDescriptorPointer = null;
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
- try {
+ try
+ {
// The sddl string consists of these parts:
// D: it's a DACL
// (A; this is an allow ACE
// ;S-1-5-33) the same permission granted to AU is also granted to restricted services
string sddlString = "D:(A;OICI;FRFWGRGW;;;AU)(A;OICI;FRFWGRGW;;;S-1-5-33)";
- if (!SafeLocalMemHandle.ConvertStringSecurityDescriptorToSecurityDescriptor(sddlString, Interop.Kernel32.PerformanceCounterOptions.SDDL_REVISION_1,
+ if (!Interop.Advapi32.ConvertStringSecurityDescriptorToSecurityDescriptor(sddlString, Interop.Kernel32.PerformanceCounterOptions.SDDL_REVISION_1,
out securityDescriptorPointer, IntPtr.Zero))
throw new InvalidOperationException(SR.Format(SR.SetSecurityDescriptorFailed));
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
bool created = false;
- while (!created && waitRetries > 0) {
- fileMappingHandle = Interop.Kernel32.CreateFileMapping((IntPtr)(-1), ref securityAttributes,
+ while (!created && waitRetries > 0)
+ {
+ _fileMappingHandle = Interop.Kernel32.CreateFileMapping((IntPtr)(-1), ref securityAttributes,
Interop.Kernel32.PageOptions.PAGE_READWRITE, 0, fileMappingSize, mappingName);
- if ((Marshal.GetLastWin32Error() != Interop.Errors.ERROR_ACCESS_DENIED) || !fileMappingHandle.IsInvalid) {
+ if ((Marshal.GetLastWin32Error() != Interop.Errors.ERROR_ACCESS_DENIED) || !_fileMappingHandle.IsInvalid)
+ {
created = true;
}
- else {
+ else
+ {
// Invalidate the old safehandle before we get rid of it. This prevents it from trying to finalize
- fileMappingHandle.SetHandleAsInvalid();
- fileMappingHandle = Interop.Kernel32.OpenFileMapping(Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE, false, mappingName);
+ _fileMappingHandle.SetHandleAsInvalid();
+ _fileMappingHandle = Interop.Kernel32.OpenFileMapping(Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE, false, mappingName);
- if ((Marshal.GetLastWin32Error() != Interop.Errors.ERROR_FILE_NOT_FOUND) || !fileMappingHandle.IsInvalid) {
+ if ((Marshal.GetLastWin32Error() != Interop.Errors.ERROR_FILE_NOT_FOUND) || !_fileMappingHandle.IsInvalid)
+ {
created = true;
}
- else {
+ else
+ {
--waitRetries;
- if (waitSleep == 0) {
+ if (waitSleep == 0)
+ {
waitSleep = 10;
}
- else {
+ else
+ {
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
}
}
- if (fileMappingHandle.IsInvalid) {
+ if (_fileMappingHandle.IsInvalid)
+ {
throw new InvalidOperationException(SR.Format(SR.CantCreateFileMapping));
}
- fileViewAddress = Interop.Kernel32.MapViewOfFile(fileMappingHandle, Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE, 0,0, UIntPtr.Zero);
- if (fileViewAddress.IsInvalid)
+ _fileViewAddress = Interop.Kernel32.MapViewOfFile(_fileMappingHandle, Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE, 0, 0, UIntPtr.Zero);
+ if (_fileViewAddress.IsInvalid)
throw new InvalidOperationException(SR.Format(SR.CantMapFileView));
// figure out what size the share memory really is.
Interop.Kernel32.MEMORY_BASIC_INFORMATION meminfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
- if (Interop.Kernel32.VirtualQuery(fileViewAddress, ref meminfo, (UIntPtr)sizeof(Interop.Kernel32.MEMORY_BASIC_INFORMATION)) == UIntPtr.Zero)
+ if (Interop.Kernel32.VirtualQuery(_fileViewAddress, ref meminfo, (UIntPtr)sizeof(Interop.Kernel32.MEMORY_BASIC_INFORMATION)) == UIntPtr.Zero)
throw new InvalidOperationException(SR.Format(SR.CantGetMappingSize));
-
- FileMappingSize = (int) meminfo.RegionSize;
+
+ _fileMappingSize = (int)meminfo.RegionSize;
}
- finally {
- if (securityDescriptorPointer != null) securityDescriptorPointer.Close();
- SecurityPermission.RevertAssert();
+ finally
+ {
+ if (securityDescriptorPointer != null)
+ securityDescriptorPointer.Close();
}
- SafeNativeMethods.InterlockedCompareExchange(fileViewAddress.DangerousGetHandle(), initialOffset, 0);
+ Interlocked.CompareExchange(ref *(int*)_fileViewAddress.DangerousGetHandle().ToPointer(), initialOffset, 0);
}
}
// SafeMarshalCopy always null terminates the char array
// before copying it to native memory
//
- private static void SafeMarshalCopy(string str, IntPtr nativePointer) {
+ private static void SafeMarshalCopy(string str, IntPtr nativePointer)
+ {
// convert str to a char array and copy it to the unmanaged memory pointer
char[] tmp = new char[str.Length + 1];
str.CopyTo(0, tmp, 0, str.Length);
// Note that in V1.0 and v1.1 there was no explicit padding defined on any of these structs. That means that
// sizeof(CategoryEntry) or Marshal.SizeOf(typeof(CategoryEntry)) returned 4 bytes less before Whidbey,
// and the int we use as IsConsistent could actually overlap the InstanceEntry SpinLock.
-
+
[StructLayout(LayoutKind.Sequential)]
- private struct CategoryEntry {
+ private struct CategoryEntry
+ {
public int SpinLock;
public int CategoryNameHashCode;
public int CategoryNameOffset;
}
[StructLayout(LayoutKind.Sequential)]
- private struct InstanceEntry {
+ private struct InstanceEntry
+ {
public int SpinLock;
public int InstanceNameHashCode;
public int InstanceNameOffset;
}
[StructLayout(LayoutKind.Sequential)]
- private struct CounterEntry {
+ private struct CounterEntry
+ {
public int SpinLock;
public int CounterNameHashCode;
public int CounterNameOffset;
public int LifetimeOffset; // this was 4 bytes of padding in v1.0/v1.1
public long Value;
public int NextCounterOffset;
- public int padding2;
+ public int padding2;
}
[StructLayout(LayoutKind.Sequential)]
- private struct CounterEntryMisaligned {
+ private struct CounterEntryMisaligned
+ {
public int SpinLock;
public int CounterNameHashCode;
public int CounterNameOffset;
}
[StructLayout(LayoutKind.Sequential)]
- private struct ProcessLifetimeEntry {
+ private struct ProcessLifetimeEntry
+ {
public int LifetimeType;
public int ProcessId;
public Int64 StartupTime;
}
-
- private class CategoryData {
+
+ private class CategoryData
+ {
public FileMapping FileMapping;
public bool EnableReuse;
public bool UseUniqueSharedMemory;
}
}
- internal class ProcessData {
- public ProcessData(int pid, long startTime) {
+ internal class ProcessData
+ {
+ public ProcessData(int pid, long startTime)
+ {
ProcessId = pid;
StartupTime = startTime;
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Diagnostics {
- using System.Security.Permissions;
- using System.Security;
- using System.Threading;
- using System.Text;
- using Microsoft.Win32;
- using System.Globalization;
- using System.ComponentModel;
- using System.Security.Principal;
- using System.Security.AccessControl;
- using System.Runtime.Versioning;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using Microsoft.Win32.SafeHandles;
- using System.Diagnostics.CodeAnalysis;
-
- internal static class SharedUtils {
-
+using System.Security.Permissions;
+using System.Threading;
+using System.Text;
+using Microsoft.Win32;
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Diagnostics.CodeAnalysis;
+
+namespace System.Diagnostics
+{
+ internal static class SharedUtils
+ {
+
internal const int UnknownEnvironment = 0;
internal const int W2kEnvironment = 1;
internal const int NtEnvironment = 2;
- internal const int NonNtEnvironment = 3;
- private static volatile int environment = UnknownEnvironment;
+ internal const int NonNtEnvironment = 3;
+ private static volatile int s_environment = UnknownEnvironment;
public const int WAIT_OBJECT_0 = 0x00000000;
- public const int WAIT_ABANDONED = 0x00000080;
+ public const int WAIT_ABANDONED = 0x00000080;
private static Object s_InternalSyncObject;
- private static Object InternalSyncObject {
- get {
- if (s_InternalSyncObject == null) {
+ private static Object InternalSyncObject
+ {
+ get
+ {
+ if (s_InternalSyncObject == null)
+ {
Object o = new Object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
}
}
- internal static Win32Exception CreateSafeWin32Exception() {
+ internal static Win32Exception CreateSafeWin32Exception()
+ {
return CreateSafeWin32Exception(0);
}
- internal static Win32Exception CreateSafeWin32Exception(int error) {
+ internal static Win32Exception CreateSafeWin32Exception(int error)
+ {
Win32Exception newException = null;
- // Need to assert SecurtiyPermission, otherwise Win32Exception
- // will not be able to get the error message. At this point the right
- // permissions have already been demanded.
- SecurityPermission securityPermission = new SecurityPermission(PermissionState.Unrestricted);
- securityPermission.Assert();
- try {
+ try
+ {
if (error == 0)
newException = new Win32Exception();
else
newException = new Win32Exception(error);
}
- finally {
- SecurityPermission.RevertAssert();
+ finally
+ {
}
return newException;
}
- internal static int CurrentEnvironment {
- get {
- if (environment == UnknownEnvironment) {
- lock (InternalSyncObject) {
- if (environment == UnknownEnvironment) {
+ internal static int CurrentEnvironment
+ {
+ get
+ {
+ if (s_environment == UnknownEnvironment)
+ {
+ lock (InternalSyncObject)
+ {
+ if (s_environment == UnknownEnvironment)
+ {
// Need to assert Environment permissions here
// the environment check is not exposed as a public method
- if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
+ if (Environment.OSVersion.Platform == PlatformID.Win32NT)
+ {
if (Environment.OSVersion.Version.Major >= 5)
- environment = W2kEnvironment;
+ s_environment = W2kEnvironment;
else
- environment = NtEnvironment;
- }
- else
- environment = NonNtEnvironment;
- }
+ s_environment = NtEnvironment;
+ }
+ else
+ s_environment = NonNtEnvironment;
+ }
}
}
-
- return environment;
- }
- }
-
- internal static void CheckEnvironment() {
+
+ return s_environment;
+ }
+ }
+
+ internal static void CheckEnvironment()
+ {
if (CurrentEnvironment == NonNtEnvironment)
throw new PlatformNotSupportedException(SR.Format(SR.WinNTRequired));
}
- internal static void CheckNtEnvironment() {
+ internal static void CheckNtEnvironment()
+ {
if (CurrentEnvironment == NtEnvironment)
throw new PlatformNotSupportedException(SR.Format(SR.Win2000Required));
}
-
- internal static void EnterMutex(string name, ref Mutex mutex) {
+
+ internal static void EnterMutex(string name, ref Mutex mutex)
+ {
string mutexName = null;
if (CurrentEnvironment == W2kEnvironment)
- mutexName = "Global\\" + name;
+ mutexName = "Global\\" + name;
else
mutexName = name;
EnterMutexWithoutGlobal(mutexName, ref mutex);
}
- [SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "matell: We pass fixed data into sec.AddAccessRule")]
- internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex) {
+ internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex)
+ {
bool createdNew;
Mutex tmpMutex = new Mutex(false, mutexName, out createdNew);
Debug.Assert(mutexOut == null, "You must pass in a null ref Mutex");
// Wait as long as necessary for the mutex.
- while (true) {
+ while (true)
+ {
// Attempt to acquire the mutex but timeout quickly if we can't.
if (!SafeWaitForMutexOnce(mutexIn, ref mutexOut))
bool ret;
RuntimeHelpers.PrepareConstrainedRegions();
- try {} finally {
+ try
+ { }
+ finally
+ {
// Wait for the mutex for half a second (long enough to gain the mutex in most scenarios and short enough to avoid
// impacting a thread abort for too long).
// Holding a mutex requires us to keep thread affinity and announce ourselves as a critical region.
Thread.BeginCriticalRegion();
Thread.BeginThreadAffinity();
- int result = WaitForSingleObjectDontCallThis(mutexIn.SafeWaitHandle, 500);
- switch (result) {
-
- case WAIT_OBJECT_0:
- case WAIT_ABANDONED:
- // Mutex was obtained, atomically record that fact.
- mutexOut = mutexIn;
- ret = true;
- break;
-
- case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT:
- // Couldn't get mutex yet, simply return and we'll try again later.
- ret = true;
- break;
-
- default:
- // Some sort of failure return immediately all the way to the caller of SafeWaitForMutex.
- ret = false;
- break;
+ int result = Interop.Kernel32.WaitForSingleObjectDontCallThis(mutexIn.SafeWaitHandle, 500);
+ switch (result)
+ {
+
+ case WAIT_OBJECT_0:
+ case WAIT_ABANDONED:
+ // Mutex was obtained, atomically record that fact.
+ mutexOut = mutexIn;
+ ret = true;
+ break;
+
+ case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT:
+ // Couldn't get mutex yet, simply return and we'll try again later.
+ ret = true;
+ break;
+
+ default:
+ // Some sort of failure return immediately all the way to the caller of SafeWaitForMutex.
+ ret = false;
+ break;
}
// If we're not leaving with the Mutex we don't require thread affinity and we're not a critical region any more.
- if (mutexOut == null) {
+ if (mutexOut == null)
+ {
Thread.EndThreadAffinity();
Thread.EndCriticalRegion();
}
return ret;
}
- // P/Invoke for the methods above. Don't call this from anywhere else.
- [DllImport(ExternDll.Kernel32, ExactSpelling=true, SetLastError=true, EntryPoint="WaitForSingleObject")]
- private static extern int WaitForSingleObjectDontCallThis(SafeWaitHandle handle, int timeout);
-
- // What if an app is locked back? Why would we use this?
- internal static string GetLatestBuildDllDirectory(string machineName) {
+ // What if an app is locked back? Why would we use this?
+ internal static string GetLatestBuildDllDirectory(string machineName)
+ {
string dllDir = "";
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 {
- if (machineName.Equals(".")) {
+ try
+ {
+ if (machineName.Equals("."))
+ {
return GetLocalBuildDirectory();
}
- else {
+ else
+ {
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);
}
if (baseKey == null)
throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, "HKEY_LOCAL_MACHINE", machineName));
complusReg = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework");
- if (complusReg != null) {
+ if (complusReg != null)
+ {
string installRoot = (string)complusReg.GetValue("InstallRoot");
- if (installRoot != null && installRoot != String.Empty) {
+ if (installRoot != null && installRoot != string.Empty)
+ {
// the "policy" subkey contains a v{major}.{minor} subkey for each version installed. There are also
// some extra subkeys like "standards" and "upgrades" we want to ignore.
// This is the full version string of the install on the remote machine we want to use (for example "v2.0.50727")
string version = null;
- if (policyKey != null) {
- try {
-
+ if (policyKey != null)
+ {
+ try
+ {
+
// First check to see if there is a version of the runtime with the same minor and major number:
RegistryKey bestKey = policyKey.OpenSubKey(versionPrefix);
- if (bestKey != null) {
- try {
+ if (bestKey != null)
+ {
+ try
+ {
version = versionPrefix + "." + GetLargestBuildNumberFromKey(bestKey);
- } finally {
+ }
+ finally
+ {
bestKey.Close();
}
- } else {
+ }
+ else
+ {
// There isn't an exact match for our version, so we will look for the largest version
// installed.
string[] majorVersions = policyKey.GetSubKeyNames();
int[] largestVersion = new int[] { -1, -1, -1 };
- for (int i = 0; i < majorVersions.Length; i++) {
+ for (int i = 0; i < majorVersions.Length; i++)
+ {
string majorVersion = majorVersions[i];
// If this looks like a key of the form v{something}.{something}, we should see if it's a usable build.
- if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains(".")) {
+ if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains("."))
+ {
int[] currentVersion = new int[] { -1, -1, -1 };
string[] splitVersion = majorVersion.Substring(1).Split('.');
- if(splitVersion.Length != 2) {
+ if (splitVersion.Length != 2)
+ {
continue;
}
- if (!Int32.TryParse(splitVersion[0], out currentVersion[0]) || !Int32.TryParse(splitVersion[1], out currentVersion[1])) {
+ if (!Int32.TryParse(splitVersion[0], out currentVersion[0]) || !Int32.TryParse(splitVersion[1], out currentVersion[1]))
+ {
continue;
}
RegistryKey k = policyKey.OpenSubKey(majorVersion);
- if (k == null) {
+ if (k == null)
+ {
// We may be able to use another subkey
continue;
}
- try {
+ try
+ {
currentVersion[2] = GetLargestBuildNumberFromKey(k);
if (currentVersion[0] > largestVersion[0]
- || ((currentVersion[0] == largestVersion[0]) && (currentVersion[1] > largestVersion[1]))) {
+ || ((currentVersion[0] == largestVersion[0]) && (currentVersion[1] > largestVersion[1])))
+ {
largestVersion = currentVersion;
}
- } finally {
+ }
+ finally
+ {
k.Close();
}
}
version = "v" + largestVersion[0] + "." + largestVersion[1] + "." + largestVersion[2];
}
- } finally {
+ }
+ finally
+ {
policyKey.Close();
}
- if (version != null && version != String.Empty) {
+ if (version != null && version != string.Empty)
+ {
StringBuilder installBuilder = new StringBuilder();
installBuilder.Append(installRoot);
if (!installRoot.EndsWith("\\", StringComparison.Ordinal))
}
}
}
- }
+ }
}
- catch {
+ catch
+ {
// ignore
}
- finally {
+ finally
+ {
if (complusReg != null)
complusReg.Close();
if (baseKey != null)
baseKey.Close();
- RegistryPermission.RevertAssert();
+ RegistryPermission.RevertAssert();
}
return dllDir;
- }
+ }
- private static int GetLargestBuildNumberFromKey(RegistryKey rootKey) {
+ private static int GetLargestBuildNumberFromKey(RegistryKey rootKey)
+ {
int largestBuild = -1;
string[] minorVersions = rootKey.GetValueNames();
- for (int i = 0; i < minorVersions.Length; i++) {
+ for (int i = 0; i < minorVersions.Length; i++)
+ {
int o;
- if (Int32.TryParse(minorVersions[i], out o)) {
+ if (Int32.TryParse(minorVersions[i], out o))
+ {
largestBuild = (largestBuild > o) ? largestBuild : o;
}
}
return largestBuild;
}
- private static string GetLocalBuildDirectory() {
+ private static string GetLocalBuildDirectory()
+ {
return RuntimeEnvironment.GetRuntimeDirectory();
}
}
-}
+}
using System.Configuration;
-namespace System.Diagnostics {
- internal class SystemDiagnosticsSection : ConfigurationSection {
- private static readonly ConfigurationPropertyCollection _properties;
- private static readonly ConfigurationProperty _propPerfCounters = new ConfigurationProperty("performanceCounters", typeof(PerfCounterSection), new PerfCounterSection(), ConfigurationPropertyOptions.None);
+namespace System.Diagnostics
+{
+ internal class SystemDiagnosticsSection : ConfigurationSection
+ {
+ private static readonly ConfigurationPropertyCollection s_properties;
+ private static readonly ConfigurationProperty s_propPerfCounters = new ConfigurationProperty("performanceCounters", typeof(PerfCounterSection), new PerfCounterSection(), ConfigurationPropertyOptions.None);
- static SystemDiagnosticsSection() {
- _properties = new ConfigurationPropertyCollection();
- _properties.Add(_propPerfCounters);
+ static SystemDiagnosticsSection()
+ {
+ s_properties = new ConfigurationPropertyCollection();
+ s_properties.Add(s_propPerfCounters);
}
[ConfigurationProperty("performanceCounters")]
- public PerfCounterSection PerfCounters {
- get {
- return (PerfCounterSection) base[_propPerfCounters];
+ public PerfCounterSection PerfCounters
+ {
+ get
+ {
+ return (PerfCounterSection)base[s_propPerfCounters];
}
}
}
}
-
+
// 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 System.IO;
-using System.Collections;
-using System.Reflection;
namespace System.Diagnostics
{
using System.ComponentModel;
using System.Security;
-using System.Security.Permissions;
using System.Security.Principal;
-using Microsoft.Win32;
-using Microsoft.Win32.SafeHandles;
-using System.Security.Claims;
-using System.Runtime.InteropServices;
namespace System
{
internal static class EnvironmentHelpers
{
- private static volatile bool s_IsAppContainerProcess;
- private static volatile bool s_IsAppContainerProcessInitalized;
+ private static volatile bool s_isAppContainerProcess;
+ private static volatile bool s_isAppContainerProcessInitalized;
internal const int TokenIsAppContainer = 29;
- public static bool IsAppContainerProcess {
- get {
- if(!s_IsAppContainerProcessInitalized) {
- if(Environment.OSVersion.Platform != PlatformID.Win32NT) {
- s_IsAppContainerProcess = false;
- } else if(Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1)) {
- // Windows 7 or older.
- s_IsAppContainerProcess = false;
- } else {
- s_IsAppContainerProcess = HasAppContainerToken();
- }
-
- s_IsAppContainerProcessInitalized = true;
+ public static bool IsAppContainerProcess
+ {
+ get
+ {
+ if (!s_isAppContainerProcessInitalized)
+ {
+ if (Environment.OSVersion.Platform != PlatformID.Win32NT)
+ {
+ s_isAppContainerProcess = false;
+ }
+ else if (Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1))
+ {
+ // Windows 7 or older.
+ s_isAppContainerProcess = false;
+ }
+ else
+ {
+ s_isAppContainerProcess = HasAppContainerToken();
+ }
+
+ s_isAppContainerProcessInitalized = true;
}
- return s_IsAppContainerProcess;
+ return s_isAppContainerProcess;
}
}
[SecuritySafeCritical]
- private static unsafe bool HasAppContainerToken() {
+ private static unsafe bool HasAppContainerToken()
+ {
int* dwIsAppContainerPtr = stackalloc int[1];
uint dwLength = 0;
- using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query)) {
- if (!GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength)) {
+ using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query))
+ {
+ if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength))
+ {
throw new Win32Exception();
}
}
return (*dwIsAppContainerPtr != 0);
}
-
- [DllImport(ExternDll.Advapi32, CharSet=CharSet.Auto, SetLastError=true)]
- internal static extern bool GetTokenInformation (
- [In] IntPtr TokenHandle,
- [In] uint TokenInformationClass,
- [In] IntPtr TokenInformation,
- [In] uint TokenInformationLength,
- [Out] out uint ReturnLength);
}
}
+++ /dev/null
-// 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.
-
-namespace System
-{
- internal static class ExternDll
- {
- public const string Kernel32 = "kernel32.dll";
- public const string Advapi32 = "advapi32.dll";
- public const string PerfCounter = "perfcounter.dll";
- }
-}
-