#if NET20
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Event methods and classes literally pulled from the .NET 4.0 implementation.
* None of this is original work. It comes straight from decompiled Microsoft
* assemblies.
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
namespace System.Diagnostics.Eventing.Reader
{
///
/// PathType
///
public enum PathType
{
///
/// The file path
///
FilePath = 2,
///
/// The log name
///
LogName = 1
}
///
/// SessionAuthentication
///
public enum SessionAuthentication
{
///
/// The default
///
Default,
///
/// The negotiate
///
Negotiate,
///
/// The kerberos
///
Kerberos,
///
/// The NTLM
///
Ntlm
}
///
///
///
public enum EventLogIsolation
{
///
/// The application
///
Application,
///
/// The system
///
System,
///
/// The custom
///
Custom
}
///
///
///
public enum EventLogMode
{
///
/// The circular
///
Circular,
///
/// The automatic backup
///
AutoBackup,
///
/// The retain
///
Retain
}
///
///
///
public enum EventLogType
{
///
/// The administrative
///
Administrative,
///
/// The operational
///
Operational,
///
/// The analytical
///
Analytical,
///
/// The debug
///
Debug
}
///
/// Defines the standard keywords that are attached to events by the event provider. For more information about keywords, see .
///
[Flags]
public enum StandardEventKeywords : long
{
///
/// The audit failure
///
AuditFailure = 0x10000000000000L,
///
/// The audit success
///
AuditSuccess = 0x20000000000000L,
///
/// The correlation hint
///
[Obsolete("Incorrect value: use CorrelationHint2 instead", false)]
CorrelationHint = 0x10000000000000L,
///
/// The correlation hint2
///
CorrelationHint2 = 0x40000000000000L,
///
/// The event log classic
///
EventLogClassic = 0x80000000000000L,
///
/// The none
///
None = 0L,
///
/// The response time
///
ResponseTime = 0x01000000000000L,
///
/// The SQM
///
Sqm = 0x08000000000000L,
///
/// The wdi context
///
WdiContext = 0x02000000000000L,
///
/// The wdi diagnostic
///
WdiDiagnostic = 0x04000000000000L
}
///
/// Represents a placeholder (bookmark) within an event stream. You can use the placeholder to mark a position and return to this position in a stream of events. An instance of this object can be obtained from an EventRecord object, in which case it corresponds to the position of that event record.
///
[Serializable, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public class EventBookmark : ISerializable
{
// Fields
private string bookmark;
// Methods
internal EventBookmark(string bookmarkText)
{
if (bookmarkText == null)
{
throw new ArgumentNullException("bookmarkText");
}
this.bookmark = bookmarkText;
}
///
/// Initializes a new instance of the class.
///
/// The information.
/// The context.
protected EventBookmark(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
this.bookmark = info.GetString("BookmarkText");
}
// Properties
internal string BookmarkText
{
get
{
return this.bookmark;
}
}
[SecurityCritical, SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
this.GetObjectData(info, context);
}
///
/// Gets the object data.
///
/// The information.
/// The context.
[SecurityCritical, SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("BookmarkText", this.bookmark);
}
}
///
/// Represents a keyword for an event. Keywords are defined in an event provider and are used to group the event with other similar events (based on the usage of the events).
///
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class EventKeyword
{
// Fields
private bool dataReady;
private string displayName;
private string name;
private ProviderMetadata pmReference;
private object syncObject;
private long value;
// Methods
internal EventKeyword(long value, ProviderMetadata pmReference)
{
this.value = value;
this.pmReference = pmReference;
this.syncObject = new object();
}
internal EventKeyword(string name, long value, string displayName)
{
this.value = value;
this.name = name;
this.displayName = displayName;
this.dataReady = true;
this.syncObject = new object();
}
// Properties
///
/// Gets the display name.
///
///
/// The display name.
///
public string DisplayName
{
get
{
this.PrepareData();
return this.displayName;
}
}
///
/// Gets the name.
///
///
/// The name.
///
public string Name
{
get
{
this.PrepareData();
return this.name;
}
}
///
/// Gets the value.
///
///
/// The value.
///
public long Value
{
get
{
return this.value;
}
}
internal void PrepareData()
{
if (!this.dataReady)
{
lock (this.syncObject)
{
if (!this.dataReady)
{
IEnumerable keywords = this.pmReference.Keywords;
this.name = null;
this.displayName = null;
this.dataReady = true;
foreach (EventKeyword keyword in keywords)
{
if (keyword.Value == this.value)
{
this.name = keyword.Name;
this.displayName = keyword.DisplayName;
break;
}
}
}
}
}
}
}
///
/// Contains an event level that is defined in an event provider. The level signifies the severity of the event.
///
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class EventLevel
{
// Fields
private bool dataReady;
private string displayName;
private string name;
private ProviderMetadata pmReference;
private object syncObject;
private int value;
// Methods
internal EventLevel(int value, ProviderMetadata pmReference)
{
this.value = value;
this.pmReference = pmReference;
this.syncObject = new object();
}
internal EventLevel(string name, int value, string displayName)
{
this.value = value;
this.name = name;
this.displayName = displayName;
this.dataReady = true;
this.syncObject = new object();
}
// Properties
///
/// Gets the display name.
///
///
/// The display name.
///
public string DisplayName
{
get
{
this.PrepareData();
return this.displayName;
}
}
///
/// Gets the name.
///
///
/// The name.
///
public string Name
{
get
{
this.PrepareData();
return this.name;
}
}
///
/// Gets the value.
///
///
/// The value.
///
public int Value
{
get
{
return this.value;
}
}
internal void PrepareData()
{
if (!this.dataReady)
{
lock (this.syncObject)
{
if (!this.dataReady)
{
IEnumerable levels = this.pmReference.Levels;
this.name = null;
this.displayName = null;
this.dataReady = true;
foreach (EventLevel level in levels)
{
if (level.Value == this.value)
{
this.name = level.Name;
this.displayName = level.DisplayName;
break;
}
}
}
}
}
}
}
///
/// EventLogConfiguration
///
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public class EventLogConfiguration : IDisposable
{
private string channelName;
private EventLogHandle handle;
private EventLogSession session;
///
/// Initializes a new instance of the class.
///
/// Name of the log.
public EventLogConfiguration(string logName) : this(logName, null) { }
///
/// Initializes a new instance of the class.
///
/// Name of the log.
/// The session.
[SecurityCritical]
public EventLogConfiguration(string logName, EventLogSession session)
{
this.handle = EventLogHandle.Zero;
EventLogPermissionHolder.GetEventLogPermission().Demand();
if (session == null)
{
session = EventLogSession.GlobalSession;
}
this.session = session;
this.channelName = logName;
this.handle = NativeWrapper.EvtOpenChannelConfig(this.session.Handle, this.channelName, 0);
}
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Releases unmanaged and - optionally - managed resources.
///
/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
[SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
}
if ((this.handle != null) && !this.handle.IsInvalid)
{
this.handle.Dispose();
}
}
///
/// Saves the changes.
///
public void SaveChanges()
{
NativeWrapper.EvtSaveChannelConfig(this.handle, 0);
}
// Properties
///
/// Gets a value indicating whether this instance is classic log.
///
///
/// true if this instance is classic log; otherwise, false.
///
public bool IsClassicLog
{
get
{
return (bool)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog);
}
}
///
/// Gets or sets a value indicating whether this instance is enabled.
///
///
/// true if this instance is enabled; otherwise, false.
///
public bool IsEnabled
{
get
{
return (bool)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, value);
}
}
///
/// Gets or sets the log file path.
///
///
/// The log file path.
///
public string LogFilePath
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, value);
}
}
///
/// Gets the log isolation.
///
///
/// The log isolation.
///
public EventLogIsolation LogIsolation
{
get
{
return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation));
}
}
///
/// Gets or sets the log mode.
///
///
/// The log mode.
///
public EventLogMode LogMode
{
get
{
object obj2 = NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention);
object obj3 = NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup);
bool flag = (obj2 != null) && ((bool)obj2);
if ((obj3 != null) && ((bool)obj3))
{
return EventLogMode.AutoBackup;
}
if (flag)
{
return EventLogMode.Retain;
}
return EventLogMode.Circular;
}
set
{
switch (value)
{
case EventLogMode.Circular:
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, false);
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, false);
return;
case EventLogMode.AutoBackup:
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, true);
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, true);
return;
case EventLogMode.Retain:
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, false);
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, true);
return;
}
}
}
///
/// Gets the name of the log.
///
///
/// The name of the log.
///
public string LogName
{
get
{
return this.channelName;
}
}
///
/// Gets the type of the log.
///
///
/// The type of the log.
///
public EventLogType LogType
{
get
{
return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType));
}
}
///
/// Gets or sets the maximum size in bytes.
///
///
/// The maximum size in bytes.
///
public long MaximumSizeInBytes
{
get
{
return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize));
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, value);
}
}
///
/// Gets the name of the owning provider.
///
///
/// The name of the owning provider.
///
public string OwningProviderName
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher);
}
}
///
/// Gets the size of the provider buffer.
///
///
/// The size of the provider buffer.
///
public int? ProviderBufferSize
{
get
{
uint? nullable = (uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigBufferSize);
if (!nullable.HasValue)
{
return null;
}
return new int?((int)nullable.GetValueOrDefault());
}
}
///
/// Gets the provider control unique identifier.
///
///
/// The provider control unique identifier.
///
public Guid? ProviderControlGuid
{
get
{
return (Guid?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigControlGuid);
}
}
///
/// Gets or sets the provider keywords.
///
///
/// The provider keywords.
///
public long? ProviderKeywords
{
get
{
ulong? nullable = (ulong?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords);
if (!nullable.HasValue)
{
return null;
}
return new long?((long)nullable.GetValueOrDefault());
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, value);
}
}
///
/// Gets the provider latency.
///
///
/// The provider latency.
///
public int? ProviderLatency
{
get
{
uint? nullable = (uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLatency);
if (!nullable.HasValue)
{
return null;
}
return new int?((int)nullable.GetValueOrDefault());
}
}
///
/// Gets or sets the provider level.
///
///
/// The provider level.
///
public int? ProviderLevel
{
get
{
uint? nullable = (uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel);
if (!nullable.HasValue)
{
return null;
}
return new int?((int)nullable.GetValueOrDefault());
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, value);
}
}
///
/// Gets the provider maximum number of buffers.
///
///
/// The provider maximum number of buffers.
///
public int? ProviderMaximumNumberOfBuffers
{
get
{
uint? nullable = (uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMaxBuffers);
if (!nullable.HasValue)
{
return null;
}
return new int?((int)nullable.GetValueOrDefault());
}
}
///
/// Gets the provider minimum number of buffers.
///
///
/// The provider minimum number of buffers.
///
public int? ProviderMinimumNumberOfBuffers
{
get
{
uint? nullable = (uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMinBuffers);
if (!nullable.HasValue)
{
return null;
}
return new int?((int)nullable.GetValueOrDefault());
}
}
///
/// Gets the provider names.
///
///
/// The provider names.
///
public IEnumerable ProviderNames
{
get
{
return (string[])NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList);
}
}
///
/// Gets or sets the security descriptor.
///
///
/// The security descriptor.
///
public string SecurityDescriptor
{
get
{
return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess);
}
set
{
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, value);
}
}
}
[Serializable, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal class EventLogException : Exception, ISerializable
{
// Fields
private int errorCode;
// Methods
public EventLogException()
{
}
public EventLogException(string message)
: base(message)
{
}
public EventLogException(string message, Exception innerException)
: base(message, innerException)
{
}
protected EventLogException(int errorCode)
{
this.errorCode = errorCode;
}
protected EventLogException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
// Properties
public override string Message
{
[SecurityCritical]
get
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
Win32Exception exception = new Win32Exception(this.errorCode);
return exception.Message;
}
}
[SecurityCritical, SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("errorCode", this.errorCode);
base.GetObjectData(info, context);
}
internal static void Throw(int errorCode)
{
switch (errorCode)
{
case 0x4c7:
case 0x71a:
throw new OperationCanceledException();
case 2:
case 3:
case 0x3a9f:
case 0x3a9a:
case 0x3ab3:
case 0x3ab4:
throw new EventLogNotFoundException(errorCode);
case 5:
throw new UnauthorizedAccessException();
case 13:
case 0x3a9d:
throw new EventLogInvalidDataException(errorCode);
case 0x3aa3:
case 0x3aa4:
throw new EventLogReadingException(errorCode);
case 0x3abd:
throw new EventLogProviderDisabledException(errorCode);
}
throw new EventLogException(errorCode);
}
}
///
/// Allows you to access the run-time properties of active event logs and event log files. These properties include the number of events in the log, the size of the log, a value that determines whether the log is full, and the last time the log was written to or accessed.
///
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class EventLogInformation
{
// Fields
private DateTime? creationTime;
private int? fileAttributes;
private long? fileSize;
private bool? isLogFull;
private DateTime? lastAccessTime;
private DateTime? lastWriteTime;
private long? oldestRecordNumber;
private long? recordCount;
// Methods
[SecurityTreatAsSafe, SecurityCritical]
internal EventLogInformation(EventLogSession session, string channelName, PathType pathType)
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
EventLogHandle handle = NativeWrapper.EvtOpenLog(session.Handle, channelName, pathType);
using (handle)
{
this.creationTime = (DateTime?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogCreationTime);
this.lastAccessTime = (DateTime?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastAccessTime);
this.lastWriteTime = (DateTime?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastWriteTime);
ulong? nullable = (ulong?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFileSize);
this.fileSize = nullable.HasValue ? (long?)(nullable.GetValueOrDefault()) : null;
uint? nullable3 = (uint?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogAttributes);
this.fileAttributes = nullable3.HasValue ? (int?)(nullable3.GetValueOrDefault()) : null;
ulong? nullable5 = (ulong?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogNumberOfLogRecords);
this.recordCount = nullable5.HasValue ? (long?)(nullable5.GetValueOrDefault()) : null;
ulong? nullable7 = (ulong?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogOldestRecordNumber);
this.oldestRecordNumber = nullable7.HasValue ? (long?)(nullable7.GetValueOrDefault()) : null;
this.isLogFull = (bool?)NativeWrapper.EvtGetLogInfo(handle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFull);
}
}
// Properties
///
/// Gets the attributes.
///
///
/// The attributes.
///
public int? Attributes
{
get
{
return this.fileAttributes;
}
}
///
/// Gets the creation time.
///
///
/// The creation time.
///
public DateTime? CreationTime
{
get
{
return this.creationTime;
}
}
///
/// Gets the size of the file.
///
///
/// The size of the file.
///
public long? FileSize
{
get
{
return this.fileSize;
}
}
///
/// Gets the is log full.
///
///
/// The is log full.
///
public bool? IsLogFull
{
get
{
return this.isLogFull;
}
}
///
/// Gets the last access time.
///
///
/// The last access time.
///
public DateTime? LastAccessTime
{
get
{
return this.lastAccessTime;
}
}
///
/// Gets the last write time.
///
///
/// The last write time.
///
public DateTime? LastWriteTime
{
get
{
return this.lastWriteTime;
}
}
///
/// Gets the oldest record number.
///
///
/// The oldest record number.
///
public long? OldestRecordNumber
{
get
{
return this.oldestRecordNumber;
}
}
///
/// Gets the record count.
///
///
/// The record count.
///
public long? RecordCount
{
get
{
return this.recordCount;
}
}
}
[Serializable, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal class EventLogInvalidDataException : EventLogException
{
// Methods
public EventLogInvalidDataException()
{
}
public EventLogInvalidDataException(string message)
: base(message)
{
}
public EventLogInvalidDataException(string message, Exception innerException)
: base(message, innerException)
{
}
internal EventLogInvalidDataException(int errorCode)
: base(errorCode)
{
}
protected EventLogInvalidDataException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
///
/// Represents a link between an event provider and an event log that the provider publishes events into. This object cannot be instantiated.
///
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class EventLogLink
{
// Fields
private uint channelId;
private string channelName;
private bool dataReady;
private string displayName;
private bool isImported;
private ProviderMetadata pmReference;
private object syncObject;
// Methods
internal EventLogLink(uint channelId, ProviderMetadata pmReference)
{
this.channelId = channelId;
this.pmReference = pmReference;
this.syncObject = new object();
}
internal EventLogLink(string channelName, bool isImported, string displayName, uint channelId)
{
this.channelName = channelName;
this.isImported = isImported;
this.displayName = displayName;
this.channelId = channelId;
this.dataReady = true;
this.syncObject = new object();
}
///
/// Gets the display name.
///
///
/// The display name.
///
public string DisplayName
{
get
{
this.PrepareData();
return this.displayName;
}
}
///
/// Gets a value indicating whether this instance is imported.
///
///
/// true if this instance is imported; otherwise, false.
///
public bool IsImported
{
get
{
this.PrepareData();
return this.isImported;
}
}
///
/// Gets the name of the log.
///
///
/// The name of the log.
///
public string LogName
{
get
{
this.PrepareData();
return this.channelName;
}
}
// Properties
internal uint ChannelId
{
get
{
return this.channelId;
}
}
private void PrepareData()
{
if (!this.dataReady)
{
lock (this.syncObject)
{
if (!this.dataReady)
{
IEnumerable logLinks = this.pmReference.LogLinks;
this.channelName = null;
this.isImported = false;
this.displayName = null;
this.dataReady = true;
foreach (EventLogLink link in logLinks)
{
if (link.ChannelId == this.channelId)
{
this.channelName = link.LogName;
this.isImported = link.IsImported;
this.displayName = link.DisplayName;
this.dataReady = true;
break;
}
}
}
}
}
}
}
[Serializable, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal class EventLogNotFoundException : EventLogException
{
// Methods
public EventLogNotFoundException()
{
}
public EventLogNotFoundException(string message)
: base(message)
{
}
public EventLogNotFoundException(string message, Exception innerException)
: base(message, innerException)
{
}
internal EventLogNotFoundException(int errorCode)
: base(errorCode)
{
}
protected EventLogNotFoundException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
///
/// Contains an array of strings that represent XPath queries for elements in the XML representation of an event, which is based on the Event Schema. The queries in this object are used to extract values from the event.
///
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public class EventLogPropertySelector : IDisposable
{
// Fields
private EventLogHandle renderContextHandleValues;
// Methods
///
/// Initializes a new instance of the class.
///
/// The property queries.
[SecurityCritical]
public EventLogPropertySelector(IEnumerable propertyQueries)
{
string[] strArray;
EventLogPermissionHolder.GetEventLogPermission().Demand();
if (propertyQueries == null)
{
throw new ArgumentNullException("propertyQueries");
}
ICollection is2 = propertyQueries as ICollection;
if (is2 != null)
{
strArray = new string[is2.Count];
is2.CopyTo(strArray, 0);
}
else
{
strArray = new List(propertyQueries).ToArray();
}
this.renderContextHandleValues = NativeWrapper.EvtCreateRenderContext(strArray.Length, strArray, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextValues);
}
// Properties
internal EventLogHandle Handle
{
get
{
return this.renderContextHandleValues;
}
}
///
/// Releases unmanaged and - optionally - managed resources.
///
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Releases unmanaged and - optionally - managed resources.
///
/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
[SecurityTreatAsSafe, SecurityCritical]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
}
if ((this.renderContextHandleValues != null) && !this.renderContextHandleValues.IsInvalid)
{
this.renderContextHandleValues.Dispose();
}
}
}
[Serializable, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal class EventLogProviderDisabledException : EventLogException
{
// Methods
public EventLogProviderDisabledException()
{
}
public EventLogProviderDisabledException(string message)
: base(message)
{
}
public EventLogProviderDisabledException(string message, Exception innerException)
: base(message, innerException)
{
}
internal EventLogProviderDisabledException(int errorCode)
: base(errorCode)
{
}
protected EventLogProviderDisabledException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
internal class EventLogQuery
{
// Fields
private string path;
private PathType pathType;
private string query;
private bool reverseDirection;
private EventLogSession session;
private bool tolerateErrors;
// Methods
public EventLogQuery(string path, PathType pathType)
: this(path, pathType, null)
{
}
public EventLogQuery(string path, PathType pathType, string query)
{
this.session = EventLogSession.GlobalSession;
this.path = path;
this.pathType = pathType;
if (query == null)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
}
else
{
this.query = query;
}
}
public bool ReverseDirection
{
get
{
return this.reverseDirection;
}
set
{
this.reverseDirection = value;
}
}
public EventLogSession Session
{
get
{
return this.session;
}
set
{
this.session = value;
}
}
public bool TolerateQueryErrors
{
get
{
return this.tolerateErrors;
}
set
{
this.tolerateErrors = value;
}
}
// Properties
internal string Path
{
get
{
return this.path;
}
}
internal string Query
{
get
{
return this.query;
}
}
internal PathType ThePathType
{
get
{
return this.pathType;
}
}
}
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true), HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal class EventLogReader : IDisposable
{
// Fields
private int batchSize;
private ProviderMetadataCachedInformation cachedMetadataInformation;
private int currentIndex;
private int eventCount;
private EventLogQuery eventQuery;
private IntPtr[] eventsBuffer;
private EventLogHandle handle;
private bool isEof;
// Methods
public EventLogReader(EventLogQuery eventQuery)
: this(eventQuery, null)
{
}
public EventLogReader(string path)
: this(new EventLogQuery(path, PathType.LogName), null)
{
}
[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;
}
this.cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, logfile, 50);
this.eventQuery = eventQuery;
this.batchSize = 0x40;
this.eventsBuffer = new IntPtr[this.batchSize];
int flags = 0;
if (this.eventQuery.ThePathType == PathType.LogName)
{
flags |= 1;
}
else
{
flags |= 2;
}
if (this.eventQuery.ReverseDirection)
{
flags |= 0x200;
}
if (this.eventQuery.TolerateQueryErrors)
{
flags |= 0x1000;
}
EventLogPermissionHolder.GetEventLogPermission().Demand();
this.handle = NativeWrapper.EvtQuery(this.eventQuery.Session.Handle, this.eventQuery.Path, this.eventQuery.Query, flags);
EventLogHandle bookmarkHandleFromBookmark = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark);
if (!bookmarkHandleFromBookmark.IsInvalid)
{
using (bookmarkHandleFromBookmark)
{
NativeWrapper.EvtSeek(this.handle, 1L, bookmarkHandleFromBookmark, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
}
public EventLogReader(string path, PathType pathType)
: this(new EventLogQuery(path, pathType), null)
{
}
// Properties
public int BatchSize
{
get
{
return this.batchSize;
}
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException("value");
}
this.batchSize = value;
}
}
public IList LogStatus
{
[SecurityCritical]
get
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
List list = null;
string[] strArray = null;
int[] numArray = null;
EventLogHandle handle = this.handle;
if (handle.IsInvalid)
{
throw new InvalidOperationException();
}
strArray = (string[])NativeWrapper.EvtGetQueryInfo(handle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames);
numArray = (int[])NativeWrapper.EvtGetQueryInfo(handle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses);
if (strArray.Length != numArray.Length)
{
throw new InvalidOperationException();
}
list = new List(strArray.Length);
for (int i = 0; i < strArray.Length; i++)
{
EventLogStatus item = new EventLogStatus(strArray[i], numArray[i]);
list.Add(item);
}
return list.AsReadOnly();
}
}
public void CancelReading()
{
NativeWrapper.EvtCancel(this.handle);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public EventRecord ReadEvent()
{
return this.ReadEvent(TimeSpan.MaxValue);
}
[SecurityCritical]
public EventRecord ReadEvent(TimeSpan timeout)
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
if (this.isEof)
{
throw new InvalidOperationException();
}
if (this.currentIndex >= this.eventCount)
{
this.GetNextBatch(timeout);
if (this.currentIndex >= this.eventCount)
{
this.isEof = true;
return null;
}
}
EventLogRecord record = new EventLogRecord(new EventLogHandle(this.eventsBuffer[this.currentIndex], true), this.eventQuery.Session, this.cachedMetadataInformation);
this.currentIndex++;
return record;
}
public void Seek(EventBookmark bookmark)
{
this.Seek(bookmark, 0L);
}
[SecurityCritical]
public void Seek(EventBookmark bookmark, long offset)
{
if (bookmark == null)
{
throw new ArgumentNullException("bookmark");
}
EventLogPermissionHolder.GetEventLogPermission().Demand();
this.SeekReset();
using (EventLogHandle handle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark))
{
NativeWrapper.EvtSeek(this.handle, offset, handle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
[SecurityCritical]
public void Seek(SeekOrigin origin, long offset)
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
switch (origin)
{
case SeekOrigin.Begin:
this.SeekReset();
NativeWrapper.EvtSeek(this.handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToFirst);
return;
case SeekOrigin.Current:
if (offset < 0L)
{
if ((this.currentIndex + offset) >= 0L)
{
this.SeekCommon(offset);
}
else
{
this.SeekCommon(offset);
}
return;
}
if ((this.currentIndex + offset) >= this.eventCount)
{
this.SeekCommon(offset);
return;
}
for (int i = this.currentIndex; i < (this.currentIndex + offset); i++)
{
NativeWrapper.EvtClose(this.eventsBuffer[i]);
}
this.currentIndex += (int)offset;
return;
case SeekOrigin.End:
this.SeekReset();
NativeWrapper.EvtSeek(this.handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToLast);
return;
}
}
[SecurityCritical]
internal void SeekCommon(long offset)
{
offset -= this.eventCount - this.currentIndex;
this.SeekReset();
NativeWrapper.EvtSeek(this.handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToCurrent);
}
[SecurityCritical]
internal void SeekReset()
{
while (this.currentIndex < this.eventCount)
{
NativeWrapper.EvtClose(this.eventsBuffer[this.currentIndex]);
this.currentIndex++;
}
this.currentIndex = 0;
this.eventCount = 0;
this.isEof = false;
}
[SecurityCritical, SecurityTreatAsSafe]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
}
while (this.currentIndex < this.eventCount)
{
NativeWrapper.EvtClose(this.eventsBuffer[this.currentIndex]);
this.currentIndex++;
}
if ((this.handle != null) && !this.handle.IsInvalid)
{
this.handle.Dispose();
}
}
[SecurityCritical]
private bool GetNextBatch(TimeSpan ts)
{
int totalMilliseconds;
if (ts == TimeSpan.MaxValue)
{
totalMilliseconds = -1;
}
else
{
totalMilliseconds = (int)ts.TotalMilliseconds;
}
if (this.batchSize != this.eventsBuffer.Length)
{
this.eventsBuffer = new IntPtr[this.batchSize];
}
int returned = 0;
if (!NativeWrapper.EvtNext(this.handle, this.batchSize, this.eventsBuffer, totalMilliseconds, 0, ref returned))
{
this.eventCount = 0;
this.currentIndex = 0;
return false;
}
this.currentIndex = 0;
this.eventCount = returned;
return true;
}
}
[Serializable, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal class EventLogReadingException : EventLogException
{
// Methods
public EventLogReadingException()
{
}
public EventLogReadingException(string message)
: base(message)
{
}
public EventLogReadingException(string message, Exception innerException)
: base(message, innerException)
{
}
internal EventLogReadingException(int errorCode)
: base(errorCode)
{
}
protected EventLogReadingException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
///
/// Enables you to read events from an event log based on an event query. The events that are read by this object are returned as EventRecord objects.
///
[HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public class EventLogRecord : EventRecord
{
private const int SYSTEM_PROPERTY_COUNT = 0x12;
private ProviderMetadataCachedInformation cachedMetadataInformation;
private string containerChannel;
[SecurityTreatAsSafe]
private EventLogHandle handle;
private IEnumerable keywordsNames;
private string levelName;
private bool levelNameReady;
private int[] matchedQueryIds;
private string opcodeName;
private bool opcodeNameReady;
private EventLogSession session;
private object syncObject;
private NativeWrapper.SystemProperties systemProperties;
private string taskName;
private bool taskNameReady;
[SecurityTreatAsSafe]
internal EventLogRecord(EventLogHandle handle, EventLogSession session, ProviderMetadataCachedInformation cachedMetadataInfo)
{
this.cachedMetadataInformation = cachedMetadataInfo;
this.handle = handle;
this.session = session;
this.systemProperties = new NativeWrapper.SystemProperties();
this.syncObject = new object();
}
///
/// Gets the activity identifier.
///
///
/// The activity identifier.
///
public override Guid? ActivityId
{
get
{
this.PrepareSystemData();
return this.systemProperties.ActivityId;
}
}
///
/// Gets the bookmark.
///
///
/// The bookmark.
///
public override EventBookmark Bookmark
{
[SecurityTreatAsSafe, SecurityCritical]
get
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
EventLogHandle bookmark = NativeWrapper.EvtCreateBookmark(null);
NativeWrapper.EvtUpdateBookmark(bookmark, this.handle);
return new EventBookmark(NativeWrapper.EvtRenderBookmark(bookmark));
}
}
///
/// Gets the container log.
///
///
/// The container log.
///
public string ContainerLog
{
get
{
if (this.containerChannel != null)
{
return this.containerChannel;
}
lock (this.syncObject)
{
if (this.containerChannel == null)
{
this.containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath);
}
return this.containerChannel;
}
}
}
///
/// Gets the identifier.
///
///
/// The identifier.
///
public override int Id
{
get
{
this.PrepareSystemData();
ushort? id = this.systemProperties.Id;
int? nullable3 = id.HasValue ? new int?(id.GetValueOrDefault()) : null;
if (!nullable3.HasValue)
{
return 0;
}
return this.systemProperties.Id.Value;
}
}
///
/// Gets the keywords.
///
///
/// The keywords.
///
public override long? Keywords
{
get
{
this.PrepareSystemData();
ulong? keywords = this.systemProperties.Keywords;
if (!keywords.HasValue)
{
return null;
}
return (long)(keywords.GetValueOrDefault());
}
}
///
/// Gets the keywords display names.
///
///
/// The keywords display names.
///
public override IEnumerable KeywordsDisplayNames
{
get
{
if (this.keywordsNames != null)
{
return this.keywordsNames;
}
lock (this.syncObject)
{
if (this.keywordsNames == null)
{
this.keywordsNames = this.cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, this.handle);
}
return this.keywordsNames;
}
}
}
///
/// Gets the level.
///
///
/// The level.
///
public override byte? Level
{
get
{
this.PrepareSystemData();
return this.systemProperties.Level;
}
}
///
/// Gets the display name of the level.
///
///
/// The display name of the level.
///
public override string LevelDisplayName
{
get
{
if (this.levelNameReady)
{
return this.levelName;
}
lock (this.syncObject)
{
if (!this.levelNameReady)
{
this.levelNameReady = true;
this.levelName = this.cachedMetadataInformation.GetLevelDisplayName(this.ProviderName, this.handle);
}
return this.levelName;
}
}
}
///
/// Gets the name of the log.
///
///
/// The name of the log.
///
public override string LogName
{
get
{
this.PrepareSystemData();
return this.systemProperties.ChannelName;
}
}
///
/// Gets the name of the machine.
///
///
/// The name of the machine.
///
public override string MachineName
{
get
{
this.PrepareSystemData();
return this.systemProperties.ComputerName;
}
}
///
/// Gets the matched query ids.
///
///
/// The matched query ids.
///
public IEnumerable MatchedQueryIds
{
get
{
if (this.matchedQueryIds != null)
{
return this.matchedQueryIds;
}
lock (this.syncObject)
{
if (this.matchedQueryIds == null)
{
this.matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs);
}
return this.matchedQueryIds;
}
}
}
///
/// Gets the opcode.
///
///
/// The opcode.
///
public override short? Opcode
{
get
{
this.PrepareSystemData();
byte? opcode = this.systemProperties.Opcode;
ushort? nullable3 = opcode.HasValue ? new ushort?(opcode.GetValueOrDefault()) : null;
if (!nullable3.HasValue)
{
return null;
}
return new short?((short)nullable3.GetValueOrDefault());
}
}
///
/// Gets the display name of the opcode.
///
///
/// The display name of the opcode.
///
public override string OpcodeDisplayName
{
get
{
lock (this.syncObject)
{
if (!this.opcodeNameReady)
{
this.opcodeNameReady = true;
this.opcodeName = this.cachedMetadataInformation.GetOpcodeDisplayName(this.ProviderName, this.handle);
}
return this.opcodeName;
}
}
}
///
/// Gets the process identifier.
///
///
/// The process identifier.
///
public override int? ProcessId
{
get
{
this.PrepareSystemData();
uint? processId = this.systemProperties.ProcessId;
if (!processId.HasValue)
{
return null;
}
return (int)processId.GetValueOrDefault();
}
}
///
/// Gets the properties.
///
///
/// The properties.
///
public override IList Properties
{
get
{
this.session.SetupUserContext();
IList