Przeglądaj źródła

* System.dll.sources: Added Win32EventLog.cs.
* EventLogEntry.cs: Added InstanceId property (2.0 only). Moved
Obsolete attribute to correct property.
* EventSourceCreationData.cs: Updated copyright. For internal ctor,
set log name to "Application" if value is null or zero-length string.
* EventLogImpl.cs: EventImpl now acts as base class for event log
implemenations.
* NullEventLog.cs: Modified to implement new abstract methods of base
class. Removed factory class.
* EventLog.cs: EventLog implementation that delegates just about
everything to individual eventlog providers. To specify the event log
implementation to use, the MONO_EVENTLOG_TYPE environment variable can
be used. Possible values are:
- win32 : read/write entries using the native win32 eventlog
- local[:path] : read/write entries as files to a local directory
- null : silently ignore all entries
The default is "null" on unix (and versions of Windows before NT,
meaning Windows 98, ...), and "win32" on Windows NT (and higher).
When "the local" implementation is used, the directory in which to
store the event logs, event sources and entries can be specified as
part of MONO_EVENTLOG_TYPE environment variable using the syntax
"local:<path>" (eg. local:/home/myuser/mono/eventlog).
* LocalFileEventLog.cs: Event log implementation which uses a local
file store. The directory to use for persistence can be specified
as part of the MONO_EVENTLOG_TYPE environment variable (see above).
If that directory is not explicitly set, then the following directory
will be used for storing eventlog entries:
- windows : %APPDATA%\mono\eventlog
- unix : /var/lib/mono/eventlog
On unix, the directory permission for individual eventlog log
directories will be set to 777 (with +t bit) allowing everyone to
read and write eventlog entries while only allowing entries to be
deleted by the user(s) that created them.
Format of log files was modified to allow it contain all necessary
information for an event log entry.
* Win32EventLog.cs: Event log implementation for Windows NT and
higher which uses the Win32 native event log for reading/writing
eventlog entries, and which uses the registry to store event log and
event source registration information.
* EventLogEntryCollection.cs: Delegate implementation to event log
implementation. Use lazy init for enumerating entries. Cache current
item in 2.0 profile.
* EventLogTest.cs: Enable tests. On 2.0 profile, set MONO_EVENTLOG_TYPE
environment variable to force local file implementation to be used for
unit tests. This avoids permission issues for the unit tests, and
allows us to clean up the files/directory that are created during the
test run. Skip tests that cannot pass when the null implementation is
active (on 1.0 profile). Added tests for all WriteEntry and WriteEvent
(2.0 only) overloads, Clear, Entries, Exists and LogNameFromSourceName.

svn path=/trunk/mcs/; revision=64088

Gert Driesen 19 lat temu
rodzic
commit
bc28d0226b

+ 4 - 0
mcs/class/System/ChangeLog

@@ -1,3 +1,7 @@
+2006-08-20  Gert Driesen  <[email protected]>
+
+	* System.dll.sources: Added Win32EventLog.cs.
+
 2006-08-14  Atsushi Enomoto  <[email protected]>
 
 	* System.dll.sources : added LocalFileEventLog.cs and NullEventLog.cs.

+ 44 - 0
mcs/class/System/System.Diagnostics/ChangeLog

@@ -1,3 +1,47 @@
+2006-08-20  Gert Driesen  <[email protected]>
+
+	* EventLogEntry.cs: Added InstanceId property (2.0 only). Moved
+	Obsolete attribute to correct property.
+	* EventSourceCreationData.cs: Updated copyright. For internal ctor,
+	set log name to "Application" if value is null or zero-length string.
+	* EventLogImpl.cs: EventImpl now acts as base class for event log 
+	implemenations.
+	* NullEventLog.cs: Modified to implement new abstract methods of base
+	class. Removed factory class.
+	* EventLog.cs: EventLog implementation that delegates just about 
+	everything to individual eventlog providers. To specify the event log
+	implementation to use, the MONO_EVENTLOG_TYPE environment variable can
+	be used. Possible values are:
+	- win32	: read/write entries using the native win32 eventlog
+	- local[:path] : read/write entries as files to a local directory
+	- null : silently ignore all entries
+	The default is "null" on unix (and versions of Windows before NT,
+	meaning Windows 98, ...), and "win32" on Windows NT (and higher).
+	When "the local" implementation is used, the directory in which to 
+	store the event logs, event sources and entries can be specified as 
+	part of MONO_EVENTLOG_TYPE environment variable using the syntax 
+	"local:<path>" (eg. local:/home/myuser/mono/eventlog).
+	* LocalFileEventLog.cs: Event log implementation which uses a local
+	file store. The directory to use for persistence can be specified
+	as part of the MONO_EVENTLOG_TYPE environment variable (see above).
+	If that directory is not explicitly set, then the following directory
+	will be used for storing eventlog entries:
+	- windows	: %APPDATA%\mono\eventlog
+	- unix		: /var/lib/mono/eventlog
+	On unix, the directory permission for individual eventlog log 
+	directories will be set to 777 (with +t bit) allowing everyone to
+	read and write eventlog entries while only allowing entries to be
+	deleted by the user(s) that created them.
+	Format of log files was modified to allow it contain all necessary
+	information for an event log entry.
+	* Win32EventLog.cs: Event log implementation for Windows NT and 
+	higher which uses the Win32 native event log for reading/writing
+	eventlog entries, and which uses the registry to store event log and
+	event source registration information.
+	* EventLogEntryCollection.cs: Delegate implementation to event log
+	implementation. Use lazy init for enumerating entries. Cache current
+	item in 2.0 profile.
+
 2006-08-14  Atsushi Enomoto  <[email protected]>
 
 	* LocalFileEventLog.cs : change lengthy environment variable name.

+ 363 - 63
mcs/class/System/System.Diagnostics/EventLog.cs

@@ -2,13 +2,14 @@
 // System.Diagnostics.EventLog.cs
 //
 // Authors:
-//   Jonathan Pryor ([email protected])
-//   Andreas Nahr ([email protected])
+//	Jonathan Pryor ([email protected])
+//	Andreas Nahr ([email protected])
+//	Gert Driesen ([email protected])
 //
-// (C) 2002
-// (C) 2003 Andreas Nahr
+// Copyright (C) 2002
+// Copyright (C) 2003 Andreas Nahr
+// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
 //
-
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -32,8 +33,13 @@
 
 using System;
 using System.Diagnostics;
+using System.Collections;
 using System.ComponentModel;
 using System.ComponentModel.Design;
+using System.Globalization;
+using System.IO;
+
+using Microsoft.Win32;
 
 namespace System.Diagnostics 
 {
@@ -42,38 +48,56 @@ namespace System.Diagnostics
 	[Designer ("Microsoft.VisualStudio.Install.EventLogInstallableComponentDesigner, " + Consts.AssemblyMicrosoft_VisualStudio)]
 	public class EventLog : Component, ISupportInitialize 
 	{
-
 		private string source;
 		private string logName;
 		private string machineName;
 		private bool doRaiseEvents = false;
 		private ISynchronizeInvoke synchronizingObject = null;
 
+		// IMPORTANT: also update constants in EventLogTest
+		internal const string LOCAL_FILE_IMPL = "local";
+		private const string WIN32_IMPL = "win32";
+		private const string NULL_IMPL = "null";
+
+		internal const string EVENTLOG_TYPE_VAR = "MONO_EVENTLOG_TYPE";
+
 		private EventLogImpl Impl;
 
-		public EventLog()
-			: this ("")
+		public EventLog() : this (string.Empty)
 		{
 		}
 
-		public EventLog(string logName)
-			: this (logName, ".")
+		public EventLog(string logName) : this (logName, ".")
 		{
 		}
 
-		public EventLog(string logName, string machineName) 
-			: this (logName, machineName, "")
+		public EventLog(string logName, string machineName)
+			: this (logName, machineName, string.Empty)
 		{
 		}
 
 		public EventLog(string logName, string machineName, string source)
 		{
+			if (logName == null) {
+				throw new ArgumentNullException ("logName");
+			}
+			if (machineName == null || machineName.Length == 0)
+#if NET_2_0
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "Invalid value '{0}' for"
+					+ " parameter 'machineName'.", machineName));
+#else
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "Invalid value {0} for"
+					+ " parameter MachineName.", machineName));
+#endif
+
 			this.source = source;
 			this.machineName = machineName;
 			this.logName = logName;
 
-			this.Impl = EventLogImpl.Create (this);
-			EventLogImpl.EntryWritten += new EntryWrittenEventHandler (EntryWrittenHandler);
+			Impl = CreateEventLogImpl (this);
+			Impl.EntryWritten += new EntryWrittenEventHandler (EntryWrittenHandler);
 		}
 
 		private void EntryWrittenHandler (object sender, EntryWrittenEventArgs e)
@@ -92,15 +116,23 @@ namespace System.Diagnostics
 		[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
 		[MonitoringDescription ("The entries in the log.")]
 		public EventLogEntryCollection Entries {
-			get {return Impl.Entries;}
+			get {return new EventLogEntryCollection(Impl);}
 		}
 
 		[ReadOnly (true), DefaultValue (""), RecommendedAsConfigurable (true)]
 		[TypeConverter ("System.Diagnostics.Design.LogConverter, " + Consts.AssemblySystem_Design)]
 		[MonitoringDescription ("Name of the log that is read and written.")]
 		public string Log {
-			get {return logName;}
-			set {logName = value;}
+			get {
+				if (source != null && source.Length > 0)
+					return GetLogName ();
+				return logName;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException ("value");
+				logName = value;
+			}
 		}
 
 		[Browsable (false)]
@@ -119,8 +151,8 @@ namespace System.Diagnostics
 		[TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
 		[MonitoringDescription ("The application name that writes the log.")]
 		public string Source {
-			get {return source;}
-			set {source = value;}
+			get { return source; }
+			set { source = (value == null) ? string.Empty : value; }
 		}
 
 		[Browsable (false), DefaultValue (null)]
@@ -130,57 +162,116 @@ namespace System.Diagnostics
 			set {synchronizingObject = value;}
 		}
 
-		public void BeginInit()
+		public void BeginInit ()
 		{
 			Impl.BeginInit();
 		}
 
-		public void Clear()
+		public void Clear ()
 		{
-			Impl.Clear();
+			string logName = Log;
+			if (logName == null || logName.Length == 0)
+				throw new ArgumentException ("Log property value has not been specified.");
+
+			if (!EventLog.Exists (logName, MachineName))
+				throw new InvalidOperationException (string.Format (
+					CultureInfo.InvariantCulture, "Event Log '{0}'"
+					+ " does not exist on computer '{1}'.", logName,
+					machineName));
+
+			Impl.Clear ();
 		}
 
-		public void Close()
+		public void Close ()
 		{
 			Impl.Close();
 		}
 
-		public static void CreateEventSource(string source, string logName)
+		public static void CreateEventSource (string source, string logName)
 		{
 			CreateEventSource (source, logName, ".");
 		}
 
-		public static void CreateEventSource(string source, 
+		public static void CreateEventSource (string source, 
 			string logName, 
 			string machineName)
 		{
-			EventLogImpl.CreateEventSource (source, logName, machineName);
+			CreateEventSource (new EventSourceCreationData (source, logName,
+				machineName));
+		}
+
+#if NET_2_0
+		[MonoTODO ("Support remote machine")]
+		public
+#else
+		private
+#endif
+		static void CreateEventSource (EventSourceCreationData sourceData)
+		{
+			if (sourceData.Source == null || sourceData.Source.Length == 0)
+				throw new ArgumentException ("Source property value has not been specified.");
+
+			if (sourceData.LogName == null || sourceData.LogName.Length == 0)
+				throw new ArgumentException ("Log property value has not been specified.");
+
+			if (SourceExists (sourceData.Source, sourceData.MachineName))
+				throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
+					"Source '{0}' already exists on '{1}'.", sourceData.Source,
+					sourceData.MachineName));
+
+			EventLogImpl impl = CreateEventLogImpl (sourceData.LogName,
+				sourceData.MachineName, sourceData.Source);
+			impl.CreateEventSource (sourceData);
 		}
 
