Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,138 @@
using System;
using System.Collections;
using System.Text;
namespace System.Collections.Generic {
/// <summary>
/// ABOUT:
/// Helps with operations that rely on bit marking to indicate whether an item in the
/// collection should be added, removed, visited already, etc.
///
/// BitHelper doesn't allocate the array; you must pass in an array or ints allocated on the
/// stack or heap. ToIntArrayLength() tells you the int array size you must allocate.
///
/// USAGE:
/// Suppose you need to represent a bit array of length (i.e. logical bit array length)
/// BIT_ARRAY_LENGTH. Then this is the suggested way to instantiate BitHelper:
/// ***************************************************************************
/// int intArrayLength = BitHelper.ToIntArrayLength(BIT_ARRAY_LENGTH);
/// BitHelper bitHelper;
/// if (intArrayLength less than stack alloc threshold)
/// int* m_arrayPtr = stackalloc int[intArrayLength];
/// bitHelper = new BitHelper(m_arrayPtr, intArrayLength);
/// else
/// int[] m_arrayPtr = new int[intArrayLength];
/// bitHelper = new BitHelper(m_arrayPtr, intArrayLength);
/// ***************************************************************************
///
/// IMPORTANT:
/// The second ctor args, length, should be specified as the length of the int array, not
/// the logical bit array. Because length is used for bounds checking into the int array,
/// it's especially important to get this correct for the stackalloc version. See the code
/// samples above; this is the value gotten from ToIntArrayLength().
///
/// The length ctor argument is the only exception; for other methods -- MarkBit and
/// IsMarked -- pass in values as indices into the logical bit array, and it will be mapped
/// to the position within the array of ints.
///
///
unsafe internal class BitHelper { // should not be serialized
private const byte MarkedBitFlag = 1;
private const byte IntSize = 32;
// m_length of underlying int array (not logical bit array)
private int m_length;
// ptr to stack alloc'd array of ints
[System.Security.SecurityCritical]
private int* m_arrayPtr;
// array of ints
private int[] m_array;
// whether to operate on stack alloc'd or heap alloc'd array
private bool useStackAlloc;
/// <summary>
/// Instantiates a BitHelper with a heap alloc'd array of ints
/// </summary>
/// <param name="bitArray">int array to hold bits</param>
/// <param name="length">length of int array</param>
[System.Security.SecurityCritical]
internal BitHelper(int* bitArrayPtr, int length) {
this.m_arrayPtr = bitArrayPtr;
this.m_length = length;
useStackAlloc = true;
}
/// <summary>
/// Instantiates a BitHelper with a heap alloc'd array of ints
/// </summary>
/// <param name="bitArray">int array to hold bits</param>
/// <param name="length">length of int array</param>
internal BitHelper(int[] bitArray, int length) {
this.m_array = bitArray;
this.m_length = length;
}
/// <summary>
/// Mark bit at specified position
/// </summary>
/// <param name="bitPosition"></param>
[System.Security.SecuritySafeCritical]
internal unsafe void MarkBit(int bitPosition) {
if (useStackAlloc) {
int bitArrayIndex = bitPosition / IntSize;
if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
m_arrayPtr[bitArrayIndex] |= (MarkedBitFlag << (bitPosition % IntSize));
}
}
else {
int bitArrayIndex = bitPosition / IntSize;
if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
m_array[bitArrayIndex] |= (MarkedBitFlag << (bitPosition % IntSize));
}
}
}
/// <summary>
/// Is bit at specified position marked?
/// </summary>
/// <param name="bitPosition"></param>
/// <returns></returns>
[System.Security.SecuritySafeCritical]
internal unsafe bool IsMarked(int bitPosition) {
if (useStackAlloc) {
int bitArrayIndex = bitPosition / IntSize;
if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
return ((m_arrayPtr[bitArrayIndex] & (MarkedBitFlag << (bitPosition % IntSize))) != 0);
}
return false;
}
else {
int bitArrayIndex = bitPosition / IntSize;
if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
return ((m_array[bitArrayIndex] & (MarkedBitFlag << (bitPosition % IntSize))) != 0);
}
return false;
}
}
/// <summary>
/// How many ints must be allocated to represent n bits. Returns (n+31)/32, but
/// avoids overflow
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
internal static int ToIntArrayLength(int n) {
return n > 0 ? ((n - 1) / IntSize + 1) : 0;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace System.Collections.Generic {
/// <summary>
/// Debug view for HashSet
/// </summary>
/// <typeparam name="T"></typeparam>
internal class HashSetDebugView<T> {
private HashSet<T> set;
public HashSetDebugView(HashSet<T> set) {
if (set == null) {
throw new ArgumentNullException("set");
}
this.set = set;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Items {
get {
return set.ToArray();
}
}
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace System.Collections.Generic {
/// <summary>
/// Equality comparer for hashsets of hashsets
/// </summary>
/// <typeparam name="T"></typeparam>
#if !FEATURE_NETCORE
[Serializable()]
#endif
internal class HashSetEqualityComparer<T> : IEqualityComparer<HashSet<T>> {
private IEqualityComparer<T> m_comparer;
public HashSetEqualityComparer() {
m_comparer = EqualityComparer<T>.Default;
}
public HashSetEqualityComparer(IEqualityComparer<T> comparer) {
if (comparer == null) {
m_comparer = EqualityComparer<T>.Default;
}
else {
m_comparer = comparer;
}
}
// using m_comparer to keep equals properties in tact; don't want to choose one of the comparers
public bool Equals(HashSet<T> x, HashSet<T> y) {
return HashSet<T>.HashSetEquals(x, y, m_comparer);
}
public int GetHashCode(HashSet<T> obj) {
int hashCode = 0;
if (obj != null) {
foreach (T t in obj) {
hashCode = hashCode ^ (m_comparer.GetHashCode(t) & 0x7FFFFFFF);
}
} // else returns hashcode of 0 for null hashsets
return hashCode;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
HashSetEqualityComparer<T> comparer = obj as HashSetEqualityComparer<T>;
if (comparer == null) {
return false;
}
return (this.m_comparer == comparer.m_comparer);
}
public override int GetHashCode() {
return m_comparer.GetHashCode();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,127 @@
//------------------------------------------------------------------------------
// <copyright file="etwprovider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing
{
[StructLayout(LayoutKind.Explicit, Size = 16)]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public struct EventDescriptor
{
[FieldOffset(0)]
private ushort m_id;
[FieldOffset(2)]
private byte m_version;
[FieldOffset(3)]
private byte m_channel;
[FieldOffset(4)]
private byte m_level;
[FieldOffset(5)]
private byte m_opcode;
[FieldOffset(6)]
private ushort m_task;
[FieldOffset(8)]
private long m_keywords;
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "opcode", Justification = "[....]: Shipped public in 3.5, breaking change to fix now.")]
public EventDescriptor(
int id,
byte version,
byte channel,
byte level,
byte opcode,
int task,
long keywords
)
{
if (id < 0)
{
throw new ArgumentOutOfRangeException("id", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
}
if (id > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException("id", SR.GetString(SR.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue));
}
m_id = (ushort)id;
m_version = version;
m_channel = channel;
m_level = level;
m_opcode = opcode;
m_keywords = keywords;
if (task < 0)
{
throw new ArgumentOutOfRangeException("task", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
}
if (task > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException("task", SR.GetString(SR.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue));
}
m_task = (ushort)task;
}
public int EventId {
get {
return m_id;
}
}
public byte Version
{
get
{
return m_version;
}
}
public byte Channel
{
get
{
return m_channel;
}
}
public byte Level
{
get
{
return m_level;
}
}
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "[....]: Shipped public in 3.5, breaking change to fix now.")]
public byte Opcode
{
get
{
return m_opcode;
}
}
public int Task
{
get
{
return m_task;
}
}
public long Keywords
{
get
{
return m_keywords;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,436 @@
//------------------------------------------------------------------------------
// <copyright file="EtwListener.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing{
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventProviderTraceListener : TraceListener
{
//
// The listener uses the EtwProvider base class.
// Because Listener data is not schematized at the moment the listener will
// log events using WriteMessageEvent method.
//
// Because WriteMessageEvent takes a string as the event payload
// all the overriden loging methods convert the arguments into strings.
// Event payload is "delimiter" separated, which can be configured
//
//
private EventProvider m_provider;
private const string s_nullStringValue = "null";
private const string s_nullStringComaValue = "null,";
private const string s_nullCStringValue = ": null";
private const string s_activityIdString = "activityId=";
private const string s_relatedActivityIdString = "relatedActivityId=";
private const string s_callStackString = " : CallStack:";
private const string s_optionDelimiter = "delimiter";
private string m_delimiter = ";";
private int m_initializedDelim = 0;
private const uint s_keyWordMask = 0xFFFFFF00;
private const int s_defaultPayloadSize = 512;
private object m_Lock = new object();
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
public string Delimiter
{
get
{
if (m_initializedDelim == 0)
{
lock (m_Lock)
{
if (m_initializedDelim == 0)
{
if (Attributes.ContainsKey(s_optionDelimiter))
{
m_delimiter = Attributes[s_optionDelimiter];
}
m_initializedDelim = 1;
}
}
if (m_delimiter == null)
throw new ArgumentNullException("Delimiter");
if (m_delimiter.Length == 0)
throw new ArgumentException(SR.GetString(SR.Argument_NeedNonemptyDelimiter));
}
return m_delimiter;
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
set
{
if (value == null)
throw new ArgumentNullException("Delimiter");
if (value.Length == 0)
throw new ArgumentException(SR.GetString(SR.Argument_NeedNonemptyDelimiter));
lock (m_Lock)
{
m_delimiter = value;
m_initializedDelim = 1;
}
}
}
protected override string[] GetSupportedAttributes()
{
return new String[] { s_optionDelimiter };
}
/// <summary>
/// This method creates an instance of the ETW provider.
/// The guid argument must be a valid GUID or a format exeption will be
/// thrown when creating an instance of the ControlGuid.
/// We need to be running on Vista or above. If not an
/// PlatformNotSupported exception will be thrown by the EventProvider.
/// </summary>
public EventProviderTraceListener(string providerId)
{
InitProvider(providerId);
}
public EventProviderTraceListener(string providerId, string name)
: base(name)
{
InitProvider(providerId);
}
public EventProviderTraceListener(string providerId, string name, string delimiter)
: base(name)
{
if (delimiter == null)
throw new ArgumentNullException("delimiter");
if (delimiter.Length == 0)
throw new ArgumentException(SR.GetString(SR.Argument_NeedNonemptyDelimiter));
m_delimiter = delimiter;
m_initializedDelim = 1;
InitProvider(providerId);
}
private void InitProvider(string providerId)
{
Guid controlGuid = new Guid(providerId);
//
// Create The ETW TraceProvider
//
m_provider = new EventProvider(controlGuid);
}
//
// override Listener methods
//
public sealed override void Flush()
{
}
public sealed override bool IsThreadSafe
{
get
{
return true;
}
}
public override void Close()
{
m_provider.Close();
}
public sealed override void Write(string message)
{
if (!m_provider.IsEnabled())
{
return;
}
m_provider.WriteMessageEvent(message, (byte)TraceEventType.Information, 0);
}
public sealed override void WriteLine(string message)
{
Write(message);
}
//
// For all the methods below the string to be logged contains:
// m_delimeter seperated data converted to string
// followed by the callstack if any.
// "id : Data1, Data2... : callstack : callstack value"
//
// The source parameter is ignored.
//
public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
if (!m_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null,null,null,null))
{
return;
}
StringBuilder dataString = new StringBuilder(s_defaultPayloadSize);
if (data != null)
{
dataString.Append(data.ToString());
}
else
{
dataString.Append(s_nullCStringValue);
}
if ((eventCache != null) && (TraceOutputOptions & TraceOptions.Callstack) != 0)
{
dataString.Append(s_callStackString);
dataString.Append(eventCache.Callstack);
m_provider.WriteMessageEvent(
dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
else
{
m_provider.WriteMessageEvent(dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
}
public sealed override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data)
{
if (!m_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
int index;
StringBuilder dataString = new StringBuilder(s_defaultPayloadSize);
if ((data != null) && (data.Length > 0) )
{
for (index = 0; index < (data.Length - 1); index++)
{
if (data[index] != null)
{
dataString.Append(data[index].ToString());
dataString.Append(Delimiter);
}
else
{
dataString.Append(s_nullStringComaValue);
}
}
if (data[index] != null)
{
dataString.Append(data[index].ToString());
}
else
{
dataString.Append(s_nullStringValue);
}
}
else
{
dataString.Append(s_nullStringValue);
}
if ((eventCache != null) && (TraceOutputOptions & TraceOptions.Callstack) != 0)
{
dataString.Append(s_callStackString);
dataString.Append(eventCache.Callstack);
m_provider.WriteMessageEvent(
dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
else
{
m_provider.WriteMessageEvent(dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
}
public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
{
if (!m_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
if ((eventCache != null) && (TraceOutputOptions & TraceOptions.Callstack) != 0)
{
m_provider.WriteMessageEvent(s_callStackString + eventCache.Callstack,
(byte)eventType,
(long)eventType & s_keyWordMask);
}
else
{
m_provider.WriteMessageEvent(String.Empty,
(byte)eventType,
(long)eventType & s_keyWordMask);
}
}
public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
if (!m_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
StringBuilder dataString = new StringBuilder(s_defaultPayloadSize);
dataString.Append(message);
if ((eventCache != null) && (TraceOutputOptions & TraceOptions.Callstack) != 0)
{
dataString.Append(s_callStackString);
dataString.Append(eventCache.Callstack);
m_provider.WriteMessageEvent(
dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
else
{
m_provider.WriteMessageEvent(dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
}
public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
if (!m_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
if (args == null)
{
if ((eventCache != null) && (TraceOutputOptions & TraceOptions.Callstack) != 0)
{
m_provider.WriteMessageEvent(format + s_callStackString + eventCache.Callstack,
(byte)eventType,
(long)eventType & s_keyWordMask);
}
else
{
m_provider.WriteMessageEvent(format,
(byte)eventType,
(long)eventType & s_keyWordMask);
}
}
else
{
if ((eventCache != null) && (TraceOutputOptions & TraceOptions.Callstack) != 0)
{
m_provider.WriteMessageEvent(String.Format(CultureInfo.InvariantCulture, format, args) + s_callStackString + eventCache.Callstack,
(byte)eventType,
(long)eventType & s_keyWordMask);
}
else
{
m_provider.WriteMessageEvent(String.Format(CultureInfo.InvariantCulture, format, args),
(byte)eventType,
(long)eventType&s_keyWordMask);
}
}
}
public override void Fail(string message, string detailMessage)
{
StringBuilder failMessage = new StringBuilder(message);
if (detailMessage != null)
{
failMessage.Append(" ");
failMessage.Append(detailMessage);
}
this.TraceEvent(null, null, TraceEventType.Error, 0, failMessage.ToString());
}
[System.Security.SecurityCritical]
public sealed override void TraceTransfer(TraceEventCache eventCache, String source, int id, string message, Guid relatedActivityId)
{
if (!m_provider.IsEnabled())
{
return;
}
StringBuilder dataString = new StringBuilder(s_defaultPayloadSize);
object correlationId = Trace.CorrelationManager.ActivityId;
if (correlationId != null)
{
Guid activityId = (Guid)correlationId;
dataString.Append(s_activityIdString);
dataString.Append(activityId.ToString());
dataString.Append(Delimiter);
}
dataString.Append(s_relatedActivityIdString);
dataString.Append(relatedActivityId.ToString());
dataString.Append(Delimiter + message);
if ((eventCache != null) && (TraceOutputOptions & TraceOptions.Callstack) != 0)
{
dataString.Append(s_callStackString);
dataString.Append(eventCache.Callstack);
m_provider.WriteMessageEvent(
dataString.ToString(),
0,
(long)TraceEventType.Transfer);
}
else
{
m_provider.WriteMessageEvent(dataString.ToString(),
0,
(long)TraceEventType.Transfer);
}
}
}
}

View File

@@ -0,0 +1,66 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: CoTaskMemSafeHandle
**
** Purpose:
** This internal class is a SafeHandle implementation over a
** native CoTaskMem allocated via StringToCoTaskMemAuto.
**
============================================================*/
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace System.Diagnostics.Eventing.Reader {
//
// Marked as SecurityCritical due to link demands from inherited
// SafeHandle members.
//
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal sealed class CoTaskMemSafeHandle : SafeHandle {
internal CoTaskMemSafeHandle()
: base(IntPtr.Zero, true) {
}
internal void SetMemory(IntPtr handle) {
SetHandle(handle);
}
internal IntPtr GetMemory() {
return handle;
}
public override bool IsInvalid {
get {
return IsClosed || handle == IntPtr.Zero;
}
}
protected override bool ReleaseHandle() {
Marshal.FreeCoTaskMem(handle);
handle = IntPtr.Zero;
return true;
}
//
// DONT compare CoTaskMemSafeHandle with CoTaskMemSafeHandle.Zero
// use IsInvalid instead. Zero is provided where a NULL handle needed
//
public static CoTaskMemSafeHandle Zero {
get {
return new CoTaskMemSafeHandle();
}
}
}
}

View File

@@ -0,0 +1,68 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: CoTaskMemUnicodeSafeHandle
**
** Purpose:
** This internal class is a SafeHandle implementation over a
** native CoTaskMem allocated via SecureStringToCoTaskMemUnicode.
**
============================================================*/
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace System.Diagnostics.Eventing.Reader {
//
// Marked as SecurityCritical due to link demands from inherited
// SafeHandle members.
//
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal sealed class CoTaskMemUnicodeSafeHandle : SafeHandle {
internal CoTaskMemUnicodeSafeHandle()
: base(IntPtr.Zero, true) {
}
internal CoTaskMemUnicodeSafeHandle(IntPtr handle, bool ownsHandle)
: base(IntPtr.Zero, ownsHandle) {
SetHandle(handle);
}
internal void SetMemory(IntPtr handle) {
SetHandle(handle);
}
internal IntPtr GetMemory() {
return handle;
}
public override bool IsInvalid {
get {
return IsClosed || handle == IntPtr.Zero;
}
}
protected override bool ReleaseHandle() {
Marshal.ZeroFreeCoTaskMemUnicode(handle);
handle = IntPtr.Zero;
return true;
}
// DONT compare CoTaskMemUnicodeSafeHandle with CoTaskMemUnicodeSafeHandle.Zero
// use IsInvalid instead. Zero is provided where a NULL handle needed
public static CoTaskMemUnicodeSafeHandle Zero {
get {
return new CoTaskMemUnicodeSafeHandle();
}
}
}
}

View File

@@ -0,0 +1,71 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventBookmark
**
** 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.
**
============================================================*/
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Runtime.Serialization;
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>
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventBookmark : ISerializable {
string bookmark;
internal EventBookmark(string bookmarkText) {
if (bookmarkText == null)
throw new ArgumentNullException("bookmarkText");
this.bookmark = bookmarkText;
}
protected EventBookmark(SerializationInfo info, StreamingContext context) {
if (info == null)
throw new ArgumentNullException("info");
this.bookmark = info.GetString("BookmarkText");
}
// SecurityCritical due to inherited link demand for GetObjectData.
[System.Security.SecurityCritical,SecurityPermissionAttribute(SecurityAction.LinkDemand,Flags = SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
GetObjectData( info, context );
}
// SecurityCritical due to inherited link demand for GetObjectData.
[System.Security.SecurityCritical,SecurityPermissionAttribute(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);
}
internal string BookmarkText { get { return bookmark; } }
}
}

View File

@@ -0,0 +1,92 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventKeyword
**
** 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>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class EventKeyword {
private long value;
private string name;
private string displayName;
private bool dataReady;
ProviderMetadata pmReference;
object syncObject;
//called from EventMetadata
internal EventKeyword(long value, ProviderMetadata pmReference) {
this.value = value;
this.pmReference = pmReference;
this.syncObject = new object();
}
//called from ProviderMetadata
internal EventKeyword(string name, long value, string displayName) {
this.value = value;
this.name = name;
this.displayName = displayName;
this.dataReady = true;
this.syncObject = new object();
}
internal void PrepareData() {
if (dataReady == true) return;
lock (syncObject) {
if (dataReady == true) return;
IEnumerable<EventKeyword> result = pmReference.Keywords;
this.name = null;
this.displayName = null;
this.dataReady = true;
foreach (EventKeyword key in result) {
if (key.Value == this.value) {
this.name = key.Name;
this.displayName = key.DisplayName;
break;
}
}
}
}
public string Name {
get {
PrepareData();
return this.name;
}
}
public long Value {
get {
return this.value;
}
}
public string DisplayName {
get {
PrepareData();
return this.displayName;
}
}
}
}

View File

@@ -0,0 +1,91 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLevel
**
** 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>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class EventLevel {
private int value;
private string name;
private string displayName;
private bool dataReady;
ProviderMetadata pmReference;
object syncObject;
//called from EventMetadata
internal EventLevel(int value, ProviderMetadata pmReference) {
this.value = value;
this.pmReference = pmReference;
this.syncObject = new object();
}
//called from ProviderMetadata
internal EventLevel(string name, int value, string displayName) {
this.value = value;
this.name = name;
this.displayName = displayName;
this.dataReady = true;
this.syncObject = new object();
}
internal void PrepareData() {
if (dataReady == true) return;
lock (syncObject) {
if (dataReady == true) return;
IEnumerable<EventLevel> result = pmReference.Levels;
this.name = null;
this.displayName = null;
this.dataReady = true;
foreach (EventLevel lev in result) {
if (lev.Value == this.value) {
this.name = lev.Name;
this.displayName = lev.DisplayName;
break;
}
}
}
}
public string Name {
get {
PrepareData();
return this.name;
}
}
public int Value {
get {
return this.value;
}
}
public string DisplayName {
get {
PrepareData();
return this.displayName;
}
}
}
}

View File

@@ -0,0 +1,261 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogConfiguration
**
** 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;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.Win32;
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>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
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) {
EventLogPermissionHolder.GetEventLogPermission().Demand();
if (session == null)
session = EventLogSession.GlobalSession;
this.session = session;
this.channelName = logName;
handle = NativeWrapper.EvtOpenChannelConfig(this.session.Handle, this.channelName, 0);
}
public string LogName {
get {
return channelName;
}
}
public EventLogType LogType {
get {
return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType));
}
}
public EventLogIsolation LogIsolation {
get {
return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation));
}
}
public bool IsEnabled {
get {
return (bool)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled);
}
set {
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, (object)value);
}
}
public bool IsClassicLog {
get {
return (bool)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog);
}
}
public string SecurityDescriptor {
get {
return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess);
}
set {
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value);
}
}
public string LogFilePath {
get {
return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath);
}
set {
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value);
}
}
public long MaximumSizeInBytes {
get {
return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize));
}
set {
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, (object)value);
}
}
public EventLogMode LogMode {
get {
object nativeRetentionObject = NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention);
object nativeAutoBackupObject = NativeWrapper.EvtGetChannelConfigProperty(this.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(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false);
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)false);
break;
case EventLogMode.AutoBackup:
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)true);
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true);
break;
case EventLogMode.Retain:
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false);
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true);
break;
}
}
}
public string OwningProviderName {
get {
return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher);
}
}
public IEnumerable<string> ProviderNames {
get {
return (string[])NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList);
}
}
public int? ProviderLevel {
get {
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel));
}
set {
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value);
}
}
public long? ProviderKeywords {
get {
return (long?)((ulong?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords));
}
set {
NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value);
}
}
public int? ProviderBufferSize {
get {
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigBufferSize));
}
}
public int? ProviderMinimumNumberOfBuffers {
get {
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMinBuffers));
}
}
public int? ProviderMaximumNumberOfBuffers {
get {
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMaxBuffers));
}
}
public int? ProviderLatency {
get {
return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLatency));
}
}
public Guid? ProviderControlGuid {
get {
return (Guid?)(NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigControlGuid));
}
}
public void SaveChanges() {
NativeWrapper.EvtSaveChannelConfig(this.handle, 0);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing) {
if (disposing) {
EventLogPermissionHolder.GetEventLogPermission().Demand();
}
if ( handle != null && !handle.IsInvalid )
handle.Dispose();
}
}
}

