Use GeneratedDllImport in System.Diagnostics.EventLog (#61990)
authorElinor Fung <elfung@microsoft.com>
Wed, 24 Nov 2021 19:39:28 +0000 (12:39 -0700)
committerGitHub <noreply@github.com>
Wed, 24 Nov 2021 19:39:28 +0000 (12:39 -0700)
18 files changed:
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ClearEventLog.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.CloseEventLog.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.DeregisterEventSource.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetNumberOfEventLogRecords.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetOldestEventLogRecord.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.NotifyChangeEventLog.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.OpenEventLog.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ReadEventLog.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegisterEventSource.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ReportEvent.cs
src/libraries/Common/src/Interop/Windows/Interop.Errors.cs
src/libraries/Common/src/Interop/Windows/Interop.Libraries.cs
src/libraries/Common/src/Interop/Windows/Kernel32/Interop.FormatMessage_SafeLibraryHandle.cs
src/libraries/Common/src/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs
src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/UnsafeNativeMethods.cs

index a432d1d..0d5be5c 100644 (file)
@@ -8,7 +8,7 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern bool ClearEventLog(SafeEventLogReadHandle hEventLog, string lpBackupFileName);
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        public static partial bool ClearEventLog(SafeEventLogReadHandle hEventLog, string lpBackupFileName);
     }
 }
index fcede9d..2084a70 100644 (file)
@@ -8,7 +8,7 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, SetLastError = true)]
-        internal static extern bool CloseEventLog(IntPtr hEventLog);
+        [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)]
+        internal static partial bool CloseEventLog(IntPtr hEventLog);
     }
 }
index b4f7123..b7886fa 100644 (file)
@@ -8,7 +8,7 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, SetLastError = true)]
-        internal static extern bool DeregisterEventSource(IntPtr hEventLog);
+        [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)]
+        internal static partial bool DeregisterEventSource(IntPtr hEventLog);
     }
 }
index 67807ae..102d520 100644 (file)
@@ -8,7 +8,7 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern bool GetNumberOfEventLogRecords(SafeEventLogReadHandle hEventLog, out int NumberOfRecords);
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        public static partial bool GetNumberOfEventLogRecords(SafeEventLogReadHandle hEventLog, out int NumberOfRecords);
     }
 }
index a3cf76c..1101a63 100644 (file)
@@ -8,8 +8,8 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
         [return: MarshalAs(UnmanagedType.Bool)]
-        public static extern bool GetOldestEventLogRecord(SafeEventLogReadHandle hEventLog, out int OldestRecord);
+        public static partial bool GetOldestEventLogRecord(SafeEventLogReadHandle hEventLog, out int OldestRecord);
     }
 }
index 7a7db2f..667f485 100644 (file)
@@ -8,8 +8,8 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
         [return: MarshalAs(UnmanagedType.Bool)]
-        public static extern bool NotifyChangeEventLog(SafeEventLogReadHandle hEventLog, SafeWaitHandle hEvent);
+        public static partial bool NotifyChangeEventLog(SafeEventLogReadHandle hEventLog, SafeWaitHandle hEvent);
     }
 }
index 31483c8..6c32736 100644 (file)
@@ -8,7 +8,7 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
-        internal static extern SafeEventLogReadHandle OpenEventLog(string lpUNCServerName, string lpSourceName);
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        internal static partial SafeEventLogReadHandle OpenEventLog(string lpUNCServerName, string lpSourceName);
     }
 }
index 5cbc26d..28369c8 100644 (file)
@@ -12,9 +12,9 @@ internal static partial class Interop
         internal const int FORWARDS_READ = 0x4;
         internal const int BACKWARDS_READ = 0x8;
 
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
         [return: MarshalAs(UnmanagedType.Bool)]
-        public static extern bool ReadEventLog(
+        public static partial bool ReadEventLog(
             SafeEventLogReadHandle hEventLog,
             int dwReadFlags,
             int dwRecordOffset,
index eadabdc..0871c0e 100644 (file)
@@ -8,7 +8,7 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
-        internal static extern SafeEventLogWriteHandle RegisterEventSource(string lpUNCServerName, string lpSourceName);
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        internal static partial SafeEventLogWriteHandle RegisterEventSource(string lpUNCServerName, string lpSourceName);
     }
 }
