Update 'Microsoft.PowerShell.CoreCLR.Eventing' to resolve conflict with 'System.Diagnostics.EventLog' (#10305)

* Update 'Microsoft.PowerShell.CoreCLR.Eventing' to resolve conflicts
* Add reference to 'System.Diagnostics.EventLog' to build Microsoft.PowerShell.Commands.Diagnostics on Unix
* Stop compiling Get/New-WinEvent on Unix
This commit is contained in:
Dongbo Wang 2019-08-08 05:44:54 -07:00 committed by Ilya
parent cf7699b4b9
commit 0d817aa547
32 changed files with 122 additions and 3868 deletions

View File

@ -3042,6 +3042,15 @@
<Component Id="cmpCE991A76187F47148F1854BC02E3524E" Guid="{39a0126f-44e9-471a-83d6-139d1636e79a}">
<File Id="fil199A45B24AFE4650B2EB5A3C3E7EC0BE" KeyPath="yes" Source="$(env.ProductSourcePath)\System.Windows.Forms.dll" />
</Component>
<Component Id="cmpAD1A205D445C43588868B205091DD390" Guid="{6b4a76d4-d968-40ee-bac1-abdb3d01b442}">
<File Id="filFC6F2DCBA0D549999D96D3624406804E" KeyPath="yes" Source="$(env.ProductSourcePath)\System.Reflection.Context.dll" />
</Component>
<Component Id="cmpD7A187ADE66347E5A7550B96BA10D493" Guid="{410b2d6d-2158-4e70-a970-37b2f14e3e82}">
<File Id="filEEF618E0250F4B8CBFE951C2A7E5C018" KeyPath="yes" Source="$(env.ProductSourcePath)\System.Data.OleDb.dll" />
</Component>
<Component Id="cmp827B25EEC28D4699BB29042B273C8CBF" Guid="{f7ccc70c-5aaf-4e6b-bf9f-c59f4e631f9c}">
<File Id="filEF6B07EDBC8F43AE8DF88CFDF798FC22" KeyPath="yes" Source="$(env.ProductSourcePath)\System.ComponentModel.Composition.Registration.dll" />
</Component>
</DirectoryRef>
</Fragment>
<Fragment>
@ -3876,6 +3885,9 @@
<ComponentRef Id="cmp765A784AADA742928B4E6376ABB7EF28" />
<ComponentRef Id="cmpC6C53A5B540B4A3C9624A0D14D5A9790" />
<ComponentRef Id="cmp6A48FC0DE86C41C297EC418A0E49CA2C" />
<ComponentRef Id="cmpAD1A205D445C43588868B205091DD390" />
<ComponentRef Id="cmpD7A187ADE66347E5A7550B96BA10D493" />
<ComponentRef Id="cmp827B25EEC28D4699BB29042B273C8CBF" />
</ComponentGroup>
</Fragment>
</Wix>

View File

@ -2191,7 +2191,6 @@ function Start-CrossGen {
"Microsoft.PowerShell.Commands.Utility.dll",
"Microsoft.PowerShell.Commands.Management.dll",
"Microsoft.PowerShell.Security.dll",
"Microsoft.PowerShell.CoreCLR.Eventing.dll",
"Microsoft.PowerShell.ConsoleHost.dll",
"System.Management.Automation.dll"
)
@ -2199,6 +2198,7 @@ function Start-CrossGen {
# Add Windows specific libraries
if ($Environment.IsWindows) {
$psCoreAssemblyList += @(
"Microsoft.PowerShell.CoreCLR.Eventing.dll",
"Microsoft.WSMan.Management.dll",
"Microsoft.WSMan.Runtime.dll",
"Microsoft.PowerShell.Commands.Diagnostics.dll",

View File

@ -27,4 +27,9 @@
<Compile Remove="gen\GetEventResources.cs" />
</ItemGroup>
<ItemGroup Condition=" '$(IsWindows)' != 'true' ">
<Compile Remove="GetEventCommand.cs" />
<Compile Remove="NewWinEventCommand.cs" />
</ItemGroup>
</Project>

View File

@ -57,7 +57,7 @@
<ItemGroup>
<!-- the following package(s) are from https://github.com/dotnet/corefx -->
<PackageReference Include="System.ServiceProcess.ServiceController" Version="4.5.0" />
<PackageReference Include="System.ServiceProcess.ServiceController" Version="4.6.0-preview7.19362.9" />
</ItemGroup>
</Project>

View File

@ -1,44 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class represents an opaque Event Bookmark obtained
** from an EventRecord. The bookmark denotes a unique identifier
** for the event instance as well as marks the location in the
** the result set of the EventReader that the event instance was
** obtained from.
**
============================================================*/
namespace System.Diagnostics.Eventing.Reader
{
//
// NOTE: This class must be generic enough to be used across
// eventing base implementations. Cannot add anything
// that ties it to one particular implementation.
//
/// <summary>
/// Represents an opaque Event Bookmark obtained from an EventRecord.
/// The bookmark denotes a unique identifier for the event instance as
/// well as marks the location in the the result set of the EventReader
/// that the event instance was obtained from.
/// </summary>
public class EventBookmark
{
private string _bookmark;
internal EventBookmark(string bookmarkText)
{
if (bookmarkText == null)
throw new ArgumentNullException("bookmarkText");
_bookmark = bookmarkText;
}
internal string BookmarkText { get { return _bookmark; } }
}
}

View File

@ -1,101 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes the metadata for a specific Keyword
** defined by a Provider. An instance of this class is obtained from
** a ProviderMetadata object.
**
============================================================*/
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Describes the metadata for a specific Keyword defined by a Provider.
/// An instance of this class is obtained from a ProviderMetadata object.
/// </summary>
public sealed class EventKeyword
{
private long _value;
private string _name;
private string _displayName;
private bool _dataReady;
private ProviderMetadata _pmReference;
private object _syncObject;
// called from EventMetadata
internal EventKeyword(long value, ProviderMetadata pmReference)
{
_value = value;
_pmReference = pmReference;
_syncObject = new object();
}
// called from ProviderMetadata
internal EventKeyword(string name, long value, string displayName)
{
_value = value;
_name = name;
_displayName = displayName;
_dataReady = true;
_syncObject = new object();
}
internal void PrepareData()
{
if (_dataReady == true) return;
lock (_syncObject)
{
if (_dataReady == true) return;
IEnumerable<EventKeyword> result = _pmReference.Keywords;
_name = null;
_displayName = null;
_dataReady = true;
foreach (EventKeyword key in result)
{
if (key.Value == _value)
{
_name = key.Name;
_displayName = key.DisplayName;
break;
}
}
}
}
public string Name
{
get
{
PrepareData();
return _name;
}
}
public long Value
{
get
{
return _value;
}
}
public string DisplayName
{
get
{
PrepareData();
return _displayName;
}
}
}
}

View File

@ -1,99 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes the metadata for a specific Level
** defined by a Provider. An instance of this class is obtained from
** a ProviderMetadata object.
**
============================================================*/
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Describes the metadata for a specific Level defined by a Provider.
/// An instance of this class is obtained from a ProviderMetadata object.
/// </summary>
public sealed class EventLevel
{
private int _value;
private string _name;
private string _displayName;
private bool _dataReady;
private ProviderMetadata _pmReference;
private object _syncObject;
// called from EventMetadata
internal EventLevel(int value, ProviderMetadata pmReference)
{
_value = value;
_pmReference = pmReference;
_syncObject = new object();
}
// called from ProviderMetadata
internal EventLevel(string name, int value, string displayName)
{
_value = value;
_name = name;
_displayName = displayName;
_dataReady = true;
_syncObject = new object();
}
internal void PrepareData()
{
if (_dataReady == true) return;
lock (_syncObject)
{
if (_dataReady == true) return;
IEnumerable<EventLevel> result = _pmReference.Levels;
_name = null;
_displayName = null;
_dataReady = true;
foreach (EventLevel lev in result)
{
if (lev.Value == _value)
{
_name = lev.Name;
_displayName = lev.DisplayName;
break;
}
}
}
}
public string Name
{
get
{
PrepareData();
return _name;
}
}
public int Value
{
get
{
return _value;
}
}
public string DisplayName
{
get
{
PrepareData();
return _displayName;
}
}
}
}

View File

@ -1,303 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class allows accessing static channel information and
** configures channel publishing and logging properties. An instance
** of this class is obtained from EventLogManagement class.
**
============================================================*/
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Log Type.
/// </summary>
public enum EventLogType
{
Administrative = 0,
Operational,
Analytical,
Debug
}
/// <summary>
/// Log Isolation.
/// </summary>
public enum EventLogIsolation
{
Application = 0,
System,
Custom
}
/// <summary>
/// Log Mode.
/// </summary>
public enum EventLogMode
{
Circular = 0,
AutoBackup,
Retain
}
/// <summary>
/// Provides access to static log information and configures
/// log publishing and log file properties.
/// </summary>
public class EventLogConfiguration : IDisposable
{
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private EventLogHandle _handle = EventLogHandle.Zero;
private EventLogSession _session = null;
private string _channelName;
public EventLogConfiguration(string logName) : this(logName, null) { }
// marked as SecurityCritical because allocates SafeHandles.
// marked as Safe because performs Demand check.
[System.Security.SecurityCritical]
public EventLogConfiguration(string logName, EventLogSession session)
{
if (session == null)
session = EventLogSession.GlobalSession;
_session = session;
_channelName = logName;
_handle = NativeWrapper.EvtOpenChannelConfig(_session.Handle, _channelName, 0);
}
public string LogName
{
get
{
return _channelName;
}
}
public EventLogType LogType
{
get
{
return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType));
}
}
public EventLogIsolation LogIsolation
{
get
{
return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation));
}
}
public bool IsEnabled
{
get
{
return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, (object)value);
}
}
public bool IsClassicLog
{
get
{
return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog);
}
}
public string SecurityDescriptor
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value);
}
}
public string LogFilePath
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value);
}
}
public long MaximumSizeInBytes
{
get
{
return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize));
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, (object)value);
}
}
public EventLogMode LogMode
{
get
{
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;
if (nativeAutoBackup)
return EventLogMode.AutoBackup;
if (nativeRetention)
return EventLogMode.Retain;
return EventLogMode.Circular;
}
set
{
switch (value)
{
case EventLogMode.Circular:
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false);
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)false);
break;
case EventLogMode.AutoBackup:
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)true);
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true);
break;
case EventLogMode.Retain:
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false);
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true);
break;
}
}
}
public string OwningProviderName
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher);
}
}
public IEnumerable<string> ProviderNames
{
get
{
return (string[])NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList);
}
}
public int? ProviderLevel
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel));
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value);
}
}
public long? ProviderKeywords
{
get
{
return (long?)((ulong?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords));
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value);
}
}
public int? ProviderBufferSize
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigBufferSize));
}
}
public int? ProviderMinimumNumberOfBuffers
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMinBuffers));
}
}
public int? ProviderMaximumNumberOfBuffers
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMaxBuffers));
}
}
public int? ProviderLatency
{
get
{
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLatency));
}
}
public Guid? ProviderControlGuid
{
get
{
return (Guid?)(NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigControlGuid));
}
}
public void SaveChanges()
{
NativeWrapper.EvtSaveChannelConfig(_handle, 0);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
}
}

