Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EventLog.cs « System.Diagnostics « System « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2c88565e580c90f8814afbe0318a3d6c08bfdf22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//
// System.Diagnostics.EventLog.cs
//
// Authors:
//	Jonathan Pryor (jonpryor@vt.edu)
//	Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//	Gert Driesen (drieseng@users.sourceforge.net)
//
// 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
// "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.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;

namespace System.Diagnostics 
{
	[DefaultEvent ("EntryWritten")]
	[InstallerType (typeof (EventLogInstaller))]
#if NET_2_0
	[MonitoringDescription ("Represents an event log")]
#else
	[Designer ("Microsoft.VisualStudio.Install.EventLogInstallableComponentDesigner, " + Consts.AssemblyMicrosoft_VisualStudio)]
#endif
	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 (string.Empty)
		{
		}

		public EventLog(string logName) : this (logName, ".")
		{
		}

		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.Trim ().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;

			Impl = CreateEventLogImpl (this);
		}

		[Browsable (false), DefaultValue (false)]
		[MonitoringDescription ("If enabled raises event when a log is written.")]
		public bool EnableRaisingEvents {
			get {return doRaiseEvents;}
			set {
				if (value == doRaiseEvents)
					return;

				if (value)
					Impl.EnableNotification ();
				else
					Impl.DisableNotification ();
				doRaiseEvents = value;
			}
		}

		[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
		[MonitoringDescription ("The entries in the log.")]
		public EventLogEntryCollection 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 {
				if (source != null && source.Length > 0)
					return GetLogName ();
				return logName;
			}
			set {
				if (value == null)
					throw new ArgumentNullException ("value");

				// log name is treated case-insensitively on all platforms
				if (string.Compare (logName, value, true) != 0) {
					logName = value;
					Reset ();
				}
			}
		}

		[Browsable (false)]
		public string LogDisplayName {
			get { return Impl.LogDisplayName; }
		}

		[ReadOnly (true), DefaultValue ("."), RecommendedAsConfigurable (true)]
		[MonitoringDescription ("Name of the machine that this log get written to.")]
		public string MachineName {
			get { return machineName; }
			set {
				if (value == null || value.Trim ().Length == 0)
					throw new ArgumentException (string.Format (
						CultureInfo.InvariantCulture, "Invalid value {0} for"
						+ " property MachineName.", value));

				if (string.Compare (machineName, value, true) != 0) {
					Close ();
					machineName = value;
				}
			}
		}

		[ReadOnly (true), DefaultValue (""), RecommendedAsConfigurable (true)]
		[TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
		[MonitoringDescription ("The application name that writes the log.")]
		public string Source {
			get { return source; }
			set {
				if (value == null)
					value = string.Empty;

				// Source only affects eventlog implementation if Source was set
				// and no Log was set
				if (source == null || source.Length == 0 && (logName == null ||logName.Length == 0)) {
					source = value;
				} else if (string.Compare (source, value, true) != 0) {
					source = value;
					Reset ();
				}
			}
		}

		[Browsable (false), DefaultValue (null)]
		[MonitoringDescription ("An object that synchronizes event handler calls.")]
		public ISynchronizeInvoke SynchronizingObject {
			get {return synchronizingObject;}
			set {synchronizingObject = value;}
		}

#if NET_2_0
		[MonoTODO]
		[ComVisibleAttribute (false)]
		[Browsable (false)]
		public OverflowAction OverflowAction {
			get { return Impl.OverflowAction; }
		}

		[MonoTODO]
		[ComVisibleAttribute (false)]
		[Browsable (false)]
		public int MinimumRetentionDays {
			get { return Impl.MinimumRetentionDays; }
		}

		[MonoTODO]
		[ComVisibleAttribute (false)]
		[Browsable (false)]
		[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
		public long MaximumKilobytes {
			get { return Impl.MaximumKilobytes; }
			set { Impl.MaximumKilobytes = value; }
		}

		[MonoTODO]
		[ComVisible (false)]
		public void ModifyOverflowPolicy (OverflowAction action, int retentionDays)
		{
			Impl.ModifyOverflowPolicy (action, retentionDays);
		}

		[MonoTODO]
		[ComVisibleAttribute (false)]
		public void RegisterDisplayName (string resourceFile, long resourceId)
		{
			Impl.RegisterDisplayName (resourceFile, resourceId);
		}
#endif

		public void BeginInit ()
		{
			Impl.BeginInit();
		}

		public void 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 ();
			Reset ();
		}

		public void Close ()
		{
			Impl.Close();
			EnableRaisingEvents = false;
		}

		internal void Reset ()
		{
			bool enableRaisingEvents = EnableRaisingEvents;
			Close ();
			EnableRaisingEvents = enableRaisingEvents;
		}

		public static void CreateEventSource (string source, string logName)
		{
			CreateEventSource (source, logName, ".");
		}

#if NET_2_0
		[Obsolete ("use CreateEventSource(EventSourceCreationData) instead")]
#endif
		public static void CreateEventSource (string source, 
			string logName, 
			string machineName)
		{
			CreateEventSource (new EventSourceCreationData (source, logName,
				machineName));
		}

#if NET_2_0
		[MonoNotSupported ("remote machine is not supported")]
		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)
		{
			Delete (logName, ".");
		}

		[MonoNotSupported ("remote machine is not supported")]
		public static void Delete (string logName, string machineName)
		{
			if (machineName == null || machineName.Trim ().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)
		{
			DeleteEventSource (source, ".");
		}

		[MonoNotSupported ("remote machine is not supported")]
		public static void DeleteEventSource (string source, string machineName)
		{
			if (machineName == null || machineName.Trim ().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)
		{
			if (Impl != null)
				Impl.Dispose (disposing);
		}

		public void EndInit()
		{
			Impl.EndInit();
		}

		public static bool Exists (string logName)
		{
			return Exists (logName, ".");
		}

		[MonoNotSupported ("remote machine is not supported")]
		public static bool Exists (string logName, string machineName)
		{
			if (machineName == null || machineName.Trim ().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 ()
		{
			return GetEventLogs (".");
		}

		[MonoNotSupported ("remote machine is not supported")]
		public static EventLog[] GetEventLogs (string machineName)
		{
			EventLogImpl impl = CreateEventLogImpl (new EventLog ());
			return impl.GetEventLogs (machineName);
		}

		[MonoNotSupported ("remote machine is not supported")]
		public static string LogNameFromSourceName (string source, string machineName)
		{
			if (machineName == null || machineName.Trim ().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)
		{
			return SourceExists (source, ".");
		}

		[MonoNotSupported ("remote machine is not supported")]
		public static bool SourceExists (string source, string machineName)
		{
			if (machineName == null || machineName.Trim ().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.SourceExists (source, machineName);
		}

		public void WriteEntry (string message)
		{
			WriteEntry (message, EventLogEntryType.Information);
		}

		public void WriteEntry (string message, EventLogEntryType type)
		{
			WriteEntry (message, type, 0);
		}

		public void WriteEntry (string message, EventLogEntryType type, 
			int eventID)
		{
			WriteEntry (message, type, eventID, 0);
		}

		public void WriteEntry (string message, EventLogEntryType type, 
			int eventID,
			short category)
		{
			WriteEntry (message, type, eventID, category, null);
		}

		public void WriteEntry (string message, EventLogEntryType type, 
			int eventID,
			short category, byte[] rawData)
		{
			WriteEntry (new string [] { message }, type, eventID,
				category, rawData);
		}

		public static void WriteEntry (string source, string message)
		{
			WriteEntry (source, message, EventLogEntryType.Information);
		}

		public static void WriteEntry (string source, string message, 
			EventLogEntryType type)
		{
			WriteEntry (source, message, type, 0);
		}

		public static void WriteEntry (string source, string message, 
			EventLogEntryType type, int eventID)
		{
			WriteEntry (source, message, type, eventID, 0);
		}

		public static void WriteEntry (string source, string message, 
			EventLogEntryType type, int eventID, short category)
		{
			WriteEntry (source, message, type, eventID, category, null);
		}

		public static void WriteEntry (string source, string message, 
			EventLogEntryType type, int eventID, short category, 
			byte[] rawData)
		{
			using (EventLog eventLog = new EventLog ()) {
				eventLog.Source = source;
				eventLog.WriteEntry (message, type, eventID, category, rawData);
			}
		}

#if NET_2_0
		[ComVisible (false)]
		public void WriteEvent (EventInstance instance, params object [] values)
		{
			WriteEvent (instance, null, values);
		}

		[ComVisible (false)]
		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 (doRaiseEvents && EntryWritten != null)
				EntryWritten (this, new EntryWrittenEventArgs (newEntry));
		}

		[MonitoringDescription ("Raised for each EventLog entry written.")]
		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;
		}
	}
}