index ee3e194..913ce34 100644 (file)
@@ -9,8 +9,8 @@ internal static partial class Interop
 {
     internal static partial class Advapi32
     {
-        [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern bool ReportEvent(
+        [GeneratedDllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)]
+        public static partial bool ReportEvent(
             SafeEventLogWriteHandle hEventLog,
             short wType,
             ushort wcategory,
index d5f6d16..5a38c91 100644 (file)
@@ -90,6 +90,7 @@ internal static partial class Interop
         internal const int ERROR_TIMEOUT = 0x5B4;
         internal const int ERROR_EVENTLOG_FILE_CHANGED = 0x5DF;
         internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD;
+        internal const int ERROR_RESOURCE_TYPE_NOT_FOUND = 0x715;
         internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717;
         internal const int ERROR_NOT_A_REPARSE_POINT = 0x1126;
     }
index 93c2bb7..81b31db 100644 (file)
@@ -34,6 +34,7 @@ internal static partial class Interop
         internal const string User32 = "user32.dll";
         internal const string Version = "version.dll";
         internal const string WebSocket = "websocket.dll";
+        internal const string Wevtapi = "wevtapi.dll";
         internal const string WinHttp = "winhttp.dll";
         internal const string WinMM = "winmm.dll";
         internal const string Wkscli = "wkscli.dll";
index 2887304..7dc7961 100644 (file)
@@ -13,8 +13,8 @@ internal static partial class Interop
         public const int FORMAT_MESSAGE_FROM_HMODULE = 0x00000800;
         public const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
 
-        [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = true)]
-        public static extern int FormatMessage(
+        [GeneratedDllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true)]
+        public static partial int FormatMessage(
             int dwFlags,
             SafeLibraryHandle lpSource,
             uint dwMessageId,
index 95ed8cb..95ef7bb 100644 (file)
@@ -13,7 +13,7 @@ internal static partial class Interop
         public const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
         public const int LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800;
 
-        [DllImport(Libraries.Kernel32, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern SafeLibraryHandle LoadLibraryExW([In] string lpwLibFileName, [In] IntPtr hFile, [In] uint dwFlags);
+        [GeneratedDllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        public static partial SafeLibraryHandle LoadLibraryExW(string lpwLibFileName, IntPtr hFile, uint dwFlags);
     }
 }
index c6f39b3..29a936c 100644 (file)
@@ -1,8 +1,8 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
-    <NoWarn>$(NoWarn);CA1838;CA1847</NoWarn>
+    <NoWarn>$(NoWarn);CA1847</NoWarn>
     <!-- Suppressions to avoid ifdefs:
             CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
             CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available -->
index b0f8ff9..bb54bd0 100644 (file)
@@ -398,9 +398,8 @@ namespace System.Diagnostics.Eventing.Reader
 
         public override string ToXml()
         {
-            StringBuilder renderBuffer = new StringBuilder(2000);
-            NativeWrapper.EvtRender(EventLogHandle.Zero, Handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventXml, renderBuffer);
-            return renderBuffer.ToString();
+            char[] renderBuffer = GC.AllocateUninitializedArray<char>(2000);
+            return NativeWrapper.EvtRenderXml(EventLogHandle.Zero, Handle, renderBuffer);
         }
 
         protected override void Dispose(bool disposing)
index ac44ce3..35ee7fe 100644 (file)
@@ -85,7 +85,7 @@ namespace System.Diagnostics.Eventing.Reader
         {
             bool status = UnsafeNativeMethods.EvtNext(queryHandle, eventSize, events, timeout, flags, ref returned);
             int win32Error = Marshal.GetLastWin32Error();
-            if (!status && win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS)
+            if (!status && win32Error != Interop.Errors.ERROR_NO_MORE_ITEMS)
                 EventLogException.Throw(win32Error);
             return win32Error == 0;
         }
@@ -153,7 +153,7 @@ namespace System.Diagnostics.Eventing.Reader
 
             if (emHandle.IsInvalid)
             {
-                if (win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS)
+                if (win32Error != Interop.Errors.ERROR_NO_MORE_ITEMS)
                     EventLogException.Throw(win32Error);
                 return null;
             }
@@ -257,24 +257,22 @@ namespace System.Diagnostics.Eventing.Reader
             return renderContextHandleValues;
         }
 
-        public static void EvtRender(
+        public static string EvtRenderXml(
                             EventLogHandle context,
                             EventLogHandle eventHandle,
-                            UnsafeNativeMethods.EvtRenderFlags flags,
-                            StringBuilder buffer)
+                            char[] buffer)
         {
             int buffUsed;
-            int propCount;
-            bool status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount);
+            UnsafeNativeMethods.EvtRenderFlags flags = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventXml;
+            bool status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Length, buffer, out buffUsed, out _);
             int win32Error = Marshal.GetLastWin32Error();
-
             if (!status)
             {
-                if (win32Error == UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                if (win32Error == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                 {
                     // Reallocate the new RenderBuffer with the right size.
-                    buffer.Capacity = buffUsed;
-                    status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount);
+                    buffer = GC.AllocateUninitializedArray<char>(buffUsed);
+                    status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Length, buffer, out buffUsed, out _);
                     win32Error = Marshal.GetLastWin32Error();
                 }
                 if (!status)
@@ -282,6 +280,12 @@ namespace System.Diagnostics.Eventing.Reader
                     EventLogException.Throw(win32Error);
                 }
             }
+
+            int len = buffUsed / sizeof(char) - 1; // buffer includes null terminator
+            if (len <= 0)
+                return string.Empty;
+
+            return new string(buffer, 0, len);
         }
 
         public static EventLogHandle EvtOpenSession(UnsafeNativeMethods.EvtLoginClass loginClass, ref UnsafeNativeMethods.EvtRpcLogin login, int timeout, int flags)