View File

@ -1,136 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes an exception thrown from Event
** Log related classes.
**
============================================================*/
using System.ComponentModel;
namespace System.Diagnostics.Eventing.Reader
{
public class EventLogException : Exception
{
internal static void Throw(int errorCode)
{
switch (errorCode)
{
case 2:
case 3:
case 15007:
case 15027:
case 15028:
case 15002:
throw new EventLogNotFoundException(errorCode);
case 13:
case 15005:
throw new EventLogInvalidDataException(errorCode);
case 1818: // RPC_S_CALL_CANCELED is converted to ERROR_CANCELLED
case 1223:
throw new OperationCanceledException();
case 15037:
throw new EventLogProviderDisabledException(errorCode);
case 5:
throw new UnauthorizedAccessException();
case 15011:
case 15012:
throw new EventLogReadingException(errorCode);
default: throw new EventLogException(errorCode);
}
}
public EventLogException() { }
public EventLogException(string message) : base(message) { }
public EventLogException(string message, Exception innerException) : base(message, innerException) { }
protected EventLogException(int errorCode) { _errorCode = errorCode; }
public override string Message
{
// marked as SecurityCritical because it uses Win32Exception.
// marked as TreatAsSafe because it performs Demand.
[System.Security.SecurityCritical]
get
{
Win32Exception win32Exception = new Win32Exception(_errorCode);
return win32Exception.Message;
}
}
private int _errorCode;
}
/// <summary>
/// The object requested by the operation is not found.
/// </summary>
public class EventLogNotFoundException : EventLogException
{
public EventLogNotFoundException() { }
public EventLogNotFoundException(string message) : base(message) { }
public EventLogNotFoundException(string message, Exception innerException) : base(message, innerException) { }
internal EventLogNotFoundException(int errorCode) : base(errorCode) { }
}
/// <summary>
/// The state of the reader cursor has become invalid, most likely due to the fact
/// that the log has been cleared. User needs to obtain a new reader object if
/// they wish to continue navigating result set.
/// </summary>
public class EventLogReadingException : EventLogException
{
public EventLogReadingException() { }
public EventLogReadingException(string message) : base(message) { }
public EventLogReadingException(string message, Exception innerException) : base(message, innerException) { }
internal EventLogReadingException(int errorCode) : base(errorCode) { }
}
/// <summary>
/// Provider has been uninstalled while ProviderMetadata operations are being performed.
/// Obtain a new ProviderMetadata object, when provider is reinstalled, to continue navigating
/// provider's metadata.
/// </summary>
public class EventLogProviderDisabledException : EventLogException
{
public EventLogProviderDisabledException() { }
public EventLogProviderDisabledException(string message) : base(message) { }
public EventLogProviderDisabledException(string message, Exception innerException) : base(message, innerException) { }
internal EventLogProviderDisabledException(int errorCode) : base(errorCode) { }
}
/// <summary>
/// Data obtained from the eventlog service, for the current operation, is invalid .
/// </summary>
public class EventLogInvalidDataException : EventLogException
{
public EventLogInvalidDataException() { }
public EventLogInvalidDataException(string message) : base(message) { }
public EventLogInvalidDataException(string message, Exception innerException) : base(message, innerException) { }
internal EventLogInvalidDataException(int errorCode) : base(errorCode) { }
}
}

View File

@ -1,65 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** The objects of this class allow access to the run-time
** properties of logs and external log files. An instance of this
** class is obtained from EventLogSession.
**
============================================================*/
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Describes the run-time properties of logs and external log files. An instance
/// of this class is obtained from EventLogSession.
/// </summary>
public sealed class EventLogInformation
{
private DateTime? _creationTime;
private DateTime? _lastAccessTime;
private DateTime? _lastWriteTime;
private long? _fileSize;
private int? _fileAttributes;
private long? _recordCount;
private long? _oldestRecordNumber;
private bool? _isLogFull;
[System.Security.SecuritySafeCritical]
internal EventLogInformation(EventLogSession session, string channelName, PathType pathType)
{
EventLogHandle logHandle = NativeWrapper.EvtOpenLog(session.Handle, channelName, pathType);
using (logHandle)
{
_creationTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogCreationTime);
_lastAccessTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastAccessTime);
_lastWriteTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastWriteTime);
_fileSize = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFileSize));
_fileAttributes = (int?)((uint?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogAttributes));
_recordCount = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogNumberOfLogRecords));
_oldestRecordNumber = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogOldestRecordNumber));
_isLogFull = (bool?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFull);
}
}
public DateTime? CreationTime { get { return _creationTime; } }
public DateTime? LastAccessTime { get { return _lastAccessTime; } }
public DateTime? LastWriteTime { get { return _lastWriteTime; } }
public long? FileSize { get { return _fileSize; } }
public int? Attributes { get { return _fileAttributes; } }
public long? RecordCount { get { return _recordCount; } }
public long? OldestRecordNumber { get { return _oldestRecordNumber; } }
public bool? IsLogFull { get { return _isLogFull; } }
}
}

View File

@ -1,118 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes the metadata for a specific Log
** Reference defined by a Provider. An instance of this class is obtained from
** a ProviderMetadata object.
**
============================================================*/
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Describes the metadata for a specific Log Reference defined
/// by a Provider. An instance of this class is obtained from
/// a ProviderMetadata object.
/// </summary>
public sealed class EventLogLink
{
private string _channelName;
private bool _isImported;
private string _displayName;
private uint _channelId;
private bool _dataReady;
private ProviderMetadata _pmReference;
private object _syncObject;
internal EventLogLink(uint channelId, ProviderMetadata pmReference)
{
_channelId = channelId;
_pmReference = pmReference;
_syncObject = new object();
}
internal EventLogLink(string channelName, bool isImported, string displayName, uint channelId)
{
_channelName = channelName;
_isImported = isImported;
_displayName = displayName;
_channelId = channelId;
_dataReady = true;
_syncObject = new object();
}
private void PrepareData()
{
if (_dataReady == true) return;
lock (_syncObject)
{
if (_dataReady == true) return;
IEnumerable<EventLogLink> result = _pmReference.LogLinks;
_channelName = null;
_isImported = false;
_displayName = null;
_dataReady = true;
foreach (EventLogLink ch in result)
{
if (ch.ChannelId == _channelId)
{
_channelName = ch.LogName;
_isImported = ch.IsImported;
_displayName = ch.DisplayName;
_dataReady = true;
break;
}
}
}
}
public string LogName
{
get
{
this.PrepareData();
return _channelName;
}
}
public bool IsImported
{
get
{
this.PrepareData();
return _isImported;
}
}
public string DisplayName
{
get
{
this.PrepareData();
return _displayName;
}
}
internal uint ChannelId
{
get
{
return _channelId;
}
}
}
}

View File

@ -1,80 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** Public class that encapsulates the information for fast
** access to Event Values of an EventLogRecord. Implements
** the EventPropertyContext abstract class. An instance of this
** class is constructed and then passed to
** EventLogRecord.GetEventPropertyValues.
**
============================================================*/
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Encapsulates the information for fast access to Event Values
/// of an EventLogRecord. An instance of this class is constructed
/// and then passed to EventLogRecord.GetEventPropertyValues.
/// </summary>
public class EventLogPropertySelector : IDisposable
{
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private EventLogHandle _renderContextHandleValues;
[System.Security.SecurityCritical]
public EventLogPropertySelector(IEnumerable<string> propertyQueries)
{
if (propertyQueries == null)
throw new ArgumentNullException("propertyQueries");
string[] paths;
ICollection<string> coll = propertyQueries as ICollection<string>;
if (coll != null)
{
paths = new string[coll.Count];
coll.CopyTo(paths, 0);
}
else
{
List<string> queries;
queries = new List<string>(propertyQueries);
paths = queries.ToArray();
}
_renderContextHandleValues = NativeWrapper.EvtCreateRenderContext(paths.Length, paths, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextValues);
}
internal EventLogHandle Handle
{
// just returning reference to security critical type, the methods
// of that type are protected by SecurityCritical as appropriate.
get
{
return _renderContextHandleValues;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
if (_renderContextHandleValues != null && !_renderContextHandleValues.IsInvalid)
_renderContextHandleValues.Dispose();
}
}
}

View File

@ -1,120 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class allows a user to define events of interest.
** An instance of this class is passed to an EventReader to actually
** obtain the EventRecords. The EventLogQuery can be as
** simple specifying that all events are of interest, or it can contain
** query / xpath expressions that indicate exactly what characteristics
** events should have.
**
============================================================*/
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Allows a user to define events of interest. An instance of this
/// class is passed to an EventReader to actually obtain the EventRecords.
/// The EventLogQuery can be as simple specifying that all events are of
/// interest, or it can contain query / xpath expressions that indicate exactly
/// what characteristics events should have.
/// </summary>
public class EventLogQuery
{
private string _query;
private string _path;
private EventLogSession _session;
private PathType _pathType;
private bool _tolerateErrors = false;
private bool _reverseDirection = false;
public EventLogQuery(string path, PathType pathType)
: this(path, pathType, null)
{
}
public EventLogQuery(string path, PathType pathType, string query)
{
_session = EventLogSession.GlobalSession;
_path = path; // can be null
_pathType = pathType;
if (query == null)
{
if (path == null)
throw new ArgumentNullException("path");
}
else
{
_query = query;
}
}
public EventLogSession Session
{
get
{
return _session;
}
set
{
_session = value;
}
}
public bool TolerateQueryErrors
{
get
{
return _tolerateErrors;
}
set
{
_tolerateErrors = value;
}
}
public bool ReverseDirection
{
get
{
return _reverseDirection;
}
set
{
_reverseDirection = value;
}
}
internal string Path
{
get
{
return _path;
}
}
internal PathType ThePathType
{
get
{
return _pathType;
}
}
internal string Query
{
get
{
return _query;
}
}
}
}