View File

@@ -0,0 +1,142 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogException
**
** Purpose:
** This public class describes an exception thrown from Event
** Log related classes.
**
============================================================*/
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace System.Diagnostics.Eventing.Reader {
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventLogException : Exception, ISerializable {
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(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { }
protected EventLogException(int errorCode) { this.errorCode = errorCode; }
// SecurityCritical due to inherited link demand for GetObjectData.
[System.Security.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", errorCode);
base.GetObjectData(info, context);
}
public override string Message {
// marked as SecurityCritical because it uses Win32Exception.
// marked as TreatAsSafe because it performs Demand.
[System.Security.SecurityCritical]
get {
EventLogPermissionHolder.GetEventLogPermission().Demand();
Win32Exception win32Exception = new Win32Exception(errorCode);
return win32Exception.Message;
}
}
private int errorCode;
}
/// <summary>
/// The object requested by the operation is not found.
/// </summary>
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventLogNotFoundException : EventLogException {
public EventLogNotFoundException() { }
public EventLogNotFoundException(string message) : base(message) { }
public EventLogNotFoundException(string message, Exception innerException) : base(message, innerException) { }
protected EventLogNotFoundException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { }
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>
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventLogReadingException : EventLogException {
public EventLogReadingException() { }
public EventLogReadingException(string message) : base(message) { }
public EventLogReadingException(string message, Exception innerException) : base(message, innerException) { }
protected EventLogReadingException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { }
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>
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventLogProviderDisabledException : EventLogException {
public EventLogProviderDisabledException() { }
public EventLogProviderDisabledException(string message) : base(message) { }
public EventLogProviderDisabledException(string message, Exception innerException) : base(message, innerException) { }
protected EventLogProviderDisabledException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { }
internal EventLogProviderDisabledException(int errorCode) : base(errorCode) { }
}
/// <summary>
/// Data obtained from the eventlog service, for the current operation, is invalid .
/// </summary>
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventLogInvalidDataException : EventLogException {
public EventLogInvalidDataException() { }
public EventLogInvalidDataException(string message) : base(message) { }
public EventLogInvalidDataException(string message, Exception innerException) : base(message, innerException) { }
protected EventLogInvalidDataException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { }
internal EventLogInvalidDataException(int errorCode) : base(errorCode) { }
}
}

View File

@@ -0,0 +1,61 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogHandle
**
** Purpose:
** This internal class is a SafeHandle implementation over a
** native EVT_HANDLE - obtained from EventLog Native Methods.
**
============================================================*/
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace System.Diagnostics.Eventing.Reader {
//
// Marked as SecurityCritical due to link demands from inherited
// SafeHandle members.
//
// marked as Safe since the only real operation that is performed
// by this class is NativeWrapper.EvtClose and that is protected
// by a full Demand() before doing any work.
[System.Security.SecuritySafeCritical]
internal sealed class EventLogHandle : SafeHandle {
// Called by P/Invoke when returning SafeHandles
private EventLogHandle()
: base(IntPtr.Zero, true) {
}
internal EventLogHandle(IntPtr handle, bool ownsHandle)
: base(IntPtr.Zero, ownsHandle) {
SetHandle(handle);
}
public override bool IsInvalid {
get {
return IsClosed || handle == IntPtr.Zero;
}
}
protected override bool ReleaseHandle() {
NativeWrapper.EvtClose(handle);
handle = IntPtr.Zero;
return true;
}
// DONT compare EventLogHandle with EventLogHandle.Zero
// use IsInvalid instead. Zero is provided where a NULL handle needed
public static EventLogHandle Zero {
get {
return new EventLogHandle();
}
}
}
}

View File

@@ -0,0 +1,68 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogInformation
**
** 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.
**
============================================================*/
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
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>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class EventLogInformation {
DateTime? creationTime;
DateTime? lastAccessTime;
DateTime? lastWriteTime;
long? fileSize;
int? fileAttributes;
long? recordCount;
long? oldestRecordNumber;
bool? isLogFull;
[System.Security.SecuritySafeCritical]
internal EventLogInformation(EventLogSession session, string channelName, PathType pathType) {
EventLogPermissionHolder.GetEventLogPermission().Demand();
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

@@ -0,0 +1,109 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogLink
**
** 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>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class EventLogLink {
private string channelName;
private bool isImported;
private string displayName;
private uint channelId;
private bool dataReady;
ProviderMetadata pmReference;
object syncObject;
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();
}
private void PrepareData() {
if (dataReady == true) return;
lock (syncObject) {
if (dataReady == true) return;
IEnumerable<EventLogLink> result = pmReference.LogLinks;
this.channelName = null;
this.isImported = false;
this.displayName = null;
this.dataReady = true;
foreach (EventLogLink ch in result) {
if (ch.ChannelId == this.channelId) {
this.channelName = ch.LogName;
this.isImported = ch.IsImported;
this.displayName = ch.DisplayName;
this.dataReady = true;
break;
}
}
}
}
public string LogName {
get {
this.PrepareData();
return this.channelName;
}
}
public bool IsImported {
get {
this.PrepareData();
return this.isImported;
}
}
public string DisplayName {
get {
this.PrepareData();
return this.displayName;
}
}
internal uint ChannelId {
get {
return channelId;
}
}
}
}

View File

@@ -0,0 +1,32 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogPermissionHolder
**
** Purpose:
** Internal class that defines the permissions that are used
** throughout the Event Log classes of this namespace.
**
============================================================*/
using System;
using System.Security.Permissions;
namespace System.Diagnostics.Eventing.Reader {
internal class EventLogPermissionHolder {
public EventLogPermissionHolder() {
}
public static EventLogPermission GetEventLogPermission() {
EventLogPermission logPermission = new EventLogPermission();
EventLogPermissionEntry permEntry =
new EventLogPermissionEntry(EventLogPermissionAccess.Administer, ".");
logPermission.PermissionEntries.Add(permEntry);
return logPermission;
}
}
}

View File

@@ -0,0 +1,84 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogPropertySelector
**
** 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;
using System.Collections.Generic;
using Microsoft.Win32;
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>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
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) {
EventLogPermissionHolder.GetEventLogPermission().Demand();
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 (disposing) {
EventLogPermissionHolder.GetEventLogPermission().Demand();
}
if (renderContextHandleValues != null && !renderContextHandleValues.IsInvalid)
renderContextHandleValues.Dispose();
}
}
}

Some files were not shown because too many files have changed in this diff Show More