@@ -321,11 +325,11 @@ namespace System.Diagnostics.Eventing.Reader
                 int error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (error == UnsafeNativeMethods.ERROR_SUCCESS)
-                    { }
-                    else
-                        if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_SUCCESS
+                        && error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
+                    {
                         EventLogException.Throw(error);
+                    }
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
                 status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded);
@@ -353,7 +357,7 @@ namespace System.Diagnostics.Eventing.Reader
                 int error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
@@ -383,7 +387,7 @@ namespace System.Diagnostics.Eventing.Reader
                 int error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
@@ -412,7 +416,7 @@ namespace System.Diagnostics.Eventing.Reader
                 int error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
@@ -442,9 +446,7 @@ namespace System.Diagnostics.Eventing.Reader
         public static string EvtFormatMessage(EventLogHandle handle, uint msgId)
         {
             int bufferNeeded;
-
-            StringBuilder sb = new StringBuilder(null);
-            bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, sb, out bufferNeeded);
+            bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, null, out bufferNeeded);
             int error = Marshal.GetLastWin32Error();
 
             // ERROR_EVT_UNRESOLVED_VALUE_INSERT and its cousins are commonly returned for raw message text.
@@ -456,12 +458,12 @@ namespace System.Diagnostics.Eventing.Reader
                 {
                     return null;
                 }
-                if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                     EventLogException.Throw(error);
             }
 
-            sb.EnsureCapacity(bufferNeeded);
-            status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, bufferNeeded, sb, out bufferNeeded);
+            char[] buffer = new char[bufferNeeded];
+            status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, bufferNeeded, buffer, out bufferNeeded);
             error = Marshal.GetLastWin32Error();
 
             if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT
@@ -474,7 +476,12 @@ namespace System.Diagnostics.Eventing.Reader
                 }
                 EventLogException.Throw(error);
             }
-            return sb.ToString();
+
+            int len = bufferNeeded - 1; // buffer includes null terminator
+            if (len <= 0)
+                return string.Empty;
+
+            return new string(buffer, 0, len);
         }
 
         public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, int index, int thePropertyId)