View File

@ -1,353 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class is used for reading event records from event log.
**
============================================================*/
using System.IO;
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// This public class is used for reading event records from event log.
/// </summary>
public class EventLogReader : IDisposable
{
private EventLogQuery _eventQuery;
private int _batchSize;
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private EventLogHandle _handle;
/// <summary>
/// Events buffer holds batched event (handles).
/// </summary>
private IntPtr[] _eventsBuffer;
/// <summary>
/// The current index where the function GetNextEvent is (inside the eventsBuffer).
/// </summary>
private int _currentIndex;
/// <summary>
/// The number of events read from the batch into the eventsBuffer.
/// </summary>
private int _eventCount;
/// <summary>
/// When the reader finishes (will always return only ERROR_NO_MORE_ITEMS).
/// For subscription, this means we need to wait for next event.
/// </summary>
private bool _isEof;
/// <summary>
/// Maintains cached display / metadata information returned from
/// EventRecords that were obtained from this reader.
/// </summary>
private ProviderMetadataCachedInformation _cachedMetadataInformation;
public EventLogReader(string path)
: this(new EventLogQuery(path, PathType.LogName), null)
{
}
public EventLogReader(string path, PathType pathType)
: this(new EventLogQuery(path, pathType), null)
{
}
public EventLogReader(EventLogQuery eventQuery)
: this(eventQuery, null)
{
}
[System.Security.SecurityCritical]
public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark)
{
if (eventQuery == null)
throw new ArgumentNullException("eventQuery");
string logfile = null;
if (eventQuery.ThePathType == PathType.FilePath)
logfile = eventQuery.Path;
_cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, logfile, 50);
// explicit data
_eventQuery = eventQuery;
// implicit
_batchSize = 64;
_eventsBuffer = new IntPtr[_batchSize];
//
// compute the flag.
//
int flag = 0;
if (_eventQuery.ThePathType == PathType.LogName)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath;
else
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath;
if (_eventQuery.ReverseDirection)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryReverseDirection;
if (_eventQuery.TolerateQueryErrors)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryTolerateQueryErrors;
_handle = NativeWrapper.EvtQuery(_eventQuery.Session.Handle,
_eventQuery.Path, _eventQuery.Query,
flag);
EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark);
if (!bookmarkHandle.IsInvalid)
{
using (bookmarkHandle)
{
NativeWrapper.EvtSeek(_handle, 1, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
}
public int BatchSize
{
get
{
return _batchSize;
}
set
{
if (value < 1)
throw new ArgumentOutOfRangeException("value");
_batchSize = value;
}
}
[System.Security.SecurityCritical]
private bool GetNextBatch(TimeSpan ts)
{
int timeout;
if (ts == TimeSpan.MaxValue)
timeout = -1;
else
timeout = (int)ts.TotalMilliseconds;
// batchSize was changed by user, reallocate buffer.
if (_batchSize != _eventsBuffer.Length) _eventsBuffer = new IntPtr[_batchSize];
int newEventCount = 0;
bool results = NativeWrapper.EvtNext(_handle, _batchSize, _eventsBuffer, timeout, 0, ref newEventCount);
if (!results)
{
_eventCount = 0;
_currentIndex = 0;
return false; // no more events in the result set
}
_currentIndex = 0;
_eventCount = newEventCount;
return true;
}
public EventRecord ReadEvent()
{
return ReadEvent(TimeSpan.MaxValue);
}
// security critical because allocates SafeHandle.
// marked as safe because performs Demand check.
[System.Security.SecurityCritical]
public EventRecord ReadEvent(TimeSpan timeout)
{
if (_isEof)
throw new InvalidOperationException();
if (_currentIndex >= _eventCount)
{
// buffer is empty, get next batch.
GetNextBatch(timeout);
if (_currentIndex >= _eventCount)
{
_isEof = true;
return null;
}
}
EventLogRecord eventInstance = new EventLogRecord(new EventLogHandle(_eventsBuffer[_currentIndex], true), _eventQuery.Session, _cachedMetadataInformation);
_currentIndex++;
return eventInstance;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
while (_currentIndex < _eventCount)
{
NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]);
_currentIndex++;
}
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
[System.Security.SecurityCritical]
internal void SeekReset()
{
//
// close all unread event handles in the buffer
//
while (_currentIndex < _eventCount)
{
NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]);
_currentIndex++;
}
// reset the indexes used by Next
_currentIndex = 0;
_eventCount = 0;
_isEof = false;
}
// marked as SecurityCritical because it allocates SafeHandle.
[System.Security.SecurityCritical]
internal void SeekCommon(long offset)
{
//
// modify offset that we're going to send to service to account for the
// fact that we've already read some events in our buffer that the user
// hasn't seen yet.
//
offset = offset - (_eventCount - _currentIndex);
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToCurrent);
}
public void Seek(EventBookmark bookmark)
{
Seek(bookmark, 0);
}
[System.Security.SecurityCritical]
public void Seek(EventBookmark bookmark, long offset)
{
if (bookmark == null)
throw new ArgumentNullException("bookmark");
SeekReset();
using (EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark))
{
NativeWrapper.EvtSeek(_handle, offset, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
[System.Security.SecurityCritical]
public void Seek(SeekOrigin origin, long offset)
{
switch (origin)
{
case SeekOrigin.Begin:
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToFirst);
return;
case SeekOrigin.End:
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToLast);
return;
case SeekOrigin.Current:
if (offset >= 0)
{
// we can reuse elements in the batch.
if (_currentIndex + offset < _eventCount)
{
//
// We don't call Seek here, we can reposition within the batch.
//
// close all event handles between [currentIndex, currentIndex + offset)
int index = _currentIndex;
while (index < _currentIndex + offset)
{
NativeWrapper.EvtClose(_eventsBuffer[index]);
index++;
}
_currentIndex = (int)(_currentIndex + offset);
// leave the eventCount unchanged
// leave the same Eof
}
else
{
SeekCommon(offset);
}
}
else
{
SeekCommon(offset);
}
return;
}
}
public void CancelReading()
{
NativeWrapper.EvtCancel(_handle);
}
public IList<EventLogStatus> LogStatus
{
[System.Security.SecurityCritical]
get
{
List<EventLogStatus> list = null;
string[] channelNames = null;
int[] errorStatuses = null;
EventLogHandle queryHandle = _handle;
if (queryHandle.IsInvalid)
throw new InvalidOperationException();
channelNames = (string[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames);
errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses);
if (channelNames.Length != errorStatuses.Length)
throw new InvalidOperationException();
list = new List<EventLogStatus>(channelNames.Length);
for (int i = 0; i < channelNames.Length; i++)
{
EventLogStatus cs = new EventLogStatus(channelNames[i], errorStatuses[i]);
list.Add(cs);
}
return list.AsReadOnly();
}
}
}
}

View File