-		public static void Delete(string logName)
+		public static void Delete (string logName)
 		{
 			Delete (logName, ".");
 		}
 
-		public static void Delete(string logName, string machineName)
+		[MonoTODO ("Support remote machine")]
+		public static void Delete (string logName, string machineName)
 		{
-			EventLogImpl.Delete (logName, machineName);
+			if (machineName == null || machineName.Length == 0)
+				throw new ArgumentException ("Invalid format for argument"
+					+ " machineName.");
+
+			if (logName == null || logName.Length == 0)
+				throw new ArgumentException ("Log to delete was not specified.");
+
+			EventLogImpl impl = CreateEventLogImpl (logName, machineName, 
+				string.Empty);
+			impl.Delete (logName, machineName);
 		}
 
-		public static void DeleteEventSource(string source)
+		public static void DeleteEventSource (string source)
 		{
 			DeleteEventSource (source, ".");
 		}
 
-		public static void DeleteEventSource(string source, 
-			string machineName)
+		[MonoTODO ("Support remote machine")]
+		public static void DeleteEventSource (string source, string machineName)
 		{
-			EventLogImpl.DeleteEventSource (source, machineName);
+			if (machineName == null || machineName.Length == 0)
+#if NET_2_0
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "Invalid value '{0}' for"
+					+ " parameter 'machineName'.", machineName));
+#else
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "Invalid value {0} for"
+					+ " parameter machineName.", machineName));
+#endif
+
+			EventLogImpl impl = CreateEventLogImpl (string.Empty, machineName,
+				source);
+			impl.DeleteEventSource (source, machineName);
 		}
 
-		protected override void Dispose(bool disposing)
+		protected override void Dispose (bool disposing)
 		{
-			Impl.Dispose (disposing);
+			if (Impl != null)
+				Impl.Dispose (disposing);
 		}
 
 		public void EndInit()
@@ -188,102 +279,181 @@ namespace System.Diagnostics
 			Impl.EndInit();
 		}
 
-		public static bool Exists(string logName)
+		public static bool Exists (string logName)
 		{
 			return Exists (logName, ".");
 		}
 
-		public static bool Exists(string logName, string machineName)
+		[MonoTODO ("Support remote machine")]
+		public static bool Exists (string logName, string machineName)
 		{
-			return EventLogImpl.Exists (logName, machineName);
+			if (machineName == null || machineName.Length == 0)
+				throw new ArgumentException ("Invalid format for argument machineName.");
+
+			if (logName == null || logName.Length == 0)
+				return false; 
+
+			EventLogImpl impl = CreateEventLogImpl (logName, machineName,
+				string.Empty);
+			return impl.Exists (logName, machineName);
 		}
 
-		public static EventLog[] GetEventLogs()
+		public static EventLog[] GetEventLogs ()
 		{
 			return GetEventLogs (".");
 		}
 
-		public static EventLog[] GetEventLogs(string machineName)
+		[MonoTODO ("Support remote machine")]
+		public static EventLog[] GetEventLogs (string machineName)
 		{
-			return EventLogImpl.GetEventLogs (machineName);
+			EventLogImpl impl = CreateEventLogImpl (new EventLog ());
+			return impl.GetEventLogs (machineName);
 		}
 
-		public static string LogNameFromSourceName(string source, 
-			string machineName)
+		[MonoTODO ("Support remote machine")]
+		public static string LogNameFromSourceName (string source, string machineName)
 		{
-			return EventLogImpl.LogNameFromSourceName (source, machineName);
+			if (machineName == null || machineName.Length == 0)
+#if NET_2_0
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "Invalid value '{0}' for"
+					+ " parameter 'MachineName'.", machineName));
+#else
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "Invalid value {0} for"
+					+ " parameter MachineName.", machineName));
+#endif
+
+			EventLogImpl impl = CreateEventLogImpl (string.Empty, machineName,
+				source);
+			return impl.LogNameFromSourceName (source, machineName);
 		}
 
-		public static bool SourceExists(string source)
+		public static bool SourceExists (string source)
 		{
 			return SourceExists (source, ".");
 		}
 
-		public static bool SourceExists(string source, string machineName)
+		[MonoTODO ("Support remote machines")]
+		public static bool SourceExists (string source, string machineName)
 		{
-			return EventLogImpl.SourceExists (source, machineName);
+			if (machineName == null || machineName.Length == 0)
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "Invalid value '{0}' for"
+					+ " parameter 'machineName'.", machineName));
+
+			EventLogImpl impl = CreateEventLogImpl (string.Empty, machineName,
+				source);
+			return impl.SourceExists (source, machineName);
 		}
 
-		public void WriteEntry(string message)
+		public void WriteEntry (string message)
 		{
 			WriteEntry (message, EventLogEntryType.Information);
 		}
 
-		public void WriteEntry(string message, EventLogEntryType type)
+		public void WriteEntry (string message, EventLogEntryType type)
 		{
 			WriteEntry (message, type, 0);
 		}
 