@@ -489,7 +496,7 @@ namespace System.Diagnostics.Eventing.Reader
 
                 if (!status)
                 {
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
@@ -519,7 +526,7 @@ namespace System.Diagnostics.Eventing.Reader
                 int win32Error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (win32Error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(win32Error);
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
@@ -549,7 +556,7 @@ namespace System.Diagnostics.Eventing.Reader
                 int win32Error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (win32Error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(win32Error);
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
@@ -663,58 +670,63 @@ namespace System.Diagnostics.Eventing.Reader
 
         public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish)
         {
-            StringBuilder sb = new StringBuilder(null);
             int channelNameNeeded;
-
-            bool status = UnsafeNativeMethods.EvtNextChannelPath(handle, 0, sb, out channelNameNeeded);
+            bool status = UnsafeNativeMethods.EvtNextChannelPath(handle, 0, null, out channelNameNeeded);
             int win32Error = Marshal.GetLastWin32Error();
             if (!status)
             {
-                if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS)
+                if (win32Error == Interop.Errors.ERROR_NO_MORE_ITEMS)
                 {
                     finish = true;
                     return null;
                 }
 
-                if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                if (win32Error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                     EventLogException.Throw(win32Error);
             }
 
-            sb.EnsureCapacity(channelNameNeeded);
-            status = UnsafeNativeMethods.EvtNextChannelPath(handle, channelNameNeeded, sb, out channelNameNeeded);
+            char[] buffer = new char[channelNameNeeded];
+            status = UnsafeNativeMethods.EvtNextChannelPath(handle, channelNameNeeded, buffer, out channelNameNeeded);
             win32Error = Marshal.GetLastWin32Error();
             if (!status)
                 EventLogException.Throw(win32Error);
 
-            return sb.ToString();
+            int len = channelNameNeeded - 1; // buffer includes null terminator
+            if (len <= 0)
+                return string.Empty;
+
+            return new string(buffer, 0, len);
         }
 
         public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish)
         {
-            StringBuilder sb = new StringBuilder(null);
             int ProviderIdNeeded;
 
-            bool status = UnsafeNativeMethods.EvtNextPublisherId(handle, 0, sb, out ProviderIdNeeded);
+            bool status = UnsafeNativeMethods.EvtNextPublisherId(handle, 0, null, out ProviderIdNeeded);
             int win32Error = Marshal.GetLastWin32Error();
             if (!status)
             {
-                if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS)
+                if (win32Error == Interop.Errors.ERROR_NO_MORE_ITEMS)
                 {
                     finish = true;
                     return null;
                 }
 
-                if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                if (win32Error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                     EventLogException.Throw(win32Error);
             }
 
-            sb.EnsureCapacity(ProviderIdNeeded);
-            status = UnsafeNativeMethods.EvtNextPublisherId(handle, ProviderIdNeeded, sb, out ProviderIdNeeded);
+            char[] buffer = new char[ProviderIdNeeded];
+            status = UnsafeNativeMethods.EvtNextPublisherId(handle, ProviderIdNeeded, buffer, out ProviderIdNeeded);
             win32Error = Marshal.GetLastWin32Error();
             if (!status)
                 EventLogException.Throw(win32Error);
 
-            return sb.ToString();
+            int len = ProviderIdNeeded - 1; // buffer includes null terminator
+            if (len <= 0)
+                return string.Empty;
+
+            return new string(buffer, 0, len);
         }
 
         public static object EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.EvtLogPropertyId enumType)
@@ -728,7 +740,7 @@ namespace System.Diagnostics.Eventing.Reader
                 int win32Error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (win32Error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(win32Error);
                 }
                 buffer = Marshal.AllocHGlobal((int)bufferNeeded);
@@ -760,7 +772,7 @@ namespace System.Diagnostics.Eventing.Reader
                 if (!status)
                 {
                     int error = Marshal.GetLastWin32Error();
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
 
@@ -861,7 +873,7 @@ namespace System.Diagnostics.Eventing.Reader
                 if (!status)
                 {
                     int error = Marshal.GetLastWin32Error();
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
 
@@ -894,9 +906,7 @@ namespace System.Diagnostics.Eventing.Reader
         public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag)
         {
             int bufferNeeded;
-            StringBuilder sb = new StringBuilder(null);
-
-            bool status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, 0, sb, out bufferNeeded);
+            bool status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, 0, null, out bufferNeeded);
             int error = Marshal.GetLastWin32Error();
 
             if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT
@@ -912,12 +922,12 @@ namespace System.Diagnostics.Eventing.Reader
                 {
                     return null;
                 }
-                if (error != (int)UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                if (error != (int)Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                     EventLogException.Throw(error);
             }
 
-            sb.EnsureCapacity(bufferNeeded);
-            status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, bufferNeeded, sb, out bufferNeeded);
+            char[] buffer = new char[bufferNeeded];
+            status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, bufferNeeded, buffer, out bufferNeeded);
             error = Marshal.GetLastWin32Error();
 
             if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT
@@ -929,7 +939,12 @@ namespace System.Diagnostics.Eventing.Reader
                 }
                 EventLogException.Throw(error);
             }
-            return sb.ToString();
+
+            int len = bufferNeeded - 1; // buffer includes null terminator
+            if (len <= 0)
+                return string.Empty;
+
+            return new string(buffer, 0, len);
         }
 
         // The EvtFormatMessage used for the obtaining of the Keywords names.
@@ -950,7 +965,7 @@ namespace System.Diagnostics.Eventing.Reader
                     {
                         return keywordsList.AsReadOnly();
                     }
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
 
@@ -1000,7 +1015,7 @@ namespace System.Diagnostics.Eventing.Reader
                 int error = Marshal.GetLastWin32Error();
                 if (!status)
                 {
-                    if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                    if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                         EventLogException.Throw(error);
                 }
 