@ -1,457 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class is an EventLog implementation of EventRecord. An
** instance of this is obtained from an EventLogReader.
**
============================================================*/
using System.Collections.Generic;
using System.Text;
namespace System.Diagnostics.Eventing.Reader
{
public class EventLogRecord : EventRecord
{
private const int SYSTEM_PROPERTY_COUNT = 18;
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
[System.Security.SecuritySafeCritical]
private EventLogHandle _handle;
private EventLogSession _session;
private NativeWrapper.SystemProperties _systemProperties;
private string _containerChannel;
private int[] _matchedQueryIds;
// a dummy object which is used only for the locking.
private object _syncObject;
// cached DisplayNames for each instance
private string _levelName = null;
private string _taskName = null;
private string _opcodeName = null;
private IEnumerable<string> _keywordsNames = null;
// cached DisplayNames for each instance
private bool _levelNameReady;
private bool _taskNameReady;
private bool _opcodeNameReady;
private ProviderMetadataCachedInformation _cachedMetadataInformation;
// marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe.
[System.Security.SecuritySafeCritical]
internal EventLogRecord(EventLogHandle handle, EventLogSession session, ProviderMetadataCachedInformation cachedMetadataInfo)
{
_cachedMetadataInformation = cachedMetadataInfo;
_handle = handle;
_session = session;
_systemProperties = new NativeWrapper.SystemProperties();
_syncObject = new object();
}
internal EventLogHandle Handle
{
// just returning reference to security critical type, the methods
// of that type are protected by SecurityCritical as appropriate.
[System.Security.SecuritySafeCritical]
get
{
return _handle;
}
}
internal void PrepareSystemData()
{
if (_systemProperties.filled)
return;
// prepare the System Context, if it is not already initialized.
_session.SetupSystemContext();
lock (_syncObject)
{
if (_systemProperties.filled == false)
{
NativeWrapper.EvtRenderBufferWithContextSystem(_session.renderContextHandleSystem, _handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues, _systemProperties, SYSTEM_PROPERTY_COUNT);
_systemProperties.filled = true;
}
}
}
public override int Id
{
get
{
PrepareSystemData();
if (_systemProperties.Id == null)
return 0;
return (int)_systemProperties.Id;
}
}
public override byte? Version
{
get
{
PrepareSystemData();
return _systemProperties.Version;
}
}
public override int? Qualifiers
{
get
{
PrepareSystemData();
return (int?)(uint?)_systemProperties.Qualifiers;
}
}
public override byte? Level
{
get
{
PrepareSystemData();
return _systemProperties.Level;
}
}
public override int? Task
{
get
{
PrepareSystemData();
return (int?)(uint?)_systemProperties.Task;
}
}
public override short? Opcode
{
get
{
PrepareSystemData();
return (short?)(ushort?)_systemProperties.Opcode;
}
}
public override long? Keywords
{
get
{
PrepareSystemData();
return (long?)_systemProperties.Keywords;
}
}
public override long? RecordId
{
get
{
PrepareSystemData();
return (long?)_systemProperties.RecordId;
}
}
public override string ProviderName
{
get
{
PrepareSystemData();
return _systemProperties.ProviderName;
}
}
public override Guid? ProviderId
{
get
{
PrepareSystemData();
return _systemProperties.ProviderId;
}
}
public override string LogName
{
get
{
PrepareSystemData();
return _systemProperties.ChannelName;
}
}
public override int? ProcessId
{
get
{
PrepareSystemData();
return (int?)_systemProperties.ProcessId;
}
}
public override int? ThreadId
{
get
{
PrepareSystemData();
return (int?)_systemProperties.ThreadId;
}
}
public override string MachineName
{
get
{
PrepareSystemData();
return _systemProperties.ComputerName;
}
}
public override System.Security.Principal.SecurityIdentifier UserId
{
get
{
PrepareSystemData();
return _systemProperties.UserId;
}
}
public override DateTime? TimeCreated
{
get
{
PrepareSystemData();
return _systemProperties.TimeCreated;
}
}
public override Guid? ActivityId
{
get
{
PrepareSystemData();
return _systemProperties.ActivityId;
}
}
public override Guid? RelatedActivityId
{
get
{
PrepareSystemData();
return _systemProperties.RelatedActivityId;
}
}
public string ContainerLog
{
get
{
if (_containerChannel != null)
return _containerChannel;
lock (_syncObject)
{
if (_containerChannel == null)
{
_containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath);
}
return _containerChannel;
}
}
}
public IEnumerable<int> MatchedQueryIds
{
get
{
if (_matchedQueryIds != null)
return _matchedQueryIds;
lock (_syncObject)
{
if (_matchedQueryIds == null)
{
_matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs);
}
return _matchedQueryIds;
}
}
}
public override EventBookmark Bookmark
{
[System.Security.SecuritySafeCritical]
get
{
EventLogHandle bookmarkHandle = NativeWrapper.EvtCreateBookmark(null);
NativeWrapper.EvtUpdateBookmark(bookmarkHandle, _handle);
string bookmarkText = NativeWrapper.EvtRenderBookmark(bookmarkHandle);
return new EventBookmark(bookmarkText);
}
}
public override string FormatDescription()
{
return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, _handle);
}
public override string FormatDescription(IEnumerable<object> values)
{
if (values == null) return this.FormatDescription();
// copy the value IEnumerable to an array.
string[] theValues = Array.Empty<string>();
int i = 0;
foreach (object o in values)
{
if (theValues.Length == i)
Array.Resize(ref theValues, i + 1);
theValues[i] = o.ToString();
i++;
}
return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, _handle, theValues);
}
public override string LevelDisplayName
{
get
{
if (_levelNameReady)
return _levelName;
lock (_syncObject)
{
if (_levelNameReady == false)
{
_levelNameReady = true;
_levelName = _cachedMetadataInformation.GetLevelDisplayName(this.ProviderName, _handle);
}
return _levelName;
}
}
}
public override string OpcodeDisplayName
{
get
{
lock (_syncObject)
{
if (_opcodeNameReady == false)
{
_opcodeNameReady = true;
_opcodeName = _cachedMetadataInformation.GetOpcodeDisplayName(this.ProviderName, _handle);
}
return _opcodeName;
}
}
}
public override string TaskDisplayName
{
get
{
if (_taskNameReady == true)
return _taskName;
lock (_syncObject)
{
if (_taskNameReady == false)
{
_taskNameReady = true;
_taskName = _cachedMetadataInformation.GetTaskDisplayName(this.ProviderName, _handle);
}
return _taskName;
}
}
}
public override IEnumerable<string> KeywordsDisplayNames
{
get
{
if (_keywordsNames != null)
return _keywordsNames;
lock (_syncObject)
{
if (_keywordsNames == null)
{
_keywordsNames = _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, _handle);
}
return _keywordsNames;
}
}
}
public override IList<EventProperty> Properties
{
get
{
_session.SetupUserContext();
IList<object> properties = NativeWrapper.EvtRenderBufferWithContextUserOrValues(_session.renderContextHandleUser, _handle);
List<EventProperty> list = new List<EventProperty>();
foreach (object value in properties)
{
list.Add(new EventProperty(value));
}
return list;
}
}
public IList<object> GetPropertyValues(EventLogPropertySelector propertySelector)
{
if (propertySelector == null)
throw new ArgumentNullException("propertySelector");
return NativeWrapper.EvtRenderBufferWithContextUserOrValues(propertySelector.Handle, _handle);
}
// marked as SecurityCritical because it allocates SafeHandle
// marked as TreatAsSafe because it performs Demand.
[System.Security.SecuritySafeCritical]
public override string ToXml()
{
StringBuilder renderBuffer = new StringBuilder(2000);
NativeWrapper.EvtRender(EventLogHandle.Zero, _handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventXml, renderBuffer);
return renderBuffer.ToString();
}
[System.Security.SecuritySafeCritical]
protected override void Dispose(bool disposing)
{
try
{
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
finally
{
base.Dispose(disposing);
}
}
// marked as SecurityCritical because allocates SafeHandle.
[System.Security.SecurityCritical]
internal static EventLogHandle GetBookmarkHandleFromBookmark(EventBookmark bookmark)
{
if (bookmark == null)
return EventLogHandle.Zero;
EventLogHandle handle = NativeWrapper.EvtCreateBookmark(bookmark.BookmarkText);
return handle;
}
}
}

View File

@ -1,297 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** Defines a session for Event Log operations. The session can
** be configured for a remote machine and can use specific
** user credentials.
============================================================*/
using System.Security;
using System.Collections.Generic;
using System.Globalization;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Session Login Type.
/// </summary>
public enum SessionAuthentication
{
Default = 0,
Negotiate = 1,
Kerberos = 2,
Ntlm = 3
}
/// <summary>
/// The type: log / external log file to query.
/// </summary>
public enum PathType
{
LogName = 1,
FilePath = 2
}
public class EventLogSession : IDisposable
{
//
// the two context handles for rendering (for EventLogRecord).
// the system and user context handles. They are both common for all the event instances and can be created only once.
// access to the data member references is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
internal EventLogHandle renderContextHandleSystem = EventLogHandle.Zero;
internal EventLogHandle renderContextHandleUser = EventLogHandle.Zero;
// the dummy sync object for the two contexts.
private object _syncObject = null;
private string _server;
private string _user;
private string _domain;
private SessionAuthentication _logOnType;
// we do not maintain the password here.
//
// access to the data member references is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private EventLogHandle _handle = EventLogHandle.Zero;
// setup the System Context, once for all the EventRecords.
[System.Security.SecuritySafeCritical]
internal void SetupSystemContext()
{
if (!this.renderContextHandleSystem.IsInvalid)
return;
lock (_syncObject)
{
if (this.renderContextHandleSystem.IsInvalid)
{
// create the SYSTEM render context
// call the EvtCreateRenderContext to get the renderContextHandleSystem, so that we can get the system/values/user properties.
this.renderContextHandleSystem = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextSystem);
}
}
}
[System.Security.SecuritySafeCritical]
internal void SetupUserContext()
{
lock (_syncObject)
{
if (this.renderContextHandleUser.IsInvalid)
{
// create the USER render context
this.renderContextHandleUser = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextUser);
}
}
}
// marked as SecurityCritical because allocates SafeHandle.
// marked as TreatAsSafe because performs Demand().
[System.Security.SecurityCritical]
public EventLogSession()
{
// handle = EventLogHandle.Zero;
_syncObject = new object();
}
public EventLogSession(string server)
:
this(server, null, null, (SecureString)null, SessionAuthentication.Default)
{
}
// marked as TreatAsSafe because performs Demand().
[System.Security.SecurityCritical]
public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType)
{
if (server == null)
server = "localhost";
_syncObject = new object();
_server = server;
_domain = domain;
_user = user;
_logOnType = logOnType;
UnsafeNativeMethods.EvtRpcLogin erLogin = new UnsafeNativeMethods.EvtRpcLogin();
erLogin.Server = _server;
erLogin.User = _user;
erLogin.Domain = _domain;
erLogin.Flags = (int)_logOnType;
erLogin.Password = CoTaskMemUnicodeSafeHandle.Zero;
try
{
if (password != null)
erLogin.Password.SetMemory(SecureStringMarshal.SecureStringToCoTaskMemUnicode(password));
// open a session using the erLogin structure.
_handle = NativeWrapper.EvtOpenSession(UnsafeNativeMethods.EvtLoginClass.EvtRpcLogin, ref erLogin, 0, 0);
}
finally
{
erLogin.Password.Dispose();
}
}
internal EventLogHandle Handle
{
get
{
return _handle;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this == s_globalSession)
throw new InvalidOperationException();
}
if (this.renderContextHandleSystem != null &&
!this.renderContextHandleSystem.IsInvalid)
this.renderContextHandleSystem.Dispose();
if (this.renderContextHandleUser != null &&
!this.renderContextHandleUser.IsInvalid)
this.renderContextHandleUser.Dispose();
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
public void CancelCurrentOperations()
{
NativeWrapper.EvtCancel(_handle);
}
private static EventLogSession s_globalSession = new EventLogSession();
public static EventLogSession GlobalSession
{
get { return s_globalSession; }
}
[System.Security.SecurityCritical]
public IEnumerable<string> GetProviderNames()
{
List<string> namesList = new List<string>(100);
using (EventLogHandle ProviderEnum = NativeWrapper.EvtOpenProviderEnum(this.Handle, 0))
{
bool finish = false;
do
{
string s = NativeWrapper.EvtNextPublisherId(ProviderEnum, ref finish);
if (finish == false) namesList.Add(s);
}
while (finish == false);
return namesList;
}
}
[System.Security.SecurityCritical]
public IEnumerable<string> GetLogNames()
{
List<string> namesList = new List<string>(100);
using (EventLogHandle channelEnum = NativeWrapper.EvtOpenChannelEnum(this.Handle, 0))
{
bool finish = false;
do
{
string s = NativeWrapper.EvtNextChannelPath(channelEnum, ref finish);
if (finish == false) namesList.Add(s);
}
while (finish == false);
return namesList;
}
}
public EventLogInformation GetLogInformation(string logName, PathType pathType)
{
if (logName == null)
throw new ArgumentNullException("logName");
return new EventLogInformation(this, logName, pathType);
}
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)
{
if (path == null)
throw new ArgumentNullException("path");
if (targetFilePath == null)
throw new ArgumentNullException("targetFilePath");
UnsafeNativeMethods.EvtExportLogFlags flag;
switch (pathType)
{
case PathType.LogName:
flag = UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogChannelPath;
break;
case PathType.FilePath:
flag = UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogFilePath;
break;
default:
throw new ArgumentOutOfRangeException("pathType");
}
if (tolerateQueryErrors == false)
NativeWrapper.EvtExportLog(this.Handle, path, query, targetFilePath, (int)flag);
else
NativeWrapper.EvtExportLog(this.Handle, path, query, targetFilePath, (int)flag | (int)UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogTolerateQueryErrors);
}
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)
{
if (targetCultureInfo == null)
targetCultureInfo = CultureInfo.CurrentCulture;
ExportLog(path, pathType, query, targetFilePath, tolerateQueryErrors);
// Ignore the CultureInfo, pass 0 to use the calling thread's locale
NativeWrapper.EvtArchiveExportedLog(this.Handle, targetFilePath, 0, 0);
}
public void ClearLog(string logName)
{
this.ClearLog(logName, null);
}
public void ClearLog(string logName, string backupPath)
{
if (logName == null)
throw new ArgumentNullException("logName");
NativeWrapper.EvtClearLog(this.Handle, logName, backupPath, 0);
}
}
}

