//----------------------------------------------------------------------------- // Function: CleanupGroup // // Purpose: Clean up all the global variables associated with this group. // // Returns: nothing // internal void CleanupGroup() { if (g_hPeerEvent != null) { g_hPeerEvent.Dispose(); g_hPeerEvent = null; } if (g_hEvent != null) { g_hEvent.Dispose(); g_hEvent = null; } if (g_hWait != null) { g_hWait.Dispose(); g_hWait = null; } if (!g_hGroup.IsNull) { PeerGroupClose(g_hGroup); g_hGroup = HGROUP.NULL; } }
public void Dispose() { if (connectEndEvent is not null) { connectEndEvent.Dispose(); connectEndEvent = null; } }
private static int Main(string[] args) { const uint QueryTimeout = 5 * 1000; // 5 seconds // Allocate QueryContext AllocateQueryContext(out var QueryContext); // Create event QueryCompletedEvent = CreateEvent(default, true, false);
public void Dispose() { m_hCallbackComplete?.Dispose(); m_hCallbackComplete = default; if (m_LockCreated) { DeleteCriticalSection(ref m_Lock); m_LockCreated = false; } }
public override bool Initialize(bool UseInputDevice) { IMMDeviceEnumerator deviceEnumerator = new(); Flow = UseInputDevice ? EDataFlow.eCapture : EDataFlow.eRender; ChatEndpoint = deviceEnumerator.GetDefaultAudioEndpoint(Flow, ERole.eCommunications); deviceEnumerator = null; // Create our shutdown event - we want an auto reset event that starts in the not-signaled state. ShutdownEvent = CreateEventEx(default, default, 0, ACCESS_MASK.SYNCHRONIZE | (uint)SynchronizationObjectAccess.EVENT_MODIFY_STATE);
// // RenderEventToXml: renders an event to xml or an xml bookmark and returns as a string // static string RenderEventToXml(SafeEventHandle evt, RenderFlags flags) { int bufferSize = 0, bufferUsed = 0, valueCount = 0; StringBuilder eventXml = new StringBuilder(bufferSize); bool result = Events.Render(IntPtr.Zero, evt.Handle, flags, bufferSize, eventXml, out bufferUsed, out valueCount); if (!result && Win32Error.ErrorInsufficientBuffer == Marshal.GetLastWin32Error()) { eventXml.Length = bufferUsed; // resize the buffer and try again bufferSize = bufferUsed; result = Events.Render(IntPtr.Zero, evt.Handle, flags, bufferSize, eventXml, out bufferUsed, out valueCount); } if (!result) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("Render failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } return(eventXml.ToString()); }
public void Dispose() { ChatEndpoint = null; RenderClient = null; CaptureClient = null; AudioClient = null; if (ChatThread is not null) { ChatThread.Dispose(); ChatThread = default; } if (ShutdownEvent is not null) { ShutdownEvent.Dispose(); ShutdownEvent = null; } if (AudioSamplesReadyEvent is not null) { AudioSamplesReadyEvent.Dispose(); AudioSamplesReadyEvent = null; } }
public static extern bool SetEvent([In] SafeEventHandle hEvent);
public static void Main(string[] args) { int exitCode = 0; bool listPublishers = true; IntPtr session = IntPtr.Zero; String publisherName = ""; bool result; IntPtr propertyValuePtr = IntPtr.Zero; try { // get command line information if (args.Length > 0) { if (args[0] == "/?") { Console.WriteLine( "Usage: PublisherMetadata [<publisherName>]\n" + "(When publisherName is not specified, the names of the first 20 publishers will be listed.)"); Environment.Exit(0); } else { publisherName = args[0]; listPublishers = false; } } if (listPublishers) { // // List the first 'n' publishers // int count = 20; Console.WriteLine("First {0} publishers: ", count); IntPtr publisherEnumPtr = Events.OpenPublisherEnum(session, 0); if (publisherEnumPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("OpenPublisherEnum failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } using (SafeEventHandle publisherEnum = new SafeEventHandle(publisherEnumPtr)) { int bufferSize = 0, bufferUsed = 0; StringBuilder publisherId = new StringBuilder(bufferSize); for (int i = 0; i < count; i++) { result = Events.NextPublisherId(publisherEnumPtr, bufferSize, publisherId, out bufferUsed); if (!result && Win32Error.ErrorInsufficientBuffer == Marshal.GetLastWin32Error()) { publisherId.Length = bufferUsed; // resize the buffer and try again bufferSize = bufferUsed; result = Events.NextPublisherId(publisherEnumPtr, bufferSize, publisherId, out bufferUsed); } if (!result) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("NextPublisherId failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } Console.WriteLine("\t{0}", publisherId.ToString()); } } } else { // // Read the specified publisher's metadata // IntPtr publisherMetadataPtr = IntPtr.Zero; IntPtr eventMetadataEnumPtr = IntPtr.Zero; int bufferSize = 0, bufferUsed = 0; publisherMetadataPtr = Events.OpenPublisherMetadata(session, publisherName, null, 0, 0); if (publisherMetadataPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("OpenPublisherMetadata failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } using (SafeEventHandle publisherMetadata = new SafeEventHandle(publisherMetadataPtr)) { PublisherMetadataPropertyID propertyId = PublisherMetadataPropertyID.MessageFilePath; propertyValuePtr = Marshal.AllocHGlobal(bufferSize); result = Events.GetPublisherMetadataPropertyBuffer(publisherMetadata.Handle, propertyId, 0, bufferSize, propertyValuePtr, out bufferUsed); if (!result && Win32Error.ErrorInsufficientBuffer == Marshal.GetLastWin32Error()) { // resize the buffer and try again Marshal.FreeHGlobal(propertyValuePtr); propertyValuePtr = Marshal.AllocHGlobal(bufferUsed); if (propertyValuePtr == IntPtr.Zero) { throw (new Exception(String.Format("Failed to allocate space for rendered data."))); } bufferSize = bufferUsed; result = Events.GetPublisherMetadataPropertyBuffer(publisherMetadata.Handle, propertyId, 0, bufferSize, propertyValuePtr, out bufferUsed); } if (!result) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("GetPublisherMetadataPropertyBuffer failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } EventVariant var = (EventVariant)Marshal.PtrToStructure(propertyValuePtr, typeof(EventVariant)); if (EventVariantType.String != var.type) { throw (new Exception(String.Format("Expected variant type {0} (String), actual {1}.", EventVariantType.String, var.type))); } Object messageFilePath = Events.VariantToObject(var); if (null == messageFilePath) { messageFilePath = "<null>"; } Console.WriteLine("MessageFilePath for publisher '{0}' is '{1}'.", publisherName, messageFilePath.ToString()); // // Read the publisher's event metadata // eventMetadataEnumPtr = Events.OpenEventMetadataEnum(publisherMetadata.Handle, 0); if (eventMetadataEnumPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("OpenEventMetadataEnum failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } } using (SafeEventHandle eventMetadataEnum = new SafeEventHandle(eventMetadataEnumPtr)) { Console.WriteLine("Publisher '{0}' contains event metadata for the following event ids:", publisherName); IntPtr eventMetadataPtr = IntPtr.Zero; while (IntPtr.Zero != (eventMetadataPtr = Events.NextEventMetadata(eventMetadataEnum.Handle, 0))) { using (SafeEventHandle eventMetadata = new SafeEventHandle(eventMetadataPtr)) { EventVariant metadataValue = new EventVariant(); bufferSize = Marshal.SizeOf(metadataValue); bufferUsed = 0; if (!Events.GetEventMetadataProperty(eventMetadata.Handle, EventMetadataPropertyID.EventID, 0, bufferSize, out metadataValue, out bufferUsed)) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("GetEventMetadataProperty failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } if (EventVariantType.UInt32 != metadataValue.type) { throw (new Exception(String.Format("Expected variant type {0} (UInt32), actual {1}.", EventVariantType.UInt32, metadataValue.type))); } Console.WriteLine("\t{0}", metadataValue.UInt32Val); } } if (Win32Error.ErrorNoMoreItems != Marshal.GetLastWin32Error()) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("NextEventMetadata failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } } } } catch (Exception e) { Console.WriteLine(e.ToString()); exitCode = 1; } finally { if (IntPtr.Zero != propertyValuePtr) { Marshal.FreeHGlobal(propertyValuePtr); } } Environment.Exit(exitCode); }
public static void Main(string[] args) { int exitCode = 0; IntPtr session = IntPtr.Zero; String logPath = "Application"; OpenLogFlags openflags = OpenLogFlags.ChannelPath; LogPropertyIdentifier propertyId = LogPropertyIdentifier.LogNumberOfLogRecords; EventVariant propertyValue = new EventVariant(); int propertySize = Marshal.SizeOf(propertyValue); int sizeNeededUsed = 0; String query = "*/System[Level <= 3 and Level >=1]"; // select all events of level warning or higher String targetFile = "%USERPROFILE%\\export.evtx"; ExportLogFlags exportflags = ExportLogFlags.ChannelPath; try { // get command line information if (args.Length > 0) { if (args[0] == "/?") { Console.WriteLine("Usage: LogSample [<logname> [<exportfile>]]"); Environment.Exit(0); } else { logPath = args[0]; if (args.Length > 1) { targetFile = args[1]; } } } // // Get log information // IntPtr logPtr = Events.OpenLog(session, logPath, openflags); if (logPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("OpenLog failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } using (SafeEventHandle logHandle = new SafeEventHandle(logPtr)) { if (!Events.GetLogInfo(logHandle.Handle, propertyId, propertySize, ref propertyValue, ref sizeNeededUsed)) { // This method allows for a sizing call (InsufficientBuffer return) but none of the properties // currently supported require memory beyond that already allocated by EventVariant. Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("GetLogInfo failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } } if (EventVariantType.UInt64 != propertyValue.type) { throw (new Exception(String.Format("Expected variant type {0} (UInt64), actual {1}.", EventVariantType.UInt64, propertyValue.type))); } Console.WriteLine("The {0} log contains {1} events.", logPath, propertyValue.UInt64Val); // // Export selected events from a log // if (!Events.ExportLog(session, logPath, query, targetFile, exportflags)) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("ExportLog failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } Console.WriteLine("Selected events from the {0} log have been exported to file {1}.", logPath, targetFile); // // Capture localized event information so that the exported log can be viewed on // systems that might not have some of the event providers installed. // int locale = 0x409; if (!Events.LocalizeExportedLog(session, targetFile, locale, LocalizeExportLogFlags.Default)) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("LocalizeExportedLog failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } Console.WriteLine("The export file {0} has been localized to locale {1} for archive.", targetFile, locale); // // Clear the log // if (!Events.ClearLog(session, logPath, null, ClearLogFlags.Default)) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("ClearLog failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } Console.WriteLine("The {0} log has been cleared.", logPath); } catch (Exception e) { Console.WriteLine(e.ToString()); exitCode = 1; } Environment.Exit(exitCode); }
public static void Main(string[] args) { int exitCode = 0; IntPtr session = IntPtr.Zero; String channelPath = "Application"; ChannelConfigPropertyID propertyId = ChannelConfigPropertyID.LogMaxSize; try { // get command line information if (args.Length > 0) { if (args[0] == "/?") { Console.WriteLine("Usage: ChannelConfig [<channelPath> [<newMaxLogSize>]]"); Environment.Exit(0); } else { channelPath = args[0]; } } // // Read a configuration property of the specified channel // IntPtr configPtr = Events.OpenChannelConfig(session, channelPath, 0); if (configPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("OpenChannelConfig failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } using (SafeEventHandle configHandle = new SafeEventHandle(configPtr)) { EventVariant propertyValue = new EventVariant(); int bufferSize = Marshal.SizeOf(propertyValue); int bufferRequired = 0; if (!Events.GetChannelConfigProperty(configHandle.Handle, propertyId, 0, bufferSize, ref propertyValue, out bufferRequired)) { // This method allows for a sizing call (InsufficientBuffer return) but the LogMaxSize property does not // require memory beyond that already allocated by EventVariant. Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("GetChannelConfigProperty failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } if (EventVariantType.UInt64 != propertyValue.type) { throw (new Exception(String.Format("Expected variant type {0} (UInt64), actual {1}.", EventVariantType.UInt64, propertyValue.type))); } Console.WriteLine("The {0} log's configured maximum size was {1} bytes.", channelPath, propertyValue.UInt64Val); // // Set and save a configuration property value // if (args.Length > 1) { propertyValue.UInt64Val = Convert.ToUInt64(args[1]); } else { propertyValue.UInt64Val *= 2; // double the maximum log size } if (!Events.SetChannelConfigProperty(configHandle.Handle, propertyId, 0, ref propertyValue)) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("SetChannelConfigProperty failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } if (!Events.SaveChannelConfig(configHandle.Handle, 0)) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("SaveChannelConfig failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } Console.WriteLine("The {0} log's maximum size has been re-configured to {1} bytes.", channelPath, propertyValue.UInt64Val); } } catch (Exception e) { Console.WriteLine(e.ToString()); exitCode = 1; } Environment.Exit(exitCode); }
public static extern bool DeleteTimerQueueTimer([In] TimerQueueHandle TimerQueue, [In] TimerQueueTimerHandle Timer, [In] SafeEventHandle CompletionEvent);
public static extern bool UnregisterWaitEx([In] SafeRegisteredWaitHandle WaitHandle, [In] SafeEventHandle CompletionEvent);
public static void Main(string[] args) { int exitCode = 0; IntPtr session = IntPtr.Zero; string channelpath; string query = null; EventSubscribeCallback callback = new EventSubscribeCallback(DisplayEventCallback); try { // parse the command line if (args.Length == 0) { Console.WriteLine("Error: No parameters provided."); PrintUsage(); Environment.Exit(1); } if (args[0] == "/?") { PrintUsage(); Environment.Exit(1); } channelpath = args[0]; char[] delimiters = { ':' }; for (int i = 1; i < args.Length; i++) { String option = args[i].Substring(1); String[] words = option.Split(delimiters, 2); words[0] = words[0].ToLower(); switch (words[0]) { case "query": case "q": if (query != null) { Console.WriteLine("Options '/query' and '/structuredquery' cannot both be specified."); PrintUsage(); Environment.Exit(1); } query = words[1]; break; case "structuredquery": case "sq": if (query != null) { Console.WriteLine("Options '/query' and '/structuredquery' cannot both be specified."); PrintUsage(); Environment.Exit(1); } using (StreamReader sr = new StreamReader(words[1])) { String line; while ((line = sr.ReadLine()) != null) { query += line;; } } break; default: throw (new Exception(String.Format("Unrecognized parameter option: {0}.", words[0]))); } } // subscribe to the event log IntPtr subscriptionPtr = Events.Subscribe( session, IntPtr.Zero, // SignalEvent (for polling) channelpath, query, IntPtr.Zero, // Bookmark IntPtr.Zero, // Context callback, SubscribeFlags.FutureEvents); if (subscriptionPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("Subscribe failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } using (SafeEventHandle subscription = new SafeEventHandle(subscriptionPtr)) { // continue listening until user stops subscription Console.WriteLine("\nPress <enter> to stop subscription.\n"); Console.Read(); } } catch (Exception e) { Console.WriteLine(e.ToString()); exitCode = 1; } Environment.Exit(exitCode); }
// // FormatEventAsText: selects and formats specific event properties and returns them in an easy to read string // static string FormatEventAsText(SafeEventHandle evt) { // first render the provider (publisher) name which will be needed to open the publisher metadata String EventText = ""; String[] valuePaths = { "Event/System/Provider/@Name" }; UInt32 numValuePaths = 1; int bufferSize = 1024, bufferUsed = 0, valueCount = 0; IntPtr values = IntPtr.Zero; bool result = false; IntPtr ctxPtr = Events.CreateRenderContext(numValuePaths, valuePaths, RenderContextFlags.RenderContextValues); if (ctxPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("CreateRenderContext failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } values = Marshal.AllocHGlobal(bufferSize); if (values == IntPtr.Zero) { throw (new Exception(String.Format("Failed to allocate space for rendered data."))); } using (SafeEventHandle ctx = new SafeEventHandle(ctxPtr)) { result = Events.RenderValues(ctx.Handle, evt.Handle, RenderFlags.RenderEventValues, bufferSize, values, out bufferUsed, out valueCount); if (!result && Win32Error.ErrorInsufficientBuffer == Marshal.GetLastWin32Error()) { // resize the buffer and try again Marshal.FreeHGlobal(values); values = Marshal.AllocHGlobal(bufferUsed); if (values == IntPtr.Zero) { throw (new Exception(String.Format("Failed to allocate space for rendered data."))); } bufferSize = bufferUsed; result = Events.RenderValues(ctx.Handle, evt.Handle, RenderFlags.RenderEventValues, bufferSize, values, out bufferUsed, out valueCount); } } if (!result) { Marshal.FreeHGlobal(values); Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("RenderValues failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } EventVariant var = (EventVariant)Marshal.PtrToStructure(values, typeof(EventVariant)); if (EventVariantType.String != var.type) { Marshal.FreeHGlobal(values); throw (new Exception(String.Format("Expected variant type {0} (String), actual {1}.", EventVariantType.String, var.type))); } Object publisher = Events.VariantToObject(var); Marshal.FreeHGlobal(values); EventText += "Source:\t\t" + publisher.ToString(); // now open the publisher metadata and read the event message IntPtr publisherMetadata = Events.OpenPublisherMetadata(IntPtr.Zero, publisher.ToString(), null, 0x409, 0); if (IntPtr.Zero == publisherMetadata) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("OpenPublisherMetadata failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } using (SafeEventHandle hPublisherMetadata = new SafeEventHandle(publisherMetadata)) { StringBuilder message = new StringBuilder(bufferSize); result = Events.FormatMessage(publisherMetadata, evt.Handle, 0, 0, values, FormatMessageFlags.FormatMessageEvent, bufferSize, message, out bufferUsed); if (!result && Win32Error.ErrorInsufficientBuffer == Marshal.GetLastWin32Error()) { // resize the buffer and try again message.Length = bufferUsed; bufferSize = bufferUsed; result = Events.FormatMessage(publisherMetadata, evt.Handle, 0, 0, IntPtr.Zero, FormatMessageFlags.FormatMessageEvent, bufferSize, message, out bufferUsed); } if (!result) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("FormatMessage failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } EventText += "\nDescription:\t" + message.ToString(); return(EventText); } }
public static extern int RegNotifyChangeKeyValue(IntPtr hKey, bool bWatchSubtree, RegChangeNotifyFilter dwNotifyFilter, SafeEventHandle hEvent, bool fAsynchronous);
public HRESULT Init() { connectEndEvent = CreateEvent(default, true, false, default);
// create the Function discovery instance and setup an event to be used to signal the end of the Search public HRESULT Init([In] bool bTurnOnSoftAP) { HRESULT hr = Win32Error.ERROR_SUCCESS; anySearchEvent = CreateEvent(default, true, false, default);
public static void Main(string[] args) { int exitCode = 0; String path; String query = "*"; QueryFlags queryflags = QueryFlags.QueryChannelPath | QueryFlags.QueryForwardDirection; UInt32 count = UInt32.MaxValue; String format = "xml"; try { // parse the command line if (args.Length == 0) { Console.WriteLine("Error: No parameters provided."); PrintUsage(); Environment.Exit(1); } if (args[0] == "/?") { PrintUsage(); Environment.Exit(1); } path = args[0]; char[] delimiters = { ':' }; for (int i = 1; i < args.Length; i++) { String option = args[i].Substring(1); String[] words = option.Split(delimiters, 2); words[0] = words[0].ToLower(); switch (words[0]) { case "logfile": case "lf": queryflags &= ~QueryFlags.QueryChannelPath; queryflags |= QueryFlags.QueryFilePath; break; case "query": case "q": query = words[1]; break; case "reversedirection": case "rd": queryflags &= ~QueryFlags.QueryForwardDirection; queryflags |= QueryFlags.QueryReverseDirection; break; case "count": case "c": count = Convert.ToUInt32(words[1]); break; case "format": case "f": format = words[1].ToLower(); if (format != "text" && format != "xml") { throw (new Exception(String.Format("Unrecognized format option: {0}.", format))); } break; default: throw (new Exception(String.Format("Unrecognized parameter option: {0}.", words[0]))); } } // query the event log IntPtr resultSetPtr = Events.Query(IntPtr.Zero, path, query, queryflags); if (resultSetPtr == IntPtr.Zero) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("Query failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } using (SafeEventHandle resultSet = new SafeEventHandle(resultSetPtr)) { // read the selected events IntPtr[] events = new IntPtr[1]; int timeout = 5000; // 5 seconds int returned = 0; UInt32 n = 0; while (Events.Next(resultSet.Handle, 1, events, timeout, 0, out returned) && n++ < count) { foreach (IntPtr evtptr in events) { using (SafeEventHandle evt = new SafeEventHandle(evtptr)) { if (format == "xml") { Console.WriteLine("\n" + RenderEventToXml(evt, RenderFlags.RenderEventXml)); } else if (format == "text") { Console.WriteLine("\n" + FormatEventAsText(evt)); } } } } if (Win32Error.ErrorNoMoreItems != Marshal.GetLastWin32Error() && Win32Error.ErrorSuccess != Marshal.GetLastWin32Error()) { Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error()); throw (new Exception(String.Format("Failed to read next event. error: {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message))); } } } catch (Exception e) { Console.WriteLine(e.ToString()); exitCode = 1; } Environment.Exit(exitCode); }
// // DisplayEventCallback: subscription callback which displays the returned event // static int DisplayEventCallback(SubscribeNotifyAction action, IntPtr context, IntPtr eventPtr) { if (SubscribeNotifyAction.Error == action) { Console.WriteLine("***** Subscription encountered an error! *****"); } else if (SubscribeNotifyAction.Deliver == action) { // display the event using (SafeEventHandle evt = new SafeEventHandle(eventPtr, false)) { Console.WriteLine("{0}", RenderEventToXml(evt, RenderFlags.RenderEventXml)); } // list the Ids of the query clauses that selected the event int bufferSize = 0, bufferRequired = 0; IntPtr variantPtr = Marshal.AllocHGlobal(bufferRequired); bool result = Events.GetEventInfo(eventPtr, EventPropertyId.EventQueryIDs, bufferSize, variantPtr, ref bufferRequired); if (!result && Win32Error.ErrorInsufficientBuffer == Marshal.GetLastWin32Error()) { // resize the buffer and try again Marshal.FreeHGlobal(variantPtr); variantPtr = Marshal.AllocHGlobal(bufferRequired); if (variantPtr == IntPtr.Zero) { Console.WriteLine("Failed to allocate space for event selection data."); return(Win32Error.ErrorOutOfMemory); } bufferSize = bufferRequired; result = Events.GetEventInfo(eventPtr, EventPropertyId.EventQueryIDs, bufferSize, variantPtr, ref bufferRequired); } if (!result) { Marshal.FreeHGlobal(variantPtr); Console.WriteLine("GetEventInfo failed with error {0}.", Marshal.GetLastWin32Error().ToString()); return(0); } // the returned variant is an array of UInt32 values which are allocated just beyond the EventVariant base memory EventVariant var = (EventVariant)Marshal.PtrToStructure(variantPtr, typeof(EventVariant)); if ((EventVariantType.UInt32 | EventVariantType.Array) != (var.type)) { Console.WriteLine("Expected variant type {0} (UInt32 Array), actual {1}.", (EventVariantType.UInt32 | EventVariantType.Array), var.type); Marshal.FreeHGlobal(variantPtr); return(1); } IntPtr currentPtr = variantPtr; currentPtr = (IntPtr)((int)currentPtr + Marshal.SizeOf(var)); String ids = ""; UInt32 id; for (int n = 0; n < var.ItemCount; n++) { id = (UInt32)Marshal.PtrToStructure(currentPtr, typeof(UInt32)); if (n != 0) { ids += ", "; } ids += Convert.ToString(id); currentPtr = (IntPtr)((int)currentPtr + Marshal.SizeOf(id)); } Console.WriteLine("(The following query Ids selected the above event: {0})", ids); Marshal.FreeHGlobal(variantPtr); } return(0); }