@@ -1031,8 +1046,7 @@ namespace System.Diagnostics.Eventing.Reader
                 stringVariants[i].StringVal = values[i];
             }
 
-            StringBuilder sb = new StringBuilder(null);
-            bool status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, 0, sb, out bufferNeeded);
+            bool status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, 0, null, out bufferNeeded);
             int error = Marshal.GetLastWin32Error();
 
             if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT
@@ -1048,12 +1062,12 @@ namespace System.Diagnostics.Eventing.Reader
                 {
                     return null;
                 }
-                if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
+                if (error != Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
                     EventLogException.Throw(error);
             }
 
-            sb.EnsureCapacity(bufferNeeded);
-            status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, bufferNeeded, sb, out bufferNeeded);
+            char[] buffer = new char[bufferNeeded];
+            status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, bufferNeeded, buffer, out bufferNeeded);
             error = Marshal.GetLastWin32Error();
 
             if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT
@@ -1065,7 +1079,12 @@ namespace System.Diagnostics.Eventing.Reader
                 }
                 EventLogException.Throw(error);
             }
-            return sb.ToString();
+
+            int len = bufferNeeded - 1; // buffer includes null terminator
+            if (len <= 0)
+                return string.Empty;
+
+            return new string(buffer, 0, len);
         }
 
         private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val)
@@ -1327,9 +1346,9 @@ namespace System.Diagnostics.Eventing.Reader
                 case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND:
                 case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND:
                 case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND:
-                case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND:
+                case Interop.Errors.ERROR_RESOURCE_LANG_NOT_FOUND:
                 case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND:
-                case UnsafeNativeMethods.ERROR_RESOURCE_TYPE_NOT_FOUND:
+                case Interop.Errors.ERROR_RESOURCE_TYPE_NOT_FOUND:
                     return true;
             }
             return false;
index 9dff026..1011901 100644 (file)
@@ -3,71 +3,15 @@
 
 using Microsoft.Win32.SafeHandles;
 using System;
-using System.Configuration.Assemblies;
-using System.Diagnostics.Eventing;
 using System.Diagnostics.Eventing.Reader;
-using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
 using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Runtime.Versioning;
 using System.Security;
-using System.Security.Principal;
 using System.Text;