View File

@ -1,48 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes the status of a particular
** log with respect to an instantiated EventLogReader.
** Since it is possible to instantiate an EventLogReader
** with a query containing multiple logs and the reader can
** be configured to tolerate errors in attaching to those logs,
** this class allows the user to determine exactly what the status
** of those logs is.
============================================================*/
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Describes the status of a particular log with respect to
/// an instantiated EventLogReader. Since it is possible to
/// instantiate an EventLogReader with a query containing
/// multiple logs and the reader can be configured to tolerate
/// errors in attaching to those logs, this class allows the
/// user to determine exactly what the status of those logs is.
/// </summary>
public sealed class EventLogStatus
{
private string _channelName;
private int _win32ErrorCode;
internal EventLogStatus(string channelName, int win32ErrorCode)
{
_channelName = channelName;
_win32ErrorCode = win32ErrorCode;
}
public string LogName
{
get { return _channelName; }
}
public int StatusCode
{
get { return _win32ErrorCode; }
}
}
}

View File

@ -1,154 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes the metadata for a specific event
** raised by Provider. An instance of this class is obtained from
** ProviderMetadata class.
**
============================================================*/
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Event Metadata.
/// </summary>
public sealed class EventMetadata
{
private long _id;
private byte _version;
private byte _channelId;
private byte _level;
private short _opcode;
private int _task;
private long _keywords;
private string _template;
private string _description;
private ProviderMetadata _pmReference;
internal EventMetadata(uint id, byte version, byte channelId,
byte level, byte opcode, short task, long keywords,
string template, string description, ProviderMetadata pmReference)
{
_id = id;
_version = version;
_channelId = channelId;
_level = level;
_opcode = opcode;
_task = task;
_keywords = keywords;
_template = template;
_description = description;
_pmReference = pmReference;
}
//
// Max value will be UINT32.MaxValue - it is a long because this property
// is really a UINT32. The legacy API allows event message ids to be declared
// as UINT32 and these event/messages may be migrated into a Provider's
// manifest as UINT32. Note that EventRecord ids are
// still declared as int, because those ids max value is UINT16.MaxValue
// and rest of the bits of the legacy event id would be stored in
// Qualifiers property.
//
public long Id
{
get
{
return _id;
}
}
public byte Version
{
get
{
return _version;
}
}
public EventLogLink LogLink
{
get
{
return new EventLogLink((uint)_channelId, _pmReference);
}
}
public EventLevel Level
{
get
{
return new EventLevel(_level, _pmReference);
}
}
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")]
public EventOpcode Opcode
{
get
{
return new EventOpcode(_opcode, _pmReference);
}
}
public EventTask Task
{
get
{
return new EventTask(_task, _pmReference);
}
}
public IEnumerable<EventKeyword> Keywords
{
get
{
List<EventKeyword> list = new List<EventKeyword>();
ulong theKeywords = unchecked((ulong)_keywords);
ulong mask = 0x8000000000000000;
// for every bit
// for (int i = 0; i < 64 && theKeywords != 0; i++)
for (int i = 0; i < 64; i++)
{
// if this bit is set
if ((theKeywords & mask) > 0)
{
// the mask is the keyword we will be searching for.
list.Add(new EventKeyword(unchecked((long)mask), _pmReference));
// theKeywords = theKeywords - mask;
}
// modify the mask to check next bit.
mask = mask >> 1;
}
return list;
}
}
public string Template
{
get
{
return _template;
}
}
public string Description
{
get
{
return _description;
}
}
}
}

View File

@ -1,98 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes the metadata for a specific Opcode
** defined by a Provider. An instance of this class is obtained from
** a ProviderMetadata object.
**
============================================================*/
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing.Reader
{
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")]
public sealed class EventOpcode
{
private int _value;
private string _name;
private string _displayName;
private bool _dataReady;
private ProviderMetadata _pmReference;
private object _syncObject;
// call from EventMetadata
internal EventOpcode(int value, ProviderMetadata pmReference)
{
_value = value;
_pmReference = pmReference;
_syncObject = new object();
}
// call from ProviderMetadata
internal EventOpcode(string name, int value, string displayName)
{
_value = value;
_name = name;
_displayName = displayName;
_dataReady = true;
_syncObject = new object();
}
internal void PrepareData()
{
lock (_syncObject)
{
if (_dataReady == true) return;
// get the data
IEnumerable<EventOpcode> result = _pmReference.Opcodes;
// set the names and display names to null
_name = null;
_displayName = null;
_dataReady = true;
foreach (EventOpcode op in result)
{
if (op.Value == _value)
{
_name = op.Name;
_displayName = op.DisplayName;
_dataReady = true;
break;
}
}
}
}
public string Name
{
get
{
PrepareData();
return _name;
}
}
public int Value
{
get
{
return _value;
}
}
public string DisplayName
{
get
{
PrepareData();
return _displayName;
}
}
}
}

View File

@ -1,33 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class defines the methods / properties for the
** individual Data Values of an EventRecord. Instances of this
** class are obtained from EventRecord.
**
============================================================*/
namespace System.Diagnostics.Eventing.Reader
{
public sealed class EventProperty
{
private object _value;
internal EventProperty(object value)
{
_value = value;
}
public object Value
{
get
{
return _value;
}
}
}
}

View File

@ -1,28 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public abstract class defines the methods / properties
** for a context object used to access a set of Data Values from
** an EventRecord.
**
============================================================*/
namespace System.Diagnostics.Eventing.Reader
{
public abstract class EventPropertyContext : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
}

View File

@ -1,87 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public abstract class defines the methods / properties
** that all events should support.
**
============================================================*/
using System.Collections.Generic;
using System.Security.Principal;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Represents an event obtained from an EventReader.
/// </summary>
public abstract class EventRecord : IDisposable
{
public abstract int Id { get; }
public abstract byte? Version { get; }
public abstract byte? Level { get; }
public abstract int? Task { get; }
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")]
public abstract short? Opcode { get; }
public abstract long? Keywords { get; }
public abstract long? RecordId { get; }
public abstract string ProviderName { get; }
public abstract Guid? ProviderId { 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 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<object> values);
public abstract string LevelDisplayName { get; }
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")]
public abstract string OpcodeDisplayName { get; }
public abstract string TaskDisplayName { get; }
public abstract IEnumerable<string> KeywordsDisplayNames { get; }
public abstract EventBookmark Bookmark { get; }
public abstract IList<EventProperty> Properties { get; }
public abstract string ToXml();
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) { }
}
}

View File

@ -1,113 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class describes the metadata for a specific Task
** defined by a Provider. An instance of this class is obtained
** from a ProviderMetadata object.
**
============================================================*/
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Describes the metadata for a specific Task defined by a Provider.
/// An instance of this class is obtained from a ProviderMetadata object.
/// </summary>
public sealed class EventTask
{
private int _value;
private string _name;
private string _displayName;
private Guid _guid;
private bool _dataReady;
private ProviderMetadata _pmReference;
private object _syncObject;
// called from EventMetadata
internal EventTask(int value, ProviderMetadata pmReference)
{
_value = value;
_pmReference = pmReference;
_syncObject = new object();
}
// called from ProviderMetadata
internal EventTask(string name, int value, string displayName, Guid guid)
{
_value = value;
_name = name;
_displayName = displayName;
_guid = guid;
_dataReady = true;
_syncObject = new object();
}
internal void PrepareData()
{
lock (_syncObject)
{
if (_dataReady == true) return;
IEnumerable<EventTask> result = _pmReference.Tasks;
_name = null;
_displayName = null;
_guid = Guid.Empty;
_dataReady = true;
foreach (EventTask task in result)
{
if (task.Value == _value)
{
_name = task.Name;
_displayName = task.DisplayName;
_guid = task.EventGuid;
_dataReady = true;
break;
}
}
}
}
public string Name
{
get
{
PrepareData();
return _name;
}
}
public int Value
{
get
{
return _value;
}
}
public string DisplayName
{
get
{
PrepareData();
return _displayName;
}
}
public Guid EventGuid
{
get
{
PrepareData();
return _guid;
}
}
}
}

View File

