using System;
using System.Collections;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Xml;
using Microsoft.SqlServer.Server;

	// TVF that returns 4 columns in order: 
        // Time (datetime), 
        // Message (nvarchar(1000), 
        // Category (nvarchar(40)), 
        // EventID (int)
public class TVLog : IEnumerator
{ 
	private EventLog m_ev;				// EventLog we are reading
	private EventLogEntryCollection m_evc;
	private int m_iRow = 0;				// EventLog enumerator
	private int m_iLimit;
	// class constructor
	public TVLog (String LogName)
	{
		m_ev = new EventLog(LogName, Environment.MachineName);
		m_evc = m_ev.Entries;
		m_iLimit = m_evc.Count-1;
	}
	
	// Three IEnumerator methods.
	public bool 	MoveNext ()	{ return m_iLimit>m_iRow++; }
	public object Current { get {
		try
		{
			return m_evc[m_iRow];
		}
		catch (Exception ex)
		{
			return null;
		}
		;
	}} // Return an eventlog entry
	public void 	Reset ()	{ m_iRow = 0; }


	// Two Tvf contract methods
	[SqlFunctionAttribute (FillRowMethodName="FillRow")]
	public static IEnumerator InitMethod (String LogName)
	{
		return new TVLog (LogName);
	}

	public static void FillRow (Object obj, out SqlDateTime Time, 
		                                    out SqlString Message, 
		                                    out SqlString Category,
		                                    out SqlInt32 InstanceID)
	{
		EventLogEntry CurrentEntry = (EventLogEntry) obj; 
		// Shred the current entry
		Time = CurrentEntry.TimeGenerated;
		if (CurrentEntry.Message.Length > 1000) {Message = CurrentEntry.Message.Substring(0,1000);}
		else { Message = CurrentEntry.Message; }
		Category = CurrentEntry.Category;
		InstanceID = (SqlInt32) CurrentEntry.InstanceId;
		
	}

} // Class 