-using System.Threading;
 
 namespace Microsoft.Win32
 {
     internal static partial class UnsafeNativeMethods
     {
-        internal const string WEVTAPI = "wevtapi.dll";
-
-        // WinError.h codes:
-
-        internal const int ERROR_SUCCESS = 0x0;
-        internal const int ERROR_FILE_NOT_FOUND = 0x2;
-        internal const int ERROR_PATH_NOT_FOUND = 0x3;
-        internal const int ERROR_ACCESS_DENIED = 0x5;
-        internal const int ERROR_INVALID_HANDLE = 0x6;
-
-        // Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough.
-        // This happens when the disk is slow and event traffic is heavy.
-        // Eventually, there are no more free (empty) buffers and the event is dropped.
-        internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
-
-        internal const int ERROR_INVALID_DRIVE = 0xF;
-        internal const int ERROR_NO_MORE_FILES = 0x12;
-        internal const int ERROR_NOT_READY = 0x15;
-        internal const int ERROR_BAD_LENGTH = 0x18;
-        internal const int ERROR_SHARING_VIOLATION = 0x20;
-        internal const int ERROR_LOCK_VIOLATION = 0x21;  // 33
-        internal const int ERROR_HANDLE_EOF = 0x26;  // 38
-        internal const int ERROR_FILE_EXISTS = 0x50;
-        internal const int ERROR_INVALID_PARAMETER = 0x57;  // 87
-        internal const int ERROR_BROKEN_PIPE = 0x6D;  // 109
-        internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;  // 122
-        internal const int ERROR_INVALID_NAME = 0x7B;
-        internal const int ERROR_BAD_PATHNAME = 0xA1;
-        internal const int ERROR_ALREADY_EXISTS = 0xB7;
-        internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
-        internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE;  // filename too long
-        internal const int ERROR_PIPE_BUSY = 0xE7;  // 231
-        internal const int ERROR_NO_DATA = 0xE8;  // 232
-        internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9;  // 233
-        internal const int ERROR_MORE_DATA = 0xEA;
-        internal const int ERROR_NO_MORE_ITEMS = 0x103;  // 259
-        internal const int ERROR_PIPE_CONNECTED = 0x217;  // 535
-        internal const int ERROR_PIPE_LISTENING = 0x218;  // 536
-        internal const int ERROR_OPERATION_ABORTED = 0x3E3;  // 995; For IO Cancellation
-        internal const int ERROR_IO_PENDING = 0x3E5;  // 997
-        internal const int ERROR_NOT_FOUND = 0x490;  // 1168
-
-        // The event size is larger than the allowed maximum (64k - header).
-        internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216;  // 534
-
-        internal const int ERROR_RESOURCE_TYPE_NOT_FOUND = 0x715;  // 1813
-        internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717;  // 1815
-
         // Event log specific codes:
 
         internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;
@@ -419,36 +363,35 @@ namespace Microsoft.Win32
             EvtSeekStrict = 0x10000
         }
 
-        [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
-        internal static extern EventLogHandle EvtQuery(
+        [GeneratedDllImport(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
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtSeek(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtSeek(
                             EventLogHandle resultSet,
                             long position,
                             EventLogHandle bookmark,
                             int timeout,
-                            [MarshalAs(UnmanagedType.I4)]EvtSeekFlags flags
-                                        );
+                            EvtSeekFlags flags);
 
-        [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
-        internal static extern EventLogHandle EvtSubscribe(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        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,
                             int flags);
 
-        [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
-        internal static extern bool EvtNext(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtNext(
                             EventLogHandle queryHandle,
                             int eventSize,
                             [MarshalAs(UnmanagedType.LPArray)] IntPtr[] events,
@@ -456,238 +399,203 @@ namespace Microsoft.Win32
                             int flags,
                             ref int returned);
 
-        [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
-        internal static extern bool EvtCancel(EventLogHandle handle);
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtCancel(EventLogHandle handle);
 
-        [DllImport(WEVTAPI)]
-        internal static extern bool EvtClose(IntPtr handle);
+        [GeneratedDllImport(Interop.Libraries.Wevtapi)]
+        internal static partial bool EvtClose(IntPtr handle);
 
-        /*
-        [DllImport(WEVTAPI, EntryPoint = "EvtClose", SetLastError = true)]
-        public static extern bool EvtClose(
-                            IntPtr eventHandle
-                                           );
-         */
-
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetEventInfo(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetEventInfo(
                             EventLogHandle eventHandle,
-                            // int propertyId
-                            [MarshalAs(UnmanagedType.I4)]EvtEventPropertyId propertyId,
+                            EvtEventPropertyId propertyId,
                             int bufferSize,
                             IntPtr bufferPtr,
-                            out int bufferUsed
-                                            );
+                            out int bufferUsed);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetQueryInfo(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetQueryInfo(
                             EventLogHandle queryHandle,
-                            [MarshalAs(UnmanagedType.I4)]EvtQueryPropertyId propertyId,
+                            EvtQueryPropertyId propertyId,
                             int bufferSize,
                             IntPtr buffer,
-                            ref int bufferRequired
-                                            );
+                            ref int bufferRequired);
 
         // PUBLISHER METADATA
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtOpenPublisherMetadata(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtOpenPublisherMetadata(
                             EventLogHandle session,
                             [MarshalAs(UnmanagedType.LPWStr)] string publisherId,
                             [MarshalAs(UnmanagedType.LPWStr)] string logFilePath,
                             int locale,
-                            int flags
-                                    );
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetPublisherMetadataProperty(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetPublisherMetadataProperty(
                             EventLogHandle publisherMetadataHandle,
-                            [MarshalAs(UnmanagedType.I4)] EvtPublisherMetadataPropertyId propertyId,
+                            EvtPublisherMetadataPropertyId propertyId,
                             int flags,
                             int publisherMetadataPropertyBufferSize,
                             IntPtr publisherMetadataPropertyBuffer,
-                            out int publisherMetadataPropertyBufferUsed
-                                    );
+                            out int publisherMetadataPropertyBufferUsed);
 
         // NEW
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetObjectArraySize(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetObjectArraySize(
                             EventLogHandle objectArray,
-                            out int objectArraySize
-                                        );
+                            out int objectArraySize);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetObjectArrayProperty(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetObjectArrayProperty(
                             EventLogHandle objectArray,
                             int propertyId,
                             int arrayIndex,
                             int flags,
                             int propertyValueBufferSize,
                             IntPtr propertyValueBuffer,
-                            out int propertyValueBufferUsed
-                                            );
+                            out int propertyValueBufferUsed);
 
         // NEW 2
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtOpenEventMetadataEnum(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtOpenEventMetadataEnum(
                             EventLogHandle publisherMetadata,
-                            int flags
-                                    );
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        // public static extern IntPtr EvtNextEventMetadata(
-        internal static extern EventLogHandle EvtNextEventMetadata(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtNextEventMetadata(
                             EventLogHandle eventMetadataEnum,
-                            int flags
-                                    );
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetEventMetadataProperty(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetEventMetadataProperty(
                             EventLogHandle eventMetadata,
-                            [MarshalAs(UnmanagedType.I4)]  EvtEventMetadataPropertyId propertyId,
+                            EvtEventMetadataPropertyId propertyId,
                             int flags,
                             int eventMetadataPropertyBufferSize,
                             IntPtr eventMetadataPropertyBuffer,
-                            out int eventMetadataPropertyBufferUsed
-                                   );
+                            out int eventMetadataPropertyBufferUsed);
 
         // Channel Configuration Native Api
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtOpenChannelEnum(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtOpenChannelEnum(
                             EventLogHandle session,
-                            int flags
-                                    );
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtNextChannelPath(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        internal static partial bool EvtNextChannelPath(
                             EventLogHandle channelEnum,
                             int channelPathBufferSize,
-                            // StringBuilder channelPathBuffer,
-                            [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder channelPathBuffer,
-                            out int channelPathBufferUsed
-                                    );
+                            [Out] char[]? channelPathBuffer,
+                            out int channelPathBufferUsed);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtOpenPublisherEnum(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtOpenPublisherEnum(
                             EventLogHandle session,
-                            int flags
-                                    );
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtNextPublisherId(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        internal static partial bool EvtNextPublisherId(
                             EventLogHandle publisherEnum,
                             int publisherIdBufferSize,
-                            [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder publisherIdBuffer,
-                            out int publisherIdBufferUsed
-                                    );
+                            [Out] char[]? publisherIdBuffer,
+                            out int publisherIdBufferUsed);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtOpenChannelConfig(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtOpenChannelConfig(
                             EventLogHandle session,
-                            [MarshalAs(UnmanagedType.LPWStr)]string channelPath,
-                            int flags
-                                    );
+                            [MarshalAs(UnmanagedType.LPWStr)] string channelPath,
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtSaveChannelConfig(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtSaveChannelConfig(
                             EventLogHandle channelConfig,
-                            int flags
-                                    );
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtSetChannelConfigProperty(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtSetChannelConfigProperty(
                             EventLogHandle channelConfig,
-                            [MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
+                            EvtChannelConfigPropertyId propertyId,
                             int flags,
-                            ref EvtVariant propertyValue
-                                    );
+                            ref EvtVariant propertyValue);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetChannelConfigProperty(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetChannelConfigProperty(
                             EventLogHandle channelConfig,
-                            [MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
+                            EvtChannelConfigPropertyId propertyId,
                             int flags,
                             int propertyValueBufferSize,
                             IntPtr propertyValueBuffer,
-                            out int propertyValueBufferUsed
-                                   );
+                            out int propertyValueBufferUsed);
 
         // Log Information Native Api
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtOpenLog(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtOpenLog(
                             EventLogHandle session,
                             [MarshalAs(UnmanagedType.LPWStr)] string path,
-                            [MarshalAs(UnmanagedType.I4)]PathType flags
-                                    );
+                            PathType flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtGetLogInfo(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtGetLogInfo(
                             EventLogHandle log,
-                            [MarshalAs(UnmanagedType.I4)]EvtLogPropertyId propertyId,
+                            EvtLogPropertyId propertyId,
                             int propertyValueBufferSize,
                             IntPtr propertyValueBuffer,
-                            out int propertyValueBufferUsed
-                                    );
+                            out int propertyValueBufferUsed);
 
         // LOG MANIPULATION
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtExportLog(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtExportLog(
                             EventLogHandle session,
-                            [MarshalAs(UnmanagedType.LPWStr)]string channelPath,
-                            [MarshalAs(UnmanagedType.LPWStr)]string query,
-                            [MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
-                            int flags
-                                        );
+                            [MarshalAs(UnmanagedType.LPWStr)] string channelPath,
+                            [MarshalAs(UnmanagedType.LPWStr)] string query,
+                            [MarshalAs(UnmanagedType.LPWStr)] string targetFilePath,
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtArchiveExportedLog(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtArchiveExportedLog(
                             EventLogHandle session,
                             [MarshalAs(UnmanagedType.LPWStr)]string logFilePath,
                             int locale,
-                            int flags
-                                        );
+                            int flags);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtClearLog(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtClearLog(
                             EventLogHandle session,
                             [MarshalAs(UnmanagedType.LPWStr)]string channelPath,
                             [MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
-                            int flags
-                                        );
+                            int flags);
 
         // RENDERING
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtCreateRenderContext(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial EventLogHandle EvtCreateRenderContext(
                             int valuePathsCount,
                             [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)]
                                 string[] valuePaths,
-                            [MarshalAs(UnmanagedType.I4)]EvtRenderContextFlags flags
-                                    );
+                            EvtRenderContextFlags flags);
 
-        [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
-        internal static extern bool EvtRender(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
+        internal static partial bool EvtRender(
                             EventLogHandle context,
                             EventLogHandle eventHandle,
                             EvtRenderFlags flags,
                             int buffSize,
-                            [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
+                            [Out] char[]? buffer,
                             out int buffUsed,
-                            out int propCount
-                                        );
+                            out int propCount);
 
-        [DllImport(WEVTAPI, EntryPoint = "EvtRender", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
-        internal static extern bool EvtRender(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, EntryPoint = "EvtRender", SetLastError = true)]
+        internal static partial bool EvtRender(
                             EventLogHandle context,
                             EventLogHandle eventHandle,
                             EvtRenderFlags flags,
                             int buffSize,
                             IntPtr buffer,
                             out int buffUsed,
-                            out int propCount
-                                        );
+                            out int propCount);
 
         [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
         internal struct EvtStringVariant
@@ -700,52 +608,53 @@ namespace Microsoft.Win32
             public uint Type;
         };
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
+#pragma warning disable DLLIMPORTGENANALYZER015 // Use 'GeneratedDllImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
+        // TODO: [DllImportGenerator] Switch to use GeneratedDllImport once we support non-blittable types.
+        [DllImport(Interop.Libraries.Wevtapi, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
         internal static extern bool EvtFormatMessage(
                              EventLogHandle publisherMetadataHandle,
                              EventLogHandle eventHandle,
                              uint messageId,
                              int valueCount,
                              EvtStringVariant[] values,
-                             [MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
+                             EvtFormatMessageFlags flags,
                              int bufferSize,
-                             [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
-                             out int bufferUsed
-                                        );
+                             [Out] char[]? buffer,
+                             out int bufferUsed);
+#pragma warning restore DLLIMPORTGENANALYZER015
 
-        [DllImport(WEVTAPI, EntryPoint = "EvtFormatMessage", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtFormatMessageBuffer(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, EntryPoint = "EvtFormatMessage", SetLastError = true)]
+        internal static partial bool EvtFormatMessageBuffer(
                              EventLogHandle publisherMetadataHandle,
                              EventLogHandle eventHandle,
                              uint messageId,
                              int valueCount,
                              IntPtr values,
-                             [MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
+                             EvtFormatMessageFlags flags,
                              int bufferSize,
                              IntPtr buffer,
-                             out int bufferUsed
-                                        );
+                             out int bufferUsed);
 
         // SESSION
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
+#pragma warning disable DLLIMPORTGENANALYZER015 // Use 'GeneratedDllImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
+        // TODO: [DllImportGenerator] Switch to use GeneratedDllImport once we support non-blittable types.
+        [DllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
         internal static extern EventLogHandle EvtOpenSession(
-                            [MarshalAs(UnmanagedType.I4)]EvtLoginClass loginClass,
+                            EvtLoginClass loginClass,
                             ref EvtRpcLogin login,
                             int timeout,
-                            int flags
-                                        );
+                            int flags);
+#pragma warning restore DLLIMPORTGENANALYZER015
 
         // BOOKMARK
-        [DllImport(WEVTAPI, EntryPoint = "EvtCreateBookmark", CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern EventLogHandle EvtCreateBookmark(
-                            [MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml
-                                        );
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, EntryPoint = "EvtCreateBookmark", SetLastError = true)]
+        internal static partial EventLogHandle EvtCreateBookmark(
+                            [MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml);
 
-        [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
-        internal static extern bool EvtUpdateBookmark(
+        [GeneratedDllImport(Interop.Libraries.Wevtapi, SetLastError = true)]
+        internal static partial bool EvtUpdateBookmark(
                             EventLogHandle bookmark,
-                            EventLogHandle eventHandle
-                                        );
+                            EventLogHandle eventHandle);
         //
         // EventLog
         //