@ -15,6 +15,7 @@
============================================================*/
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Principal;
@ -52,6 +53,43 @@ namespace System.Diagnostics.Eventing.Reader
}
}
private static void ThrowEventLogException(int errorCode)
{
string message = new Win32Exception(errorCode).Message;
switch (errorCode)
{
case 2:
case 3:
case 15007:
case 15027:
case 15028:
case 15002:
throw new EventLogNotFoundException(message);
case 13:
case 15005:
throw new EventLogInvalidDataException(message);
case 1818: // RPC_S_CALL_CANCELED is converted to ERROR_CANCELLED
case 1223:
throw new OperationCanceledException();
case 15037:
throw new EventLogProviderDisabledException(message);
case 5:
throw new UnauthorizedAccessException();
case 15011:
case 15012:
throw new EventLogReadingException(message);
default:
throw new EventLogException(message);
}
}
[System.Security.SecurityCritical]
public static EventLogHandle EvtQuery(
EventLogHandle session,
@ -62,7 +100,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle handle = UnsafeNativeMethods.EvtQuery(session, path, query, flags);
int win32Error = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return handle;
}
@ -77,7 +115,7 @@ namespace System.Diagnostics.Eventing.Reader
bool status = UnsafeNativeMethods.EvtSeek(resultSet, position, bookmark, timeout, flags);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
[System.Security.SecurityCritical]
@ -92,7 +130,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)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return win32Error == 0;
}
@ -102,7 +140,7 @@ namespace System.Diagnostics.Eventing.Reader
if (!UnsafeNativeMethods.EvtCancel(handle))
{
int win32Error = Marshal.GetLastWin32Error();
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
}
@ -133,7 +171,7 @@ namespace System.Diagnostics.Eventing.Reader
int win32Error = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return handle;
}
@ -144,7 +182,7 @@ namespace System.Diagnostics.Eventing.Reader
bool status = UnsafeNativeMethods.EvtGetObjectArraySize(objectArray, out arraySize);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return arraySize;
}
@ -154,7 +192,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle emEnumHandle = UnsafeNativeMethods.EvtOpenEventMetadataEnum(ProviderMetadata, flags);
int win32Error = Marshal.GetLastWin32Error();
if (emEnumHandle.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return emEnumHandle;
}
@ -168,7 +206,7 @@ namespace System.Diagnostics.Eventing.Reader
if (emHandle.IsInvalid)
{
if (win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return null;
}
@ -181,7 +219,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle channelEnum = UnsafeNativeMethods.EvtOpenChannelEnum(session, flags);
int win32Error = Marshal.GetLastWin32Error();
if (channelEnum.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return channelEnum;
}
@ -191,7 +229,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle pubEnum = UnsafeNativeMethods.EvtOpenPublisherEnum(session, flags);
int win32Error = Marshal.GetLastWin32Error();
if (pubEnum.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return pubEnum;
}
@ -201,7 +239,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle handle = UnsafeNativeMethods.EvtOpenChannelConfig(session, channelPath, flags);
int win32Error = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return handle;
}
@ -211,7 +249,7 @@ namespace System.Diagnostics.Eventing.Reader
bool status = UnsafeNativeMethods.EvtSaveChannelConfig(channelConfig, flags);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
[System.Security.SecurityCritical]
@ -220,7 +258,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle logHandle = UnsafeNativeMethods.EvtOpenLog(session, path, flags);
int win32Error = Marshal.GetLastWin32Error();
if (logHandle.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return logHandle;
}
@ -236,7 +274,7 @@ namespace System.Diagnostics.Eventing.Reader
status = UnsafeNativeMethods.EvtExportLog(session, channelPath, query, targetFilePath, flags);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
[System.Security.SecuritySafeCritical]
@ -250,7 +288,7 @@ namespace System.Diagnostics.Eventing.Reader
status = UnsafeNativeMethods.EvtArchiveExportedLog(session, logFilePath, locale, flags);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
[System.Security.SecuritySafeCritical]
@ -264,7 +302,7 @@ namespace System.Diagnostics.Eventing.Reader
status = UnsafeNativeMethods.EvtClearLog(session, channelPath, targetFilePath, flags);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
[System.Security.SecurityCritical]
@ -276,7 +314,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle renderContextHandleValues = UnsafeNativeMethods.EvtCreateRenderContext(valuePathsCount, valuePaths, flags);
int win32Error = Marshal.GetLastWin32Error();
if (renderContextHandleValues.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return renderContextHandleValues;
}
@ -304,7 +342,7 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
}
}
@ -315,7 +353,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle handle = UnsafeNativeMethods.EvtOpenSession(loginClass, ref login, timeout, flags);
int win32Error = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return handle;
}
@ -325,7 +363,7 @@ namespace System.Diagnostics.Eventing.Reader
EventLogHandle handle = UnsafeNativeMethods.EvtCreateBookmark(bookmarkXml);
int win32Error = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return handle;
}
@ -335,7 +373,7 @@ namespace System.Diagnostics.Eventing.Reader
bool status = UnsafeNativeMethods.EvtUpdateBookmark(bookmark, eventHandle);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
[System.Security.SecuritySafeCritical]
@ -353,14 +391,14 @@ namespace System.Diagnostics.Eventing.Reader
if (error == UnsafeNativeMethods.ERROR_SUCCESS) { }
else
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded);
error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(error);
ThrowEventLogException(error);
UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer);
return ConvertToObject(varVal);
@ -384,14 +422,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetQueryInfo(handle, enumType, bufferNeeded, buffer, ref bufferNeeded);
error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(error);
ThrowEventLogException(error);
UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer);
return ConvertToObject(varVal);
@ -415,14 +453,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded);
error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(error);
ThrowEventLogException(error);
UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer);
return ConvertToObject(varVal);
@ -445,14 +483,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded);
error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(error);
ThrowEventLogException(error);
//
// note: there is a case where returned variant does have allocated native resources
@ -496,7 +534,7 @@ namespace System.Diagnostics.Eventing.Reader
}
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
sb.EnsureCapacity(bufferNeeded);
@ -522,7 +560,7 @@ namespace System.Diagnostics.Eventing.Reader
return null;
}
EventLogException.Throw(error);
ThrowEventLogException(error);
}
return sb.ToString();
@ -542,14 +580,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetObjectArrayProperty(objArrayHandle, thePropertyId, index, 0, bufferNeeded, buffer, out bufferNeeded);
error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(error);
ThrowEventLogException(error);
UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer);
return ConvertToObject(varVal);
@ -573,14 +611,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetEventMetadataProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded);
win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer);
return ConvertToObject(varVal);
@ -605,14 +643,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetChannelConfigProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded);
win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
//
// note: there is a case where returned variant does have allocated native resources
@ -717,7 +755,7 @@ namespace System.Diagnostics.Eventing.Reader
bool status = UnsafeNativeMethods.EvtSetChannelConfigProperty(handle, enumType, 0, ref varVal);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
}
@ -738,14 +776,14 @@ namespace System.Diagnostics.Eventing.Reader
}
if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
sb.EnsureCapacity(channelNameNeeded);
status = UnsafeNativeMethods.EvtNextChannelPath(handle, channelNameNeeded, sb, out channelNameNeeded);
win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return sb.ToString();
}
@ -767,14 +805,14 @@ namespace System.Diagnostics.Eventing.Reader
}
if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
sb.EnsureCapacity(ProviderIdNeeded);
status = UnsafeNativeMethods.EvtNextPublisherId(handle, ProviderIdNeeded, sb, out ProviderIdNeeded);
win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
return sb.ToString();
}
@ -792,14 +830,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtGetLogInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded);
win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer);
return ConvertToObject(varVal);
@ -826,14 +864,14 @@ namespace System.Diagnostics.Eventing.Reader
{
int error = Marshal.GetLastWin32Error();
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
if (propCount != SYSTEM_PROPERTY_COUNT)
throw new InvalidOperationException("We do not have " + SYSTEM_PROPERTY_COUNT + " variants given for the UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues flag. (System Properties)");
@ -929,14 +967,14 @@ namespace System.Diagnostics.Eventing.Reader
{
int error = Marshal.GetLastWin32Error();
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount);
int win32Error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(win32Error);
ThrowEventLogException(win32Error);
List<object> valuesList = new List<object>(propCount);
if (propCount > 0)
@ -987,7 +1025,7 @@ namespace System.Diagnostics.Eventing.Reader
}
if (error != (int)UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
sb.EnsureCapacity(bufferNeeded);
@ -1006,7 +1044,7 @@ namespace System.Diagnostics.Eventing.Reader
return null;
}
EventLogException.Throw(error);
ThrowEventLogException(error);
}
return sb.ToString();
@ -1038,7 +1076,7 @@ namespace System.Diagnostics.Eventing.Reader
}
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal(bufferNeeded * 2);
@ -1056,7 +1094,7 @@ namespace System.Diagnostics.Eventing.Reader
return keywordsList;
}
EventLogException.Throw(error);
ThrowEventLogException(error);
}
IntPtr pointer = buffer;
@ -1095,14 +1133,14 @@ namespace System.Diagnostics.Eventing.Reader
if (!status)
{
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
buffer = Marshal.AllocHGlobal((int)bufferNeeded);
status = UnsafeNativeMethods.EvtRender(EventLogHandle.Zero, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount);
error = Marshal.GetLastWin32Error();
if (!status)
EventLogException.Throw(error);
ThrowEventLogException(error);
return Marshal.PtrToStringUni(buffer);
}
@ -1149,7 +1187,7 @@ namespace System.Diagnostics.Eventing.Reader
}
if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
EventLogException.Throw(error);
ThrowEventLogException(error);
}
sb.EnsureCapacity(bufferNeeded);
@ -1168,7 +1206,7 @@ namespace System.Diagnostics.Eventing.Reader
return null;
}
EventLogException.Throw(error);
ThrowEventLogException(error);
}
return sb.ToString();

View File

