From adc1f734b5731d0e607856f2cd9ad213e8bba2d3 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Fri, 19 Sep 2025 08:34:08 -0400 Subject: [PATCH 1/7] Annotate `System.Diagnostics.EventLog` with Nullable Reference Types --- .../Windows/Advapi32/Interop.ClearEventLog.cs | 2 +- .../Windows/Advapi32/Interop.ReportEvent.cs | 2 +- .../System/Diagnostics/NetFrameworkUtils.cs | 22 +- .../ref/System.Diagnostics.EventLog.cs | 215 +++++++++--------- .../ref/System.Diagnostics.EventLog.csproj | 4 - .../src/CompatibilitySuppressions.xml | 36 +++ ...ystem.Diagnostics.EventLog.Messages.csproj | 1 - .../src/System.Diagnostics.EventLog.csproj | 4 - .../Diagnostics/EntryWrittenEventArgs.cs | 4 +- .../Diagnostics/EntryWrittenEventHandler.cs | 2 +- .../src/System/Diagnostics/EventLog.cs | 120 +++++----- .../src/System/Diagnostics/EventLogEntry.cs | 35 +-- .../Diagnostics/EventLogEntryCollection.cs | 4 +- .../System/Diagnostics/EventLogInternal.cs | 137 ++++++----- .../Diagnostics/EventLogTraceListener.cs | 39 ++-- .../Diagnostics/EventSourceCreationData.cs | 12 +- .../System/Diagnostics/Reader/EventKeyword.cs | 24 +- .../System/Diagnostics/Reader/EventLevel.cs | 24 +- .../Reader/EventLogConfiguration.cs | 40 ++-- .../Diagnostics/Reader/EventLogException.cs | 20 +- .../System/Diagnostics/Reader/EventLogLink.cs | 27 ++- .../Reader/EventLogPropertySelector.cs | 3 +- .../Diagnostics/Reader/EventLogQuery.cs | 8 +- .../Diagnostics/Reader/EventLogReader.cs | 16 +- .../Diagnostics/Reader/EventLogRecord.cs | 52 ++--- .../Diagnostics/Reader/EventLogSession.cs | 44 ++-- .../Diagnostics/Reader/EventLogStatus.cs | 4 +- .../Diagnostics/Reader/EventLogWatcher.cs | 42 ++-- .../Diagnostics/Reader/EventMetadata.cs | 6 +- .../System/Diagnostics/Reader/EventOpcode.cs | 23 +- .../Diagnostics/Reader/EventProperty.cs | 4 +- .../System/Diagnostics/Reader/EventRecord.cs | 18 +- .../Reader/EventRecordWrittenEventArgs.cs | 6 +- .../System/Diagnostics/Reader/EventTask.cs | 24 +- .../Diagnostics/Reader/NativeWrapper.cs | 174 +++++++------- .../Diagnostics/Reader/ProviderMetadata.cs | 134 +++++------ .../ProviderMetadataCachedInformation.cs | 23 +- .../Diagnostics/Reader/UnsafeNativeMethods.cs | 52 +++-- 38 files changed, 738 insertions(+), 669 deletions(-) diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ClearEventLog.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ClearEventLog.cs index d7b80aa25cd97c..e56e4632249dde 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ClearEventLog.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ClearEventLog.cs @@ -10,6 +10,6 @@ internal static partial class Advapi32 { [LibraryImport(Libraries.Advapi32, EntryPoint = "ClearEventLogW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool ClearEventLog(SafeEventLogReadHandle hEventLog, string lpBackupFileName); + public static partial bool ClearEventLog(SafeEventLogReadHandle hEventLog, string? lpBackupFileName); } } diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ReportEvent.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ReportEvent.cs index ee8ad9e93a5643..1a02c0a7bc9780 100644 --- a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ReportEvent.cs +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ReportEvent.cs @@ -16,7 +16,7 @@ public static partial bool ReportEvent( short wType, ushort wcategory, uint dwEventID, - byte[] lpUserSid, + byte[]? lpUserSid, short wNumStrings, int dwDataSize, IntPtr lpStrings, diff --git a/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs b/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs index 87f56dcdc242f4..1ab826c45cc1ad 100644 --- a/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs +++ b/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs @@ -14,13 +14,13 @@ namespace System.Diagnostics { internal static partial class NetFrameworkUtils { - internal static void EnterMutex(string name, ref Mutex mutex) + internal static void EnterMutex(string name, ref Mutex? mutex) { string mutexName = "Global\\" + name; EnterMutexWithoutGlobal(mutexName, ref mutex); } - internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex) + internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex? mutex) { Mutex tmpMutex = new Mutex(false, mutexName, out _); @@ -44,7 +44,7 @@ internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex) // just to allow us to poll for abort). A limitation of CERs in Whidbey (and part of the problem that put us in this // position in the first place) is that a CER root in a method will cause the entire method to delay thread aborts. So we // need to carefully partition the real CER part of out logic in a sub-method (and ensure the jit doesn't inline on us). - private static bool SafeWaitForMutex(Mutex mutexIn, ref Mutex mutexOut) + private static bool SafeWaitForMutex(Mutex mutexIn, ref Mutex? mutexOut) { Debug.Assert(mutexOut == null, "You must pass in a null ref Mutex"); @@ -68,7 +68,7 @@ private static bool SafeWaitForMutex(Mutex mutexIn, ref Mutex mutexOut) // The portion of SafeWaitForMutex that runs under a CER and thus must not block for a arbitrary period of time. // This method must not be inlined (to stop the CER accidently spilling into the calling method). [MethodImplAttribute(MethodImplOptions.NoInlining)] - private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex mutexOut) + private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex? mutexOut) { bool ret; @@ -117,8 +117,8 @@ private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex mutexOut) internal static string GetLatestBuildDllDirectory(string machineName) { string dllDir = ""; - RegistryKey baseKey = null; - RegistryKey complusReg = null; + RegistryKey? baseKey = null; + RegistryKey? complusReg = null; try { @@ -133,7 +133,7 @@ internal static string GetLatestBuildDllDirectory(string machineName) complusReg = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework"); if (complusReg != null) { - string installRoot = (string)complusReg.GetValue("InstallRoot"); + string? installRoot = (string?)complusReg.GetValue("InstallRoot"); if (installRoot != null && installRoot != string.Empty) { // the "policy" subkey contains a v{major}.{minor} subkey for each version installed. There are also @@ -141,17 +141,17 @@ internal static string GetLatestBuildDllDirectory(string machineName) // first we figure out what version we are... string versionPrefix = "v" + Environment.Version.Major + "." + Environment.Version.Minor; - RegistryKey policyKey = complusReg.OpenSubKey("policy"); + RegistryKey? policyKey = complusReg.OpenSubKey("policy"); // 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; + string? version = null; 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); + RegistryKey? bestKey = policyKey.OpenSubKey(versionPrefix); if (bestKey != null) { @@ -191,7 +191,7 @@ internal static string GetLatestBuildDllDirectory(string machineName) continue; } - RegistryKey k = policyKey.OpenSubKey(majorVersion); + RegistryKey? k = policyKey.OpenSubKey(majorVersion); if (k == null) { // We may be able to use another subkey diff --git a/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs b/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs index 4a1404af7248e8..668824144ddc12 100644 --- a/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs @@ -9,10 +9,10 @@ namespace System.Diagnostics public partial class EntryWrittenEventArgs : System.EventArgs { public EntryWrittenEventArgs() { } - public EntryWrittenEventArgs(System.Diagnostics.EventLogEntry entry) { } - public System.Diagnostics.EventLogEntry Entry { get { throw null; } } + public EntryWrittenEventArgs(System.Diagnostics.EventLogEntry? entry) { } + public System.Diagnostics.EventLogEntry? Entry { get { throw null; } } } - public delegate void EntryWrittenEventHandler(object sender, System.Diagnostics.EntryWrittenEventArgs e); + public delegate void EntryWrittenEventHandler(object? sender, System.Diagnostics.EntryWrittenEventArgs e); public partial class EventInstance { public EventInstance(long instanceId, int categoryId) { } @@ -39,7 +39,7 @@ public EventLog(string logName, string machineName, string source) { } [System.ComponentModel.SettingsBindableAttribute(true)] public string Log { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - public string LogDisplayName { get { throw null; } } + public string? LogDisplayName { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(".")] [System.ComponentModel.ReadOnlyAttribute(true)] [System.ComponentModel.SettingsBindableAttribute(true)] @@ -57,8 +57,8 @@ public EventLog(string logName, string machineName, string source) { } public string Source { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(null)] - public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get { throw null; } set { } } - public event System.Diagnostics.EntryWrittenEventHandler EntryWritten { add { } remove { } } + public System.ComponentModel.ISynchronizeInvoke? SynchronizingObject { get { throw null; } set { } } + public event System.Diagnostics.EntryWrittenEventHandler? EntryWritten { add { } remove { } } public void BeginInit() { } public void Clear() { } public void Close() { } @@ -72,29 +72,29 @@ public static void DeleteEventSource(string source) { } public static void DeleteEventSource(string source, string machineName) { } protected override void Dispose(bool disposing) { } public void EndInit() { } - public static bool Exists(string logName) { throw null; } - public static bool Exists(string logName, string machineName) { throw null; } + public static bool Exists([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] string? logName) { throw null; } + public static bool Exists([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] string? logName, string machineName) { throw null; } public static System.Diagnostics.EventLog[] GetEventLogs() { throw null; } public static System.Diagnostics.EventLog[] GetEventLogs(string machineName) { throw null; } public static string LogNameFromSourceName(string source, string machineName) { throw null; } public void ModifyOverflowPolicy(System.Diagnostics.OverflowAction action, int retentionDays) { } public void RegisterDisplayName(string resourceFile, long resourceId) { } - public static bool SourceExists(string source) { throw null; } - public static bool SourceExists(string source, string machineName) { throw null; } - public void WriteEntry(string message) { } - public void WriteEntry(string message, System.Diagnostics.EventLogEntryType type) { } - public void WriteEntry(string message, System.Diagnostics.EventLogEntryType type, int eventID) { } - public void WriteEntry(string message, System.Diagnostics.EventLogEntryType type, int eventID, short category) { } - public void WriteEntry(string message, System.Diagnostics.EventLogEntryType type, int eventID, short category, byte[] rawData) { } - public static void WriteEntry(string source, string message) { } - public static void WriteEntry(string source, string message, System.Diagnostics.EventLogEntryType type) { } - public static void WriteEntry(string source, string message, System.Diagnostics.EventLogEntryType type, int eventID) { } - public static void WriteEntry(string source, string message, System.Diagnostics.EventLogEntryType type, int eventID, short category) { } - public static void WriteEntry(string source, string message, System.Diagnostics.EventLogEntryType type, int eventID, short category, byte[] rawData) { } - public void WriteEvent(System.Diagnostics.EventInstance instance, byte[] data, params object[] values) { } - public void WriteEvent(System.Diagnostics.EventInstance instance, params object[] values) { } - public static void WriteEvent(string source, System.Diagnostics.EventInstance instance, byte[] data, params object[] values) { } - public static void WriteEvent(string source, System.Diagnostics.EventInstance instance, params object[] values) { } + public static bool SourceExists([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] string? source) { throw null; } + public static bool SourceExists([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] string? source, string machineName) { throw null; } + public void WriteEntry(string? message) { } + public void WriteEntry(string? message, System.Diagnostics.EventLogEntryType type) { } + public void WriteEntry(string? message, System.Diagnostics.EventLogEntryType type, int eventID) { } + public void WriteEntry(string? message, System.Diagnostics.EventLogEntryType type, int eventID, short category) { } + public void WriteEntry(string? message, System.Diagnostics.EventLogEntryType type, int eventID, short category, byte[]? rawData) { } + public static void WriteEntry(string source, string? message) { } + public static void WriteEntry(string source, string? message, System.Diagnostics.EventLogEntryType type) { } + public static void WriteEntry(string source, string? message, System.Diagnostics.EventLogEntryType type, int eventID) { } + public static void WriteEntry(string source, string? message, System.Diagnostics.EventLogEntryType type, int eventID, short category) { } + public static void WriteEntry(string source, string? message, System.Diagnostics.EventLogEntryType type, int eventID, short category, byte[]? rawData) { } + public void WriteEvent(System.Diagnostics.EventInstance instance, byte[]? data, params object?[]? values) { } + public void WriteEvent(System.Diagnostics.EventInstance instance, params object?[]? values) { } + public static void WriteEvent(string source, System.Diagnostics.EventInstance instance, byte[] data, params object?[]? values) { } + public static void WriteEvent(string source, System.Diagnostics.EventInstance instance, params object?[]? values) { } } [System.ComponentModel.DesignTimeVisibleAttribute(false)] [System.ComponentModel.ToolboxItemAttribute(false)] @@ -116,8 +116,8 @@ internal EventLogEntry() { } public string Source { get { throw null; } } public System.DateTime TimeGenerated { get { throw null; } } public System.DateTime TimeWritten { get { throw null; } } - public string UserName { get { throw null; } } - public bool Equals(System.Diagnostics.EventLogEntry otherEntry) { throw null; } + public string? UserName { get { throw null; } } + public bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] System.Diagnostics.EventLogEntry? otherEntry) { throw null; } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class EventLogEntryCollection : System.Collections.ICollection, System.Collections.IEnumerable @@ -142,33 +142,30 @@ public enum EventLogEntryType public sealed partial class EventLogTraceListener : System.Diagnostics.TraceListener { public EventLogTraceListener() { } - public EventLogTraceListener(System.Diagnostics.EventLog eventLog) { } + public EventLogTraceListener(System.Diagnostics.EventLog? eventLog) { } public EventLogTraceListener(string source) { } - public System.Diagnostics.EventLog EventLog { get { throw null; } set { } } + public System.Diagnostics.EventLog? EventLog { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public override string Name { get { throw null; } set { } } public override void Close() { } protected override void Dispose(bool disposing) { } - [System.Runtime.InteropServices.ComVisibleAttribute(false)] - public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType severity, int id, object data) { } - [System.Runtime.InteropServices.ComVisibleAttribute(false)] - public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType severity, int id, params object[] data) { } - [System.Runtime.InteropServices.ComVisibleAttribute(false)] - public override void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string message) { } - [System.Runtime.InteropServices.ComVisibleAttribute(false)] - public override void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string format, params object[] args) { } - public override void Write(string message) { } - public override void WriteLine(string message) { } + public override void TraceData(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, object? data) { } + public override void TraceData(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, params object?[]? data) { } + public override void TraceEvent(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string? message) { } + public override void TraceEvent(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string? format, params object?[]? args) { } + public override void Write(string? message) { } + public override void WriteLine(string? message) { } } public partial class EventSourceCreationData { public EventSourceCreationData(string source, string logName) { } public int CategoryCount { get { throw null; } set { } } - public string CategoryResourceFile { get { throw null; } set { } } + public string? CategoryResourceFile { get { throw null; } set { } } public string LogName { get { throw null; } set { } } public string MachineName { get { throw null; } set { } } - public string MessageResourceFile { get { throw null; } set { } } - public string ParameterResourceFile { get { throw null; } set { } } - public string Source { get { throw null; } set { } } + public string? MessageResourceFile { get { throw null; } set { } } + public string? ParameterResourceFile { get { throw null; } set { } } + public string? Source { get { throw null; } set { } } } public enum OverflowAction { @@ -186,30 +183,30 @@ internal EventBookmark() { } public sealed partial class EventKeyword { internal EventKeyword() { } - public string DisplayName { get { throw null; } } - public string Name { get { throw null; } } + public string? DisplayName { get { throw null; } } + public string? Name { get { throw null; } } public long Value { get { throw null; } } } public sealed partial class EventLevel { internal EventLevel() { } - public string DisplayName { get { throw null; } } - public string Name { get { throw null; } } + public string? DisplayName { get { throw null; } } + public string? Name { get { throw null; } } public int Value { get { throw null; } } } public partial class EventLogConfiguration : System.IDisposable { public EventLogConfiguration(string logName) { } - public EventLogConfiguration(string logName, System.Diagnostics.Eventing.Reader.EventLogSession session) { } + public EventLogConfiguration(string logName, System.Diagnostics.Eventing.Reader.EventLogSession? session) { } public bool IsClassicLog { get { throw null; } } public bool IsEnabled { get { throw null; } set { } } - public string LogFilePath { get { throw null; } set { } } + public string? LogFilePath { get { throw null; } set { } } public System.Diagnostics.Eventing.Reader.EventLogIsolation LogIsolation { get { throw null; } } public System.Diagnostics.Eventing.Reader.EventLogMode LogMode { get { throw null; } set { } } public string LogName { get { throw null; } } public System.Diagnostics.Eventing.Reader.EventLogType LogType { get { throw null; } } public long MaximumSizeInBytes { get { throw null; } set { } } - public string OwningProviderName { get { throw null; } } + public string? OwningProviderName { get { throw null; } } public int? ProviderBufferSize { get { throw null; } } public System.Guid? ProviderControlGuid { get { throw null; } } public long? ProviderKeywords { get { throw null; } set { } } @@ -217,8 +214,8 @@ public EventLogConfiguration(string logName, System.Diagnostics.Eventing.Reader. public int? ProviderLevel { get { throw null; } set { } } public int? ProviderMaximumNumberOfBuffers { get { throw null; } } public int? ProviderMinimumNumberOfBuffers { get { throw null; } } - public System.Collections.Generic.IEnumerable ProviderNames { get { throw null; } } - public string SecurityDescriptor { get { throw null; } set { } } + public System.Collections.Generic.IEnumerable? ProviderNames { get { throw null; } } + public string? SecurityDescriptor { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void SaveChanges() { } @@ -232,8 +229,8 @@ protected EventLogException(int errorCode) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] #endif protected EventLogException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public EventLogException(string message) { } - public EventLogException(string message, System.Exception innerException) { } + public EventLogException(string? message) { } + public EventLogException(string? message, System.Exception? innerException) { } public override string Message { get { throw null; } } #if NET [System.ObsoleteAttribute("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId = "SYSLIB0051", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] @@ -261,8 +258,8 @@ public EventLogInvalidDataException() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] #endif protected EventLogInvalidDataException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public EventLogInvalidDataException(string message) { } - public EventLogInvalidDataException(string message, System.Exception innerException) { } + public EventLogInvalidDataException(string? message) { } + public EventLogInvalidDataException(string? message, System.Exception? innerException) { } } public enum EventLogIsolation { @@ -273,9 +270,9 @@ public enum EventLogIsolation public sealed partial class EventLogLink { internal EventLogLink() { } - public string DisplayName { get { throw null; } } + public string? DisplayName { get { throw null; } } public bool IsImported { get { throw null; } } - public string LogName { get { throw null; } } + public string? LogName { get { throw null; } } } public enum EventLogMode { @@ -291,8 +288,8 @@ public EventLogNotFoundException() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] #endif protected EventLogNotFoundException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public EventLogNotFoundException(string message) { } - public EventLogNotFoundException(string message, System.Exception innerException) { } + public EventLogNotFoundException(string? message) { } + public EventLogNotFoundException(string? message, System.Exception? innerException) { } } public partial class EventLogPropertySelector : System.IDisposable { @@ -308,13 +305,13 @@ public EventLogProviderDisabledException() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] #endif protected EventLogProviderDisabledException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public EventLogProviderDisabledException(string message) { } - public EventLogProviderDisabledException(string message, System.Exception innerException) { } + public EventLogProviderDisabledException(string? message) { } + public EventLogProviderDisabledException(string? message, System.Exception? innerException) { } } public partial class EventLogQuery { - public EventLogQuery(string path, System.Diagnostics.Eventing.Reader.PathType pathType) { } - public EventLogQuery(string path, System.Diagnostics.Eventing.Reader.PathType pathType, string query) { } + public EventLogQuery(string? path, System.Diagnostics.Eventing.Reader.PathType pathType) { } + public EventLogQuery(string? path, System.Diagnostics.Eventing.Reader.PathType pathType, string? query) { } public bool ReverseDirection { get { throw null; } set { } } public System.Diagnostics.Eventing.Reader.EventLogSession Session { get { throw null; } set { } } public bool TolerateQueryErrors { get { throw null; } set { } } @@ -322,7 +319,7 @@ public EventLogQuery(string path, System.Diagnostics.Eventing.Reader.PathType pa public partial class EventLogReader : System.IDisposable { public EventLogReader(System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery) { } - public EventLogReader(System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery, System.Diagnostics.Eventing.Reader.EventBookmark bookmark) { } + public EventLogReader(System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery, System.Diagnostics.Eventing.Reader.EventBookmark? bookmark) { } public EventLogReader(string path) { } public EventLogReader(string path, System.Diagnostics.Eventing.Reader.PathType pathType) { } public int BatchSize { get { throw null; } set { } } @@ -330,8 +327,8 @@ public EventLogReader(string path, System.Diagnostics.Eventing.Reader.PathType p public void CancelReading() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - public System.Diagnostics.Eventing.Reader.EventRecord ReadEvent() { throw null; } - public System.Diagnostics.Eventing.Reader.EventRecord ReadEvent(System.TimeSpan timeout) { throw null; } + public System.Diagnostics.Eventing.Reader.EventRecord? ReadEvent() { throw null; } + public System.Diagnostics.Eventing.Reader.EventRecord? ReadEvent(System.TimeSpan timeout) { throw null; } public void Seek(System.Diagnostics.Eventing.Reader.EventBookmark bookmark) { } public void Seek(System.Diagnostics.Eventing.Reader.EventBookmark bookmark, long offset) { } public void Seek(System.IO.SeekOrigin origin, long offset) { } @@ -344,25 +341,25 @@ public EventLogReadingException() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] #endif protected EventLogReadingException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public EventLogReadingException(string message) { } - public EventLogReadingException(string message, System.Exception innerException) { } + public EventLogReadingException(string? message) { } + public EventLogReadingException(string? message, System.Exception? innerException) { } } public partial class EventLogRecord : System.Diagnostics.Eventing.Reader.EventRecord { internal EventLogRecord() { } public override System.Guid? ActivityId { get { throw null; } } public override System.Diagnostics.Eventing.Reader.EventBookmark Bookmark { get { throw null; } } - public string ContainerLog { get { throw null; } } + public string? ContainerLog { get { throw null; } } public override int Id { get { throw null; } } public override long? Keywords { get { throw null; } } - public override System.Collections.Generic.IEnumerable KeywordsDisplayNames { get { throw null; } } + public override System.Collections.Generic.IEnumerable? KeywordsDisplayNames { get { throw null; } } public override byte? Level { get { throw null; } } - public override string LevelDisplayName { get { throw null; } } - public override string LogName { get { throw null; } } - public override string MachineName { get { throw null; } } - public System.Collections.Generic.IEnumerable MatchedQueryIds { get { throw null; } } + public override string? LevelDisplayName { get { throw null; } } + public override string? LogName { get { throw null; } } + public override string? MachineName { get { throw null; } } + public System.Collections.Generic.IEnumerable? MatchedQueryIds { get { throw null; } } public override short? Opcode { get { throw null; } } - public override string OpcodeDisplayName { get { throw null; } } + public override string? OpcodeDisplayName { get { throw null; } } public override int? ProcessId { get { throw null; } } public override System.Collections.Generic.IList Properties { get { throw null; } } public override System.Guid? ProviderId { get { throw null; } } @@ -371,26 +368,26 @@ internal EventLogRecord() { } public override long? RecordId { get { throw null; } } public override System.Guid? RelatedActivityId { get { throw null; } } public override int? Task { get { throw null; } } - public override string TaskDisplayName { get { throw null; } } + public override string? TaskDisplayName { get { throw null; } } public override int? ThreadId { get { throw null; } } public override System.DateTime? TimeCreated { get { throw null; } } - public override System.Security.Principal.SecurityIdentifier UserId { get { throw null; } } + public override System.Security.Principal.SecurityIdentifier? UserId { get { throw null; } } public override byte? Version { get { throw null; } } protected override void Dispose(bool disposing) { } - public override string FormatDescription() { throw null; } - public override string FormatDescription(System.Collections.Generic.IEnumerable values) { throw null; } - public System.Collections.Generic.IList GetPropertyValues(System.Diagnostics.Eventing.Reader.EventLogPropertySelector propertySelector) { throw null; } + public override string? FormatDescription() { throw null; } + public override string? FormatDescription(System.Collections.Generic.IEnumerable? values) { throw null; } + public System.Collections.Generic.IList GetPropertyValues(System.Diagnostics.Eventing.Reader.EventLogPropertySelector propertySelector) { throw null; } public override string ToXml() { throw null; } } public partial class EventLogSession : System.IDisposable { public EventLogSession() { } public EventLogSession(string server) { } - public EventLogSession(string server, string domain, string user, System.Security.SecureString password, System.Diagnostics.Eventing.Reader.SessionAuthentication logOnType) { } + public EventLogSession(string server, string? domain, string? user, System.Security.SecureString? password, System.Diagnostics.Eventing.Reader.SessionAuthentication logOnType) { } public static System.Diagnostics.Eventing.Reader.EventLogSession GlobalSession { get { throw null; } } public void CancelCurrentOperations() { } public void ClearLog(string logName) { } - public void ClearLog(string logName, string backupPath) { } + public void ClearLog(string logName, string? backupPath) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void ExportLog(string path, System.Diagnostics.Eventing.Reader.PathType pathType, string query, string targetFilePath) { } @@ -404,7 +401,7 @@ public void ExportLogAndMessages(string path, System.Diagnostics.Eventing.Reader public sealed partial class EventLogStatus { internal EventLogStatus() { } - public string LogName { get { throw null; } } + public string? LogName { get { throw null; } } public int StatusCode { get { throw null; } } } public enum EventLogType @@ -418,37 +415,37 @@ public partial class EventLogWatcher : System.IDisposable { public EventLogWatcher(System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery) { } public EventLogWatcher(System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery, System.Diagnostics.Eventing.Reader.EventBookmark bookmark) { } - public EventLogWatcher(System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery, System.Diagnostics.Eventing.Reader.EventBookmark bookmark, bool readExistingEvents) { } + public EventLogWatcher(System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery, System.Diagnostics.Eventing.Reader.EventBookmark? bookmark, bool readExistingEvents) { } public EventLogWatcher(string path) { } public bool Enabled { get { throw null; } set { } } - public event System.EventHandler EventRecordWritten { add { } remove { } } + public event System.EventHandler? EventRecordWritten { add { } remove { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public sealed partial class EventMetadata { internal EventMetadata() { } - public string Description { get { throw null; } } + public string? Description { get { throw null; } } public long Id { get { throw null; } } public System.Collections.Generic.IEnumerable Keywords { get { throw null; } } public System.Diagnostics.Eventing.Reader.EventLevel Level { get { throw null; } } public System.Diagnostics.Eventing.Reader.EventLogLink LogLink { get { throw null; } } public System.Diagnostics.Eventing.Reader.EventOpcode Opcode { get { throw null; } } public System.Diagnostics.Eventing.Reader.EventTask Task { get { throw null; } } - public string Template { get { throw null; } } + public string? Template { get { throw null; } } public byte Version { get { throw null; } } } public sealed partial class EventOpcode { internal EventOpcode() { } - public string DisplayName { get { throw null; } } - public string Name { get { throw null; } } + public string? DisplayName { get { throw null; } } + public string? Name { get { throw null; } } public int Value { get { throw null; } } } public sealed partial class EventProperty { internal EventProperty() { } - public object Value { get { throw null; } } + public object? Value { get { throw null; } } } public abstract partial class EventRecord : System.IDisposable { @@ -457,13 +454,13 @@ protected EventRecord() { } public abstract System.Diagnostics.Eventing.Reader.EventBookmark Bookmark { get; } public abstract int Id { get; } public abstract long? Keywords { get; } - public abstract System.Collections.Generic.IEnumerable KeywordsDisplayNames { get; } + public abstract System.Collections.Generic.IEnumerable? KeywordsDisplayNames { get; } public abstract byte? Level { get; } - public abstract string LevelDisplayName { get; } - public abstract string LogName { get; } - public abstract string MachineName { get; } + public abstract string? LevelDisplayName { get; } + public abstract string? LogName { get; } + public abstract string? MachineName { get; } public abstract short? Opcode { get; } - public abstract string OpcodeDisplayName { get; } + public abstract string? OpcodeDisplayName { get; } public abstract int? ProcessId { get; } public abstract System.Collections.Generic.IList Properties { get; } public abstract System.Guid? ProviderId { get; } @@ -472,29 +469,29 @@ protected EventRecord() { } public abstract long? RecordId { get; } public abstract System.Guid? RelatedActivityId { get; } public abstract int? Task { get; } - public abstract string TaskDisplayName { get; } + public abstract string? TaskDisplayName { get; } public abstract int? ThreadId { get; } public abstract System.DateTime? TimeCreated { get; } - public abstract System.Security.Principal.SecurityIdentifier UserId { get; } + public abstract System.Security.Principal.SecurityIdentifier? UserId { get; } public abstract byte? Version { get; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - public abstract string FormatDescription(); - public abstract string FormatDescription(System.Collections.Generic.IEnumerable values); + public abstract string? FormatDescription(); + public abstract string? FormatDescription(System.Collections.Generic.IEnumerable? values); public abstract string ToXml(); } public sealed partial class EventRecordWrittenEventArgs : System.EventArgs { internal EventRecordWrittenEventArgs() { } - public System.Exception EventException { get { throw null; } } - public System.Diagnostics.Eventing.Reader.EventRecord EventRecord { get { throw null; } } + public System.Exception? EventException { get { throw null; } } + public System.Diagnostics.Eventing.Reader.EventRecord? EventRecord { get { throw null; } } } public sealed partial class EventTask { internal EventTask() { } - public string DisplayName { get { throw null; } } + public string? DisplayName { get { throw null; } } public System.Guid EventGuid { get { throw null; } } - public string Name { get { throw null; } } + public string? Name { get { throw null; } } public int Value { get { throw null; } } } public enum PathType @@ -505,19 +502,19 @@ public enum PathType public partial class ProviderMetadata : System.IDisposable { public ProviderMetadata(string providerName) { } - public ProviderMetadata(string providerName, System.Diagnostics.Eventing.Reader.EventLogSession session, System.Globalization.CultureInfo targetCultureInfo) { } - public string DisplayName { get { throw null; } } + public ProviderMetadata(string providerName, System.Diagnostics.Eventing.Reader.EventLogSession? session, System.Globalization.CultureInfo? targetCultureInfo) { } + public string? DisplayName { get { throw null; } } public System.Collections.Generic.IEnumerable Events { get { throw null; } } - public System.Uri HelpLink { get { throw null; } } + public System.Uri? HelpLink { get { throw null; } } public System.Guid Id { get { throw null; } } public System.Collections.Generic.IList Keywords { get { throw null; } } public System.Collections.Generic.IList Levels { get { throw null; } } public System.Collections.Generic.IList LogLinks { get { throw null; } } - public string MessageFilePath { get { throw null; } } + public string? MessageFilePath { get { throw null; } } public string Name { get { throw null; } } public System.Collections.Generic.IList Opcodes { get { throw null; } } - public string ParameterFilePath { get { throw null; } } - public string ResourceFilePath { get { throw null; } } + public string? ParameterFilePath { get { throw null; } } + public string? ResourceFilePath { get { throw null; } } public System.Collections.Generic.IList Tasks { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } diff --git a/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.csproj b/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.csproj index 9f8931ebfeab3f..2e7c254eb777d9 100644 --- a/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.csproj +++ b/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.csproj @@ -1,10 +1,6 @@ $(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) - - - disable - $(NoWarn);nullable diff --git a/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml b/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml index 11804bbda76ae3..08421677ce8efd 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml @@ -23,4 +23,40 @@ lib/netstandard2.0/System.Diagnostics.EventLog.dll lib/net462/System.Diagnostics.EventLog.dll + + CP0016 + M:System.Diagnostics.EventLog.SourceExists(System.String,System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] + ref/net10.0/System.Diagnostics.EventLog.dll + runtimes/win/lib/net10.0/System.Diagnostics.EventLog.dll + + + CP0016 + M:System.Diagnostics.EventLog.SourceExists(System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] + ref/net10.0/System.Diagnostics.EventLog.dll + runtimes/win/lib/net10.0/System.Diagnostics.EventLog.dll + + + CP0016 + M:System.Diagnostics.EventLog.SourceExists(System.String,System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] + ref/net8.0/System.Diagnostics.EventLog.dll + runtimes/win/lib/net8.0/System.Diagnostics.EventLog.dll + + + CP0016 + M:System.Diagnostics.EventLog.SourceExists(System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] + ref/net8.0/System.Diagnostics.EventLog.dll + runtimes/win/lib/net8.0/System.Diagnostics.EventLog.dll + + + CP0016 + M:System.Diagnostics.EventLog.SourceExists(System.String,System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] + ref/net9.0/System.Diagnostics.EventLog.dll + runtimes/win/lib/net9.0/System.Diagnostics.EventLog.dll + + + CP0016 + M:System.Diagnostics.EventLog.SourceExists(System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] + ref/net9.0/System.Diagnostics.EventLog.dll + runtimes/win/lib/net9.0/System.Diagnostics.EventLog.dll + \ No newline at end of file diff --git a/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj b/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj index b5ca42ec6522b9..60067ea14aa1aa 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj +++ b/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj @@ -1,7 +1,6 @@ netstandard2.0 - disable EventLogMessages.res diff --git a/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj b/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj index 4c75b91cba6a42..aa226cc936cb3a 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj +++ b/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj @@ -10,10 +10,6 @@ Commonly Used Types: System.Diagnostics.EventLog - - - disable - $(NoWarn);nullable diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventArgs.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventArgs.cs index 2d757b50ff92af..447a36a141d31b 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventArgs.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventArgs.cs @@ -9,11 +9,11 @@ public EntryWrittenEventArgs() { } - public EntryWrittenEventArgs(EventLogEntry entry) + public EntryWrittenEventArgs(EventLogEntry? entry) { Entry = entry; } - public EventLogEntry Entry { get; } + public EventLogEntry? Entry { get; } } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventHandler.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventHandler.cs index d648ad228230a7..1b508d5e2bc5c2 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventHandler.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EntryWrittenEventHandler.cs @@ -3,5 +3,5 @@ namespace System.Diagnostics { - public delegate void EntryWrittenEventHandler(object sender, EntryWrittenEventArgs e); + public delegate void EntryWrittenEventHandler(object? sender, EntryWrittenEventArgs e); } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index bd756ee6acc8ec..980676c9122dc3 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -61,7 +61,7 @@ public EventLogEntryCollection Entries } [Browsable(false)] - public string LogDisplayName + public string? LogDisplayName { get { @@ -150,7 +150,7 @@ internal bool ComponentDesignMode get => this.DesignMode; } - internal object ComponentGetService(Type service) + internal object? ComponentGetService(Type service) { return GetService(service); } @@ -171,7 +171,7 @@ public bool EnableRaisingEvents /// [Browsable(false)] [DefaultValue(null)] - public ISynchronizeInvoke SynchronizingObject + public ISynchronizeInvoke? SynchronizingObject { get => _underlyingEventLog.SynchronizingObject; set => _underlyingEventLog.SynchronizingObject = value; @@ -205,7 +205,7 @@ public string Source /// /// Raised each time any application writes an entry to the event log. /// - public event EntryWrittenEventHandler EntryWritten + public event EntryWrittenEventHandler? EntryWritten { add { @@ -248,7 +248,7 @@ public static void CreateEventSource(EventSourceCreationData sourceData) ArgumentNullException.ThrowIfNull(sourceData); string logName = sourceData.LogName; - string source = sourceData.Source; + string? source = sourceData.Source; string machineName = sourceData.MachineName; if (!SyntaxCheck.CheckMachineName(machineName)) @@ -265,7 +265,7 @@ public static void CreateEventSource(EventSourceCreationData sourceData) if (source.Length + EventLogKey.Length > 254) throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length)); - Mutex mutex = null; + Mutex? mutex = null; try { NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex); @@ -277,11 +277,11 @@ public static void CreateEventSource(EventSourceCreationData sourceData) throw new ArgumentException(SR.Format(SR.SourceAlreadyExists, source, machineName)); } - RegistryKey baseKey = null; - RegistryKey eventKey = null; - RegistryKey logKey = null; - RegistryKey sourceLogKey = null; - RegistryKey sourceKey = null; + RegistryKey? baseKey = null; + RegistryKey? eventKey = null; + RegistryKey? logKey = null; + RegistryKey? sourceLogKey = null; + RegistryKey? sourceKey = null; try { if (machineName == ".") @@ -309,7 +309,7 @@ public static void CreateEventSource(EventSourceCreationData sourceData) } bool createLogKey = (logKey == null); - if (createLogKey) + if (logKey == null) { if (SourceExists(logName, machineName, true)) { @@ -368,9 +368,9 @@ public static void Delete(string logName, string machineName) if (!ValidLogName(logName, false)) throw new InvalidOperationException(SR.BadLogName); - RegistryKey eventlogkey = null; + RegistryKey? eventlogkey = null; - Mutex mutex = null; + Mutex? mutex = null; try { NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex); @@ -382,7 +382,7 @@ public static void Delete(string logName, string machineName) throw new InvalidOperationException(SR.Format(SR.RegKeyNoAccess, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog", machineName)); } - using (RegistryKey logKey = eventlogkey.OpenSubKey(logName)) + using (RegistryKey? logKey = eventlogkey.OpenSubKey(logName)) { if (logKey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, logName, machineName)); @@ -398,11 +398,11 @@ public static void Delete(string logName, string machineName) logToClear.Close(); } - string filename = null; + string? filename = null; try { //most of the time, the "File" key does not exist, but we'll still give it a whirl - filename = (string)logKey.GetValue("File"); + filename = (string?)logKey.GetValue("File"); } catch { } if (filename != null) @@ -440,11 +440,11 @@ public static void DeleteEventSource(string source, string machineName) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } - Mutex mutex = null; + Mutex? mutex = null; try { NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex); - RegistryKey key = null; + RegistryKey? key = null; // First open the key read only so we can do some checks. This is important so we get the same // exceptions even if we don't have write access to the reg key. using (key = FindSourceRegistration(source, machineName, true)) @@ -466,7 +466,7 @@ public static void DeleteEventSource(string source, string machineName) try { - key = FindSourceRegistration(source, machineName, false); + key = FindSourceRegistration(source, machineName, false)!; key.DeleteSubKeyTree(source); } finally @@ -491,12 +491,12 @@ public void EndInit() _underlyingEventLog.EndInit(); } - public static bool Exists(string logName) + public static bool Exists([NotNullWhen(true)] string? logName) { return Exists(logName, "."); } - public static bool Exists(string logName, string machineName) + public static bool Exists([NotNullWhen(true)] string? logName, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName))); @@ -504,8 +504,8 @@ public static bool Exists(string logName, string machineName) if (string.IsNullOrEmpty(logName)) return false; - RegistryKey eventkey = null; - RegistryKey logKey = null; + RegistryKey? eventkey = null; + RegistryKey? logKey = null; try { @@ -523,16 +523,16 @@ public static bool Exists(string logName, string machineName) } } - private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly) + private static RegistryKey? FindSourceRegistration(string source, string machineName, bool readOnly) { return FindSourceRegistration(source, machineName, readOnly, false); } - private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly, bool wantToCreate) + private static RegistryKey? FindSourceRegistration(string? source, string machineName, bool readOnly, bool wantToCreate) { if (!string.IsNullOrEmpty(source)) { - RegistryKey eventkey = null; + RegistryKey? eventkey = null; try { eventkey = GetEventLogRegKey(machineName, !readOnly); @@ -543,7 +543,7 @@ private static RegistryKey FindSourceRegistration(string source, string machineN return null; } - StringBuilder inaccessibleLogs = null; + StringBuilder? inaccessibleLogs = null; // Most machines will return only { "Application", "System", "Security" }, // but you can create your own if you want. string[] logNames = eventkey.GetSubKeyNames(); @@ -551,10 +551,10 @@ private static RegistryKey FindSourceRegistration(string source, string machineN { // see if the source is registered in this log. // NOTE: A source name must be unique across ALL LOGS! - RegistryKey sourceKey = null; + RegistryKey? sourceKey = null; try { - RegistryKey logKey = eventkey.OpenSubKey(logNames[i], /*writable*/!readOnly); + RegistryKey? logKey = eventkey.OpenSubKey(logNames[i], /*writable*/!readOnly); if (logKey != null) { sourceKey = logKey.OpenSubKey(source, /*writable*/!readOnly); @@ -625,9 +625,9 @@ public static EventLog[] GetEventLogs(string machineName) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } - string[] logNames = null; + string[]? logNames = null; - RegistryKey eventkey = null; + RegistryKey? eventkey = null; try { // we figure out what logs are on the machine by looking in the registry. @@ -667,9 +667,9 @@ public static EventLog[] GetEventLogs(string machineName) return logs.ToArray(); } - internal static RegistryKey GetEventLogRegKey(string machine, bool writable) + internal static RegistryKey? GetEventLogRegKey(string machine, bool writable) { - RegistryKey lmkey = null; + RegistryKey? lmkey = null; try { @@ -703,7 +703,7 @@ internal static string GetDllPath(string machineName) string assmLocation = typeof(EventLog).Assembly.Location; if (!string.IsNullOrEmpty(assmLocation)) { - dllPath = Path.Combine(Path.GetDirectoryName(assmLocation), AltDllName); + dllPath = Path.Combine(Path.GetDirectoryName(assmLocation)!, AltDllName); } else { @@ -714,24 +714,24 @@ internal static string GetDllPath(string machineName) return dllPath; } - public static bool SourceExists(string source) + public static bool SourceExists([NotNullWhen(true)] string? source) { return SourceExists(source, "."); } - public static bool SourceExists(string source, string machineName) + public static bool SourceExists([NotNullWhen(true)] string? source, string machineName) { return SourceExists(source, machineName, false); } - internal static bool SourceExists(string source, string machineName, bool wantToCreate) + internal static bool SourceExists([NotNullWhen(true)] string? source, string machineName, bool wantToCreate) { if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } - using (RegistryKey keyFound = FindSourceRegistration(source, machineName, true, wantToCreate)) + using (RegistryKey? keyFound = FindSourceRegistration(source, machineName, true, wantToCreate)) { return (keyFound != null); } @@ -744,7 +744,7 @@ public static string LogNameFromSourceName(string source, string machineName) internal static string _InternalLogNameFromSourceName(string source, string machineName) { - using (RegistryKey key = FindSourceRegistration(source, machineName, true)) + using (RegistryKey? key = FindSourceRegistration(source, machineName, true)) { if (key == null) return string.Empty; @@ -805,7 +805,7 @@ private static string FixupPath(string path) return Path.GetFullPath(path); } - internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) + internal static string? TryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) { if (insertionStrings.Length == 0) { @@ -813,7 +813,7 @@ internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageN } // If you pass in an empty array UnsafeTryFormatMessage will just pull out the message. - string formatString = UnsafeTryFormatMessage(hModule, messageNum, Array.Empty()); + string? formatString = UnsafeTryFormatMessage(hModule, messageNum, Array.Empty()); if (formatString == null) { @@ -822,7 +822,7 @@ internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageN int largestNumber = 0; - StringBuilder sb = null; + StringBuilder? sb = null; for (int i = 0; i < formatString.Length; i++) { if (formatString[i] == '%') @@ -876,9 +876,9 @@ internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageN // FormatMessageW will AV if you don't pass in enough format strings. If you call TryFormatMessage we ensure insertionStrings // is long enough. You don't want to call this directly unless you're sure insertionStrings is long enough! - internal static string UnsafeTryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) + internal static string? UnsafeTryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) { - string msg = null; + string? msg = null; int msgLen = 0; var buf = new char[1024]; @@ -971,47 +971,47 @@ internal static bool ValidLogName(string logName, bool ignoreEmpty) return true; } - public void WriteEntry(string message) + public void WriteEntry(string? message) { WriteEntry(message, EventLogEntryType.Information, (short)0, 0, null); } - public static void WriteEntry(string source, string message) + public static void WriteEntry(string source, string? message) { WriteEntry(source, message, EventLogEntryType.Information, (short)0, 0, null); } - public void WriteEntry(string message, EventLogEntryType type) + public void WriteEntry(string? message, EventLogEntryType type) { WriteEntry(message, type, (short)0, 0, null); } - public static void WriteEntry(string source, string message, EventLogEntryType type) + public static void WriteEntry(string source, string? message, EventLogEntryType type) { WriteEntry(source, message, type, (short)0, 0, null); } - public void WriteEntry(string message, EventLogEntryType type, int eventID) + public void WriteEntry(string? message, EventLogEntryType type, int eventID) { WriteEntry(message, type, eventID, 0, null); } - public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID) + public static void WriteEntry(string source, string? message, EventLogEntryType type, int eventID) { WriteEntry(source, message, type, eventID, 0, null); } - public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) + public void WriteEntry(string? message, EventLogEntryType type, int eventID, short category) { WriteEntry(message, type, eventID, category, null); } - public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category) + public static void WriteEntry(string source, string? message, EventLogEntryType type, int eventID, short category) { WriteEntry(source, message, type, eventID, category, null); } - public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData) + public static void WriteEntry(string source, string? message, EventLogEntryType type, int eventID, short category, byte[]? rawData) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { @@ -1019,22 +1019,22 @@ public static void WriteEntry(string source, string message, EventLogEntryType t } } - public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData) + public void WriteEntry(string? message, EventLogEntryType type, int eventID, short category, byte[]? rawData) { _underlyingEventLog.WriteEntry(message, type, eventID, category, rawData); } - public void WriteEvent(EventInstance instance, params object[] values) + public void WriteEvent(EventInstance instance, params object?[]? values) { WriteEvent(instance, null, values); } - public void WriteEvent(EventInstance instance, byte[] data, params object[] values) + public void WriteEvent(EventInstance instance, byte[]? data, params object?[]? values) { _underlyingEventLog.WriteEvent(instance, data, values); } - public static void WriteEvent(string source, EventInstance instance, params object[] values) + public static void WriteEvent(string source, EventInstance instance, params object?[]? values) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { @@ -1042,7 +1042,7 @@ public static void WriteEvent(string source, EventInstance instance, params obje } } - public static void WriteEvent(string source, EventInstance instance, byte[] data, params object[] values) + public static void WriteEvent(string source, EventInstance instance, byte[] data, params object?[]? values) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { @@ -1051,7 +1051,7 @@ public static void WriteEvent(string source, EventInstance instance, byte[] data } // The EventLog.set_Source used to do some normalization and throw some exceptions. We mimic that behavior here. - private static string CheckAndNormalizeSourceName(string source) + private static string CheckAndNormalizeSourceName(string? source) { source ??= string.Empty; diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs index d18b40c71d3a08..61466a3988766c 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; @@ -19,8 +20,8 @@ public sealed class EventLogEntry : Component, ISerializable internal byte[] dataBuf; internal int bufOffset; private readonly EventLogInternal owner; - private string category; - private string message; + private string? category; + private string? message; internal EventLogEntry(byte[] buf, int offset, EventLogInternal log) { @@ -91,8 +92,8 @@ public string Category { if (category == null) { - string dllName = GetMessageLibraryNames("CategoryMessageFile"); - string cat = owner.FormatMessageWrapper(dllName, (uint)CategoryNumber, null); + string? dllName = GetMessageLibraryNames("CategoryMessageFile"); + string? cat = owner.FormatMessageWrapper(dllName, (uint)CategoryNumber, null); if (cat == null) category = "(" + CategoryNumber.ToString(CultureInfo.CurrentCulture) + ")"; else @@ -148,9 +149,9 @@ public string Message { if (message == null) { - string dllNames = GetMessageLibraryNames("EventMessageFile"); + string? dllNames = GetMessageLibraryNames("EventMessageFile"); int msgId = IntFrom(dataBuf, bufOffset + FieldOffsets.EVENTID); - string msg = owner.FormatMessageWrapper(dllNames, (uint)msgId, ReplacementStrings); + string? msg = owner.FormatMessageWrapper(dllNames, (uint)msgId, ReplacementStrings); if (msg == null) { StringBuilder msgBuf = new StringBuilder(SR.Format(SR.MessageNotFormatted, msgId, Source)); @@ -264,7 +265,7 @@ public DateTime TimeWritten /// /// The username of the account associated with this entry by the writing application. /// - public string UserName + public string? UserName { get { @@ -298,7 +299,7 @@ private static char CharFrom(byte[] buf, int offset) return (char)ShortFrom(buf, offset); } - public bool Equals(EventLogEntry otherEntry) + public bool Equals([NotNullWhen(true)] EventLogEntry? otherEntry) { if (otherEntry == null) return false; @@ -336,11 +337,11 @@ internal string ReplaceMessageParameters(string msg, string[] insertionStrings) int startCopyIdx = 0; int msgLength = msg.Length; StringBuilder buf = new StringBuilder(); - string paramDLLNames = GetMessageLibraryNames("ParameterMessageFile"); + string? paramDLLNames = GetMessageLibraryNames("ParameterMessageFile"); while (percentIdx >= 0) { - string param = null; + string? param = null; int lasNumIdx = percentIdx + 1; while (lasNumIdx < msgLength && char.IsDigit(msg, lasNumIdx)) lasNumIdx++; @@ -369,10 +370,10 @@ internal string ReplaceMessageParameters(string msg, string[] insertionStrings) return buf.ToString(); } - private static RegistryKey GetSourceRegKey(string logName, string source, string machineName) + private static RegistryKey? GetSourceRegKey(string logName, string source, string machineName) { - RegistryKey eventKey = null; - RegistryKey logKey = null; + RegistryKey? eventKey = null; + RegistryKey? logKey = null; try { @@ -387,17 +388,17 @@ private static RegistryKey GetSourceRegKey(string logName, string source, string } } - private string GetMessageLibraryNames(string libRegKey) + private string? GetMessageLibraryNames(string libRegKey) { // get the value stored in the registry - string fileName = null; - RegistryKey regKey = null; + string? fileName = null; + RegistryKey? regKey = null; try { regKey = GetSourceRegKey(owner.Log, Source, owner.MachineName); if (regKey != null) { - fileName = (string)regKey.GetValue(libRegKey); + fileName = (string?)regKey.GetValue(libRegKey); } } finally diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntryCollection.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntryCollection.cs index 729966e3bf7716..f234554874f9d4 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntryCollection.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntryCollection.cs @@ -40,7 +40,7 @@ public IEnumerator GetEnumerator() return new EntriesEnumerator(this); } - internal EventLogEntry GetEntryAtNoThrow(int index) + internal EventLogEntry? GetEntryAtNoThrow(int index) { return _log.GetEntryAtNoThrow(index); } @@ -71,7 +71,7 @@ private sealed class EntriesEnumerator : IEnumerator { private readonly EventLogEntryCollection entries; private int num = -1; - private EventLogEntry cachedEntry; + private EventLogEntry? cachedEntry; internal EntriesEnumerator(EventLogEntryCollection entries) { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index f32c41f3041a99..b6cdaec5d3bcdb 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -6,6 +6,7 @@ using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; @@ -18,22 +19,22 @@ namespace System.Diagnostics { internal sealed class EventLogInternal : IDisposable, ISupportInitialize { - private EventLogEntryCollection entriesCollection; + private EventLogEntryCollection? entriesCollection; internal string logName; // used in monitoring for event postings. private int lastSeenCount; // holds the machine we're on, or null if it's the local machine internal readonly string machineName; // the delegate to call when an event arrives - internal EntryWrittenEventHandler onEntryWrittenHandler; + internal EntryWrittenEventHandler? onEntryWrittenHandler; // holds onto the handle for reading - private SafeEventLogReadHandle readHandle; + private SafeEventLogReadHandle? readHandle; // the source name - used only when writing internal readonly string sourceName; // holds onto the handle for writing - private SafeEventLogWriteHandle writeHandle; + private SafeEventLogWriteHandle? writeHandle; - private string logDisplayName; + private string? logDisplayName; // cache system state variables // the initial size of the buffer (it can be made larger if necessary) private const int BUF_SIZE = 40000; @@ -41,7 +42,7 @@ internal sealed class EventLogInternal : IDisposable, ISupportInitialize // the same as BUF_SIZE, because the cache only holds whole entries) private int bytesCached; // the actual cache buffer - private byte[] cache; + private byte[]? cache; // the number of the entry at the beginning of the cache private int firstCachedEntry = -1; // the number of the entry that we got out of the cache most recently @@ -49,7 +50,7 @@ internal sealed class EventLogInternal : IDisposable, ISupportInitialize // where that entry was private int lastSeenPos; //support for threadpool based deferred execution - private ISynchronizeInvoke synchronizingObject; + private ISynchronizeInvoke? synchronizingObject; // the EventLog object that publicly exposes this instance. private readonly EventLog parent; @@ -68,10 +69,10 @@ internal sealed class EventLogInternal : IDisposable, ISupportInitialize private BitVector32 boolFlags; - private Hashtable messageLibraries; + private Hashtable? messageLibraries; private static readonly Hashtable listenerInfos = new Hashtable(StringComparer.OrdinalIgnoreCase); - private object m_InstanceLockObject; + private object? m_InstanceLockObject; private object InstanceLockObject { get @@ -86,7 +87,7 @@ private object InstanceLockObject } } - private static object s_InternalSyncObject; + private static object? s_InternalSyncObject; private static object InternalSyncObject { get @@ -101,11 +102,11 @@ private static object InternalSyncObject } } - public EventLogInternal(string logName, string machineName) : this(logName, machineName, "", null) + public EventLogInternal(string logName, string machineName) : this(logName, machineName, "", null! /* Special case with no parent */) { } - public EventLogInternal(string logName, string machineName, string source) : this(logName, machineName, source, null) + public EventLogInternal(string logName, string machineName, string source) : this(logName, machineName, source, null! /* Special case with no parent */) { } @@ -158,6 +159,7 @@ private bool IsOpen } } + [MemberNotNullWhen(true, nameof(readHandle))] private bool IsOpenForRead { get @@ -166,6 +168,7 @@ private bool IsOpenForRead } } + [MemberNotNullWhen(true, nameof(writeHandle))] private bool IsOpenForWrite { get @@ -174,7 +177,7 @@ private bool IsOpenForWrite } } - public string LogDisplayName + public string? LogDisplayName { get { @@ -184,7 +187,7 @@ public string LogDisplayName string currentMachineName = this.machineName; if (GetLogName(currentMachineName) != null) { - RegistryKey logkey = null; + RegistryKey? logkey = null; try { @@ -193,14 +196,14 @@ public string LogDisplayName if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, GetLogName(currentMachineName), currentMachineName)); - string resourceDll = (string)logkey.GetValue("DisplayNameFile"); + string? resourceDll = (string?)logkey.GetValue("DisplayNameFile"); if (resourceDll == null) { logDisplayName = GetLogName(currentMachineName); } else { - int resourceId = (int)logkey.GetValue("DisplayNameID"); + int resourceId = (int)logkey.GetValue("DisplayNameID")!; logDisplayName = FormatMessageWrapper(resourceDll, (uint)resourceId, null); logDisplayName ??= GetLogName(currentMachineName); } @@ -248,7 +251,7 @@ public long MaximumKilobytes { string currentMachineName = this.machineName; - object val = GetLogRegValue(currentMachineName, "MaxSize"); + object? val = GetLogRegValue(currentMachineName, "MaxSize"); if (val != null) { int intval = (int)val; // cast to an int first to unbox @@ -287,7 +290,7 @@ public OverflowAction OverflowAction { string currentMachineName = this.machineName; - object retentionobj = GetLogRegValue(currentMachineName, "Retention"); + object? retentionobj = GetLogRegValue(currentMachineName, "Retention"); if (retentionobj != null) { int retention = (int)retentionobj; @@ -310,7 +313,7 @@ public int MinimumRetentionDays { string currentMachineName = this.machineName; - object retentionobj = GetLogRegValue(currentMachineName, "Retention"); + object? retentionobj = GetLogRegValue(currentMachineName, "Retention"); if (retentionobj != null) { int retention = (int)retentionobj; @@ -374,13 +377,13 @@ internal SafeEventLogReadHandle ReadHandle } } - public ISynchronizeInvoke SynchronizingObject + public ISynchronizeInvoke? SynchronizingObject { get { if (this.synchronizingObject == null && parent.ComponentDesignMode) { - IDesignerHost host = (IDesignerHost)parent.ComponentGetService(typeof(IDesignerHost)); + IDesignerHost? host = (IDesignerHost?)parent.ComponentGetService(typeof(IDesignerHost)); if (host != null) { object baseComponent = host.RootComponent; @@ -410,19 +413,20 @@ private static void AddListenerComponent(EventLogInternal component, string comp { lock (InternalSyncObject) { - LogListeningInfo info = (LogListeningInfo)listenerInfos[compLogName]; + LogListeningInfo? info = (LogListeningInfo?)listenerInfos[compLogName]; if (info != null) { info.listeningComponents.Add(component); return; } - info = new LogListeningInfo(); + + info = new LogListeningInfo( + handleOwner: new EventLogInternal(compLogName, compMachineName), + waitHandle: new AutoResetEvent(false)); info.listeningComponents.Add(component); - info.handleOwner = new EventLogInternal(compLogName, compMachineName); // tell the event log system about it - info.waitHandle = new AutoResetEvent(false); bool success = Interop.Advapi32.NotifyChangeEventLog(info.handleOwner.ReadHandle, info.waitHandle.SafeWaitHandle); if (!success) throw new InvalidOperationException(SR.CantMonitorEventLog, new Win32Exception()); @@ -432,7 +436,7 @@ private static void AddListenerComponent(EventLogInternal component, string comp } } - public event EntryWrittenEventHandler EntryWritten + public event EntryWrittenEventHandler? EntryWritten { add { @@ -560,9 +564,9 @@ private void CompletionCallback() { EventLogEntry entry = GetEntryWithOldest(i); if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) - this.SynchronizingObject.BeginInvoke(this.onEntryWrittenHandler, new object[] { this, new EntryWrittenEventArgs(entry) }); + this.SynchronizingObject.BeginInvoke(this.onEntryWrittenHandler!, new object[] { this, new EntryWrittenEventArgs(entry) }); else - onEntryWrittenHandler(this, new EntryWrittenEventArgs(entry)); + onEntryWrittenHandler!(this, new EntryWrittenEventArgs(entry)); i++; } @@ -641,7 +645,7 @@ public void EndInit() StartListening(currentMachineName, GetLogName(currentMachineName)); } - internal string FormatMessageWrapper(string dllNameList, uint messageNum, string[] insertionStrings) + internal string? FormatMessageWrapper(string? dllNameList, uint messageNum, string[]? insertionStrings) { if (dllNameList == null) return null; @@ -656,7 +660,7 @@ internal string FormatMessageWrapper(string dllNameList, uint messageNum, string if (string.IsNullOrEmpty(dllName)) continue; - SafeLibraryHandle hModule; + SafeLibraryHandle? hModule; if (IsOpen) { @@ -676,7 +680,7 @@ internal string FormatMessageWrapper(string dllNameList, uint messageNum, string if (hModule.IsInvalid) continue; - string msg = null; + string? msg = null; try { msg = EventLog.TryFormatMessage(hModule, messageNum, insertionStrings); @@ -839,13 +843,13 @@ private int GetCachedEntryPos(int entryIndex) internal EventLogEntry GetEntryAt(int index) { - EventLogEntry entry = GetEntryAtNoThrow(index); + EventLogEntry? entry = GetEntryAtNoThrow(index); if (entry == null) throw new ArgumentException(SR.Format(SR.IndexOutOfBounds, index.ToString())); return entry; } - internal EventLogEntry GetEntryAtNoThrow(int index) + internal EventLogEntry? GetEntryAtNoThrow(int index) { if (!IsOpenForRead) OpenForRead(this.machineName); @@ -853,7 +857,7 @@ internal EventLogEntry GetEntryAtNoThrow(int index) if (index < 0 || index >= EntryCount) return null; index += OldestEntryNumber; - EventLogEntry entry = null; + EventLogEntry? entry = null; try { @@ -868,6 +872,9 @@ internal EventLogEntry GetEntryAtNoThrow(int index) private EventLogEntry GetEntryWithOldest(int index) { + Debug.Assert(readHandle != null); + Debug.Assert(cache != null); + int entryPos = GetCachedEntryPos(index); if (entryPos >= 0) { @@ -928,9 +935,9 @@ private EventLogEntry GetEntryWithOldest(int index) return new EventLogEntry(cache, 0, this); } - internal static RegistryKey GetEventLogRegKey(string machine, bool writable) + internal static RegistryKey? GetEventLogRegKey(string machine, bool writable) { - RegistryKey lmkey = null; + RegistryKey? lmkey = null; try { @@ -959,8 +966,8 @@ private RegistryKey GetLogRegKey(string currentMachineName, bool writable) if (!ValidLogName(logname, false)) throw new InvalidOperationException(SR.BadLogName); - RegistryKey eventkey = null; - RegistryKey logkey = null; + RegistryKey? eventkey = null; + RegistryKey? logkey = null; try { @@ -980,9 +987,9 @@ private RegistryKey GetLogRegKey(string currentMachineName, bool writable) return logkey; } - private object GetLogRegValue(string currentMachineName, string valuename) + private object? GetLogRegValue(string currentMachineName, string valuename) { - RegistryKey logkey = null; + RegistryKey? logkey = null; try { @@ -990,7 +997,7 @@ private object GetLogRegValue(string currentMachineName, string valuename) if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, GetLogName(currentMachineName), currentMachineName)); - object val = logkey.GetValue(valuename); + object? val = logkey.GetValue(valuename); return val; } finally @@ -1001,11 +1008,13 @@ private object GetLogRegValue(string currentMachineName, string valuename) private int GetNextEntryPos(int pos) { + Debug.Assert(cache != null); return pos + IntFrom(cache, pos); } private int GetPreviousEntryPos(int pos) { + Debug.Assert(cache != null); return pos - IntFrom(cache, pos - 4); } @@ -1037,6 +1046,7 @@ public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) logkey.SetValue("Retention", retentionvalue, RegistryValueKind.DWord); } + [MemberNotNull(nameof(readHandle))] private void OpenForRead(string currentMachineName) { if (this.boolFlags[Flag_disposed]) @@ -1061,7 +1071,7 @@ private void OpenForRead(string currentMachineName) SafeEventLogReadHandle handle = Interop.Advapi32.OpenEventLog(currentMachineName, logname); if (handle.IsInvalid) { - Win32Exception e = null; + Win32Exception? e = null; if (Marshal.GetLastWin32Error() != 0) { e = new Win32Exception(); @@ -1073,6 +1083,7 @@ private void OpenForRead(string currentMachineName) readHandle = handle; } + [MemberNotNull(nameof(writeHandle))] private void OpenForWrite(string currentMachineName) { //Cannot allocate the writeHandle if the object has been disposed, since finalization has been suppressed. @@ -1085,7 +1096,7 @@ private void OpenForWrite(string currentMachineName) SafeEventLogWriteHandle handle = Interop.Advapi32.RegisterEventSource(currentMachineName, sourceName); if (handle.IsInvalid) { - Win32Exception e = null; + Win32Exception? e = null; if (Marshal.GetLastWin32Error() != 0) { e = new Win32Exception(); @@ -1132,7 +1143,7 @@ private static void RemoveListenerComponent(EventLogInternal component, string c { lock (InternalSyncObject) { - LogListeningInfo info = (LogListeningInfo)listenerInfos[compLogName]; + LogListeningInfo? info = (LogListeningInfo?)listenerInfos[compLogName]; Debug.Assert(info != null); // remove the requested component from the list. info.listeningComponents.Remove(component); @@ -1141,7 +1152,7 @@ private static void RemoveListenerComponent(EventLogInternal component, string c // if that was the last interested compononent, destroy the handles and stop listening. info.handleOwner.Dispose(); //Unregister the thread pool wait handle - info.registeredWaitHandle.Unregister(info.waitHandle); + info.registeredWaitHandle?.Unregister(info.waitHandle); // close the handle info.waitHandle.Close(); listenerInfos[compLogName] = null; @@ -1166,9 +1177,9 @@ private void StartRaisingEvents(string currentMachineName, string currentLogName boolFlags[Flag_monitoring] = true; } - private static void StaticCompletionCallback(object context, bool wasSignaled) + private static void StaticCompletionCallback(object? context, bool wasSignaled) { - LogListeningInfo info = (LogListeningInfo)context; + LogListeningInfo? info = (LogListeningInfo?)context; if (info == null) return; // get a snapshot of the components to fire the event on @@ -1236,7 +1247,7 @@ private void VerifyAndCreateSource(string sourceName, string currentMachineName) if (!EventLog.SourceExists(sourceName, currentMachineName, true)) { - Mutex mutex = null; + Mutex? mutex = null; try { @@ -1282,8 +1293,8 @@ private void VerifyAndCreateSource(string sourceName, string currentMachineName) boolFlags[Flag_sourceVerified] = true; } - public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, - byte[] rawData) + public void WriteEntry(string? message, EventLogEntryType type, int eventID, short category, + byte[]? rawData) { if (eventID < 0 || eventID > ushort.MaxValue) @@ -1305,10 +1316,10 @@ public void WriteEntry(string message, EventLogEntryType type, int eventID, shor // (message-file driven) logging techniques. // Our DLL has 64K different entries; all of them just display the first // insertion string. - InternalWriteEvent((uint)eventID, (ushort)category, type, new string[] { message }, rawData, currentMachineName); + InternalWriteEvent((uint)eventID, (ushort)category, type, new string?[] { message }, rawData, currentMachineName); } - public void WriteEvent(EventInstance instance, byte[] data, params object[] values) + public void WriteEvent(EventInstance instance, byte[]? data, params object?[]? values) { ArgumentNullException.ThrowIfNull(instance); @@ -1323,25 +1334,22 @@ public void WriteEvent(EventInstance instance, byte[] data, params object[] valu VerifyAndCreateSource(Source, currentMachineName); - string[] strings = null; + string[]? strings = null; if (values != null) { strings = new string[values.Length]; for (int i = 0; i < values.Length; i++) { - if (values[i] != null) - strings[i] = values[i].ToString(); - else - strings[i] = string.Empty; + strings[i] = values[i]?.ToString() ?? string.Empty; } } InternalWriteEvent((uint)instance.InstanceId, (ushort)instance.CategoryId, instance.EntryType, strings, data, currentMachineName); } - private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType type, string[] strings, - byte[] rawData, string currentMachineName) + private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType type, string?[]? strings, + byte[]? rawData, string currentMachineName) { strings ??= Array.Empty(); if (strings.Length >= 256) @@ -1353,7 +1361,7 @@ private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType // make sure the strings aren't too long. MSDN says each string has a limit of 32k (32768) characters, but // experimentation shows that it doesn't like anything larger than 32766 - if (strings[i].Length > 32766) + if (strings[i]!.Length > 32766) throw new ArgumentException(SR.LogEntryTooLong); } rawData ??= Array.Empty(); @@ -1376,7 +1384,7 @@ private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType stringRoots[strIndex] = stringHandles[strIndex].AddrOfPinnedObject(); } - byte[] sid = null; + byte[]? sid = null; // actually report the event bool success = Interop.Advapi32.ReportEvent(writeHandle, (short)type, category, eventID, sid, (short)strings.Length, rawData.Length, stringsRootHandle.AddrOfPinnedObject(), rawData); @@ -1399,8 +1407,13 @@ private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType private sealed class LogListeningInfo { + public LogListeningInfo(EventLogInternal handleOwner, AutoResetEvent waitHandle) + { + this.handleOwner = handleOwner; + this.waitHandle = waitHandle; + } public EventLogInternal handleOwner; - public RegisteredWaitHandle registeredWaitHandle; + public RegisteredWaitHandle? registeredWaitHandle; public AutoResetEvent waitHandle; public List listeningComponents = new(); } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs index c6ef001b641fc0..002a11a2ec41b0 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Text; @@ -15,7 +16,7 @@ public EventLogTraceListener() { } - public EventLogTraceListener(EventLog eventLog) + public EventLogTraceListener(EventLog? eventLog) : base(eventLog != null ? eventLog.Source : string.Empty) { EventLog = eventLog; @@ -29,12 +30,13 @@ public EventLogTraceListener(string source) }; } - public EventLog EventLog + public EventLog? EventLog { get; set; } + [AllowNull] public override string Name { get @@ -73,12 +75,12 @@ protected override void Dispose(bool disposing) } } - public override void Write(string message) => EventLog?.WriteEntry(message); + public override void Write(string? message) => EventLog?.WriteEntry(message); - public override void WriteLine(string message) => Write(message); + public override void WriteLine(string? message) => Write(message); [ComVisible(false)] - public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string format, params object[] args) + public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType severity, int id, string? format, params object?[]? args) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, severity, id, format, args, null, null)) return; @@ -87,45 +89,45 @@ public override void TraceEvent(TraceEventCache eventCache, string source, Trace if (args == null || args.Length == 0) { - EventLog.WriteEvent(data, format); + EventLog!.WriteEvent(data, format); } else if (string.IsNullOrEmpty(format)) { - string[] strings = new string[args.Length]; + string?[] strings = new string[args.Length]; for (int i = 0; i < args.Length; i++) { - strings[i] = args[i].ToString(); + strings[i] = args[i]?.ToString(); } - EventLog.WriteEvent(data, strings); + EventLog!.WriteEvent(data, strings); } else { - EventLog.WriteEvent(data, string.Format(CultureInfo.InvariantCulture, format, args)); + EventLog!.WriteEvent(data, string.Format(CultureInfo.InvariantCulture, format, args)); } } [ComVisible(false)] - public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string message) + public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType severity, int id, string? message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, severity, id, message, null, null, null)) return; - EventLog.WriteEvent(CreateEventInstance(severity, id), message); + EventLog!.WriteEvent(CreateEventInstance(severity, id), message); } [ComVisible(false)] - public override void TraceData(TraceEventCache eventCache, string source, TraceEventType severity, int id, object data) + public override void TraceData(TraceEventCache? eventCache, string source, TraceEventType severity, int id, object? data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, severity, id, null, null, data, null)) return; - EventLog.WriteEvent(CreateEventInstance(severity, id), new object[] { data }); + EventLog!.WriteEvent(CreateEventInstance(severity, id), new object?[] { data }); } [ComVisible(false)] - public override void TraceData(TraceEventCache eventCache, string source, TraceEventType severity, int id, params object[] data) + public override void TraceData(TraceEventCache? eventCache, string source, TraceEventType severity, int id, params object?[]? data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, severity, id, null, null, null, data)) return; @@ -140,12 +142,13 @@ public override void TraceData(TraceEventCache eventCache, string source, TraceE if (i != 0) sb.Append(", "); - if (data[i] != null) - sb.Append(data[i].ToString()); + object? datum = data[i]; + if (datum != null) + sb.Append(datum.ToString()); } } - EventLog.WriteEvent(inst, new object[] { sb.ToString() }); + EventLog!.WriteEvent(inst, new object[] { sb.ToString() }); } private static EventInstance CreateEventInstance(TraceEventType severity, int id) diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventSourceCreationData.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventSourceCreationData.cs index 30330c9e6b6009..a9ccf9670dde4c 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventSourceCreationData.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventSourceCreationData.cs @@ -9,13 +9,13 @@ public class EventSourceCreationData private EventSourceCreationData() { } - public EventSourceCreationData(string source, string logName) + public EventSourceCreationData(string? source, string logName) { Source = source; LogName = logName; } - internal EventSourceCreationData(string source, string logName, string machineName) : this(source, logName) + internal EventSourceCreationData(string? source, string logName, string machineName) : this(source, logName) { MachineName = machineName; } @@ -24,13 +24,13 @@ internal EventSourceCreationData(string source, string logName, string machineNa public string MachineName { get; set; } = "."; - public string Source { get; set; } + public string? Source { get; set; } - public string MessageResourceFile { get; set; } + public string? MessageResourceFile { get; set; } - public string ParameterResourceFile { get; set; } + public string? ParameterResourceFile { get; set; } - public string CategoryResourceFile { get; set; } + public string? CategoryResourceFile { get; set; } public int CategoryCount { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventKeyword.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventKeyword.cs index fb720d84e98cfa..9cd8d4fbe9559f 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventKeyword.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventKeyword.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing.Reader { @@ -11,10 +12,11 @@ namespace System.Diagnostics.Eventing.Reader /// public sealed class EventKeyword { - private string _name; - private string _displayName; - private bool _dataReady; - private readonly ProviderMetadata _pmReference; + private string? _name; + private string? _displayName; + [MemberNotNullWhen(false, nameof(_pmReference))] + private bool DataReady { get; set; } + private readonly ProviderMetadata? _pmReference; private readonly object _syncObject; internal EventKeyword(long value, ProviderMetadata pmReference) @@ -24,30 +26,30 @@ internal EventKeyword(long value, ProviderMetadata pmReference) _syncObject = new object(); } - internal EventKeyword(string name, long value, string displayName) + internal EventKeyword(string? name, long value, string? displayName) { Value = value; _name = name; _displayName = displayName; - _dataReady = true; + DataReady = true; _syncObject = new object(); } internal void PrepareData() { - if (_dataReady) + if (DataReady) return; lock (_syncObject) { - if (_dataReady) + if (DataReady) return; IEnumerable result = _pmReference.Keywords; _name = null; _displayName = null; - _dataReady = true; + DataReady = true; foreach (EventKeyword key in result) { @@ -61,7 +63,7 @@ internal void PrepareData() } } - public string Name + public string? Name { get { @@ -72,7 +74,7 @@ public string Name public long Value { get; } - public string DisplayName + public string? DisplayName { get { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLevel.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLevel.cs index 8cdbdf5635ef4f..599fe51dac0d26 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLevel.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLevel.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing.Reader { @@ -11,10 +12,11 @@ namespace System.Diagnostics.Eventing.Reader /// public sealed class EventLevel { - private string _name; - private string _displayName; - private bool _dataReady; - private readonly ProviderMetadata _pmReference; + private string? _name; + private string? _displayName; + [MemberNotNullWhen(false, nameof(_pmReference))] + private bool DataReady { get; set; } + private readonly ProviderMetadata? _pmReference; private readonly object _syncObject; internal EventLevel(int value, ProviderMetadata pmReference) @@ -24,29 +26,29 @@ internal EventLevel(int value, ProviderMetadata pmReference) _syncObject = new object(); } - internal EventLevel(string name, int value, string displayName) + internal EventLevel(string? name, int value, string? displayName) { Value = value; _name = name; _displayName = displayName; - _dataReady = true; + DataReady = true; _syncObject = new object(); } internal void PrepareData() { - if (_dataReady) + if (DataReady) return; lock (_syncObject) { - if (_dataReady) + if (DataReady) return; IEnumerable result = _pmReference.Levels; _name = null; _displayName = null; - _dataReady = true; + DataReady = true; foreach (EventLevel lev in result) { if (lev.Value == Value) @@ -59,7 +61,7 @@ internal void PrepareData() } } - public string Name + public string? Name { get { @@ -70,7 +72,7 @@ public string Name public int Value { get; } - public string DisplayName + public string? DisplayName { get { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs index 1c58e48bb216c9..c3f368ab65b6e5 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs @@ -49,7 +49,7 @@ public class EventLogConfiguration : IDisposable public EventLogConfiguration(string logName) : this(logName, null) { } - public EventLogConfiguration(string logName, EventLogSession session) + public EventLogConfiguration(string logName, EventLogSession? session) { session ??= EventLogSession.GlobalSession; @@ -65,7 +65,7 @@ public EventLogType LogType { get { - return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType)); + return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType)!); } } @@ -73,7 +73,7 @@ public EventLogIsolation LogIsolation { get { - return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation)); + return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation)!); } } @@ -81,7 +81,7 @@ public bool IsEnabled { get { - return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled); + return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled)!; } set { @@ -93,31 +93,31 @@ public bool IsClassicLog { get { - return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog); + return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog)!; } } - public string SecurityDescriptor + public string? SecurityDescriptor { get { - return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess); + return (string?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess); } set { - NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object?)value); } } - public string LogFilePath + public string? LogFilePath { get { - return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath); + return (string?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath); } set { - NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object?)value); } } @@ -125,7 +125,7 @@ public long MaximumSizeInBytes { get { - return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize)); + return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize)!); } set { @@ -137,8 +137,8 @@ public EventLogMode LogMode { get { - object nativeRetentionObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention); - object nativeAutoBackupObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup); + object? nativeRetentionObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention); + object? nativeAutoBackupObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup); bool nativeRetention = nativeRetentionObject == null ? false : (bool)nativeRetentionObject; bool nativeAutoBackup = nativeAutoBackupObject == null ? false : (bool)nativeAutoBackupObject; @@ -171,19 +171,19 @@ public EventLogMode LogMode } } - public string OwningProviderName + public string? OwningProviderName { get { - return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher); + return (string?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher); } } - public IEnumerable ProviderNames + public IEnumerable? ProviderNames { get { - return (string[])NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList); + return (string?[]?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList); } } @@ -195,7 +195,7 @@ public int? ProviderLevel } set { - NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object?)value); } } @@ -207,7 +207,7 @@ public long? ProviderKeywords } set { - NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object?)value); } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogException.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogException.cs index 4de5abf9f0fee1..f6beb84fea6e3e 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogException.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogException.cs @@ -49,8 +49,8 @@ internal static void Throw(int errorCode) } public EventLogException() { } - public EventLogException(string message) : base(message) { } - public EventLogException(string message, Exception innerException) : base(message, innerException) { } + public EventLogException(string? message) : base(message) { } + public EventLogException(string? message, Exception? innerException) : base(message, innerException) { } protected EventLogException(int errorCode) { _errorCode = errorCode; @@ -96,8 +96,8 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont public class EventLogNotFoundException : EventLogException { public EventLogNotFoundException() { } - public EventLogNotFoundException(string message) : base(message) { } - public EventLogNotFoundException(string message, Exception innerException) : base(message, innerException) { } + public EventLogNotFoundException(string? message) : base(message) { } + public EventLogNotFoundException(string? message, Exception? innerException) : base(message, innerException) { } internal EventLogNotFoundException(int errorCode) : base(errorCode) { } #if NET [Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] @@ -115,8 +115,8 @@ protected EventLogNotFoundException(SerializationInfo serializationInfo, Streami public class EventLogReadingException : EventLogException { public EventLogReadingException() { } - public EventLogReadingException(string message) : base(message) { } - public EventLogReadingException(string message, Exception innerException) : base(message, innerException) { } + public EventLogReadingException(string? message) : base(message) { } + public EventLogReadingException(string? message, Exception? innerException) : base(message, innerException) { } internal EventLogReadingException(int errorCode) : base(errorCode) { } #if NET [Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] @@ -134,8 +134,8 @@ protected EventLogReadingException(SerializationInfo serializationInfo, Streamin public class EventLogProviderDisabledException : EventLogException { public EventLogProviderDisabledException() { } - public EventLogProviderDisabledException(string message) : base(message) { } - public EventLogProviderDisabledException(string message, Exception innerException) : base(message, innerException) { } + public EventLogProviderDisabledException(string? message) : base(message) { } + public EventLogProviderDisabledException(string? message, Exception? innerException) : base(message, innerException) { } internal EventLogProviderDisabledException(int errorCode) : base(errorCode) { } #if NET [Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] @@ -151,8 +151,8 @@ protected EventLogProviderDisabledException(SerializationInfo serializationInfo, public class EventLogInvalidDataException : EventLogException { public EventLogInvalidDataException() { } - public EventLogInvalidDataException(string message) : base(message) { } - public EventLogInvalidDataException(string message, Exception innerException) : base(message, innerException) { } + public EventLogInvalidDataException(string? message) : base(message) { } + public EventLogInvalidDataException(string? message, Exception? innerException) : base(message, innerException) { } internal EventLogInvalidDataException(int errorCode) : base(errorCode) { } #if NET [Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogLink.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogLink.cs index e409e8225f539f..d5833030391171 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogLink.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogLink.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing.Reader { @@ -12,11 +13,13 @@ namespace System.Diagnostics.Eventing.Reader /// public sealed class EventLogLink { - private string _channelName; + private string? _channelName; private bool _isImported; - private string _displayName; - private bool _dataReady; - private readonly ProviderMetadata _pmReference; + private string? _displayName; + + [MemberNotNullWhen(false, nameof(_pmReference))] + private bool DataReady { get; set; } + private readonly ProviderMetadata? _pmReference; private readonly object _syncObject; internal EventLogLink(uint channelId, ProviderMetadata pmReference) @@ -26,25 +29,25 @@ internal EventLogLink(uint channelId, ProviderMetadata pmReference) _syncObject = new object(); } - internal EventLogLink(string channelName, bool isImported, string displayName, uint channelId) + internal EventLogLink(string? channelName, bool isImported, string? displayName, uint channelId) { _channelName = channelName; _isImported = isImported; _displayName = displayName; ChannelId = channelId; - _dataReady = true; + DataReady = true; _syncObject = new object(); } private void PrepareData() { - if (_dataReady) + if (DataReady) return; lock (_syncObject) { - if (_dataReady) + if (DataReady) return; IEnumerable result = _pmReference.LogLinks; @@ -52,7 +55,7 @@ private void PrepareData() _channelName = null; _isImported = false; _displayName = null; - _dataReady = true; + DataReady = true; foreach (EventLogLink ch in result) { @@ -62,7 +65,7 @@ private void PrepareData() _isImported = ch.IsImported; _displayName = ch.DisplayName; - _dataReady = true; + DataReady = true; break; } @@ -70,7 +73,7 @@ private void PrepareData() } } - public string LogName + public string? LogName { get { @@ -88,7 +91,7 @@ public bool IsImported } } - public string DisplayName + public string? DisplayName { get { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs index f16e8fc1328203..2a30a5c2c7ba07 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs @@ -19,8 +19,7 @@ public EventLogPropertySelector(IEnumerable propertyQueries) string[] paths; - ICollection coll = propertyQueries as ICollection; - if (coll != null) + if (propertyQueries is ICollection coll) { paths = new string[coll.Count]; coll.CopyTo(paths, 0); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogQuery.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogQuery.cs index 3f2470902e7a07..68689cb6afbea0 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogQuery.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogQuery.cs @@ -12,12 +12,12 @@ namespace System.Diagnostics.Eventing.Reader /// public class EventLogQuery { - public EventLogQuery(string path, PathType pathType) + public EventLogQuery(string? path, PathType pathType) : this(path, pathType, null) { } - public EventLogQuery(string path, PathType pathType, string query) + public EventLogQuery(string? path, PathType pathType, string? query) { Session = EventLogSession.GlobalSession; Path = path; // can be null @@ -40,10 +40,10 @@ public EventLogQuery(string path, PathType pathType, string query) public bool ReverseDirection { get; set; } - internal string Path { get; } + internal string? Path { get; } internal PathType ThePathType { get; } - internal string Query { get; } + internal string? Query { get; } } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs index 9325a298db1970..0731b9aea4cd12 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs @@ -47,12 +47,12 @@ public class EventLogReader : IDisposable /// private readonly ProviderMetadataCachedInformation _cachedMetadataInformation; - public EventLogReader(string path) + public EventLogReader(string? path) : this(new EventLogQuery(path, PathType.LogName), null) { } - public EventLogReader(string path, PathType pathType) + public EventLogReader(string? path, PathType pathType) : this(new EventLogQuery(path, pathType), null) { } @@ -62,11 +62,11 @@ public EventLogReader(EventLogQuery eventQuery) { } - public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark) + public EventLogReader(EventLogQuery eventQuery, EventBookmark? bookmark) { ArgumentNullException.ThrowIfNull(eventQuery); - string logfile = null; + string? logfile = null; if (eventQuery.ThePathType == PathType.FilePath) logfile = eventQuery.Path; @@ -149,12 +149,12 @@ private bool GetNextBatch(TimeSpan ts) return true; } - public EventRecord ReadEvent() + public EventRecord? ReadEvent() { return ReadEvent(TimeSpan.MaxValue); } - public EventRecord ReadEvent(TimeSpan timeout) + public EventRecord? ReadEvent(TimeSpan timeout) { if (_isEof) throw new InvalidOperationException(); @@ -306,8 +306,8 @@ public IList LogStatus if (queryHandle.IsInvalid) throw new InvalidOperationException(); - string[] channelNames = (string[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames); - int[] errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses); + string?[] channelNames = (string?[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames)!; + int[] errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses)!; if (channelNames.Length != errorStatuses.Length) throw new InvalidOperationException(); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs index 4ce0b0dcdd1452..f241519dbc88b8 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs @@ -12,17 +12,17 @@ public class EventLogRecord : EventRecord private readonly EventLogSession _session; private readonly NativeWrapper.SystemProperties _systemProperties; - private string _containerChannel; - private int[] _matchedQueryIds; + private string? _containerChannel; + private int[]? _matchedQueryIds; // A dummy object which is used only for the locking. private readonly object _syncObject; // Cached DisplayNames for each instance - private string _levelName; - private string _taskName; - private string _opcodeName; - private IEnumerable _keywordsNames; + private string? _levelName; + private string? _taskName; + private string? _opcodeName; + private IEnumerable? _keywordsNames; // Cached DisplayNames for each instance private bool _levelNameReady; @@ -142,7 +142,7 @@ public override string ProviderName get { PrepareSystemData(); - return _systemProperties.ProviderName; + return _systemProperties.ProviderName!; } } @@ -155,7 +155,7 @@ public override Guid? ProviderId } } - public override string LogName + public override string? LogName { get { @@ -182,7 +182,7 @@ public override int? ThreadId } } - public override string MachineName + public override string? MachineName { get { @@ -191,7 +191,7 @@ public override string MachineName } } - public override System.Security.Principal.SecurityIdentifier UserId + public override System.Security.Principal.SecurityIdentifier? UserId { get { @@ -227,7 +227,7 @@ public override Guid? RelatedActivityId } } - public string ContainerLog + public string? ContainerLog { get { @@ -235,12 +235,12 @@ public string ContainerLog return _containerChannel; lock (_syncObject) { - return _containerChannel ??= (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath); + return _containerChannel ??= (string?)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath); } } } - public IEnumerable MatchedQueryIds + public IEnumerable? MatchedQueryIds { get { @@ -248,7 +248,7 @@ public IEnumerable MatchedQueryIds return _matchedQueryIds; lock (_syncObject) { - return _matchedQueryIds ??= (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs); + return _matchedQueryIds ??= (int[]?)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs); } } } @@ -267,18 +267,18 @@ public override EventBookmark Bookmark } } - public override string FormatDescription() + public override string? FormatDescription() { return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, Handle); } - public override string FormatDescription(IEnumerable values) + public override string? FormatDescription(IEnumerable? values) { if (values == null) return this.FormatDescription(); // Copy the value IEnumerable to an array. - string[] theValues = Array.Empty(); + string?[] theValues = Array.Empty(); int i = 0; foreach (object o in values) { @@ -286,7 +286,7 @@ public override string FormatDescription(IEnumerable values) Array.Resize(ref theValues, i + 1); if (o is EventProperty elp) { - theValues[i] = elp.Value.ToString(); + theValues[i] = elp.Value?.ToString(); } else { @@ -298,7 +298,7 @@ public override string FormatDescription(IEnumerable values) return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, Handle, theValues); } - public override string LevelDisplayName + public override string? LevelDisplayName { get { @@ -316,7 +316,7 @@ public override string LevelDisplayName } } - public override string OpcodeDisplayName + public override string? OpcodeDisplayName { get { @@ -332,7 +332,7 @@ public override string OpcodeDisplayName } } - public override string TaskDisplayName + public override string? TaskDisplayName { get { @@ -350,7 +350,7 @@ public override string TaskDisplayName } } - public override IEnumerable KeywordsDisplayNames + public override IEnumerable? KeywordsDisplayNames { get { @@ -368,9 +368,9 @@ public override IList Properties get { _session.SetupUserContext(); - IList properties = NativeWrapper.EvtRenderBufferWithContextUserOrValues(_session.renderContextHandleUser, Handle); + IList properties = NativeWrapper.EvtRenderBufferWithContextUserOrValues(_session.renderContextHandleUser, Handle); List list = new List(); - foreach (object value in properties) + foreach (object? value in properties) { list.Add(new EventProperty(value)); } @@ -378,7 +378,7 @@ public override IList Properties } } - public IList GetPropertyValues(EventLogPropertySelector propertySelector) + public IList GetPropertyValues(EventLogPropertySelector propertySelector) { ArgumentNullException.ThrowIfNull(propertySelector); @@ -404,7 +404,7 @@ protected override void Dispose(bool disposing) } } - internal static EventLogHandle GetBookmarkHandleFromBookmark(EventBookmark bookmark) + internal static EventLogHandle GetBookmarkHandleFromBookmark(EventBookmark? bookmark) { if (bookmark == null) return EventLogHandle.Zero; diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs index 0273fc976a8214..972c436b910e45 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs @@ -47,9 +47,9 @@ public class EventLogSession : IDisposable // The dummy sync object for the two contexts. private readonly object _syncObject; - private readonly string _server; - private readonly string _user; - private readonly string _domain; + private readonly string? _server; + private readonly string? _user; + private readonly string? _domain; private readonly SessionAuthentication _logOnType; // Setup the System Context, once for all the EventRecords. @@ -87,12 +87,11 @@ public EventLogSession() } public EventLogSession(string server) - : - this(server, null, null, (SecureString)null, SessionAuthentication.Default) + : this(server, null, null, (SecureString?)null, SessionAuthentication.Default) { } - public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType) + public EventLogSession(string server, string? domain, string? user, SecureString? password, SessionAuthentication logOnType) { server ??= "localhost"; @@ -103,13 +102,12 @@ public EventLogSession(string server, string domain, string user, SecureString p _user = user; _logOnType = logOnType; - UnsafeNativeMethods.EvtRpcLogin erLogin = default; - erLogin.Server = _server; - erLogin.User = _user; - erLogin.Domain = _domain; - erLogin.Flags = (int)_logOnType; - erLogin.Password = CoTaskMemUnicodeSafeHandle.Zero; - + UnsafeNativeMethods.EvtRpcLogin erLogin = new UnsafeNativeMethods.EvtRpcLogin( + server: _server, + user: _user, + domain: _domain, + flags: (int)_logOnType, + password: CoTaskMemUnicodeSafeHandle.Zero); try { if (password != null) @@ -172,9 +170,12 @@ public IEnumerable GetProviderNames() do { - string s = NativeWrapper.EvtNextPublisherId(ProviderEnum, ref finish); + string? s = NativeWrapper.EvtNextPublisherId(ProviderEnum, ref finish); if (!finish) + { + Debug.Assert(s != null, "value should only be null when there are no more items"); namesList.Add(s); + } } while (!finish); @@ -192,9 +193,12 @@ public IEnumerable GetLogNames() do { - string s = NativeWrapper.EvtNextChannelPath(channelEnum, ref finish); + string? s = NativeWrapper.EvtNextChannelPath(channelEnum, ref finish); if (!finish) + { + Debug.Assert(s != null, "value should only be null when there are no more items"); namesList.Add(s); + } } while (!finish); @@ -209,12 +213,12 @@ public EventLogInformation GetLogInformation(string logName, PathType pathType) return new EventLogInformation(this, logName, pathType); } - public void ExportLog(string path, PathType pathType, string query, string targetFilePath) + public void ExportLog(string path, PathType pathType, string? query, string targetFilePath) { this.ExportLog(path, pathType, query, targetFilePath, false); } - public void ExportLog(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors) + public void ExportLog(string path, PathType pathType, string? query, string targetFilePath, bool tolerateQueryErrors) { ArgumentNullException.ThrowIfNull(path); ArgumentNullException.ThrowIfNull(targetFilePath); @@ -231,12 +235,12 @@ public void ExportLog(string path, PathType pathType, string query, string targe NativeWrapper.EvtExportLog(this.Handle, path, query, targetFilePath, (int)flag | (int)UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogTolerateQueryErrors); } - public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath) + public void ExportLogAndMessages(string path, PathType pathType, string? query, string targetFilePath) { this.ExportLogAndMessages(path, pathType, query, targetFilePath, false, CultureInfo.CurrentCulture); } - public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors, CultureInfo targetCultureInfo) + public void ExportLogAndMessages(string path, PathType pathType, string? query, string targetFilePath, bool tolerateQueryErrors, CultureInfo? targetCultureInfo) { ExportLog(path, pathType, query, targetFilePath, tolerateQueryErrors); // Ignore the CultureInfo, pass 0 to use the calling thread's locale @@ -248,7 +252,7 @@ public void ClearLog(string logName) this.ClearLog(logName, null); } - public void ClearLog(string logName, string backupPath) + public void ClearLog(string logName, string? backupPath) { ArgumentNullException.ThrowIfNull(logName); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogStatus.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogStatus.cs index e996d4d40f16e1..3f164b9600fa56 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogStatus.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogStatus.cs @@ -13,13 +13,13 @@ namespace System.Diagnostics.Eventing.Reader /// public sealed class EventLogStatus { - internal EventLogStatus(string channelName, int win32ErrorCode) + internal EventLogStatus(string? channelName, int win32ErrorCode) { LogName = channelName; StatusCode = win32ErrorCode; } - public string LogName { get; } + public string? LogName { get; } public int StatusCode { get; } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs index f3de1b2d0a7e19..75a40bf2b5b575 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.Win32; @@ -12,27 +13,29 @@ namespace System.Diagnostics.Eventing.Reader /// public class EventLogWatcher : IDisposable { - public event EventHandler EventRecordWritten; + public event EventHandler? EventRecordWritten; private readonly EventLogQuery _eventQuery; - private readonly EventBookmark _bookmark; + private readonly EventBookmark? _bookmark; private readonly bool _readExistingEvents; - private EventLogHandle _handle; + private EventLogHandle? _handle; private readonly IntPtr[] _eventsBuffer; private int _numEventsInBuffer; - private bool _isSubscribing; + + [MemberNotNullWhen(true, nameof(_handle))] + private bool IsSubscribing { get; set; } private int _callbackThreadId; - private AutoResetEvent _subscriptionWaitHandle; - private AutoResetEvent _unregisterDoneHandle; - private RegisteredWaitHandle _registeredWaitHandle; + private AutoResetEvent? _subscriptionWaitHandle; + private AutoResetEvent? _unregisterDoneHandle; + private RegisteredWaitHandle? _registeredWaitHandle; /// /// Maintains cached display / metadata information returned from /// EventRecords that were obtained from this reader. /// private readonly ProviderMetadataCachedInformation cachedMetadataInformation; - private EventLogException asyncException; + private EventLogException? asyncException; public EventLogWatcher(string path) : this(new EventLogQuery(path, PathType.LogName), null, false) @@ -44,12 +47,12 @@ public EventLogWatcher(EventLogQuery eventQuery) { } - public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark) + public EventLogWatcher(EventLogQuery eventQuery, EventBookmark? bookmark) : this(eventQuery, bookmark, false) { } - public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark, bool readExistingEvents) + public EventLogWatcher(EventLogQuery eventQuery, EventBookmark? bookmark, bool readExistingEvents) { ArgumentNullException.ThrowIfNull(eventQuery); @@ -76,15 +79,15 @@ public bool Enabled { get { - return _isSubscribing; + return IsSubscribing; } set { - if (value && !_isSubscribing) + if (value && !IsSubscribing) { StartSubscribing(); } - else if (!value && _isSubscribing) + else if (!value && IsSubscribing) { StopSubscribing(); } @@ -96,7 +99,7 @@ internal void StopSubscribing() // C:\public\System.Diagnostics.Eventing\Microsoft\Win32\SafeHandles; // Need to set isSubscribing to false before waiting for completion of callback. - _isSubscribing = false; + IsSubscribing = false; if (_registeredWaitHandle != null) { @@ -143,9 +146,10 @@ internal void StopSubscribing() } } + [MemberNotNull(nameof(_handle))] internal void StartSubscribing() { - if (_isSubscribing) + if (IsSubscribing) { throw new InvalidOperationException(); } @@ -190,7 +194,7 @@ internal void StartSubscribing() flag); } - _isSubscribing = true; + IsSubscribing = true; RequestEvents(); @@ -202,7 +206,7 @@ internal void StartSubscribing() false); } - internal void SubscribedEventsAvailableCallback(object state, bool timedOut) + internal void SubscribedEventsAvailableCallback(object? state, bool timedOut) { _callbackThreadId = Environment.CurrentManagedThreadId; try @@ -226,7 +230,7 @@ private void RequestEvents() do { - if (!_isSubscribing) + if (!IsSubscribing) { break; } @@ -266,7 +270,7 @@ private void HandleEventsRequestCompletion() for (int i = 0; i < _numEventsInBuffer; i++) { - if (!_isSubscribing) + if (!IsSubscribing) { break; } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventMetadata.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventMetadata.cs index 4e2d2128b6ff79..77ac1c51813adb 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventMetadata.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventMetadata.cs @@ -20,7 +20,7 @@ public sealed class EventMetadata internal EventMetadata(uint id, byte version, byte channelId, byte level, byte opcode, short task, long keywords, - string template, string description, ProviderMetadata pmReference) + string? template, string? description, ProviderMetadata pmReference) { Id = id; Version = version; @@ -107,8 +107,8 @@ public IEnumerable Keywords } } - public string Template { get; } + public string? Template { get; } - public string Description { get; } + public string? Description { get; } } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventOpcode.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventOpcode.cs index e7d9599ea31742..00d702fc776c29 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventOpcode.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventOpcode.cs @@ -13,10 +13,11 @@ namespace System.Diagnostics.Eventing.Reader public sealed class EventOpcode { private readonly int _value; - private string _name; - private string _displayName; - private bool _dataReady; - private readonly ProviderMetadata _pmReference; + private string? _name; + private string? _displayName; + [MemberNotNullWhen(false, nameof(_pmReference))] + private bool DataReady { get; set; } + private readonly ProviderMetadata? _pmReference; private readonly object _syncObject; internal EventOpcode(int value, ProviderMetadata pmReference) @@ -26,12 +27,12 @@ internal EventOpcode(int value, ProviderMetadata pmReference) _syncObject = new object(); } - internal EventOpcode(string name, int value, string displayName) + internal EventOpcode(string? name, int value, string? displayName) { _value = value; _name = name; _displayName = displayName; - _dataReady = true; + DataReady = true; _syncObject = new object(); } @@ -39,7 +40,7 @@ internal void PrepareData() { lock (_syncObject) { - if (_dataReady) + if (DataReady) return; // Get the data @@ -47,21 +48,21 @@ internal void PrepareData() // Set the names and display names to null _name = null; _displayName = null; - _dataReady = true; + DataReady = true; foreach (EventOpcode op in result) { if (op.Value == _value) { _name = op.Name; _displayName = op.DisplayName; - _dataReady = true; + DataReady = true; break; } } } } // End Prepare Data - public string Name + public string? Name { get { @@ -78,7 +79,7 @@ public int Value } } - public string DisplayName + public string? DisplayName { get { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventProperty.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventProperty.cs index 3261c961642227..9e6edae0033c3d 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventProperty.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventProperty.cs @@ -5,11 +5,11 @@ namespace System.Diagnostics.Eventing.Reader { public sealed class EventProperty { - internal EventProperty(object value) + internal EventProperty(object? value) { Value = value; } - public object Value { get; } + public object? Value { get; } } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecord.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecord.cs index fef001669eda75..e214e0b7c18d5d 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecord.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecord.cs @@ -24,26 +24,26 @@ public abstract class EventRecord : IDisposable public abstract string ProviderName { get; } public abstract Guid? ProviderId { get; } - public abstract string LogName { get; } + public abstract string? LogName { get; } public abstract int? ProcessId { get; } public abstract int? ThreadId { get; } - public abstract string MachineName { get; } - public abstract SecurityIdentifier UserId { get; } + public abstract string? MachineName { get; } + public abstract SecurityIdentifier? UserId { get; } public abstract DateTime? TimeCreated { get; } public abstract Guid? ActivityId { get; } public abstract Guid? RelatedActivityId { get; } public abstract int? Qualifiers { get; } - public abstract string FormatDescription(); - public abstract string FormatDescription(IEnumerable values); + public abstract string? FormatDescription(); + public abstract string? FormatDescription(IEnumerable? values); - public abstract string LevelDisplayName { get; } + public abstract string? LevelDisplayName { get; } - public abstract string OpcodeDisplayName { get; } - public abstract string TaskDisplayName { get; } - public abstract IEnumerable KeywordsDisplayNames { get; } + public abstract string? OpcodeDisplayName { get; } + public abstract string? TaskDisplayName { get; } + public abstract IEnumerable? KeywordsDisplayNames { get; } public abstract EventBookmark Bookmark { get; } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecordWrittenEventArgs.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecordWrittenEventArgs.cs index 37b75611c465bf..850e1db2bd7ddc 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecordWrittenEventArgs.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventRecordWrittenEventArgs.cs @@ -9,20 +9,20 @@ namespace System.Diagnostics.Eventing.Reader public sealed class EventRecordWrittenEventArgs : EventArgs { internal EventRecordWrittenEventArgs(EventLogRecord record) { EventRecord = record; } - internal EventRecordWrittenEventArgs(Exception exception) { EventException = exception; } + internal EventRecordWrittenEventArgs(Exception? exception) { EventException = exception; } /// /// The EventRecord being notified. /// NOTE: If non null, then caller is required to call Dispose(). /// - public EventRecord EventRecord { get; } + public EventRecord? EventRecord { get; } /// /// If any error occurred during subscription, this will be non-null. /// After a notification containing an exception, no more notifications will /// be made for this subscription. /// - public Exception EventException { get; } + public Exception? EventException { get; } } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventTask.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventTask.cs index f193b89bc5c18a..d05595132f32f4 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventTask.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventTask.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing.Reader { @@ -11,11 +12,12 @@ namespace System.Diagnostics.Eventing.Reader /// public sealed class EventTask { - private string _name; - private string _displayName; + private string? _name; + private string? _displayName; private Guid _guid; - private bool _dataReady; - private readonly ProviderMetadata _pmReference; + [MemberNotNullWhen(false, nameof(_pmReference))] + private bool DataReady { get; set; } + private readonly ProviderMetadata? _pmReference; private readonly object _syncObject; internal EventTask(int value, ProviderMetadata pmReference) @@ -25,13 +27,13 @@ internal EventTask(int value, ProviderMetadata pmReference) _syncObject = new object(); } - internal EventTask(string name, int value, string displayName, Guid guid) + internal EventTask(string? name, int value, string? displayName, Guid guid) { Value = value; _name = name; _displayName = displayName; _guid = guid; - _dataReady = true; + DataReady = true; _syncObject = new object(); } @@ -39,7 +41,7 @@ internal void PrepareData() { lock (_syncObject) { - if (_dataReady) + if (DataReady) return; IEnumerable result = _pmReference.Tasks; @@ -47,7 +49,7 @@ internal void PrepareData() _name = null; _displayName = null; _guid = Guid.Empty; - _dataReady = true; + DataReady = true; foreach (EventTask task in result) { @@ -56,14 +58,14 @@ internal void PrepareData() _name = task.Name; _displayName = task.DisplayName; _guid = task.EventGuid; - _dataReady = true; + DataReady = true; break; } } } } - public string Name + public string? Name { get { @@ -74,7 +76,7 @@ public string Name public int Value { get; } - public string DisplayName + public string? DisplayName { get { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs index 401c40e866f771..7b5f2b45965df7 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs @@ -33,13 +33,13 @@ public sealed class SystemProperties public byte? Opcode; public ulong? Keywords; public ulong? RecordId; - public string ProviderName; + public string? ProviderName; public Guid? ProviderId; - public string ChannelName; + public string? ChannelName; public uint? ProcessId; public uint? ThreadId; - public string ComputerName; - public System.Security.Principal.SecurityIdentifier UserId; + public string? ComputerName; + public System.Security.Principal.SecurityIdentifier? UserId; public DateTime? TimeCreated; public Guid? ActivityId; public Guid? RelatedActivityId; @@ -51,8 +51,8 @@ public SystemProperties() public static EventLogHandle EvtQuery( EventLogHandle session, - string path, - string query, + string? path, + string? query, int flags) { EventLogHandle handle = UnsafeNativeMethods.EvtQuery(session, path, query, flags); @@ -114,8 +114,8 @@ public static void EvtClose(IntPtr handle) public static EventLogHandle EvtOpenProviderMetadata( EventLogHandle session, - string ProviderId, - string logFilePath, + string? ProviderId, + string? logFilePath, int flags) { // ignore locale and pass 0 instead: that way, the thread locale will be retrieved in the API layer @@ -157,7 +157,7 @@ public static EventLogHandle EvtOpenEventMetadataEnum(EventLogHandle ProviderMet } // returns null if EOF - public static EventLogHandle EvtNextEventMetadata(EventLogHandle eventMetadataEnum, int flags) + public static EventLogHandle? EvtNextEventMetadata(EventLogHandle eventMetadataEnum, int flags) { EventLogHandle emHandle = UnsafeNativeMethods.EvtNextEventMetadata(eventMetadataEnum, flags); int win32Error = Marshal.GetLastWin32Error(); @@ -236,7 +236,7 @@ public static EventLogHandle EvtOpenLog(EventLogHandle session, string path, Pat public static void EvtExportLog( EventLogHandle session, string channelPath, - string query, + string? query, string targetFilePath, int flags) { @@ -263,7 +263,7 @@ public static void EvtArchiveExportedLog( public static void EvtClearLog( EventLogHandle session, string channelPath, - string targetFilePath, + string? targetFilePath, int flags) { bool status; @@ -275,7 +275,7 @@ public static void EvtClearLog( public static EventLogHandle EvtCreateRenderContext( int valuePathsCount, - string[] valuePaths, + string[]? valuePaths, UnsafeNativeMethods.EvtRenderContextFlags flags) { EventLogHandle renderContextHandleValues = UnsafeNativeMethods.EvtCreateRenderContext(valuePathsCount, valuePaths, flags); @@ -329,7 +329,7 @@ public static EventLogHandle EvtOpenSession(UnsafeNativeMethods.EvtLoginClass lo return handle; } - public static EventLogHandle EvtCreateBookmark(string bookmarkXml) + public static EventLogHandle EvtCreateBookmark(string? bookmarkXml) { EventLogHandle handle = UnsafeNativeMethods.EvtCreateBookmark(bookmarkXml); int win32Error = Marshal.GetLastWin32Error(); @@ -350,7 +350,7 @@ public static void EvtUpdateBookmark(EventLogHandle bookmark, EventLogHandle eve EventLogException.Throw(win32Error); } - public static object EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods.EvtEventPropertyId enumType) + public static object? EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods.EvtEventPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; @@ -383,7 +383,7 @@ public static object EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods. } } - public static object EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods.EvtQueryPropertyId enumType) + public static object? EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods.EvtQueryPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded = 0; @@ -412,7 +412,7 @@ public static object EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods. } } - public static object EvtGetPublisherMetadataProperty(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) + public static object? EvtGetPublisherMetadataProperty(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; @@ -479,10 +479,10 @@ internal static EventLogHandle EvtGetPublisherMetadataPropertyHandle(EventLogHan } // implies UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId flag. - public static string EvtFormatMessage(EventLogHandle handle, uint msgId) + public static string? EvtFormatMessage(EventLogHandle handle, uint msgId) { int bufferNeeded; - Span emptyBuffer = [ '\0' ]; // issue: https://github.com/dotnet/runtime/issues/100198 + Span emptyBuffer = ['\0']; // issue: https://github.com/dotnet/runtime/issues/100198 bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, emptyBuffer, out bufferNeeded); int error = Marshal.GetLastWin32Error(); @@ -521,7 +521,7 @@ public static string EvtFormatMessage(EventLogHandle handle, uint msgId) return new string(buffer, 0, len); } - public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, int index, int thePropertyId) + public static object? EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, int index, int thePropertyId) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; @@ -552,7 +552,7 @@ public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, in } } - public static object EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNativeMethods.EvtEventMetadataPropertyId enumType) + public static object? EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNativeMethods.EvtEventMetadataPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; @@ -582,7 +582,7 @@ public static object EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNa } } - public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType) + public static object? EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; @@ -619,7 +619,7 @@ public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNa } } - public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object val) + public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object? val) { UnsafeNativeMethods.EvtVariant varVal = default; @@ -632,55 +632,55 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati switch (enumType) { case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; - varVal.Bool = (bool)val ? 1u : 0u; - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; + varVal.Bool = (bool)val ? 1u : 0u; + } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; - taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); - varVal.StringVal = taskMem.GetMemory(); - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; + taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); + varVal.StringVal = taskMem.GetMemory(); + } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; - taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); - varVal.StringVal = taskMem.GetMemory(); - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; + taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); + varVal.StringVal = taskMem.GetMemory(); + } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; - varVal.ULong = (ulong)((long)val); - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; + varVal.ULong = (ulong)((long)val); + } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32; - varVal.UInteger = (uint)((int)val); - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32; + varVal.UInteger = (uint)((int)val); + } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; - varVal.ULong = (ulong)((long)val); - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; + varVal.ULong = (ulong)((long)val); + } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; - varVal.Bool = (bool)val ? 1u : 0u; - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; + varVal.Bool = (bool)val ? 1u : 0u; + } + break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup: - { - varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; - varVal.Bool = (bool)val ? 1u : 0u; - } - break; + { + varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; + varVal.Bool = (bool)val ? 1u : 0u; + } + break; default: throw new InvalidOperationException(); } @@ -696,7 +696,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati } } - public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) + public static string? EvtNextChannelPath(EventLogHandle handle, ref bool finish) { int channelNameNeeded; bool status = UnsafeNativeMethods.EvtNextChannelPath(handle, 0, null, out channelNameNeeded); @@ -726,7 +726,7 @@ public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) return new string(buffer, 0, len); } - public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish) + public static string? EvtNextPublisherId(EventLogHandle handle, ref bool finish) { int ProviderIdNeeded; @@ -757,7 +757,7 @@ public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish) return new string(buffer, 0, len); } - public static object EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.EvtLogPropertyId enumType) + public static object? EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.EvtLogPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; @@ -818,7 +818,7 @@ public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle switch (i) { case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderName: - systemProperties.ProviderName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); + systemProperties.ProviderName = (string?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderGuid: systemProperties.ProviderId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); @@ -860,13 +860,13 @@ public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle systemProperties.ThreadId = (uint?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemChannel: - systemProperties.ChannelName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); + systemProperties.ChannelName = (string?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemComputer: - systemProperties.ComputerName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); + systemProperties.ComputerName = (string?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemUserID: - systemProperties.UserId = (SecurityIdentifier)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid); + systemProperties.UserId = (SecurityIdentifier?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemVersion: systemProperties.Version = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); @@ -887,7 +887,7 @@ public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle // EvtRenderContextFlags can be both: EvtRenderContextFlags.EvtRenderContextUser and EvtRenderContextFlags.EvtRenderContextValues // Render with Context = ContextUser or ContextValues (with user defined Xpath query strings) - public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandle contextHandle, EventLogHandle eventHandle) + public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandle contextHandle, EventLogHandle eventHandle) { IntPtr buffer = IntPtr.Zero; IntPtr pointer; @@ -911,7 +911,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl if (!status) EventLogException.Throw(win32Error); - List valuesList = new List(propCount); + List valuesList = new List(propCount); if (propCount > 0) { pointer = buffer; @@ -931,10 +931,10 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl } } - public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) + public static string? EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) { int bufferNeeded; - Span emptyBuffer = [ '\0' ]; // issue: https://github.com/dotnet/runtime/issues/100198 + Span emptyBuffer = ['\0']; // issue: https://github.com/dotnet/runtime/issues/100198 bool status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, 0, emptyBuffer, out bufferNeeded); int error = Marshal.GetLastWin32Error(); @@ -983,11 +983,11 @@ public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLo } // The EvtFormatMessage used for the obtaining of the Keywords names. - public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) + public static IEnumerable? EvtFormatMessageRenderKeywords(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - Span emptyBuffer = [ '\0' ]; // issue: https://github.com/dotnet/runtime/issues/100198 + Span emptyBuffer = ['\0']; // issue: https://github.com/dotnet/runtime/issues/100198 try { @@ -1021,7 +1021,7 @@ public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle while (true) { - string s = Marshal.PtrToStringUni(pointer); + string? s = Marshal.PtrToStringUni(pointer); if (string.IsNullOrEmpty(s)) break; keywordsList.Add(s); @@ -1061,7 +1061,7 @@ public static string EvtRenderBookmark(EventLogHandle eventHandle) if (!status) EventLogException.Throw(error); - return Marshal.PtrToStringUni(buffer); + return Marshal.PtrToStringUni(buffer)!; } finally { @@ -1071,10 +1071,10 @@ public static string EvtRenderBookmark(EventLogHandle eventHandle) } // Get the formatted description, using the msgId for FormatDescription(string []) - public static string EvtFormatMessageFormatDescription(EventLogHandle handle, EventLogHandle eventHandle, string[] values) + public static string? EvtFormatMessageFormatDescription(EventLogHandle handle, EventLogHandle eventHandle, string?[] values) { int bufferNeeded; - Span emptyBuffer = [ '\0' ]; // issue: https://github.com/dotnet/runtime/issues/100198 + Span emptyBuffer = ['\0']; // issue: https://github.com/dotnet/runtime/issues/100198 UnsafeNativeMethods.EvtStringVariant[] stringVariants = new UnsafeNativeMethods.EvtStringVariant[values.Length]; for (int i = 0; i < values.Length; i++) @@ -1124,7 +1124,7 @@ public static string EvtFormatMessageFormatDescription(EventLogHandle handle, Ev return new string(buffer, 0, len); } - private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) + private static object? ConvertToObject(UnsafeNativeMethods.EvtVariant val) { switch (val.Type) { @@ -1243,7 +1243,7 @@ private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) } } - public static object ConvertToObject(UnsafeNativeMethods.EvtVariant val, UnsafeNativeMethods.EvtVariantType desiredType) + public static object? ConvertToObject(UnsafeNativeMethods.EvtVariant val, UnsafeNativeMethods.EvtVariantType desiredType) { if (val.Type == (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull) return null; @@ -1253,7 +1253,7 @@ public static object ConvertToObject(UnsafeNativeMethods.EvtVariant val, UnsafeN return ConvertToObject(val); } - public static string ConvertToString(UnsafeNativeMethods.EvtVariant val) + public static string? ConvertToString(UnsafeNativeMethods.EvtVariant val) { if (val.StringVal == IntPtr.Zero) return string.Empty; @@ -1261,7 +1261,7 @@ public static string ConvertToString(UnsafeNativeMethods.EvtVariant val) return Marshal.PtrToStringUni(val.StringVal); } - public static string ConvertToAnsiString(UnsafeNativeMethods.EvtVariant val) + public static string? ConvertToAnsiString(UnsafeNativeMethods.EvtVariant val) { if (val.AnsiString == IntPtr.Zero) return string.Empty; @@ -1352,7 +1352,7 @@ public static unsafe DateTime[] ConvertToSysTimeArray(UnsafeNativeMethods.EvtVar } } - public static unsafe string[] ConvertToStringArray(UnsafeNativeMethods.EvtVariant val, bool ansi) + public static unsafe string?[] ConvertToStringArray(UnsafeNativeMethods.EvtVariant val, bool ansi) { IntPtr* ptr = (IntPtr*)val.Reference; if (ptr == null || val.Count == 0) @@ -1361,7 +1361,7 @@ public static unsafe string[] ConvertToStringArray(UnsafeNativeMethods.EvtVarian } else { - string[] stringArray = new string[val.Count]; + string?[] stringArray = new string[val.Count]; for (int i = 0; i < val.Count; i++) { stringArray[i] = ansi ? Marshal.PtrToStringAnsi(ptr[i]) : Marshal.PtrToStringUni(ptr[i]); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs index 746195435488ba..97c94f2ad86d73 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs @@ -27,19 +27,19 @@ public class ProviderMetadata : IDisposable private readonly string _providerName; private readonly CultureInfo _cultureInfo; - private readonly string _logFilePath; + private readonly string? _logFilePath; // caching of the IEnumerable, , , on the ProviderMetadata // they do not change with every call. - private IList _levels; - private IList _opcodes; - private IList _tasks; - private IList _keywords; - private IList _standardLevels; - private IList _standardOpcodes; - private IList _standardTasks; - private IList _standardKeywords; - private IList _channelReferences; + private IList? _levels; + private IList? _opcodes; + private IList? _tasks; + private IList? _keywords; + private IList? _standardLevels; + private IList? _standardOpcodes; + private IList? _standardTasks; + private IList? _standardKeywords; + private IList? _channelReferences; private readonly object _syncObject; @@ -48,12 +48,12 @@ public ProviderMetadata(string providerName) { } - public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo) + public ProviderMetadata(string providerName, EventLogSession? session, CultureInfo? targetCultureInfo) : this(providerName, session, targetCultureInfo, null) { } - internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath) + internal ProviderMetadata(string providerName, EventLogSession? session, CultureInfo? targetCultureInfo, string? logFilePath) { targetCultureInfo ??= CultureInfo.CurrentCulture; session ??= EventLogSession.GlobalSession; @@ -85,39 +85,39 @@ public Guid Id { get { - return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid); + return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid)!; } } - public string MessageFilePath + public string? MessageFilePath { get { - return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath); + return (string?)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath); } } - public string ResourceFilePath + public string? ResourceFilePath { get { - return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath); + return (string?)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath); } } - public string ParameterFilePath + public string? ParameterFilePath { get { - return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath); + return (string?)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath); } } - public Uri HelpLink + public Uri? HelpLink { get { - string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink); + string? helpLinkStr = (string?)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink); if (string.IsNullOrEmpty(helpLinkStr)) return null; return new Uri(helpLinkStr); @@ -128,11 +128,11 @@ private uint ProviderMessageID { get { - return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID); + return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID)!; } } - public string DisplayName + public string? DisplayName { get { @@ -165,11 +165,11 @@ public IList LogLinks for (int index = 0; index < arraySize; index++) { - string channelName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath); + string? channelName = (string?)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath); - uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID); + uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID)!; - uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags); + uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags)!; bool isImported; if (flag == (int)UnsafeNativeMethods.EvtChannelReferenceFlags.EvtChannelReferenceImported) @@ -177,8 +177,8 @@ public IList LogLinks else isImported = false; - int channelRefMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceMessageID))); - string channelRefDisplayName; + int channelRefMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceMessageID)!)); + string? channelRefDisplayName; // if channelRefMessageId == -1, we do not have anything in the message table. if (channelRefMessageId == -1) @@ -235,9 +235,9 @@ internal enum ObjectTypeName Keyword = 3 } - internal string FindStandardLevelDisplayName(string name, uint value) + internal string? FindStandardLevelDisplayName(string? name, uint value) { - _standardLevels ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); + _standardLevels ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels)!; foreach (EventLevel standardLevel in _standardLevels) { if (standardLevel.Name == name && standardLevel.Value == value) @@ -245,9 +245,9 @@ internal string FindStandardLevelDisplayName(string name, uint value) } return null; } - internal string FindStandardOpcodeDisplayName(string name, uint value) + internal string? FindStandardOpcodeDisplayName(string? name, uint value) { - _standardOpcodes ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); + _standardOpcodes ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes)!; foreach (EventOpcode standardOpcode in _standardOpcodes) { if (standardOpcode.Name == name && standardOpcode.Value == value) @@ -255,9 +255,9 @@ internal string FindStandardOpcodeDisplayName(string name, uint value) } return null; } - internal string FindStandardKeywordDisplayName(string name, long value) + internal string? FindStandardKeywordDisplayName(string? name, long value) { - _standardKeywords ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); + _standardKeywords ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords)!; foreach (EventKeyword standardKeyword in _standardKeywords) { if (standardKeyword.Name == name && standardKeyword.Value == value) @@ -265,9 +265,9 @@ internal string FindStandardKeywordDisplayName(string name, long value) } return null; } - internal string FindStandardTaskDisplayName(string name, uint value) + internal string? FindStandardTaskDisplayName(string? name, uint value) { - _standardTasks ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); + _standardTasks ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks)!; foreach (EventTask standardTask in _standardTasks) { if (standardTask.Name == name && standardTask.Value == value) @@ -276,7 +276,7 @@ internal string FindStandardTaskDisplayName(string name, uint value) return null; } - internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty) + internal object? GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty) { EventLogHandle elHandle = EventLogHandle.Zero; @@ -287,10 +287,10 @@ internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNat UnsafeNativeMethods.EvtPublisherMetadataPropertyId propMessageId; ObjectTypeName objectTypeName; - List levelList = null; - List opcodeList = null; - List keywordList = null; - List taskList = null; + List? levelList = null; + List? opcodeList = null; + List? keywordList = null; + List? taskList = null; elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(providerHandle, metadataProperty); @@ -335,22 +335,22 @@ internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNat } for (int index = 0; index < arraySize; index++) { - string generalName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propName); + string? generalName = (string?)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propName); uint generalValue = 0; long generalValueKeyword = 0; if (objectTypeName != ObjectTypeName.Keyword) { - generalValue = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue); + generalValue = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue)!; } else { - generalValueKeyword = unchecked((long)((ulong)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue))); + generalValueKeyword = unchecked((long)((ulong)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue)!)); } - int generalMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propMessageId))); + int generalMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propMessageId)!)); - string generalDisplayName = null; + string? generalDisplayName = null; if (generalMessageId == -1) { @@ -379,17 +379,17 @@ internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNat switch (objectTypeName) { case ObjectTypeName.Level: - levelList.Add(new EventLevel(generalName, (int)generalValue, generalDisplayName)); + levelList!.Add(new EventLevel(generalName, (int)generalValue, generalDisplayName)); break; case ObjectTypeName.Opcode: - opcodeList.Add(new EventOpcode(generalName, (int)(generalValue >> 16), generalDisplayName)); + opcodeList!.Add(new EventOpcode(generalName, (int)(generalValue >> 16), generalDisplayName)); break; case ObjectTypeName.Keyword: - keywordList.Add(new EventKeyword(generalName, (long)generalValueKeyword, generalDisplayName)); + keywordList!.Add(new EventKeyword(generalName, (long)generalValueKeyword, generalDisplayName)); break; case ObjectTypeName.Task: - Guid taskGuid = (Guid)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskEventGuid); - taskList.Add(new EventTask(generalName, (int)generalValue, generalDisplayName, taskGuid)); + Guid taskGuid = (Guid)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskEventGuid)!; + taskList!.Add(new EventTask(generalName, (int)generalValue, generalDisplayName, taskGuid)); break; default: return null; @@ -421,7 +421,7 @@ public IList Levels if (_levels != null) return _levels; - el = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); + el = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels)!; _levels = el.AsReadOnly(); } return _levels; @@ -438,7 +438,7 @@ public IList Opcodes if (_opcodes != null) return _opcodes; - eo = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); + eo = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes)!; _opcodes = eo.AsReadOnly(); } return _opcodes; @@ -455,7 +455,7 @@ public IList Keywords if (_keywords != null) return _keywords; - ek = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); + ek = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords)!; _keywords = ek.AsReadOnly(); } return _keywords; @@ -472,7 +472,7 @@ public IList Tasks if (_tasks != null) return _tasks; - et = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); + et = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks)!; _tasks = et.AsReadOnly(); } return _tasks; @@ -491,7 +491,7 @@ public IEnumerable Events { while (true) { - EventLogHandle emHandle = emHandle = NativeWrapper.EvtNextEventMetadata(emEnumHandle, 0); + EventLogHandle? emHandle = NativeWrapper.EvtNextEventMetadata(emEnumHandle, 0); if (emHandle == null) break; @@ -499,17 +499,17 @@ public IEnumerable Events { unchecked { - uint emId = (uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventID); - byte emVersion = (byte)((uint)(NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventVersion))); - byte emChannelId = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventChannel)); - byte emLevel = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventLevel)); - byte emOpcode = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventOpcode)); - short emTask = (short)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTask)); - long emKeywords = (long)(ulong)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventKeyword); - string emTemplate = (string)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTemplate); - int messageId = (int)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventMessageID)); - - string emMessage = (messageId == -1) + uint emId = (uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventID)!; + byte emVersion = (byte)((uint)(NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventVersion))!); + byte emChannelId = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventChannel)!); + byte emLevel = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventLevel)!); + byte emOpcode = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventOpcode)!); + short emTask = (short)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTask)!); + long emKeywords = (long)(ulong)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventKeyword)!; + string? emTemplate = (string?)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTemplate); + int messageId = (int)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventMessageID)!); + + string? emMessage = (messageId == -1) ? null : NativeWrapper.EvtFormatMessage(_handle, (uint)messageId); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadataCachedInformation.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadataCachedInformation.cs index 4d0d292f8b90b1..4084746a90ff58 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadataCachedInformation.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadataCachedInformation.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using Microsoft.Win32; @@ -18,7 +19,7 @@ internal sealed class ProviderMetadataCachedInformation private readonly Dictionary _cache; private readonly int _maximumCacheSize; private readonly EventLogSession _session; - private readonly string _logfile; + private readonly string? _logfile; private sealed class ProviderMetadataId { @@ -28,9 +29,9 @@ public ProviderMetadataId(string providerName, CultureInfo cultureInfo) TheCultureInfo = cultureInfo; } - public override bool Equals(object obj) + public override bool Equals([NotNullWhen(true)] object? obj) { - ProviderMetadataId rhs = obj as ProviderMetadataId; + ProviderMetadataId? rhs = obj as ProviderMetadataId; if (rhs == null) return false; if (ProviderName.Equals(rhs.ProviderName) && (TheCultureInfo == rhs.TheCultureInfo)) @@ -60,7 +61,7 @@ public CacheItem(ProviderMetadata pm) public ProviderMetadata ProviderMetadata { get; } } - public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize) + public ProviderMetadataCachedInformation(EventLogSession session, string? logfile, int maximumCacheSize) { Debug.Assert(session != null); _session = session; @@ -104,7 +105,7 @@ private void FlushOldestEntry() { double maxPassedTime = -10; DateTime timeNow = DateTime.Now; - ProviderMetadataId keyToDelete = null; + ProviderMetadataId? keyToDelete = null; // Get the entry in the cache which was not accessed for the longest time. foreach (KeyValuePair kvp in _cache) @@ -175,7 +176,7 @@ private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) } } - public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle) + public string? GetFormatDescription(string ProviderName, EventLogHandle eventHandle) { lock (this) { @@ -193,7 +194,7 @@ public string GetFormatDescription(string ProviderName, EventLogHandle eventHand } } - public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values) + public string? GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string?[] values) { lock (this) { @@ -210,7 +211,7 @@ public string GetFormatDescription(string ProviderName, EventLogHandle eventHand } } - public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) + public string? GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { @@ -220,7 +221,7 @@ public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandl } } - public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) + public string? GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { @@ -230,7 +231,7 @@ public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHand } } - public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) + public string? GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { @@ -240,7 +241,7 @@ public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle } } - public IEnumerable GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) + public IEnumerable? GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) { lock (this) { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/UnsafeNativeMethods.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/UnsafeNativeMethods.cs index 9f9e2862e0293d..a1a6f65a7a0e72 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/UnsafeNativeMethods.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/UnsafeNativeMethods.cs @@ -350,11 +350,21 @@ internal struct EvtRpcLogin [MarshalAs(UnmanagedType.LPWStr)] public string Server; [MarshalAs(UnmanagedType.LPWStr)] - public string User; + public string? User; [MarshalAs(UnmanagedType.LPWStr)] - public string Domain; + public string? Domain; public CoTaskMemUnicodeSafeHandle Password; public int Flags; + + public EvtRpcLogin(string server, string? user, string? domain, CoTaskMemUnicodeSafeHandle password, int flags) + { + Server = server; + User = user; + Domain = domain; + Password = password; + Flags = flags; + } + #if NET [CustomMarshaller(typeof(EvtRpcLogin), MarshalMode.ManagedToUnmanagedRef, typeof(ValueMarshaller))] public static class Marshaller @@ -404,13 +414,13 @@ public EvtRpcLogin ToManaged() } return new EvtRpcLogin - { - Server = Marshal.PtrToStringUni(_value.Server), - User = Marshal.PtrToStringUni(_value.User), - Domain = Marshal.PtrToStringUni(_value.Domain), - Password = _passwordHandle, - Flags = _value.Flags - }; + ( + server: Marshal.PtrToStringUni(_value.Server)!, + user: Marshal.PtrToStringUni(_value.User), + domain: Marshal.PtrToStringUni(_value.Domain), + password: _passwordHandle, + flags: _value.Flags + ); } public void Free() @@ -443,8 +453,8 @@ internal enum EvtSeekFlags [LibraryImport(Interop.Libraries.Wevtapi, SetLastError = true)] internal static partial EventLogHandle EvtQuery( EventLogHandle session, - [MarshalAs(UnmanagedType.LPWStr)] string path, - [MarshalAs(UnmanagedType.LPWStr)] string query, + [MarshalAs(UnmanagedType.LPWStr)] string? path, + [MarshalAs(UnmanagedType.LPWStr)] string? query, int flags); // SEEK @@ -461,8 +471,8 @@ internal static partial bool EvtSeek( internal static partial EventLogHandle EvtSubscribe( EventLogHandle session, SafeWaitHandle signalEvent, - [MarshalAs(UnmanagedType.LPWStr)] string path, - [MarshalAs(UnmanagedType.LPWStr)] string query, + [MarshalAs(UnmanagedType.LPWStr)] string? path, + [MarshalAs(UnmanagedType.LPWStr)] string? query, EventLogHandle bookmark, IntPtr context, IntPtr callback, @@ -508,8 +518,8 @@ internal static partial bool EvtGetQueryInfo( [LibraryImport(Interop.Libraries.Wevtapi, SetLastError = true)] internal static partial EventLogHandle EvtOpenPublisherMetadata( EventLogHandle session, - [MarshalAs(UnmanagedType.LPWStr)] string publisherId, - [MarshalAs(UnmanagedType.LPWStr)] string logFilePath, + [MarshalAs(UnmanagedType.LPWStr)] string? publisherId, + [MarshalAs(UnmanagedType.LPWStr)] string? logFilePath, int locale, int flags); @@ -645,7 +655,7 @@ internal static partial bool EvtGetLogInfo( internal static partial bool EvtExportLog( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)] string channelPath, - [MarshalAs(UnmanagedType.LPWStr)] string query, + [MarshalAs(UnmanagedType.LPWStr)] string? query, [MarshalAs(UnmanagedType.LPWStr)] string targetFilePath, int flags); @@ -662,7 +672,7 @@ internal static partial bool EvtArchiveExportedLog( internal static partial bool EvtClearLog( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)] string channelPath, - [MarshalAs(UnmanagedType.LPWStr)] string targetFilePath, + [MarshalAs(UnmanagedType.LPWStr)] string? targetFilePath, int flags); // RENDERING @@ -670,7 +680,7 @@ internal static partial bool EvtClearLog( internal static partial EventLogHandle EvtCreateRenderContext( int valuePathsCount, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] - string[] valuePaths, + string[]? valuePaths, EvtRenderContextFlags flags); [LibraryImport(Interop.Libraries.Wevtapi, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] @@ -702,7 +712,7 @@ internal static partial bool EvtRender( internal struct EvtStringVariant { [MarshalAs(UnmanagedType.LPWStr), FieldOffset(0)] - public string StringVal; + public string? StringVal; [FieldOffset(8)] public uint Count; [FieldOffset(12)] @@ -759,7 +769,7 @@ internal static partial bool EvtFormatMessage( EventLogHandle eventHandle, uint messageId, int valueCount, - EvtStringVariant[] values, + EvtStringVariant[]? values, EvtFormatMessageFlags flags, int bufferSize, Span buffer, @@ -789,7 +799,7 @@ internal static partial EventLogHandle EvtOpenSession( // BOOKMARK [LibraryImport(Interop.Libraries.Wevtapi, EntryPoint = "EvtCreateBookmark", SetLastError = true)] internal static partial EventLogHandle EvtCreateBookmark( - [MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml); + [MarshalAs(UnmanagedType.LPWStr)] string? bookmarkXml); [LibraryImport(Interop.Libraries.Wevtapi, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] From 67aaffcc9071f299f71e2e4fb241d15218997949 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Fri, 19 Sep 2025 08:43:17 -0400 Subject: [PATCH 2/7] Remove compatibility suppressions, build seems to work without them now --- .../src/CompatibilitySuppressions.xml | 36 ------------------- 1 file changed, 36 deletions(-) diff --git a/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml b/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml index 08421677ce8efd..11804bbda76ae3 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Diagnostics.EventLog/src/CompatibilitySuppressions.xml @@ -23,40 +23,4 @@ lib/netstandard2.0/System.Diagnostics.EventLog.dll lib/net462/System.Diagnostics.EventLog.dll - - CP0016 - M:System.Diagnostics.EventLog.SourceExists(System.String,System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] - ref/net10.0/System.Diagnostics.EventLog.dll - runtimes/win/lib/net10.0/System.Diagnostics.EventLog.dll - - - CP0016 - M:System.Diagnostics.EventLog.SourceExists(System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] - ref/net10.0/System.Diagnostics.EventLog.dll - runtimes/win/lib/net10.0/System.Diagnostics.EventLog.dll - - - CP0016 - M:System.Diagnostics.EventLog.SourceExists(System.String,System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] - ref/net8.0/System.Diagnostics.EventLog.dll - runtimes/win/lib/net8.0/System.Diagnostics.EventLog.dll - - - CP0016 - M:System.Diagnostics.EventLog.SourceExists(System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] - ref/net8.0/System.Diagnostics.EventLog.dll - runtimes/win/lib/net8.0/System.Diagnostics.EventLog.dll - - - CP0016 - M:System.Diagnostics.EventLog.SourceExists(System.String,System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] - ref/net9.0/System.Diagnostics.EventLog.dll - runtimes/win/lib/net9.0/System.Diagnostics.EventLog.dll - - - CP0016 - M:System.Diagnostics.EventLog.SourceExists(System.String)$0:[T:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute] - ref/net9.0/System.Diagnostics.EventLog.dll - runtimes/win/lib/net9.0/System.Diagnostics.EventLog.dll - \ No newline at end of file From 583ebbf35a8c987245f8df21acc65fc13e08ecf2 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Fri, 19 Sep 2025 20:01:34 -0400 Subject: [PATCH 3/7] Initial PR feedback --- .../src/System/Diagnostics/EventLog.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index 980676c9122dc3..7d8e3c6469622a 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -308,9 +308,10 @@ public static void CreateEventSource(EventSourceCreationData sourceData) throw new ArgumentException(SR.Format(SR.InvalidCustomerLogName, logName)); } - bool createLogKey = (logKey == null); + bool createLogKey = false; if (logKey == null) { + createLogKey = true; if (SourceExists(logName, machineName, true)) { if (".".Equals(machineName)) From 949f417c15f015dfe61c9df12667548d9846618b Mon Sep 17 00:00:00 2001 From: Michael Render Date: Fri, 19 Sep 2025 23:29:15 -0400 Subject: [PATCH 4/7] PR feedback --- .../src/System/Diagnostics/EventLogInternal.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index b6cdaec5d3bcdb..ed87ee8c545144 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -203,8 +203,11 @@ public string? LogDisplayName } else { - int resourceId = (int)logkey.GetValue("DisplayNameID")!; - logDisplayName = FormatMessageWrapper(resourceDll, (uint)resourceId, null); + object? resourceIdObject = logkey.GetValue("DisplayNameID"); + if (resourceIdObject is not null) + { + logDisplayName = FormatMessageWrapper(resourceDll, (uint)(int)resourceIdObject, null); + } logDisplayName ??= GetLogName(currentMachineName); } } @@ -349,6 +352,7 @@ public bool EnableRaisingEvents } } + [MemberNotNull(nameof(readHandle))] private int OldestEntryNumber { get @@ -873,11 +877,11 @@ internal EventLogEntry GetEntryAt(int index) private EventLogEntry GetEntryWithOldest(int index) { Debug.Assert(readHandle != null); - Debug.Assert(cache != null); int entryPos = GetCachedEntryPos(index); if (entryPos >= 0) { + Debug.Assert(cache != null, "Cannot get a non-negative position out of GetCachedEntryPos unless we have a cache"); return new EventLogEntry(cache, entryPos, this); } @@ -1152,7 +1156,7 @@ private static void RemoveListenerComponent(EventLogInternal component, string c // if that was the last interested compononent, destroy the handles and stop listening. info.handleOwner.Dispose(); //Unregister the thread pool wait handle - info.registeredWaitHandle?.Unregister(info.waitHandle); + info.registeredWaitHandle.Unregister(info.waitHandle); // close the handle info.waitHandle.Close(); listenerInfos[compLogName] = null; @@ -1413,7 +1417,7 @@ public LogListeningInfo(EventLogInternal handleOwner, AutoResetEvent waitHandle) this.waitHandle = waitHandle; } public EventLogInternal handleOwner; - public RegisteredWaitHandle? registeredWaitHandle; + public RegisteredWaitHandle registeredWaitHandle = null!; // Initialized in AddListenerComponent public AutoResetEvent waitHandle; public List listeningComponents = new(); } From c35e76eeb1fb77dcfe532ed22ac75eb1cbebcf64 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Sun, 21 Sep 2025 15:27:42 -0400 Subject: [PATCH 5/7] Address scenario where EventLog.EntryWritten event is not subscribed to --- .../src/System/Diagnostics/EventLogInternal.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index ed87ee8c545144..a86199d59ea0d5 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -567,10 +567,17 @@ private void CompletionCallback() while (i < count) { EventLogEntry entry = GetEntryWithOldest(i); - if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) - this.SynchronizingObject.BeginInvoke(this.onEntryWrittenHandler!, new object[] { this, new EntryWrittenEventArgs(entry) }); - else - onEntryWrittenHandler!(this, new EntryWrittenEventArgs(entry)); + if (onEntryWrittenHandler != null) + { + if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) + { + this.SynchronizingObject.BeginInvoke(this.onEntryWrittenHandler, new object[] { this, new EntryWrittenEventArgs(entry) }); + } + else + { + onEntryWrittenHandler(this, new EntryWrittenEventArgs(entry)); + } + } i++; } From 950bf63423587f7731dbd2bcd37aab9d67762dd5 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Sun, 21 Sep 2025 15:32:39 -0400 Subject: [PATCH 6/7] Move null suppression from EventLogInternal constructor overloads to callsites --- .../src/System/Diagnostics/EventLog.cs | 6 +++--- .../src/System/Diagnostics/EventLogInternal.cs | 10 +--------- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index 7d8e3c6469622a..5fd9797b261aa9 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -1014,7 +1014,7 @@ public static void WriteEntry(string source, string? message, EventLogEntryType public static void WriteEntry(string source, string? message, EventLogEntryType type, int eventID, short category, byte[]? rawData) { - using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) + using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source), parent: null! /* Special case - EventLogInternal instance is immediately used */)) { log.WriteEntry(message, type, eventID, category, rawData); } @@ -1037,7 +1037,7 @@ public void WriteEvent(EventInstance instance, byte[]? data, params object?[]? v public static void WriteEvent(string source, EventInstance instance, params object?[]? values) { - using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) + using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source), parent: null! /* Special case - EventLogInternal instance is immediately used */)) { log.WriteEvent(instance, null, values); } @@ -1045,7 +1045,7 @@ public static void WriteEvent(string source, EventInstance instance, params obje public static void WriteEvent(string source, EventInstance instance, byte[] data, params object?[]? values) { - using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) + using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source), parent: null! /* Special case - EventLogInternal instance is immediately used */)) { log.WriteEvent(instance, data, values); } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index a86199d59ea0d5..9574e9141f529d 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -102,14 +102,6 @@ private static object InternalSyncObject } } - public EventLogInternal(string logName, string machineName) : this(logName, machineName, "", null! /* Special case with no parent */) - { - } - - public EventLogInternal(string logName, string machineName, string source) : this(logName, machineName, source, null! /* Special case with no parent */) - { - } - public EventLogInternal(string logName, string machineName, string source, EventLog parent) { ArgumentNullException.ThrowIfNull(logName); @@ -426,7 +418,7 @@ private static void AddListenerComponent(EventLogInternal component, string comp info = new LogListeningInfo( - handleOwner: new EventLogInternal(compLogName, compMachineName), + handleOwner: new EventLogInternal(compLogName, compMachineName, string.Empty, parent: null! /* Special handling for EventLogInternals in listenerInfos; no parent is applicable */), waitHandle: new AutoResetEvent(false)); info.listeningComponents.Add(component); From a06202c9f494bc8db9f83835b7c5bdd46ccb0726 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Sun, 21 Sep 2025 16:26:55 -0400 Subject: [PATCH 7/7] Add back in attributes deleted from the GenerateReferenceAssemblySource run --- .../ref/System.Diagnostics.EventLog.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs b/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs index 668824144ddc12..1e6a848841f14b 100644 --- a/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/ref/System.Diagnostics.EventLog.cs @@ -149,9 +149,13 @@ public EventLogTraceListener(string source) { } public override string Name { get { throw null; } set { } } public override void Close() { } protected override void Dispose(bool disposing) { } + [System.Runtime.InteropServices.ComVisibleAttribute(false)] public override void TraceData(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, object? data) { } + [System.Runtime.InteropServices.ComVisibleAttribute(false)] public override void TraceData(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, params object?[]? data) { } + [System.Runtime.InteropServices.ComVisibleAttribute(false)] public override void TraceEvent(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string? message) { } + [System.Runtime.InteropServices.ComVisibleAttribute(false)] public override void TraceEvent(System.Diagnostics.TraceEventCache? eventCache, string source, System.Diagnostics.TraceEventType severity, int id, string? format, params object?[]? args) { } public override void Write(string? message) { } public override void WriteLine(string? message) { }