C# Example

The Log Parser scriptable COM components can be easily consumed by .NET applications using the COM interop feature of the .NET Framework.

The COM interop feature of the .NET framework allows users to instantiate and use COM objects through the use of Runtime Callable Wrappers (RCW).
The RCW is a .NET class that wraps a COM object and gives a .NET application the notion that it's interacting with a managed .NET component.
RCW's are created by either using the Type Library Importer (tlbimp.exe) tool, or by importing a reference to the Log Parser scriptable COM objects through the Microsoft Visual Studio® .NET user interface.
In either case, the RCW's are generated and stored in an assembly named "Interop.MSUtil.dll", which contains Runtime Callable Wrappers for all of the Log Parser scriptable COM components. By referencing this assembly, our .NET applications can use the Log Parser scriptable COM components as if they were managed .NET components.

The following example C# application executes a Log Parser query that returns the latest 50 events from the System event log, printing the query results to the console output:

using System;
using LogQuery = Interop.MSUtil.LogQueryClassClass;
using EventLogInputFormat = Interop.MSUtil.COMEventLogInputContextClassClass;
using LogRecordSet = Interop.MSUtil.ILogRecordset;

class LogParserSample
{
	public static void Main(string[] Args)
	{
		try
		{
			// Instantiate the LogQuery object
			LogQuery oLogQuery = new LogQuery();

			// Instantiate the Event Log Input Format object
			EventLogInputFormat oEVTInputFormat = new EventLogInputFormat();

			// Set its "direction" parameter to "BW"
			oEVTInputFormat.direction = "BW";

			// Create the query
			string query = @"SELECT TOP 50 SourceName, EventID, Message FROM System";

			// Execute the query
			LogRecordSet oRecordSet = oLogQuery.Execute(query, oEVTInputFormat);

			// Browse the recordset
			for(; !oRecordSet.atEnd(); oRecordSet.moveNext())
			{
				Console.WriteLine(oRecordSet.getRecord().toNativeString(","));
		}

			// Close the recordset
			oRecordSet.close();
	}
		catch(System.Runtime.InteropServices.COMException exc)
		{
			Console.WriteLine("Unexpected error: " + exc.Message);
	}
}
}

The following steps describe how to build this sample application:

  1. Build an interop assembly containing the Runtime Callable Wrappers for the Log Parser scriptable COM components.
    This step can by executed in two different ways: In either case, an assembly named "Interop.MSUtil.dll" is created.
  2. Compile the sample source file into an executable, referencing the newly created "Interop.MSUtil.dll" assembly.
    From a command-line shell, this step can be executed as follows:
    C:\>csc /r:Interop.MSUtil.dll /out:Events.exe sample.cs
    

© 2004 Microsoft Corporation. All rights reserved.