@ -1,599 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This public class exposes all the metadata for a specific
** Provider. An instance of this class is obtained from
** EventLogManagement and is scoped to a single Locale.
**
============================================================*/
using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Exposes all the metadata for a specific event Provider. An instance
/// of this class is obtained from EventLogManagement and is scoped to a
/// single Locale.
/// </summary>
public class ProviderMetadata : IDisposable
{
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private EventLogHandle _handle = EventLogHandle.Zero;
private EventLogHandle _defaultProviderHandle = EventLogHandle.Zero;
private EventLogSession _session = null;
private string _providerName;
private CultureInfo _cultureInfo;
private string _logFilePath;
// caching of the IEnumerable<EventLevel>, <EventTask>, <EventKeyword>, <EventOpcode> on the ProviderMetadata
// they do not change with every call.
private IList<EventLevel> _levels = null;
private IList<EventOpcode> _opcodes = null;
private IList<EventTask> _tasks = null;
private IList<EventKeyword> _keywords = null;
private IList<EventLevel> _standardLevels = null;
private IList<EventOpcode> _standardOpcodes = null;
private IList<EventTask> _standardTasks = null;
private IList<EventKeyword> _standardKeywords = null;
private IList<EventLogLink> _channelReferences = null;
private object _syncObject;
public ProviderMetadata(string providerName)
: this(providerName, null, null, null)
{
}
public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo)
: this(providerName, session, targetCultureInfo, null)
{
}
// SecurityCritical since it allocates SafeHandles.
// Marked TreatAsSafe since we perform the Demand check.
[System.Security.SecuritySafeCritical]
internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath)
{
if (targetCultureInfo == null)
targetCultureInfo = CultureInfo.CurrentCulture;
if (session == null)
session = EventLogSession.GlobalSession;
_session = session;
_providerName = providerName;
_cultureInfo = targetCultureInfo;
_logFilePath = logFilePath;
_handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0);
_syncObject = new object();
}
internal EventLogHandle Handle
{
get
{
return _handle;
}
}
public string Name
{
get { return _providerName; }
}
public Guid Id
{
get
{
return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid);
}
}
public string MessageFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath);
}
}
public string ResourceFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath);
}
}
public string ParameterFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath);
}
}
public Uri HelpLink
{
get
{
string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink);
if (helpLinkStr == null || helpLinkStr.Length == 0)
return null;
return new Uri(helpLinkStr);
}
}
private uint ProviderMessageID
{
get
{
return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID);
}
}
public string DisplayName
{
[System.Security.SecurityCritical]
get
{
uint msgId = (uint)this.ProviderMessageID;
if (msgId == 0xffffffff)
return null;
return NativeWrapper.EvtFormatMessage(_handle, msgId);
}
}
public IList<EventLogLink> LogLinks
{
[System.Security.SecurityCritical]
get
{
EventLogHandle elHandle = EventLogHandle.Zero;
try
{
lock (_syncObject)
{
if (_channelReferences != null)
return _channelReferences;
elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferences);
int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle);
List<EventLogLink> channelList = new List<EventLogLink>(arraySize);
for (int index = 0; index < arraySize; index++)
{
string channelName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath);
uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID);
uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags);
bool isImported;
if (flag == (int)UnsafeNativeMethods.EvtChannelReferenceFlags.EvtChannelReferenceImported) isImported = true;
else isImported = false;
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)
{
channelRefDisplayName = null;
}
else
{
channelRefDisplayName = NativeWrapper.EvtFormatMessage(_handle, unchecked((uint)channelRefMessageId));
}
if (channelRefDisplayName == null && isImported)
{
if (string.Compare(channelName, "Application", StringComparison.OrdinalIgnoreCase) == 0)
channelRefMessageId = 256;
else if (string.Compare(channelName, "System", StringComparison.OrdinalIgnoreCase) == 0)
channelRefMessageId = 258;
else if (string.Compare(channelName, "Security", StringComparison.OrdinalIgnoreCase) == 0)
channelRefMessageId = 257;
else
channelRefMessageId = -1;
if (channelRefMessageId != -1)
{
if (_defaultProviderHandle.IsInvalid)
{
_defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0);
}
channelRefDisplayName = NativeWrapper.EvtFormatMessage(_defaultProviderHandle, unchecked((uint)channelRefMessageId));
}
}
channelList.Add(new EventLogLink(channelName, isImported, channelRefDisplayName, channelId));
}
_channelReferences = channelList.AsReadOnly();
}
return _channelReferences;
}
finally
{
elHandle.Dispose();
}
}
}
internal enum ObjectTypeName
{
Level = 0,
Opcode = 1,
Task = 2,
Keyword = 3
}
internal string FindStandardLevelDisplayName(string name, uint value)
{
if (_standardLevels == null)
_standardLevels = (List<EventLevel>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
foreach (EventLevel standardLevel in _standardLevels)
{
if (standardLevel.Name == name && standardLevel.Value == value)
return standardLevel.DisplayName;
}
return null;
}
internal string FindStandardOpcodeDisplayName(string name, uint value)
{
if (_standardOpcodes == null)
_standardOpcodes = (List<EventOpcode>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
foreach (EventOpcode standardOpcode in _standardOpcodes)
{
if (standardOpcode.Name == name && standardOpcode.Value == value)
return standardOpcode.DisplayName;
}
return null;
}
internal string FindStandardKeywordDisplayName(string name, long value)
{
if (_standardKeywords == null)
_standardKeywords = (List<EventKeyword>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
foreach (EventKeyword standardKeyword in _standardKeywords)
{
if (standardKeyword.Name == name && standardKeyword.Value == value)
return standardKeyword.DisplayName;
}
return null;
}
internal string FindStandardTaskDisplayName(string name, uint value)
{
if (_standardTasks == null)
_standardTasks = (List<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
foreach (EventTask standardTask in _standardTasks)
{
if (standardTask.Name == name && standardTask.Value == value)
return standardTask.DisplayName;
}
return null;
}
[System.Security.SecuritySafeCritical]
internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty)
{
EventLogHandle elHandle = EventLogHandle.Zero;
try
{
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propName;
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propValue;
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propMessageId;
ObjectTypeName objectTypeName;
List<EventLevel> levelList = null;
List<EventOpcode> opcodeList = null;
List<EventKeyword> keywordList = null;
List<EventTask> taskList = null;
elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(providerHandle, metadataProperty);
int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle);
switch (metadataProperty)
{
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelMessageID;
objectTypeName = ObjectTypeName.Level;
levelList = new List<EventLevel>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeMessageID;
objectTypeName = ObjectTypeName.Opcode;
opcodeList = new List<EventOpcode>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordMessageID;
objectTypeName = ObjectTypeName.Keyword;
keywordList = new List<EventKeyword>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskMessageID;
objectTypeName = ObjectTypeName.Task;
taskList = new List<EventTask>(arraySize);
break;
default:
return null;
}
for (int index = 0; index < arraySize; index++)
{
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);
}
else
{
generalValueKeyword = unchecked((long)((ulong)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue)));
}
int generalMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propMessageId)));
string generalDisplayName = null;
if (generalMessageId == -1)
{
if (providerHandle != _defaultProviderHandle)
{
if (_defaultProviderHandle.IsInvalid)
{
_defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0);
}
switch (objectTypeName)
{
case ObjectTypeName.Level:
generalDisplayName = FindStandardLevelDisplayName(generalName, generalValue);
break;
case ObjectTypeName.Opcode:
generalDisplayName = FindStandardOpcodeDisplayName(generalName, generalValue >> 16);
break;
case ObjectTypeName.Keyword:
generalDisplayName = FindStandardKeywordDisplayName(generalName, generalValueKeyword);
break;
case ObjectTypeName.Task:
generalDisplayName = FindStandardTaskDisplayName(generalName, generalValue);
break;
default:
generalDisplayName = null;
break;
}
}
}
else
{
generalDisplayName = NativeWrapper.EvtFormatMessage(providerHandle, unchecked((uint)generalMessageId));
}
switch (objectTypeName)
{
case ObjectTypeName.Level:
levelList.Add(new EventLevel(generalName, (int)generalValue, generalDisplayName));
break;
case ObjectTypeName.Opcode:
opcodeList.Add(new EventOpcode(generalName, (int)(generalValue >> 16), generalDisplayName));
break;
case ObjectTypeName.Keyword:
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));
break;
default:
return null;
}
}
switch (objectTypeName)
{
case ObjectTypeName.Level:
return levelList;
case ObjectTypeName.Opcode:
return opcodeList;
case ObjectTypeName.Keyword:
return keywordList;
case ObjectTypeName.Task:
return taskList;
}
return null;
}
finally
{
elHandle.Dispose();
}
}
public IList<EventLevel> Levels
{
get
{
List<EventLevel> el;
lock (_syncObject)
{
if (_levels != null)
return _levels;
el = (List<EventLevel>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
_levels = el.AsReadOnly();
}
return _levels;
}
}
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcodes", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")]
public IList<EventOpcode> Opcodes
{
get
{
List<EventOpcode> eo;
lock (_syncObject)
{
if (_opcodes != null)
return _opcodes;
eo = (List<EventOpcode>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
_opcodes = eo.AsReadOnly();
}
return _opcodes;
}
}
public IList<EventKeyword> Keywords
{
get
{
List<EventKeyword> ek;
lock (_syncObject)
{
if (_keywords != null)
return _keywords;
ek = (List<EventKeyword>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
_keywords = ek.AsReadOnly();
}
return _keywords;
}
}
public IList<EventTask> Tasks
{
get
{
List<EventTask> et;
lock (_syncObject)
{
if (_tasks != null)
return _tasks;
et = (List<EventTask>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
_tasks = et.AsReadOnly();
}
return _tasks;
}
}
public IEnumerable<EventMetadata> Events
{
[System.Security.SecurityCritical]
get
{
List<EventMetadata> emList = new List<EventMetadata>();
EventLogHandle emEnumHandle = NativeWrapper.EvtOpenEventMetadataEnum(_handle, 0);
using (emEnumHandle)
{
while (true)
{
EventLogHandle emHandle = emHandle = NativeWrapper.EvtNextEventMetadata(emEnumHandle, 0);
if (emHandle == null)
break;
using (emHandle)
{
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)
? null
: NativeWrapper.EvtFormatMessage(_handle, (uint)messageId);
EventMetadata em = new EventMetadata(emId, emVersion, emChannelId, emLevel, emOpcode, emTask, emKeywords, emTemplate, emMessage, this);
emList.Add(em);
}
}
}
return emList.AsReadOnly();
}
}
}
// throws if Provider metadata has been uninstalled since this object was created.
internal void CheckReleased()
{
lock (_syncObject)
{
this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
}
}

View File

@ -1,312 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** This internal class exposes a limited set of cached Provider
** metadata information. It is meant to support the Metadata
**
============================================================*/
using System.Globalization;
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
//
// this class does not expose underlying Provider metadata objects. Instead it
// exposes a limited set of Provider metadata information from the cache. The reason
// for this is so the cache can easily Dispose the metadata object without worrying
// about who is using it.
//
internal class ProviderMetadataCachedInformation
{
private Dictionary<ProviderMetadataId, CacheItem> _cache;
private int _maximumCacheSize;
private EventLogSession _session;
private string _logfile;
private class ProviderMetadataId
{
private string _providerName;
private CultureInfo _cultureInfo;
public ProviderMetadataId(string providerName, CultureInfo cultureInfo)
{
_providerName = providerName;
_cultureInfo = cultureInfo;
}
public override bool Equals(object obj)
{
ProviderMetadataId rhs = obj as ProviderMetadataId;
if (rhs == null) return false;
if (_providerName.Equals(rhs._providerName) && (_cultureInfo == rhs._cultureInfo))
return true;
return false;
}
public override int GetHashCode()
{
return _providerName.GetHashCode() ^ _cultureInfo.GetHashCode();
}
public string ProviderName
{
get
{
return _providerName;
}
}
public CultureInfo TheCultureInfo
{
get
{
return _cultureInfo;
}
}
}
private class CacheItem
{
private ProviderMetadata _pm;
private DateTime _theTime;
public CacheItem(ProviderMetadata pm)
{
_pm = pm;
_theTime = DateTime.Now;
}
public DateTime TheTime
{
get
{
return _theTime;
}
set
{
_theTime = value;
}
}
public ProviderMetadata ProviderMetadata
{
get
{
return _pm;
}
}
}
public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize)
{
Debug.Assert(session != null);
_session = session;
_logfile = logfile;
_cache = new Dictionary<ProviderMetadataId, CacheItem>();
_maximumCacheSize = maximumCacheSize;
}
private bool IsCacheFull()
{
return _cache.Count == _maximumCacheSize;
}
private bool IsProviderinCache(ProviderMetadataId key)
{
return _cache.ContainsKey(key);
}
private void DeleteCacheEntry(ProviderMetadataId key)
{
if (!IsProviderinCache(key))
return;
CacheItem value = _cache[key];
_cache.Remove(key);
value.ProviderMetadata.Dispose();
}
private void AddCacheEntry(ProviderMetadataId key, ProviderMetadata pm)
{
if (IsCacheFull())
FlushOldestEntry();
CacheItem value = new CacheItem(pm);
_cache.Add(key, value);
return;
}
private void FlushOldestEntry()
{
double maxPassedTime = -10;
DateTime timeNow = DateTime.Now;
ProviderMetadataId keyToDelete = null;
// get the entry in the cache which was not accessed for the longest time.
foreach (KeyValuePair<ProviderMetadataId, CacheItem> kvp in _cache)
{
// the time difference (in ms) between the timeNow and the last used time of each entry
TimeSpan timeDifference = timeNow.Subtract(kvp.Value.TheTime);
// for the "unused" items (with ReferenceCount == 0) -> can possible be deleted.
if (timeDifference.TotalMilliseconds >= maxPassedTime)
{
maxPassedTime = timeDifference.TotalMilliseconds;
keyToDelete = kvp.Key;
}
}
if (keyToDelete != null)
DeleteCacheEntry(keyToDelete);
}
private static void UpdateCacheValueInfoForHit(CacheItem cacheItem)
{
cacheItem.TheTime = DateTime.Now;
}
private ProviderMetadata GetProviderMetadata(ProviderMetadataId key)
{
if (!IsProviderinCache(key))
{
ProviderMetadata pm;
try
{
pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile);
}
catch (EventLogNotFoundException)
{
pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo);
}
AddCacheEntry(key, pm);
return pm;
}
else
{
CacheItem cacheItem = _cache[key];
ProviderMetadata pm = cacheItem.ProviderMetadata;
//
// check Provider metadata to be sure it's hasn't been
// uninstalled since last time it was used.
//
try
{
pm.CheckReleased();
UpdateCacheValueInfoForHit(cacheItem);
}
catch (EventLogException)
{
DeleteCacheEntry(key);
try
{
pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile);
}
catch (EventLogNotFoundException)
{
pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo);
}
AddCacheEntry(key, pm);
}
return pm;
}
}
// marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe.
[System.Security.SecuritySafeCritical]
public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle)
{
lock (this)
{
ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture);
try
{
ProviderMetadata pm = GetProviderMetadata(key);
return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent);
}
catch (EventLogNotFoundException)
{
return null;
}
}
}
public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values)
{
lock (this)
{
ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture);
ProviderMetadata pm = GetProviderMetadata(key);
try
{
return NativeWrapper.EvtFormatMessageFormatDescription(pm.Handle, eventHandle, values);
}
catch (EventLogNotFoundException)
{
return null;
}
}
}
// marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe.
[System.Security.SecuritySafeCritical]
public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle)
{
lock (this)
{
ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture);
ProviderMetadata pm = GetProviderMetadata(key);
return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageLevel);
}
}
// marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe.
[System.Security.SecuritySafeCritical]
public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle)
{
lock (this)
{
ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture);
ProviderMetadata pm = GetProviderMetadata(key);
return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageOpcode);
}
}
// marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe.
[System.Security.SecuritySafeCritical]
public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle)
{
lock (this)
{
ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture);
ProviderMetadata pm = GetProviderMetadata(key);
return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageTask);
}
}
// marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe.
[System.Security.SecuritySafeCritical]
public IEnumerable<string> GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle)
{
lock (this)
{
ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture);
ProviderMetadata pm = GetProviderMetadata(key);
return NativeWrapper.EvtFormatMessageRenderKeywords(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageKeyword);
}
}
}
}