-		public void WriteEntry(string message, EventLogEntryType type, 
+		public void WriteEntry (string message, EventLogEntryType type, 
 			int eventID)
 		{
 			WriteEntry (message, type, eventID, 0);
 		}
 
-		public void WriteEntry(string message, EventLogEntryType type, 
+		public void WriteEntry (string message, EventLogEntryType type, 
 			int eventID,
 			short category)
 		{
 			WriteEntry (message, type, eventID, category, null);
 		}
 
-		public void WriteEntry(string message, EventLogEntryType type, 
+		public void WriteEntry (string message, EventLogEntryType type, 
 			int eventID,
 			short category, byte[] rawData)
 		{
-			Impl.WriteEntry (message, type, eventID, category, rawData);
+			WriteEntry (new string [] { message }, type, eventID,
+				category, rawData);
 		}
 
-		public static void WriteEntry(string source, string message)
+		public static void WriteEntry (string source, string message)
 		{
 			WriteEntry (source, message, EventLogEntryType.Information);
 		}
 
-		public static void WriteEntry(string source, string message, 
+		public static void WriteEntry (string source, string message, 
 			EventLogEntryType type)
 		{
-			WriteEntry (source, message, EventLogEntryType.Information, 0);
+			WriteEntry (source, message, type, 0);
 		}
 
-		public static void WriteEntry(string source, string message, 
+		public static void WriteEntry (string source, string message, 
 			EventLogEntryType type, int eventID)
 		{
-			WriteEntry (source, message, EventLogEntryType.Information, eventID, 0);
+			WriteEntry (source, message, type, eventID, 0);
 		}
 
-		public static void WriteEntry(string source, string message, 
+		public static void WriteEntry (string source, string message, 
 			EventLogEntryType type, int eventID, short category)
 		{
-			WriteEntry (source, message, EventLogEntryType.Information, eventID, category, null);
+			WriteEntry (source, message, type, eventID, category, null);
 		}
 
-		public static void WriteEntry(string source, string message, 
+		public static void WriteEntry (string source, string message, 
 			EventLogEntryType type, int eventID, short category, 
 			byte[] rawData)
 		{
-			EventLogImpl.WriteEntry (source, message, type, eventID, category, rawData);
+			using (EventLog eventLog = new EventLog ()) {
+				eventLog.Source = source;
+				eventLog.WriteEntry (message, type, eventID, category, rawData);
+			}
+		}
+
+#if NET_2_0
+		public void WriteEvent (EventInstance instance, params object [] values)
+		{
+			WriteEvent (instance, null, values);
 		}
 
+		public void WriteEvent (EventInstance instance, byte [] data, params object [] values)
+		{
+			if (instance == null)
+				throw new ArgumentNullException ("instance");
+
+			string [] replacementStrings = null;
+			if (values != null) {
+				replacementStrings = new string [values.Length];
+				for (int i = 0; i < values.Length; i++) {
+					object value = values [i];
+					if (value == null)
+						replacementStrings [i] = string.Empty;
+					else
+						replacementStrings [i] = values [i].ToString ();
+				}
+			} else {
+				replacementStrings = new string [0];
+			}
+
+			WriteEntry (replacementStrings, instance.EntryType, instance
+				.InstanceId, (short) instance.CategoryId, data);
+		}
+
+		public static void WriteEvent (string source, EventInstance instance, params object [] values)
+		{
+			WriteEvent (source, instance, null, values);
+		}
+
+		public static void WriteEvent (string source, EventInstance instance, byte [] data, params object [] values)
+		{
+			using (EventLog eventLog = new EventLog ()) {
+				eventLog.Source = source;
+				eventLog.WriteEvent (instance, data, values);
+			}
+		}
+#endif
+
 		internal void OnEntryWritten (EventLogEntry newEntry)
 		{
 			if (EntryWritten != null)
@@ -291,7 +461,137 @@ namespace System.Diagnostics
 		}
 
 		[MonitoringDescription ("Raised for each EventLog entry written.")]
+		[MonoTODO ("Use FSM for local file implementation, and NotifyChangeEventLog for win32")]
 		public event EntryWrittenEventHandler EntryWritten;
+
+		internal string GetLogName ()
+		{
+			if (logName != null && logName.Length > 0)
+				return logName;
+
+			// if no log name has been set, then use source to determine name of log
+			logName = LogNameFromSourceName (source, machineName);
+			return logName;
+		}
+
+		private static EventLogImpl CreateEventLogImpl (string logName, string machineName, string source)
+		{
+			EventLog eventLog = new EventLog (logName, machineName, source);
+			return CreateEventLogImpl (eventLog);
+		}
+
+		private static EventLogImpl CreateEventLogImpl (EventLog eventLog)
+		{
+			switch (EventLogImplType) {
+			case LOCAL_FILE_IMPL:
+				return new LocalFileEventLog (eventLog);
+			case WIN32_IMPL:
+				return new Win32EventLog (eventLog);
+			case NULL_IMPL:
+				return new NullEventLog (eventLog);
+			default:
+				// we should never get here
+				throw new NotSupportedException (string.Format (
+					CultureInfo.InvariantCulture, "Eventlog implementation"
+					+ " '{0}' is not supported.", EventLogImplType));
+			}
+		}
+
+		private static bool Win32EventLogEnabled {
+			get {
+				return (Environment.OSVersion.Platform == PlatformID.Win32NT);
+			}
+		}
+
+		// IMPORTANT: also modify corresponding property in EventLogTest
+		private static string EventLogImplType
+		{
+			get {
+				string implType = Environment.GetEnvironmentVariable (EVENTLOG_TYPE_VAR);
+				if (implType == null) {
+					if (Win32EventLogEnabled)
+						return WIN32_IMPL;
+					implType = NULL_IMPL;
+				} else {
+					if (Win32EventLogEnabled && string.Compare (implType, WIN32_IMPL, true) == 0)
+						implType = WIN32_IMPL;
+					else if (string.Compare (implType, NULL_IMPL, true) == 0)
+						implType = NULL_IMPL;
+					else if (string.Compare (implType, 0, LOCAL_FILE_IMPL, 0, LOCAL_FILE_IMPL.Length, true) == 0)
+						implType = LOCAL_FILE_IMPL;
+					else
+						throw new NotSupportedException (string.Format (
+							CultureInfo.InvariantCulture, "Eventlog implementation"
+							+ " '{0}' is not supported.", implType));
+				}
+				return implType;
+			}
+		}
+
+		private void WriteEntry (string [] replacementStrings, EventLogEntryType type, long instanceID, short category, byte [] rawData)
+		{
+			if (Source.Length == 0)
+				throw new ArgumentException ("Source property was not set"
+					+ "before writing to the event log.");
+
+			if (!Enum.IsDefined (typeof (EventLogEntryType), type))
+				throw new InvalidEnumArgumentException ("type", (int) type,
+					typeof (EventLogEntryType));
+
+#if NET_2_0
+			ValidateEventID (instanceID);
+#endif
+
+			if (!SourceExists (Source, MachineName)) {
+				if (Log == null || Log.Length == 0) {
+					Log = "Application";
+				}
+				CreateEventSource (Source, Log, MachineName);
+
+#if ONLY_1_1
+				ValidateEventID (instanceID);
+#endif
+			} else if (logName != null && logName.Length != 0) {
+#if ONLY_1_1
+				ValidateEventID (instanceID);
+#endif
+				string actualLog = LogNameFromSourceName (Source, MachineName);
+				if (string.Compare (logName, actualLog, true, CultureInfo.InvariantCulture) != 0)
+					throw new ArgumentException (string.Format (
+						CultureInfo.InvariantCulture, "The source '{0}' is not"
+						+ " registered in log '{1}' (it is registered in log"
+						+ " '{2}'). The Source and Log properties must be"
+						+ " matched, or you may set Log to the empty string,"
+						+ " and it will automatically be matched to the Source"
+						+ " property.", Source, logName, actualLog));
+			}
+
+#if ONLY_1_1
+			ValidateEventID (instanceID);
+#endif
+
+			if (rawData == null)
+				rawData = new byte [0];
+
+			Impl.WriteEntry (replacementStrings, type, (uint) instanceID, category, rawData);
+		}
+
+		private void ValidateEventID (long instanceID)
+		{
+			int eventID = GetEventID (instanceID);
+			if (eventID < ushort.MinValue || eventID > ushort.MaxValue)
+				throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
+					"Invalid eventID value '{0}'. It must be in the range between"
+					+ " '{1}' and '{2}'.", instanceID, ushort.MinValue, ushort.MaxValue));
+		}
+
+		internal static int GetEventID (long instanceID)
+		{
+			long inst = (instanceID < 0) ? -instanceID : instanceID;
+
+			// MSDN: eventID equals the InstanceId with the top two bits masked
+			int eventID = (int) (inst & 0x3fffffff);
+			return (instanceID < 0) ? -eventID : eventID;
+		}
 	}
 }
-

+ 23 - 7
mcs/class/System/System.Diagnostics/EventLogEntry.cs

@@ -31,6 +31,9 @@
 //
 
 using System.ComponentModel;
+#if NET_2_0
+using System.Runtime.InteropServices;
+#endif
 using System.Runtime.Serialization;
 using System.Security.Permissions;
 
@@ -56,12 +59,15 @@ namespace System.Diagnostics
 		private DateTime timeGenerated;
 		private DateTime timeWritten;
 		private string userName;
+#if NET_2_0
+		private long instanceId;
+#endif
 
 		internal EventLogEntry (string category, short categoryNumber, int index, 
-					int eventID, string message, string source,
-					string userName, string machineName, EventLogEntryType entryType,
-					DateTime timeGenerated, DateTime timeWritten, byte[] data,
-					string[] replacementStrings)
+					int eventID, string source, string message, string userName, 
+					string machineName, EventLogEntryType entryType, 
+					DateTime timeGenerated, DateTime timeWritten, byte[] data, 
+					string[] replacementStrings, long instanceId)
 		{
 			this.category = category;
 			this.categoryNumber = categoryNumber;
@@ -76,6 +82,9 @@ namespace System.Diagnostics
 			this.timeGenerated = timeGenerated;
 			this.timeWritten = timeWritten;
 			this.userName = userName;
+#if NET_2_0
+			this.instanceId = instanceId;
+#endif
 		}
 
 		[MonoTODO]
@@ -98,14 +107,14 @@ namespace System.Diagnostics
 			get { return data; }
 		}
 
-#if NET_2_0
-		[Obsolete ("Use InstanceId")]
-#endif
 		[MonitoringDescription ("The type of this event entry.")]
 		public EventLogEntryType EntryType {
 			get { return entryType; }
 		}
 
+#if NET_2_0
+		[Obsolete ("Use InstanceId")]
+#endif
 		[MonitoringDescription ("An ID number for this event entry.")]
 		public int EventID {
 			get { return eventID; }
@@ -116,6 +125,13 @@ namespace System.Diagnostics
 			get { return index; }
 		}
 
+#if NET_2_0
+		[ComVisible (false)]
+		public long InstanceId {
+			get { return instanceId; }
+		}
+#endif
+
 		[MonitoringDescription ("The Computer on which this event entry occured.")]
 		public string MachineName {
 			get { return machineName; }

+ 68 - 13
mcs/class/System/System.Diagnostics/EventLogEntryCollection.cs

@@ -37,44 +37,99 @@ namespace System.Diagnostics {
 
 	public class EventLogEntryCollection : ICollection, IEnumerable {
 
-		private ArrayList eventLogs = new ArrayList ();
+		readonly EventLogImpl _impl;
 
-		internal EventLogEntryCollection(IEnumerable entries)
+		internal EventLogEntryCollection(EventLogImpl impl)
 		{
-			foreach (object entry in entries)
-				eventLogs.Add (entry);
+			_impl = impl;
 		}
 
 		public int Count {
-			get {return eventLogs.Count;}
+			get { return _impl.EntryCount; }
 		}
 
 		public virtual EventLogEntry this [int index] {
-			get {return (EventLogEntry) eventLogs[index];}
+			get { return _impl[index]; }
 		}
 
 		bool ICollection.IsSynchronized {
-			get {return eventLogs.IsSynchronized;}
+			get { return false; }
 		}
 
 		object ICollection.SyncRoot {
-			get {return eventLogs.SyncRoot;}
+			get { return this; }
 		}
 
-		public void CopyTo (EventLogEntry[] eventLogs, int index)
+		public void CopyTo (EventLogEntry[] eventLogEntries, int index)
 		{
-			eventLogs.CopyTo (eventLogs, index);
+			EventLogEntry[] entries = _impl.GetEntries ();
+			Array.Copy (entries, 0, eventLogEntries, index, entries.Length);
 		}
 
 		public IEnumerator GetEnumerator ()
 		{
-			return eventLogs.GetEnumerator ();
+			return new EventLogEntryEnumerator (_impl);
 		}
 
 		void ICollection.CopyTo (Array array, int index)
 		{
-			eventLogs.CopyTo (array, index);
+			EventLogEntry[] entries = _impl.GetEntries ();
+			Array.Copy (entries, 0, array, index, entries.Length);
 		}
-	}
+
+		private class EventLogEntryEnumerator : IEnumerator
+		{
+			internal EventLogEntryEnumerator (EventLogImpl impl)
+			{
+				_impl = impl;
+			}
+
+			object IEnumerator.Current {
+				get { return Current; }
+			}
+
+			public EventLogEntry Current {
+				get {
+#if NET_2_0
+					if (_currentEntry != null)
+						return _currentEntry;
+#else
+					if (_currentIndex >= 0 && _currentIndex < _impl.EntryCount)
+						return _impl [_currentIndex];
+#endif
+
+					throw new InvalidOperationException ("No current EventLog"
+						+ " entry available, cursor is located before the first"
+						+ " or after the last element of the enumeration.");
+				}
+			}
+
+			public bool MoveNext ()
+			{
+				_currentIndex++;
+#if NET_2_0
+				if (_currentIndex >= _impl.EntryCount) {
+					_currentEntry = null;
+					return false;
+				}
+				_currentEntry = _impl [_currentIndex];
+				return true;
+#else
+				return (_currentIndex < _impl.EntryCount);
+#endif
+			}
+
+			public void Reset ()
+			{
+				_currentIndex = - 1;
+			}
+
+			readonly EventLogImpl _impl;
+			int _currentIndex = -1;
+#if NET_2_0
+			EventLogEntry _currentEntry;
+#endif
+		}
+}
 }
 

+ 92 - 84
mcs/class/System/System.Diagnostics/EventLogImpl.cs

@@ -4,11 +4,11 @@
 // Authors:
 //   Andreas Nahr ([email protected])
 //   Atsushi Enomoto  <[email protected]>
+//   Gert Driesen ([email protected])
 //
 // (C) 2003 Andreas Nahr
 // (C) 2006 Novell, Inc.
 //
-
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -31,134 +31,142 @@
 //
 
 using System;
-using System.Diagnostics;
 using System.ComponentModel;
 using System.ComponentModel.Design;
-using System.Collections;
+using System.Diagnostics;
 using System.Globalization;
-using System.IO;
-using System.Net;
+
+using Microsoft.Win32;
 
 namespace System.Diagnostics
 {
 	internal abstract class EventLogImpl
 	{
-		static EventLogFactory factory;
+		readonly EventLog _coreEventLog;
 
-		static EventLogImpl ()
+		protected EventLogImpl (EventLog coreEventLog)
 		{
-			factory = GetFactory ();
+			_coreEventLog = coreEventLog;
 		}
 
-		static EventLogFactory GetFactory ()
-		{
-			if (LocalFileEventLogUtil.IsEnabled)
-				return new LocalFileEventLogFactory ();
+		public event EntryWrittenEventHandler EntryWritten;
 
-			//throw new NotSupportedException (String.Format ("No EventLog implementation is supported. Consider setting MONO_LOCAL_EVENTLOG_PATH environment variable."));
-			return new NullEventLogFactory ();
+		protected EventLog CoreEventLog {
+			get { return _coreEventLog; }
 		}
 
-		EventLog log;
+		public int EntryCount {
+			get {
+				if (_coreEventLog.Log == null || _coreEventLog.Log.Length == 0) {
+					throw new ArgumentException ("Log property is not set.");
+				}
 
-		protected EventLogImpl (EventLog coreEventLog)
-		{
-			this.log = coreEventLog;
-		}
+				if (!EventLog.Exists (_coreEventLog.Log, _coreEventLog.MachineName)) {
+					throw new InvalidOperationException (string.Format (
+						CultureInfo.InvariantCulture, "The event log '{0}' on "
+						+ " computer '{1}' does not exist.", _coreEventLog.Log,
+						_coreEventLog.MachineName));
+				}
 
-		public static EventLogImpl Create (EventLog source)
-		{
-			return factory.Create (source);
+				return GetEntryCount ();
+			}
 		}
 
-		public static event EntryWrittenEventHandler EntryWritten;
-
-		public abstract EventLogEntryCollection Entries { get; }
-
-		public abstract string LogDisplayName { get; }
+		public EventLogEntry this[int index] {
+			get {
+				if (_coreEventLog.Log == null || _coreEventLog.Log.Length == 0) {
+					throw new ArgumentException ("Log property is not set.");
+				}
 
-		public abstract void BeginInit ();
-
-		public abstract void Clear ();
+				if (!EventLog.Exists (_coreEventLog.Log, _coreEventLog.MachineName)) {
+					throw new InvalidOperationException (string.Format (
+						CultureInfo.InvariantCulture, "The event log '{0}' on "
+						+ " computer '{1}' does not exist.", _coreEventLog.Log,
+						_coreEventLog.MachineName));
+				}
 
-		public abstract void Close ();
+				if (index < 0 || index >= EntryCount)
+					throw new ArgumentException ("Index out of range");
 
-		public static void CreateEventSource (string source, string logName, string machineName)
-		{
-			factory.CreateEventSource (source, logName, machineName);
+				return GetEntry (index);
+			}
 		}
 
-		public static void Delete (string logName, string machineName)
-		{
-			factory.Delete (logName, machineName);
+		public string LogDisplayName {
+			get {
+#if NET_2_0
+				// to-do perform valid character checks
+				if (_coreEventLog.Log != null && _coreEventLog.Log.Length == 0) {
+					throw new InvalidOperationException ("Event log names must"
+						+ " consist of printable characters and cannot contain"
+						+ " \\, *, ?, or spaces.");
+				}
+#endif
+				if (_coreEventLog.Log != null) {
+					if (!EventLog.Exists (_coreEventLog.Log, _coreEventLog.MachineName)) {
+						throw new InvalidOperationException (string.Format (
+							CultureInfo.InvariantCulture, "Cannot find Log {0}"
+							+ " on computer {1}.", _coreEventLog.Log,
+							_coreEventLog.MachineName));
+					}
+				}
+
+				return GetLogDisplayName ();
+			}
 		}
 
-		public static void DeleteEventSource (string source, string machineName)
+		public EventLogEntry [] GetEntries ()
 		{
-			factory.DeleteEventSource (source, machineName);
+			string logName = CoreEventLog.Log;
+			if (logName == null || logName.Length == 0)
+				throw new ArgumentException ("Log property value has not been specified.");
+
+			if (!EventLog.Exists (logName))
+				throw new InvalidOperationException (string.Format (
+					CultureInfo.InvariantCulture, "The event log '{0}' on "
+					+ " computer '{1}' does not exist.", logName,
+					_coreEventLog.MachineName));
+
+			int entryCount = GetEntryCount ();
+			EventLogEntry [] entries = new EventLogEntry [entryCount];
+			for (int i = 0; i < entryCount; i++) {
+				entries [i] = GetEntry (i);
+			}
+			return entries;
 		}
 
-		public abstract void Dispose (bool disposing);
-
-		public abstract void EndInit ();
+		public abstract void BeginInit ();
 
-		public static bool Exists (string logName, string machineName)
-		{
-			return factory.Exists (logName, machineName);
-		}
+		public abstract void Clear ();
 
-		public static EventLog[] GetEventLogs (string machineName)
-		{
-			return factory.GetEventLogs (machineName);
-		}
+		public abstract void Close ();
 
-		public static string LogNameFromSourceName (string source, string machineName)
-		{
-			return factory.LogNameFromSourceName (source, machineName);
-		}
+		public abstract void CreateEventSource (EventSourceCreationData sourceData);
 
-		public static bool SourceExists (string source, string machineName)
-		{
-			return factory.SourceExists (source, machineName);
-		}
+		public abstract void Delete (string logName, string machineName);
 
-		public void WriteEntry (string message, EventLogEntryType type, int eventID, short category, byte[] rawData)
-		{
-			WriteEntry (log.Source, message, type, eventID, category, rawData);
-		}
+		public abstract void DeleteEventSource (string source, string machineName);
 
-		public static void WriteEntry (string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData)
-		{
-			factory.WriteEntry (source, message, type, eventID, category, rawData);
-			if (EntryWritten != null) {
-				// FIXME: some arguments are improper.
-				EventLogEntry e = new EventLogEntry ("",
-					category, 0, eventID, message, source,
-					"", ".", type, DateTime.Now, DateTime.Now,
-					rawData, null);
-				EntryWritten (null, new EntryWrittenEventArgs (e));
-			}
-		}
-	}
+		public abstract void Dispose (bool disposing);
 
-	internal abstract class EventLogFactory
-	{
-		public abstract EventLogImpl Create (EventLog source);
+		public abstract void EndInit ();
 
-		public abstract void CreateEventSource (string source, string logName, string machineName);
+		public abstract bool Exists (string logName, string machineName);
 
-		public abstract void Delete (string logName, string machineName);
+		protected abstract int GetEntryCount ();
 
-		public abstract void DeleteEventSource (string source, string machineName);
+		protected abstract EventLogEntry GetEntry (int index);
 
-		public abstract bool Exists (string logName, string machineName);
+		public abstract EventLog [] GetEventLogs (string machineName);
 
-		public abstract EventLog[] GetEventLogs (string machineName);
+		protected abstract string GetLogDisplayName ();
 
 		public abstract string LogNameFromSourceName (string source, string machineName);
 
 		public abstract bool SourceExists (string source, string machineName);
 
-		public abstract void WriteEntry (string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData);
+		public abstract void WriteEntry (string [] replacementStrings, EventLogEntryType type, uint instanceID, short category, byte[] rawData);
+
+		protected abstract string FormatMessage (string source, uint messageID, string [] replacementStrings);
 	}
 }

+ 11 - 5
mcs/class/System/System.Diagnostics/EventSourceCreationData.cs

@@ -1,10 +1,10 @@
 //
 // System.Diagnostics.EventSourceCreationData
 //
-// Authors:
-//	Gert Driesen ([email protected])
+// Author:
+//	Gert Driesen <[email protected]>
 //
-// (C) 2006 Novell
+// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
 //
 //
 // Permission is hereby granted, free of charge, to any person obtaining
@@ -45,14 +45,20 @@ namespace System.Diagnostics
 		int _categoryCount;
 
 		public EventSourceCreationData (string source, string logName)
-			: this (source, logName, ".")
 		{
+			_source = source;
+			_logName = logName;
+			_machineName = ".";
 		}
 
 		internal EventSourceCreationData (string source, string logName, string machineName)
 		{
 			_source = source;
-			_logName = logName;
+			if (logName == null || logName.Length == 0) {
+				_logName = "Application";
+			} else {
+				_logName = logName;
+			}
 			_machineName = machineName;
 		}
 

+ 275 - 163
mcs/class/System/System.Diagnostics/LocalFileEventLog.cs

@@ -1,12 +1,12 @@
 //
-// LocalFileEventLog.cs
+// System.Diagnostics.LocalFileEventLog.cs
 //
 // Author:
 //   Atsushi Enomoto  <[email protected]>
+//   Gert Driesen  <[email protected]>
 //
-// (C) 2006 Novell, Inc.
+// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
 //
-
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -29,246 +29,358 @@
 //
 
 using System;
-using System.Diagnostics;
-using System.ComponentModel;
-using System.ComponentModel.Design;
 using System.Collections;
+using System.ComponentModel;
+using System.Diagnostics;
 using System.Globalization;
 using System.IO;
-using System.Net;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
 
 namespace System.Diagnostics
 {
-	class LocalFileEventLogUtil
+	internal class LocalFileEventLog : EventLogImpl
 	{
-		public const string DateFormat = "yyyyMMddHHmmssfff";
+		const string DateFormat = "yyyyMMddHHmmssfff";
+		static readonly object lockObject = new object ();
 
-		static readonly string path;
+		public LocalFileEventLog (EventLog coreEventLog) : base (coreEventLog)
+		{
+		}
 
-		static LocalFileEventLogUtil ()
+		public override void BeginInit () {
+		}
+
+		public override void Clear ()
 		{
-			string env = Environment.GetEnvironmentVariable ("MONO_EVENTLOG_PATH");
-			if (env != null)
-				path = Path.GetFullPath (env);
+			string logDir = FindLogStore (CoreEventLog.Log);
+			if (!Directory.Exists (logDir))
+				return;
+
+			foreach (string file in Directory.GetFiles (logDir, "*.log"))
+				File.Delete (file);
 		}
 
-		public static bool IsEnabled {
-			get { return path != null && Directory.Exists (path); }
+		public override void Close ()
+		{
+			// we don't hold any unmanaged resources
 		}
 
-		public static string GetSourceDir (string source)
+		public override void CreateEventSource (EventSourceCreationData sourceData)
 		{
-			foreach (string log in GetLogDirectories ()) {
-				string sd = Path.Combine (log, source);
-				if (Directory.Exists (sd))
-					return sd;
-			}
-			return null;
+			// construct path for storing log entries
+			string logDir = FindLogStore (sourceData.LogName);
+			// create event log store (if necessary), and modify access
+			// permissions (unix only)
+			CreateLogStore (logDir, sourceData.LogName);
+			// create directory for event source, so we can check if the event
+			// source already exists
+			string sourceDir = Path.Combine (logDir, sourceData.Source);
+			Directory.CreateDirectory (sourceDir);
 		}
 
-		public static string GetLogDir (string logName)
+		public override void Delete (string logName, string machineName)
 		{
-			return Path.Combine (Path.Combine (path, "logs"), logName);
+			string logDir = FindLogStore (logName);
+			if (!Directory.Exists (logDir))
+				throw new InvalidOperationException (string.Format (
+					CultureInfo.InvariantCulture, "Event Log '{0}'"
+					+ " does not exist on computer '{1}'.", logName,
+					machineName));
+
+			Directory.Delete (logDir, true);
 		}
 
-		public static string [] GetLogDirectories ()
+		public override void DeleteEventSource (string source, string machineName)
 		{
-			return Directory.GetDirectories (Path.Combine (path, "logs"));
+			if (!Directory.Exists (EventLogStore))
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "The source '{0}' is not"
+					+ " registered on computer '{1}'.", source, machineName));
+
+			string sourceDir = FindSourceDirectory (source);
+			if (sourceDir == null)
+				throw new ArgumentException (string.Format (
+					CultureInfo.InvariantCulture, "The source '{0}' is not"
+					+ " registered on computer '{1}'.", source, machineName));
+			Directory.Delete (sourceDir);
 		}
-	}
 
-	class LocalFileEventLog : EventLogImpl
-	{
-		static readonly string [] empty_strings = new string [0];
+		public override void Dispose (bool disposing)
+		{
+			Close ();
+		}
 
-		EventLog log;
-		string source_path;
+		public override void EndInit () { }
 
-		public LocalFileEventLog (EventLog log)
-			: base (log)
+		public override bool Exists (string logName, string machineName)
 		{
-			this.log = log;
-			source_path = LocalFileEventLogUtil.GetSourceDir (log.Source);
-			if (!Directory.Exists (source_path))
-				throw new SystemException (String.Format ("INTERNAL ERROR: directory for {0} does not exist.", log.Source));
+			string logDir = FindLogStore (logName);
+			return Directory.Exists (logDir);
 		}
 
-		public override EventLogEntryCollection Entries {
-			get {
-				ArrayList list = new ArrayList ();
-				int index = 0;
-				foreach (string file in Directory.GetFiles (source_path, "*.log"))
-					list.Add (LoadLogEntry (file, index++));
-				return new EventLogEntryCollection ((EventLogEntry []) list.ToArray (typeof (EventLogEntry)));
-			}
+		[MonoTODO ("Use MessageTable from PE for lookup")]
+		protected override string FormatMessage (string source, uint eventID, string [] replacementStrings)
+		{
+			return string.Join (", ", replacementStrings);
 		}
 
-		public override string LogDisplayName {
-			get { return log.Log; }
+		protected override int GetEntryCount ()
+		{
+			string logDir = FindLogStore (CoreEventLog.Log);
+			if (!Directory.Exists (logDir))
+				return 0;
+
+			string[] logFiles = Directory.GetFiles (logDir, "*.log");
+			return logFiles.Length;
 		}
 
-		EventLogEntry LoadLogEntry (string file, int index)
+		protected override EventLogEntry GetEntry (int index)
 		{
+			string logDir = FindLogStore (CoreEventLog.Log);
+
+			// our file names are one-based
+			string file = Path.Combine (logDir, (index + 1).ToString (
+				CultureInfo.InvariantCulture) + ".log");
+
 			using (TextReader tr = File.OpenText (file)) {
-				int id = int.Parse (tr.ReadLine ().Substring (9));
+				int eventIndex = int.Parse (Path.GetFileNameWithoutExtension (file),
+					CultureInfo.InvariantCulture);
+				uint instanceID = uint.Parse (tr.ReadLine ().Substring (12),
+					CultureInfo.InvariantCulture);
 				EventLogEntryType type = (EventLogEntryType)
 					Enum.Parse (typeof (EventLogEntryType), tr.ReadLine ().Substring (11));
+				string source = tr.ReadLine ().Substring (8);
 				string category = tr.ReadLine ().Substring (10);
-				int size = int.Parse (tr.ReadLine ().Substring (15));
-				char [] buf = new char [size];
-				tr.Read (buf, 0, size);
-				string filename = Path.GetFileName (file).Substring (0, LocalFileEventLogUtil.DateFormat.Length);
-				DateTime date = DateTime.ParseExact (filename, LocalFileEventLogUtil.DateFormat, CultureInfo.InvariantCulture);
+				short categoryNumber = short.Parse(category, CultureInfo.InvariantCulture);
+				string categoryName = "(" + category + ")";
+				DateTime timeGenerated = DateTime.ParseExact (tr.ReadLine ().Substring (15),
+					DateFormat, CultureInfo.InvariantCulture);
+				DateTime timeWritten = File.GetLastWriteTime (file);
+				int stringNums = int.Parse (tr.ReadLine ().Substring (20));
+				ArrayList replacementTemp = new ArrayList ();
+				StringBuilder sb = new StringBuilder ();
+				while (replacementTemp.Count < stringNums) {
+					char c = (char) tr.Read ();
+					if (c == '\0') {
+						replacementTemp.Add (sb.ToString ());
+						sb.Length = 0;
+					} else {
+						sb.Append (c);
+					}
+				}
+				string [] replacementStrings = new string [replacementTemp.Count];
+				replacementTemp.CopyTo (replacementStrings, 0);
+
+				string message = FormatMessage (source, instanceID, replacementStrings);
+				int eventID = EventLog.GetEventID (instanceID);
+
 				byte [] bin = Convert.FromBase64String (tr.ReadToEnd ());
-				// FIXME: categoryNumber, index, userName, two dates
-				return new EventLogEntry (category, 0, index,
-					id, new string (buf), log.Source, "", log.MachineName,
-					type, date, date, bin, empty_strings);
+				return new EventLogEntry (categoryName, categoryNumber, eventIndex,
+					eventID, source, message, null, Environment.MachineName,
+					type, timeGenerated, timeWritten, bin, replacementStrings,
+					instanceID);
 			}
 		}
 
-		public override void BeginInit ()
-		{
-		}
-
-		public override void Clear ()
+		public override EventLog [] GetEventLogs (string machineName)
 		{
-			foreach (string file in Directory.GetFiles (source_path, "*.log"))
-				File.Delete (file);
+			if (!Directory.Exists (EventLogStore))
+				return new EventLog [0];
+			
+			string [] logDirs = Directory.GetDirectories (EventLogStore, "*");
+			EventLog [] eventLogs = new EventLog [logDirs.Length];
+			for (int i = 0; i < logDirs.Length; i++) {
+				EventLog eventLog = new EventLog (Path.GetFileName (
+					logDirs [i]), machineName);
+				eventLogs [i] = eventLog;
+			}
+			return eventLogs;
 		}
 
-		public override void Close ()
+		[MonoTODO]
+		protected override string GetLogDisplayName ()
 		{
+			return CoreEventLog.Log;
 		}
 
-		public override void Dispose (bool disposing)
+		public override string	LogNameFromSourceName (string source, string machineName)
 		{
-			Close ();
-		}
+			if (!Directory.Exists (EventLogStore))
+				return string.Empty;
 
-		public override void EndInit ()
-		{
+			string sourceDir = FindSourceDirectory (source);
+			if (sourceDir == null)
+				return string.Empty;
+			DirectoryInfo info = new DirectoryInfo (sourceDir);
+			return info.Parent.Name;
 		}
-	}
-
-	// Creates a log repository at MONO_LOCAL_EVENTLOG_DIR, which consists of
-	// 	- 
-	internal class LocalFileEventLogFactory : EventLogFactory
-	{
-		static readonly IPAddress local_ip = IPAddress.Parse ("127.0.0.1");
 
-		public LocalFileEventLogFactory ()
+		public override bool SourceExists (string source, string machineName)
 		{
+			if (!Directory.Exists (EventLogStore))
+				return false;
+			string sourceDir = FindSourceDirectory (source);
+			return (sourceDir != null);
 		}
 
-		public override EventLogImpl Create (EventLog log)
+		public override void WriteEntry (string [] replacementStrings, EventLogEntryType type, uint instanceID, short category, byte [] rawData)
 		{
-			if (!SourceExists (log.Source, log.MachineName))
-				CreateEventSource (log.Source, log.Log, log.MachineName);
-			return new LocalFileEventLog (log);
-		}
+			lock (lockObject) {
+				string logDir = FindLogStore (CoreEventLog.Log);
 
-		void VerifyMachine (string machineName)
-		{
-			if (machineName != ".") {
-				IPHostEntry entry =
+				int index = GetNewIndex ();
+				string logPath = Path.Combine (logDir, index.ToString (CultureInfo.InvariantCulture) + ".log");
+				try {
+					using (TextWriter w = File.CreateText (logPath)) {
 #if NET_2_0
-					Dns.GetHostEntry (machineName);
+						w.WriteLine ("InstanceID: {0}", instanceID.ToString (CultureInfo.InvariantCulture));
 #else
-					Dns.Resolve (machineName);
+						w.WriteLine ("InstanceID: {0}", instanceID.ToString (CultureInfo.InvariantCulture));
 #endif
-				if (Array.IndexOf (entry.AddressList, local_ip) < 0)
-					throw new NotSupportedException (String.Format ("LocalFileEventLog does not support remote machine: {0}", machineName));
+						w.WriteLine ("EntryType: {0}", (int) type);
+						w.WriteLine ("Source: {0}", CoreEventLog.Source);
+						w.WriteLine ("Category: {0}", category.ToString (CultureInfo.InvariantCulture));
+						w.WriteLine ("TimeGenerated: {0}", DateTime.Now.ToString (
+							DateFormat, CultureInfo.InvariantCulture));
+						w.WriteLine ("ReplacementStrings: {0}", replacementStrings.
+							Length.ToString (CultureInfo.InvariantCulture));
+						StringBuilder sb = new StringBuilder ();
+						for (int i = 0; i < replacementStrings.Length; i++) {
+							string replacement = replacementStrings [i];
+							sb.Append (replacement);
+							sb.Append ('\0');
+						}
+						w.Write (sb.ToString ());
+						w.Write (Convert.ToBase64String (rawData));
+					}
+				} catch (IOException) {
+					File.Delete (logPath);
+				}
 			}
 		}
 
-		public override void CreateEventSource (string source, string logName, string machineName)
-		{
-			VerifyMachine (machineName);
-
-			string sourceDir = LocalFileEventLogUtil.GetSourceDir (source);
-			if (sourceDir != null)
-				throw new ArgumentException (String.Format ("Source '{0}' already exists on the local machine.", source));
-
-			string logDir = LocalFileEventLogUtil.GetLogDir (logName);
-			if (!Directory.Exists (logDir))
-				Directory.CreateDirectory (logDir);
-			Directory.CreateDirectory (Path.Combine (logDir, source));
-		}
-
-		public override void Delete (string logName, string machineName)
+		private string FindSourceDirectory (string source)
 		{
-			VerifyMachine (machineName);
-
-			string logDir = LocalFileEventLogUtil.GetLogDir (logName);
-			if (Directory.Exists (logDir))
-				Directory.Delete (logDir);
+			string sourceDir = null;
+
+			string [] logDirs = Directory.GetDirectories (EventLogStore, "*");
+			for (int i = 0; i < logDirs.Length; i++) {
+				string [] sourceDirs = Directory.GetDirectories (logDirs [i], "*");
+				for (int j = 0; j < sourceDirs.Length; j++) {
+					string relativeDir = Path.GetFileName (sourceDirs [j]);
+					// use a case-insensitive comparison
+					if (string.Compare (relativeDir, source, true, CultureInfo.InvariantCulture) == 0) {
+						sourceDir = sourceDirs [j];
+						break;
+					}
+				}
+			}
+			return sourceDir;
 		}
 
-		public override void DeleteEventSource (string source, string machineName)
-		{
-			VerifyMachine (machineName);
-
-			string sourceDir = LocalFileEventLogUtil.GetSourceDir (source);
-			if (Directory.Exists (sourceDir))
-				Directory.Delete (sourceDir);
-			else
-				throw new ArgumentException (String.Format ("Event source '{0}' does not exist on the local machine."), source);
+		private bool RunningOnLinux {
+			get {
+				return ((int) Environment.OSVersion.Platform == 4 ||
+#if NET_2_0
+					Environment.OSVersion.Platform == PlatformID.Unix);
+#else
+					(int) Environment.OSVersion.Platform == 128);
+#endif
+			}
 		}
 
-		public override bool Exists (string logName, string machineName)
-		{
-			VerifyMachine (machineName);
+		private string FindLogStore (string logName) {
+			// we'll use a case-insensitive lookup to match the MS behaviour
+			// while still allowing the original casing of the log name to be
+			// retained
+			string [] logDirs = Directory.GetDirectories (EventLogStore, "*");
+			for (int i = 0; i < logDirs.Length; i++) {
+				string relativeDir = Path.GetFileName (logDirs [i]);
+				// use a case-insensitive comparison
+				if (string.Compare (relativeDir, logName, true, CultureInfo.InvariantCulture) == 0) {
+					return logDirs [i];
+				}
+			}
 
-			return Directory.Exists (LocalFileEventLogUtil.GetLogDir (logName));
+			return Path.Combine (EventLogStore, logName);
 		}
 
-		public override EventLog[] GetEventLogs (string machineName)
-		{
-			VerifyMachine (machineName);
-
-			ArrayList al = new ArrayList ();
-			foreach (string log in LocalFileEventLogUtil.GetLogDirectories ())
-				al.Add (new EventLog (log));
-			return (EventLog []) al.ToArray (typeof (EventLog));
+		private string EventLogStore {
+			get {
+				// for the local file implementation, the MONO_EVENTLOG_TYPE
+				// environment variable can contain the path of the event log
+				// store by using the following syntax: local:<path>
+				string eventLogType = Environment.GetEnvironmentVariable (EventLog.EVENTLOG_TYPE_VAR);
+				if (eventLogType != null && eventLogType.Length > EventLog.LOCAL_FILE_IMPL.Length + 1)
+					return eventLogType.Substring (EventLog.LOCAL_FILE_IMPL.Length + 1);
+				if (RunningOnLinux) {
+					return "/var/lib/mono/eventlog";
+				} else {
+					return Path.Combine (Environment.GetFolderPath (
+						Environment.SpecialFolder.CommonApplicationData),
+						"mono/eventlog");
+				}
+			}
 		}
 
-		public override string LogNameFromSourceName (string source, string machineName)
+		private void CreateLogStore (string logDir, string logName)
 		{
-			VerifyMachine (machineName);
-
-			string sourceDir = LocalFileEventLogUtil.GetSourceDir (source);
-			if (sourceDir == null)
-				throw new ArgumentException (String.Format ("Event source '{0}' does not exist on the local machine."), source);
-			return Directory.GetParent (sourceDir).Name;
+			if (!Directory.Exists (logDir)) {
+				Directory.CreateDirectory (logDir);
+				// MS does not allow an event source to be named after an already
+				// existing event log. To speed up checking whether a given event
+				// source already exists (either as a event source or event log)
+				// we create an event source directory named after the event log.
+				// This matches what MS does with the registry-based registration.
+				Directory.CreateDirectory (Path.Combine (logDir, logName));
+				if (RunningOnLinux) {
+					ModifyAccessPermissions (logDir, "777");
+					ModifyAccessPermissions (logDir, "+t");
+				}
+			}
 		}
 
-		public override bool SourceExists (string source, string machineName)
-		{
-			VerifyMachine (machineName);
-
-			return LocalFileEventLogUtil.GetSourceDir (source) != null;
+		private int GetNewIndex () {
+			// our file names are one-based
+			int maxIndex = 0;
+			string[] logFiles = Directory.GetFiles (FindLogStore (CoreEventLog.Log), "*.log");
+			for (int i = 0; i < logFiles.Length; i++) {
+				try {
+					string file = logFiles[i];
+					int index = int.Parse (Path.GetFileNameWithoutExtension (
+						file), CultureInfo.InvariantCulture);
+					if (index > maxIndex)
+						maxIndex = index;
+				} catch {
+				}
+			}
+			return ++maxIndex;
 		}
 
-		public override void WriteEntry (string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData)
+		private static void ModifyAccessPermissions (string path, string permissions)
 		{
-			if (!SourceExists (source, "."))
-				throw new ArgumentException (String.Format ("Event source '{0}' does not exist on the local machine."), source);
-			string sourceDir = LocalFileEventLogUtil.GetSourceDir (source);
-			string path = Path.Combine (sourceDir, DateTime.Now.ToString (LocalFileEventLogUtil.DateFormat) + ".log");
+			ProcessStartInfo pi = new ProcessStartInfo ();
+			pi.FileName = "chmod";
+			pi.RedirectStandardOutput = true;
+			pi.RedirectStandardError = true;
+			pi.UseShellExecute = false;
+			pi.Arguments = string.Format ("{0} \"{1}\"", permissions, path);
+
+			Process p = null;
 			try {
-				using (TextWriter w = File.CreateText (path)) {
-					w.WriteLine ("EventID: {0}", eventID);
-					w.WriteLine ("EntryType: {0}", type);
-					w.WriteLine ("Category: {0}", category);
-					w.WriteLine ("MessageLength: {0}", message.Length);
-					w.Write (message);
-					if (rawData != null)
-						w.Write (Convert.ToBase64String (rawData));
-				}
-			} catch (IOException) {
-				File.Delete (path);
+				p = Process.Start (pi);
+			} catch (Exception ex) {
+				throw new SecurityException ("Access permissions could not be modified.", ex);
+			}
+
+			p.WaitForExit ();
+			if (p.ExitCode != 0) {
+				p.Close ();
+				throw new SecurityException ("Access permissions could not be modified.");
 			}
+			p.Close ();
 		}
 	}
 }

+ 28 - 32
mcs/class/System/System.Diagnostics/NullEventLog.cs

@@ -3,6 +3,7 @@
 //
 // Author:
 //   Atsushi Enomoto  <[email protected]>
+//   Gert Driesen  <[email protected]>
 //
 // (C) 2006 Novell, Inc.
 //
@@ -30,42 +31,39 @@
 
 using System;
 using System.Diagnostics;
-using System.ComponentModel;
-using System.ComponentModel.Design;
-using System.Collections;
-using System.Globalization;
-using System.IO;
-using System.Net;
 
 namespace System.Diagnostics
 {
+	// Empty implementation that does not need any specific platform
+	// but should be enough to get applications to run that WRITE to eventlog
 	internal class NullEventLog : EventLogImpl
 	{
-		EventLogEntryCollection empty_entries =
-			new EventLogEntryCollection (new EventLogEntry [0]);
-
 		public NullEventLog (EventLog coreEventLog)
 			: base (coreEventLog)
 		{
 		}
 
-		public override EventLogEntryCollection Entries {
-			get { return empty_entries; }
+		public override void BeginInit ()
+		{
 		}
 
-		public override string LogDisplayName {
-			get { return String.Empty; }
+		public override void Clear ()
+		{
 		}
 
-		public override void BeginInit ()
+		public override void Close ()
 		{
 		}
 
-		public override void Clear ()
+		public override void CreateEventSource (EventSourceCreationData sourceData)
 		{
 		}
 
-		public override void Close ()
+		public override void Delete (string logName, string machineName)
+		{
+		}
+
+		public override void DeleteEventSource (string source, string machineName)
 		{
 		}
 
@@ -76,42 +74,40 @@ namespace System.Diagnostics
 		public override void EndInit ()
 		{
 		}
-	}
 
-	internal class NullEventLogFactory : EventLogFactory
-	{
-		EventLog [] empty_logs = new EventLog [0];
-
-		public override EventLogImpl Create (EventLog source)
+		public override bool Exists (string logName, string machineName)
 		{
-			return new NullEventLog (source);
+			return true;
 		}
 
-		public override void CreateEventSource (string source, string logName, string machineName)
+		protected override string FormatMessage (string source, uint messageID, string [] replacementStrings)
 		{
+			return string.Join (", ", replacementStrings);
 		}
 
-		public override void Delete (string logName, string machineName)
+		protected override int GetEntryCount ()
 		{
+			return 0;
 		}
 
-		public override void DeleteEventSource (string source, string machineName)
+		protected override EventLogEntry GetEntry (int index)
 		{
+			return null;
 		}
 
-		public override bool Exists (string logName, string machineName)
+		public override EventLog [] GetEventLogs (string machineName)
 		{
-			return false;
+			return new EventLog [0];
 		}
 
-		public override EventLog [] GetEventLogs (string machineName)
+		protected override string GetLogDisplayName ()
 		{
-			return empty_logs;
+			return CoreEventLog.Log;
 		}
 
 		public override string LogNameFromSourceName (string source, string machineName)
 		{
-			return String.Empty;
+			return null;
 		}
 
 		public override bool SourceExists (string source, string machineName)
@@ -119,7 +115,7 @@ namespace System.Diagnostics
 			return false;
 		}
 
-		public override void WriteEntry (string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData)
+		public override void WriteEntry (string [] replacementStrings, EventLogEntryType type, uint instanceID, short category, byte [] rawData)
 		{
 		}
 	}

+ 811 - 0
mcs/class/System/System.Diagnostics/Win32EventLog.cs

@@ -0,0 +1,811 @@
+//
+// System.Diagnostics.Win32EventLog.cs
+//
+// Author:
+//	Gert Driesen <[email protected]>
+//
+// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
+//
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text;
+
+using Microsoft.Win32;
+
+namespace System.Diagnostics
+{
+	internal class Win32EventLog : EventLogImpl
+	{
+		private const int MESSAGE_NOT_FOUND = 317;
+
+		public Win32EventLog (EventLog coreEventLog)
+			: base (coreEventLog)
+		{
+		}
+
+		public override void BeginInit ()
+		{
+		}
+
+		public override void Clear ()
+		{
+			IntPtr hEventLog = OpenEventLog ();
+			try {
+				int ret = PInvoke.ClearEventLog (hEventLog, null);
+				if (ret != 1) {
+					throw new Win32Exception (Marshal.GetLastWin32Error ());
+				}
+			} finally {
+				CloseEventLog (hEventLog);
+			}
+		}
+
+		public override void Close ()
+		{
+			// we don't hold any unmanaged resources
+		}
+
+		public override void CreateEventSource (EventSourceCreationData sourceData)
+		{
+			using (RegistryKey eventLogKey = GetEventLogKey (sourceData.MachineName, true)) {
+				if (eventLogKey == null)
+					throw new InvalidOperationException ("EventLog registry key is missing.");
+
+				bool logKeyCreated = false;
+				RegistryKey logKey = null;
+				try {
+					logKey = eventLogKey.OpenSubKey (sourceData.LogName, true);
+					if (logKey == null) {
+						logKey = eventLogKey.CreateSubKey (sourceData.LogName);
+						logKey.SetValue ("Sources", new string [] { sourceData.LogName,
+							sourceData.Source });
+						UpdateLogRegistry (logKey);
+
+						using (RegistryKey sourceKey = logKey.CreateSubKey (sourceData.LogName)) {
+							UpdateSourceRegistry (sourceKey, sourceData);
+						}
+
+						logKeyCreated = true;
+					}
+
+					if (sourceData.LogName != sourceData.Source) {
+						if (!logKeyCreated) {
+							string [] sources = (string []) logKey.GetValue ("Sources");
+							if (sources == null) {
+								logKey.SetValue ("Sources", new string [] { sourceData.LogName,
+									sourceData.Source });
+							} else {
+								bool found = false;
+								for (int i = 0; i < sources.Length; i++) {
+									if (sources [i] == sourceData.Source) {
+										found = true;
+										break;
+									}
+								}
+								if (!found) {
+									string [] newSources = new string [sources.Length + 1];
+									Array.Copy (sources, 0, newSources, 0, sources.Length);
+									newSources [sources.Length] = sourceData.Source;
+									logKey.SetValue ("Sources", newSources);
+								}
+							}
+						}
+						using (RegistryKey sourceKey = logKey.CreateSubKey (sourceData.Source)) {
+							UpdateSourceRegistry (sourceKey, sourceData);
+						}
+					}
+				} finally {
+					if (logKey != null)
+						logKey.Close ();
+				}
+			}
+		}
+
+		public override void Delete (string logName, string machineName)
+		{
+			using (RegistryKey eventLogKey = GetEventLogKey (machineName, true)) {
+				if (eventLogKey == null)
+					throw new InvalidOperationException ("The event log key does not exist.");
+
+				using (RegistryKey logKey = eventLogKey.OpenSubKey (logName, false)) {
+					if (logKey == null)
+						throw new InvalidOperationException (string.Format (
+							CultureInfo.InvariantCulture, "Event Log '{0}'"
+							+ " does not exist on computer '{1}'.", logName,
+							machineName));
+
+					// remove all eventlog entries for specified log
+					CoreEventLog.Clear ();
+
+					// remove file holding event log entries
+					string file = (string) logKey.GetValue ("File");
+					if (file != null) {
+						try {
+							File.Delete (file);
+						} catch (Exception) {
+							// .NET seems to ignore failures here
+						}
+					}
+				}
+
+				eventLogKey.DeleteSubKeyTree (logName);
+			}
+		}
+
+		public override void DeleteEventSource (string source, string machineName)
+		{
+			using (RegistryKey logKey = FindLogKeyBySource (source, machineName, true)) {
+				if (logKey == null) {
+					throw new ArgumentException (string.Format (
+						CultureInfo.InvariantCulture, "The source '{0}' is not"
+						+ " registered on computer '{1}'.", source, machineName));
+				}
+
+				logKey.DeleteSubKeyTree (source);
+
+				string [] sources = (string []) logKey.GetValue ("Sources");
+				if (sources != null) {
+					ArrayList temp = new ArrayList ();
+					for (int i = 0; i < sources.Length; i++)
+						if (sources [i] != source)
+							temp.Add (sources [i]);
+					string [] newSources = new string [temp.Count];
+					temp.CopyTo (newSources, 0);
+					logKey.SetValue ("Sources", newSources);
+				}
+			}
+		}
+
+		public override void Dispose (bool disposing)
+		{
+			Close ();
+		}
+
+		public override void EndInit ()
+		{
+		}
+
+		public override bool Exists (string logName, string machineName)
+		{
+			using (RegistryKey logKey = FindLogKeyByName (logName, machineName, false)) {
+				return (logKey != null);
+			}
+		}
+
+		[MonoTODO] // ParameterResourceFile ??
+		protected override string FormatMessage (string source, uint messageID, string [] replacementStrings)
+		{
+			string formattedMessage = null;
+
+			string [] msgResDlls = GetMessageResourceDlls (source, "EventMessageFile");
+			for (int i = 0; i < msgResDlls.Length; i++) {
+				formattedMessage = FetchMessage (msgResDlls [i],
+					messageID, replacementStrings);
+				if (formattedMessage != null)
+					break;
+			}
+
+			return formattedMessage != null ? formattedMessage : string.Join (
+				", ", replacementStrings);
+		}
+
+		private string FormatCategory (string source, int category)
+		{
+			string formattedCategory = null;
+
+			string [] msgResDlls = GetMessageResourceDlls (source, "CategoryMessageFile");
+			for (int i = 0; i < msgResDlls.Length; i++) {
+				formattedCategory = FetchMessage (msgResDlls [i],
+					(uint) category, new string [0]);
+				if (formattedCategory != null)
+					break;
+			}
+
+			return formattedCategory != null ? formattedCategory : "(" +
+				category.ToString (CultureInfo.InvariantCulture) + ")";
+		}
+
+		protected override int GetEntryCount ()
+		{
+			IntPtr hEventLog = OpenEventLog ();
+			try {
+				int entryCount = 0;
+				int retVal = PInvoke.GetNumberOfEventLogRecords (hEventLog, ref entryCount);
+				if (retVal != 1) {
+					throw new Win32Exception (Marshal.GetLastWin32Error ());
+				}
+				return entryCount;
+			} finally {
+				CloseEventLog (hEventLog);
+			}
+		}
+
+		protected override EventLogEntry GetEntry (int index)
+		{
+			// http://msdn.microsoft.com/library/en-us/eventlog/base/readeventlog.asp
+			// http://msdn.microsoft.com/library/en-us/eventlog/base/eventlogrecord_str.asp
+			// http://www.whitehats.ca/main/members/Malik/malik_eventlogs/malik_eventlogs.html
+
+			index += OldestEventLogEntry;
+
+			IntPtr hEventLog = OpenEventLog ();
+			try {
+				int bytesRead = 0;
+				int minBufferNeeded = 0;
+
+				byte [] buffer = new byte [0x7ffff]; // according to MSDN this is the max size of the buffer
+				int length = buffer.Length;
+
+				int ret = PInvoke.ReadEventLog (hEventLog, ReadFlags.Seek |
+					ReadFlags.ForwardsRead, index, buffer, length,
+					ref bytesRead, ref minBufferNeeded);
+				if (ret != 1) {
+					throw new Win32Exception (Marshal.GetLastWin32Error ());
+				}
+
+				MemoryStream ms = new MemoryStream (buffer);
+				BinaryReader br = new BinaryReader (ms);
+
+				// skip first 8 bytes
+				br.ReadBytes (8);
+
+				int recordNumber = br.ReadInt32 (); // 8
+
+				int timeGeneratedSeconds = br.ReadInt32 (); // 12
+				int timeWrittenSeconds = br.ReadInt32 (); // 16
+				uint instanceID = br.ReadUInt32 ();
+				int eventID = EventLog.GetEventID (instanceID);
+				short eventType = br.ReadInt16 (); // 24
+				short numStrings = br.ReadInt16 (); ; // 26
+				short categoryNumber = br.ReadInt16 (); ; // 28
+				// skip reservedFlags
+				br.ReadInt16 (); // 30
+				// skip closingRecordNumber
+				br.ReadInt32 (); // 32
+				int stringOffset = br.ReadInt32 (); // 36
+				int userSidLength = br.ReadInt32 (); // 40
+				int userSidOffset = br.ReadInt32 (); // 44
+				int dataLength = br.ReadInt32 (); // 48
+				int dataOffset = br.ReadInt32 (); // 52
+
+				DateTime timeGenerated = new DateTime (1970, 1, 1).AddSeconds (
+					timeGeneratedSeconds);
+
+				DateTime timeWritten = new DateTime (1970, 1, 1).AddSeconds (
+					timeWrittenSeconds);
+
+				StringBuilder sb = new StringBuilder ();
+				while (br.PeekChar () != '\0')
+					sb.Append (br.ReadChar ());
+				br.ReadChar (); // skip the null-char
+
+				string sourceName = sb.ToString ();
+
+				sb.Length = 0;
+				while (br.PeekChar () != '\0')
+					sb.Append (br.ReadChar ());
+				br.ReadChar (); // skip the null-char
+				string machineName = sb.ToString ();
+
+				sb.Length = 0;
+				while (br.PeekChar () != '\0')
+					sb.Append (br.ReadChar ());
+				br.ReadChar (); // skip the null-char
+
+				string userName = null;
+				if (userSidLength != 0) {
+					// TODO: lazy init ?
+					ms.Position = userSidOffset;
+					byte [] sid = br.ReadBytes (userSidLength);
+					userName = LookupAccountSid (machineName, sid);
+				}
+
+				ms.Position = stringOffset;
+				string [] replacementStrings = new string [numStrings];
+				for (int i = 0; i < numStrings; i++) {
+					sb.Length = 0;
+					while (br.PeekChar () != '\0')
+						sb.Append (br.ReadChar ());
+					br.ReadChar (); // skip the null-char
+					replacementStrings [i] = sb.ToString ();
+				}
+
+				byte [] data = new byte [dataLength];
+				ms.Position = dataOffset;
+				br.Read (data, 0, dataLength);
+
+				// TODO: lazy fetch ??
+				string message = this.FormatMessage (sourceName, instanceID, replacementStrings);
+				string category = FormatCategory (sourceName, categoryNumber);
+
+				return new EventLogEntry (category, (short) categoryNumber, recordNumber,
+					eventID, sourceName, message, userName, machineName,
+					(EventLogEntryType) eventType, timeGenerated, timeWritten,
+					data, replacementStrings, instanceID);
+			} finally {
+				CloseEventLog (hEventLog);
+			}
+		}
+
+		public override EventLog [] GetEventLogs (string machineName)
+		{
+			using (RegistryKey eventLogKey = GetEventLogKey (machineName, false)) {
+				if (eventLogKey == null) {
+					throw new InvalidOperationException ("TODO");
+				}
+				string [] logNames = eventLogKey.GetSubKeyNames ();
+				EventLog [] eventLogs = new EventLog [logNames.Length];
+				for (int i = 0; i < logNames.Length; i++) {
+					EventLog eventLog = new EventLog (logNames [i], machineName);
+					eventLogs [i] = eventLog;
+				}
+				return eventLogs;
+			}
+		}
+
+		[MonoTODO]
+		protected override string GetLogDisplayName ()
+		{
+			return CoreEventLog.Log;
+		}
+
+		public override string LogNameFromSourceName (string source, string machineName)
+		{
+			using (RegistryKey logKey = FindLogKeyBySource (source, machineName, false)) {
+				if (logKey == null)
+					return string.Empty;
+
+				return GetLogName (logKey);
+			}
+		}
+
+		public override bool SourceExists (string source, string machineName)
+		{
+			RegistryKey logKey = FindLogKeyBySource (source, machineName, false);
+			if (logKey != null) {
+				logKey.Close ();
+				return true;
+			}
+			return false;
+		}
+
+		public override void WriteEntry (string [] replacementStrings, EventLogEntryType type, uint instanceID, short category, byte [] rawData)
+		{
+			IntPtr hEventLog = RegisterEventSource ();
+			try {
+				int ret = PInvoke.ReportEvent (hEventLog, (ushort) type,
+					(ushort) category, instanceID, IntPtr.Zero,
+					(ushort) replacementStrings.Length,
+					(uint) rawData.Length, replacementStrings, rawData);
+				if (ret != 1) {
+					throw new Win32Exception (Marshal.GetLastWin32Error ());
+				}
+			} finally {
+				DeregisterEventSource (hEventLog);
+			}
+		}
+
+		private static void UpdateLogRegistry (RegistryKey logKey)
+		{
+			// TODO: write other Log values:
+			// - MaxSize
+			// - Retention
+			// - AutoBackupLogFiles
+
+			if (logKey.GetValue ("File") == null) {
+				string logName = GetLogName (logKey);
+				string file;
+				if (logName.Length > 8) {
+					file = logName.Substring (0, 8) + ".evt";
+				} else {
+					file = logName + ".evt";
+				}
+				string configPath = Path.Combine (Environment.GetFolderPath (
+					Environment.SpecialFolder.System), "config");
+				logKey.SetValue ("File", Path.Combine (configPath, file));
+			}
+
+		}
+
+		private static void UpdateSourceRegistry (RegistryKey sourceKey, EventSourceCreationData data)
+		{
+			if (data.CategoryCount > 0)
+				sourceKey.SetValue ("CategoryCount", data.CategoryCount);
+
+			if (data.CategoryResourceFile != null && data.CategoryResourceFile.Length > 0)
+				sourceKey.SetValue ("CategoryMessageFile", data.CategoryResourceFile);
+
+			if (data.MessageResourceFile != null && data.MessageResourceFile.Length > 0) {
+				sourceKey.SetValue ("EventMessageFile", data.MessageResourceFile);
+			} else {
+				// FIXME: write default once we have approval for shipping EventLogMessages.dll
+			}
+
+			if (data.ParameterResourceFile != null && data.ParameterResourceFile.Length > 0)
+				sourceKey.SetValue ("ParameterMessageFile", data.ParameterResourceFile);
+		}
+
+		private static string GetLogName (RegistryKey logKey)
+		{
+			string logName = logKey.Name;
+			return logName.Substring (logName.LastIndexOf ("\\") + 1);
+		}
+
+		[MonoTODO ("Support remote machines")]
+		private static RegistryKey GetEventLogKey (string machineName, bool writable)
+		{
+			return Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Services\EventLog", writable);
+		}
+
+		private static RegistryKey FindSourceKeyByName (string source, string machineName, bool writable)
+		{
+			if (source == null || source.Length == 0)
+				return null;
+
+			RegistryKey eventLogKey = null;
+			try {
+				eventLogKey = GetEventLogKey (machineName, writable);
+				if (eventLogKey == null)
+					return null;
+
+				string [] subKeys = eventLogKey.GetSubKeyNames ();
+				for (int i = 0; i < subKeys.Length; i++) {
+					using (RegistryKey logKey = eventLogKey.OpenSubKey (subKeys [i], writable)) {
+						if (logKey == null)
+							break;
+
+						RegistryKey sourceKey = logKey.OpenSubKey (source, writable);
+						if (sourceKey != null)
+							return sourceKey;
+					}
+				}
+				return null;
+			} finally {
+				if (eventLogKey != null)
+					eventLogKey.Close ();
+			}
+		}
+
+		private static RegistryKey FindLogKeyByName (string logName, string machineName, bool writable)
+		{
+			using (RegistryKey eventLogKey = GetEventLogKey (machineName, writable)) {
+				if (eventLogKey == null) {
+					return null;
+				}
+
+				return eventLogKey.OpenSubKey (logName, writable);
+			}
+		}
+
+		private static RegistryKey FindLogKeyBySource (string source, string machineName, bool writable)
+		{
+			if (source == null || source.Length == 0)
+				return null;
+
+			RegistryKey eventLogKey = null;
+			try {
+				eventLogKey = GetEventLogKey (machineName, writable);
+				if (eventLogKey == null)
+					return null;
+
+				string [] subKeys = eventLogKey.GetSubKeyNames ();
+				for (int i = 0; i < subKeys.Length; i++) {
+					RegistryKey sourceKey = null;
+					try {
+						RegistryKey logKey = eventLogKey.OpenSubKey (subKeys [i], writable);
+						if (logKey != null) {
+							sourceKey = logKey.OpenSubKey (source, writable);
+							if (sourceKey != null)
+								return logKey;
+						}
+					} finally {
+						if (sourceKey != null)
+							sourceKey.Close ();
+					}
+				}
+				return null;
+			} finally {
+				if (eventLogKey != null)
+					eventLogKey.Close ();
+			}
+		}
+
+		private int OldestEventLogEntry {
+			get {
+				IntPtr hEventLog = OpenEventLog ();
+				try {
+					int oldestEventLogEntry = 0;
+					int ret = PInvoke.GetOldestEventLogRecord (hEventLog, ref oldestEventLogEntry);
+					if (ret != 1) {
+						throw new Win32Exception (Marshal.GetLastWin32Error ());
+					}
+					return oldestEventLogEntry;
+				} finally {
+					CloseEventLog (hEventLog);
+				}
+			}
+		}
+
+		private void CloseEventLog (IntPtr hEventLog)
+		{
+			int ret = PInvoke.CloseEventLog (hEventLog);
+			if (ret != 1) {
+				throw new Win32Exception (Marshal.GetLastWin32Error ());
+			}
+		}
+
+		private void DeregisterEventSource (IntPtr hEventLog)
+		{
+			int ret = PInvoke.DeregisterEventSource (hEventLog);
+			if (ret != 1) {
+				throw new Win32Exception (Marshal.GetLastWin32Error ());
+			}
+		}
+
+		private static string LookupAccountSid (string machineName, byte [] sid)
+		{
+			// http://www.pinvoke.net/default.aspx/advapi32/LookupAccountSid.html
+			// http://msdn.microsoft.com/library/en-us/secauthz/security/lookupaccountsid.asp
+
+			StringBuilder name = new StringBuilder ();
+			uint cchName = (uint) name.Capacity;
+			StringBuilder referencedDomainName = new StringBuilder ();
+			uint cchReferencedDomainName = (uint) referencedDomainName.Capacity;
+			SidNameUse sidUse;
+
+			string accountName = null;
+
+			while (accountName == null) {
+				bool retOk = PInvoke.LookupAccountSid (machineName, sid, name, ref cchName,
+					referencedDomainName, ref cchReferencedDomainName,
+					out sidUse);
+				if (!retOk) {
+					int err = Marshal.GetLastWin32Error ();
+					if (err == PInvoke.ERROR_INSUFFICIENT_BUFFER) {
+						name.EnsureCapacity ((int) cchName);
+						referencedDomainName.EnsureCapacity ((int) cchReferencedDomainName);
+					} else {
+						// TODO: write warning ?
+						accountName = string.Empty;
+					}
+				} else {
+					accountName = string.Format ("{0}\\{1}", referencedDomainName.ToString (),
+						name.ToString ());
+				}
+			}
+			return accountName;
+		}
+
+		private static string FetchMessage (string msgDll, uint messageID, string [] replacementStrings)
+		{
+			// http://msdn.microsoft.com/library/en-us/debug/base/formatmessage.asp
+			// http://msdn.microsoft.com/msdnmag/issues/02/08/CQA/
+			// http://msdn.microsoft.com/netframework/programming/netcf/cffaq/default.aspx
+
+			IntPtr msgDllHandle = PInvoke.LoadLibraryEx (msgDll, IntPtr.Zero,
+				LoadFlags.LibraryAsDataFile);
+			if (msgDllHandle == IntPtr.Zero)
+				// TODO: write warning
+				return null;
+
+			IntPtr lpMsgBuf = IntPtr.Zero;
+			IntPtr [] arguments = new IntPtr [replacementStrings.Length];
+
+			try {
+				for (int i = 0; i < replacementStrings.Length; i++) {
+					// TODO: use StringToHGlobalAuto once bug #79117 is fixed
+					arguments [i] = Marshal.StringToHGlobalUni (
+						replacementStrings [i]);
+				}
+
+				int ret = PInvoke.FormatMessage (FormatMessageFlags.ArgumentArray |
+					FormatMessageFlags.FromHModule | FormatMessageFlags.AllocateBuffer,
+					msgDllHandle, messageID, 0, ref lpMsgBuf, 0, arguments);
+				if (ret != 0) {
+					// TODO: use PtrToStringAuto once bug #79117 is fixed
+					string sRet = Marshal.PtrToStringUni (lpMsgBuf);
+					lpMsgBuf = PInvoke.LocalFree (lpMsgBuf);
+					// remove trailing whitespace (CRLF)
+					return sRet.TrimEnd (null);
+				} else {
+					int err = Marshal.GetLastWin32Error ();
+					if (err == MESSAGE_NOT_FOUND) {
+						// do not consider this a failure (or even warning) as
+						// multiple message resource DLLs may have been configured
+						// and as such we just need to try the next library if
+						// the current one does not contain a message for this
+						// ID
+					} else {
+						// TODO: report warning
+					}
+				}
+			} finally {
+				PInvoke.FreeLibrary (msgDllHandle);
+			}
+			return null;
+		}
+
+		private string [] GetMessageResourceDlls (string source, string valueName)
+		{
+			// Some event sources (such as Userenv) have multiple message
+			// resource DLLs, delimited by a semicolon.
+
+			RegistryKey sourceKey = FindSourceKeyByName (source,
+				CoreEventLog.MachineName, false);
+			if (sourceKey != null) {
+				string value = sourceKey.GetValue (valueName) as string;
+				if (value != null) {
+					string [] msgResDlls = value.Split (';');
+					return msgResDlls;
+				}
+			}
+			return new string [0];
+		}
+
+		private IntPtr OpenEventLog ()
+		{
+			string logName = CoreEventLog.GetLogName ();
+			IntPtr hEventLog = PInvoke.OpenEventLog (CoreEventLog.MachineName,
+				logName);
+			if (hEventLog == IntPtr.Zero) {
+				throw new InvalidOperationException (string.Format (
+					CultureInfo.InvariantCulture, "Event Log '{0}' on computer"
+					+ " '{1}' cannot be opened."), new Win32Exception ());
+			}
+			return hEventLog;
+		}
+
+		private IntPtr RegisterEventSource ()
+		{
+			IntPtr hEventLog = PInvoke.OpenEventLog (CoreEventLog.MachineName,
+				CoreEventLog.Source);
+			if (hEventLog == IntPtr.Zero) {
+				throw new InvalidOperationException (string.Format (
+					CultureInfo.InvariantCulture, "Event Log '{0}' on computer"
+					+ " '{1}' cannot be opened."), new Win32Exception ());
+			}
+			return hEventLog;
+		}
+
+		private class PInvoke
+		{
+			[DllImport ("advapi32.dll", SetLastError=true)]
+			public static extern int ClearEventLog (IntPtr hEventLog, string lpBackupFileName);
+
+			[DllImport ("advapi32.dll", SetLastError=true)]
+			public static extern int CloseEventLog (IntPtr hEventLog);
+
+			[DllImport ("advapi32.dll", SetLastError=true)]
+			public static extern int DeregisterEventSource (IntPtr hEventLog);
+
+			[DllImport ("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
+			public static extern int FormatMessage (FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, ref IntPtr lpBuffer, int nSize, IntPtr [] arguments);
+
+			[DllImport ("kernel32.dll", SetLastError=true)]
+			public static extern bool FreeLibrary (IntPtr hModule);
+
+			[DllImport ("advapi32.dll", SetLastError=true)]
+			public static extern int GetNumberOfEventLogRecords (IntPtr hEventLog, ref int NumberOfRecords);
+
+			[DllImport ("advapi32.dll", SetLastError=true)]
+			public static extern int GetOldestEventLogRecord (IntPtr hEventLog, ref int OldestRecord);
+
+			[DllImport ("kernel32.dll", SetLastError=true)]
+			public static extern IntPtr LoadLibraryEx (string lpFileName, IntPtr hFile, LoadFlags dwFlags);
+
+			[DllImport ("kernel32.dll", SetLastError=true)]
+			public static extern IntPtr LocalFree (IntPtr hMem);
+
+			[DllImport ("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
+			public static extern bool LookupAccountSid (
+				string lpSystemName,
+				[MarshalAs (UnmanagedType.LPArray)] byte [] Sid,
+				StringBuilder lpName,
+				ref uint cchName,
+				StringBuilder ReferencedDomainName,
+				ref uint cchReferencedDomainName,
+				out SidNameUse peUse);
+
+			[DllImport ("advapi32.dll", SetLastError=true)]
+			public static extern IntPtr OpenEventLog (string machineName, string logName);
+
+			[DllImport ("advapi32.dll", SetLastError=true)]
+			public static extern IntPtr RegisterEventSource (string machineName, string sourceName);
+
+			[DllImport ("Advapi32.dll", SetLastError = true)]
+			public static extern int ReportEvent (IntPtr hHandle, ushort wType,
+				ushort wCategory, uint dwEventID, IntPtr sid, ushort wNumStrings,
+				uint dwDataSize, string [] lpStrings, byte [] lpRawData);
+
+			[DllImport ("advapi32.dll", SetLastError = true)]
+			public static extern int ReadEventLog (IntPtr hEventLog, ReadFlags dwReadFlags, int dwRecordOffset, byte [] buffer, int nNumberOfBytesToRead, ref int pnBytesRead, ref int pnMinNumberOfBytesNeeded);
+
+			public const int ERROR_INSUFFICIENT_BUFFER = 122;
+		}
+
+		private enum ReadFlags
+		{
+			Sequential = 0x001,
+			Seek = 0x002,
+			ForwardsRead = 0x004,
+			BackwardsRead = 0x008
+		}
+
+		private enum LoadFlags: uint
+		{
+			LibraryAsDataFile = 0x002
+		}
+
+		[Flags]
+		private enum FormatMessageFlags
+		{
+			AllocateBuffer = 0x100,
+			IgnoreInserts = 0x200,
+			FromHModule = 0x0800,
+			FromSystem = 0x1000,
+			ArgumentArray = 0x2000
+		}
+
+		private enum SidNameUse
+		{
+			User = 1,
+			Group,
+			Domain,
+			lias,
+			WellKnownGroup,
+			DeletedAccount,
+			Invalid,
+			Unknown,
+			Computer
+		}
+	}
+}
+
+// http://msdn.microsoft.com/library/en-us/eventlog/base/eventlogrecord_str.asp:
+//
+// struct EVENTLOGRECORD {
+//	int Length;
+//	int Reserved;
+//	int RecordNumber;
+//	int TimeGenerated;
+//	int TimeWritten;
+//	int EventID;
+//	short EventType;
+//	short NumStrings;
+//	short EventCategory;
+//	short ReservedFlags;
+//	int ClosingRecordNumber;
+//	int StringOffset;
+//	int UserSidLength;
+//	int UserSidOffset;
+//	int DataLength;
+//	int DataOffset;
+// }
+//
+// http://www.whitehats.ca/main/members/Malik/malik_eventlogs/malik_eventlogs.html

+ 1 - 0
mcs/class/System/System.dll.sources

@@ -485,6 +485,7 @@ System.Diagnostics/TraceLevel.cs
 System.Diagnostics/TraceListenerCollection.cs
 System.Diagnostics/TraceListener.cs
 System.Diagnostics/TraceSwitch.cs
+System.Diagnostics/Win32EventLog.cs
 System/FileStyleUriParser.cs
 System/FtpStyleUriParser.cs
 System/GenericUriParser.cs

+ 10 - 0
mcs/class/System/Test/System.Diagnostics/ChangeLog

@@ -1,3 +1,13 @@
+2006-08-20  Gert Driesen  <[email protected]>
+
+	* EventLogTest.cs: Enable tests. On 2.0 profile, set MONO_EVENTLOG_TYPE
+	environment variable to force local file implementation to be used for
+	unit tests. This avoids permission issues for the unit tests, and
+	allows us to clean up the files/directory that are created during the
+	test run. Skip tests that cannot pass when the null implementation is
+	active (on 1.0 profile). Added tests for all WriteEntry and WriteEvent
+	(2.0 only) overloads, Clear, Entries, Exists and LogNameFromSourceName.
+
 2006-08-11  Gert Driesen  <[email protected]>
 
 	* EventLogTest.cs: new test, currently not enabled due to UnixRegistry

Plik diff jest za duży
+ 583 - 98
mcs/class/System/Test/System.Diagnostics/EventLogTest.cs


Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików