Checking if the eventlog registry key is actually an eventlog (dotnet/corefx#38430)
authorAnirudh Agnihotry <anirudhagnihotry098@gmail.com>
Wed, 26 Jun 2019 01:48:20 +0000 (18:48 -0700)
committermsftbot[bot] <48340428+msftbot[bot]@users.noreply.github.com>
Wed, 26 Jun 2019 01:48:20 +0000 (01:48 +0000)
*  checking if the eventlog registry key is actually an eventlog

* optimising the code a  little bit

* modified test

* skipping test on .net frameworj

Commit migrated from https://github.com/dotnet/corefx/commit/18f5e7b7f9c13b309f7ac978747c828ed417e543

src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs
src/libraries/System.Diagnostics.EventLog/tests/EventLogTests/EventLogTests.cs

index 730c11c..c9c90a4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Collections.Generic;
 using System.ComponentModel;
 using System.Globalization;
 using System.IO;
@@ -655,14 +656,20 @@ namespace System.Diagnostics
                 eventkey?.Close();
             }
             // now create EventLog objects that point to those logs
-            EventLog[] logs = new EventLog[logNames.Length];
+            List<EventLog> logs = new List<EventLog>(logNames.Length);
             for (int i = 0; i < logNames.Length; i++)
             {
                 EventLog log = new EventLog(logNames[i], machineName);
-                logs[i] = log;
+                SafeEventLogReadHandle handle = Interop.Advapi32.OpenEventLog(machineName, logNames[i]);
+
+                if (!handle.IsInvalid)
+                {
+                    handle.Close();
+                    logs.Add(log);
+                }
             }
 
-            return logs;
+            return logs.ToArray();
         }
 
         internal static RegistryKey GetEventLogRegKey(string machine, bool writable)
index 4cd4217..0bd8310 100644 (file)
@@ -349,5 +349,16 @@ namespace System.Diagnostics.Tests
                 Assert.Contains("", eventlog.Entries.LastOrDefault()?.Message ?? "");
             }
         }
+
+        [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
+        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
+        public void GetEventLogEntriesTest()
+        {
+            foreach (var eventLog in EventLog.GetEventLogs())
+            {
+                // Accessing eventlog properties should not throw.
+                Assert.True(eventLog.Entries.Count >= 0);
+            }
+        }
     }
 }