View File

@ -1,158 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*============================================================
**
**
** Purpose:
** Contains eventing constants defined by the Windows
** environment.
**
============================================================*/
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// WindowsEventLevel.
/// </summary>
public enum StandardEventLevel
{
/// <summary>
/// Log always.
/// </summary>
LogAlways = 0,
/// <summary>
/// Only critical errors.
/// </summary>
Critical,
/// <summary>
/// All errors, including previous levels.
/// </summary>
Error,
/// <summary>
/// All warnings, including previous levels.
/// </summary>
Warning,
/// <summary>
/// All informational events, including previous levels.
/// </summary>
Informational,
/// <summary>
/// All events, including previous levels.
/// </summary>
Verbose
}
/// <summary>
/// WindowsEventTask.
/// </summary>
public enum StandardEventTask
{
/// <summary>
/// Undefined task.
/// </summary>
None = 0
}
/// <summary>
/// EventOpcode.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")]
public enum StandardEventOpcode
{
/// <summary>
/// An informational event.
/// </summary>
Info = 0,
/// <summary>
/// An activity start event.
/// </summary>
Start,
/// <summary>
/// An activity end event.
/// </summary>
Stop,
/// <summary>
/// A trace collection start event.
/// </summary>
DataCollectionStart,
/// <summary>
/// A trace collection end event.
/// </summary>
DataCollectionStop,
/// <summary>
/// An extensional event.
/// </summary>
Extension,
/// <summary>
/// A reply event.
/// </summary>
Reply,
/// <summary>
/// An event representing the activity resuming from the suspension.
/// </summary>
Resume,
/// <summary>
/// An event representing the activity is suspended, pending another activity's completion.
/// </summary>
Suspend,
/// <summary>
/// An event representing the activity is transferred to another component, and can continue to work.
/// </summary>
Send,
/// <summary>
/// An event representing receiving an activity transfer from another component.
/// </summary>
Receive = 240
}
/// <summary>
/// EventOpcode.
/// </summary>
[Flags]
public enum StandardEventKeywords : long
{
/// <summary>
/// Wild card value.
/// </summary>
None = 0x0,
/// <summary>
/// Events providing response time information.
/// </summary>
ResponseTime = 0x01000000000000,
/// <summary>
/// WDI context events.
/// </summary>
WdiContext = 0x02000000000000,
/// <summary>
/// WDI diagnostic events.
/// </summary>
WdiDiagnostic = 0x04000000000000,
/// <summary>
/// SQM events.
/// </summary>
Sqm = 0x08000000000000,
/// <summary>
/// FAiled security audits.
/// </summary>
AuditFailure = 0x10000000000000,
/// <summary>
/// Successful security audits.
/// </summary>
AuditSuccess = 0x20000000000000,
/// <summary>
/// Incorrect CorrelationHint value mistakenly shipped in .NET 3.5. Don't use: duplicates AuditFailure.
/// </summary>
[Obsolete("Incorrect value: use CorrelationHint2 instead", false)]
CorrelationHint = 0x10000000000000,
/// <summary>
/// Transfer events where the related Activity ID is a computed value and not a GUID.
/// </summary>
CorrelationHint2 = 0x40000000000000,
/// <summary>
/// Events raised using classic eventlog API.
/// </summary>
EventLogClassic = 0x80000000000000
}
}

View File

@ -8,7 +8,7 @@
<ItemGroup>
<!-- the following package(s) are from https://github.com/dotnet/corefx -->
<PackageReference Include="System.Security.Principal.Windows" Version="4.6.0-preview7.19362.9" />
<PackageReference Include="System.Diagnostics.EventLog" Version="4.6.0-preview7.19362.9" />
</ItemGroup>
</Project>

View File

@ -30,7 +30,7 @@
<PackageReference Include="System.Private.ServiceModel" Version="4.6.0-preview6.final" />
<!-- the source could not be found for the following package(s) -->
<PackageReference Include="Microsoft.NETCore.Windows.ApiSets" Version="1.0.1" />
<PackageReference Include="Microsoft.Windows.Compatibility" Version="2.1.1" />
<PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0-preview7.19362.9" />
</ItemGroup>
</Project>

View File

@ -9,7 +9,7 @@
<ProjectReference Include="..\System.Management.Automation\System.Management.Automation.csproj" />
<ProjectReference Include="..\Microsoft.WSMan.Runtime\Microsoft.WSMan.Runtime.csproj" />
<!-- the following package(s) are from https://github.com/dotnet/corefx -->
<PackageReference Include="System.ServiceProcess.ServiceController" Version="4.5.0" />
<PackageReference Include="System.ServiceProcess.ServiceController" Version="4.6.0-preview7.19362.9" />
</ItemGroup>
<PropertyGroup>

View File

@ -6,8 +6,11 @@
<AssemblyName>System.Management.Automation</AssemblyName>
</PropertyGroup>
<ItemGroup>
<ItemGroup Condition=" '$(IsWindows)' == 'true' ">
<ProjectReference Include="..\Microsoft.PowerShell.CoreCLR.Eventing\Microsoft.PowerShell.CoreCLR.Eventing.csproj" />
</ItemGroup>
<ItemGroup>
<!-- the following package(s) are from https://github.com/JamesNK/Newtonsoft.Json -->
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<!-- the following package(s) are from https://github.com/dotnet/corefx -->

View File

@ -336,9 +336,8 @@ Describe "Set/New/Remove-Service cmdlet tests" -Tags "Feature", "RequireAdminOnW
Name = $servicename;
BinaryPathName = "$PSHOME\pwsh.exe"
}
$service = New-Service @parameters
$service | Should -Not -BeNullOrEmpty
$script = { Set-Service $service -DisplayName $newdisplayname }
$script = { New-Service @parameters | Set-Service -DisplayName $newdisplayname }
{ & $script } | Should -Not -Throw
$service = Get-Service -Name $servicename
$service.DisplayName | Should -BeExactly $newdisplayname