Esempio n. 1
0
        public bool Equals(EventLogEntry otherEntry)
        {
            if (otherEntry == null)
            {
                return(false);
            }
            int ourLen   = IntFrom(dataBuf, bufOffset + FieldOffsets.LENGTH);
            int theirLen = IntFrom(otherEntry.dataBuf, otherEntry.bufOffset + FieldOffsets.LENGTH);

            if (ourLen != theirLen)
            {
                return(false);
            }
            int min = bufOffset;
            int max = bufOffset + ourLen;
            int j   = otherEntry.bufOffset;

            for (int i = min; i < max; i++, j++)
            {
                if (dataBuf[i] != otherEntry.dataBuf[j])
                {
                    return(false);
                }
            }

            return(true);
        }
 public bool Equals(EventLogEntry otherEntry)
 {
     if (otherEntry == null)
     {
         return false;
     }
     int num = this.IntFrom(this.dataBuf, this.bufOffset);
     int num2 = this.IntFrom(otherEntry.dataBuf, otherEntry.bufOffset);
     if (num != num2)
     {
         return false;
     }
     int bufOffset = this.bufOffset;
     int num4 = this.bufOffset + num;
     int index = otherEntry.bufOffset;
     int num6 = bufOffset;
     while (num6 < num4)
     {
         if (this.dataBuf[num6] != otherEntry.dataBuf[index])
         {
             return false;
         }
         num6++;
         index++;
     }
     return true;
 }
Esempio n. 3
0
        private void NotifyEventThread()
        {
            while (true)
            {
                _notifyResetEvent.WaitOne();
                lock (this) {
                    // after a clear, we something get notified
                    // twice for the same entry
                    if (_notifying)
                    {
                        return;
                    }
                    _notifying = true;
                }

                try {
                    int oldest_entry = OldestEventLogEntry;
                    if (_lastEntryWritten < oldest_entry)
                    {
                        _lastEntryWritten = oldest_entry;
                    }
                    int current_entry = _lastEntryWritten - oldest_entry;
                    int last_entry    = EntryCount + oldest_entry;
                    for (int i = current_entry; i < (last_entry - 1); i++)
                    {
                        EventLogEntry entry = GetEntry(i);
                        CoreEventLog.OnEntryWritten(entry);
                    }
                    _lastEntryWritten = last_entry;
                } finally {
                    lock (this)
                        _notifying = false;
                }
            }
        }
Esempio n. 4
0
 internal void OnEntryWritten(EventLogEntry newEntry)
 {
     if (doRaiseEvents && EntryWritten != null)
     {
         EntryWritten(this, new EntryWrittenEventArgs(newEntry));
     }
 }
Esempio n. 5
0
        private ObjectDump GetDump(EventLogEntry entry)
        {
            var posOfPeriod = entry.Message.IndexOf(".");
            var message = entry.Message.Trim();

            if (posOfPeriod > 0)
            {
                message = message.Substring(0, posOfPeriod);
            }

            if (entry.InstanceId == EventInstanceIdShutdown)
            {
                message = "The System is shutting down ";// + entry.Message;
            }

            var dump = new ObjectDump();
            dump.Headers.Add("Time");
            dump.Headers.Add("Message");
            dump.Data.Add(entry.TimeGenerated.ToString("dd-MMM-yyyy HH:mm"));
            dump.Data.Add(message);

            if (VerboseOutput)
            {
                dump.Headers.Insert(1, "InstanceId");
                dump.Data.Insert(1, entry.InstanceId.ToString());
            }

            return dump;
        }
Esempio n. 6
0
        public EventLogEntry [] GetEntries()
        {
            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);
        }
Esempio n. 7
0
        public bool Equals(EventLogEntry otherEntry)
        {
            if (otherEntry == null)
            {
                return(false);
            }
            int num  = this.IntFrom(this.dataBuf, this.bufOffset);
            int num2 = this.IntFrom(otherEntry.dataBuf, otherEntry.bufOffset);

            if (num != num2)
            {
                return(false);
            }
            int bufOffset = this.bufOffset;
            int num4      = this.bufOffset + num;
            int index     = otherEntry.bufOffset;
            int num6      = bufOffset;

            while (num6 < num4)
            {
                if (this.dataBuf[num6] != otherEntry.dataBuf[index])
                {
                    return(false);
                }
                num6++;
                index++;
            }
            return(true);
        }
Esempio n. 8
0
        internal int GetMatchingEventLogCount()
        {
            int result = 0;

            LastEntries = new List <EventLogEntryEx>();
            using (diag.EventLog log = new diag.EventLog(EventLog, Computer))
            {
                DateTime currentTime = DateTime.Now;
                int      counter     = 0;
                int      listSize    = log.Entries.Count - 1;

                for (int i = listSize; i >= 0; i--)
                {
                    try
                    {
                        diag.EventLogEntry entry = log.Entries[i];

                        if (WithInLastXEntries > 0 && WithInLastXEntries <= counter)
                        {
                            break;
                        }
                        if (WithInLastXMinutes > 0 && entry.TimeGenerated.AddMinutes(WithInLastXMinutes) < currentTime)
                        {
                            break;
                        }

                        EventLogEntryEx newentry = new EventLogEntryEx();
                        newentry.Category       = entry.Category;
                        newentry.EntryType      = entry.EntryType;
                        newentry.EventId        = (int)(entry.InstanceId & 65535);
                        newentry.MachineName    = entry.MachineName;
                        newentry.LogName        = EventLog;
                        newentry.Source         = entry.Source;
                        newentry.Message        = entry.Message;
                        newentry.MessageSummary = newentry.Message.Length > 80 ? newentry.Message.Substring(0, 80) : newentry.Message;
                        //if (TextFilter.Length > 0)
                        //    newentry.Message = entry.Message;
                        newentry.TimeGenerated = entry.TimeGenerated;
                        newentry.UserName      = entry.UserName;

                        if (MatchEntry(newentry))
                        {
                            LastEntries.Add(newentry);
                            result++;
                        }
                        counter++;
                    }
                    catch (Exception ex)
                    {
                        string errStr = ex.ToString();
                        if (!(errStr.Contains("is out of bounds") || errStr.Contains("outside the bounds")))
                        {
                            throw;
                        }
                    }
                }
            }
            return(result);
        }
 public void isSimpleEntryWriten()
 {
     EventLog ea=new EventLog("Test Log",".","Test Log");
     LogManager.Log("Hello world!");
     EventLogEntry[] entries=new EventLogEntry[ea.Entries.Count];
     ea.Entries.CopyTo(entries,0);
     Assertion.AssertEquals("Hello world!",entries[0].Message);
     ea.Clear();
 }
Esempio n. 10
0
        private void AddRow(EventLogEntry entry)
        {
            try
            {
                object[] dr = new object[] { entry.Message, entry.TimeGenerated.ToString(), entry.EntryType.ToString(),
                (entry.UserName != null) ? entry.UserName : "******" };

                dtLogger.Rows.Add(dr);
            }
            catch { }
        }
 private QvxDataRow MakeEntry(EventLogEntry evl, QvxTable table)
 {
     var row = new QvxDataRow();
     row[table.Fields[0]] = evl.Category;
     row[table.Fields[1]] = evl.EntryType.ToString();
     row[table.Fields[2]] = evl.Message;
     row[table.Fields[3]] = evl.CategoryNumber.ToString();
     row[table.Fields[4]] = evl.Index.ToString();
     row[table.Fields[5]] = evl.MachineName;
     row[table.Fields[6]] = evl.Source;
     row[table.Fields[7]] = evl.TimeGenerated.ToString();
     return row;
 }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EntrySummary"/> class.
        /// </summary>
        /// <param name="entry"></param>
        public EntrySummary(EventLogEntry entry)
            : this()
        {
            Category = entry.Category;
            CategoryNumber = entry.CategoryNumber;
            EntryType = (EntryType)entry.EntryType; // Cast to a serializable type
            InstanceId = entry.InstanceId;
            Index = entry.Index;
            Message = entry.Message;
            Source = entry.Source;
            TimeGenerated = entry.TimeGenerated;
            TimeWritten = entry.TimeWritten;

            MachineName = entry.MachineName;
            MachineDisplayName = entry.MachineName;
        }
Esempio n. 13
0
        private void NotifyEventThread(ManualResetEvent resetEvent)
        {
            if (resetEvent == null)
            {
                return;
            }

            while (true)
            {
                try {
                    resetEvent.WaitOne();
                } catch (ObjectDisposedException) {
                    // Notifications have been disabled and event
                    // has been closed but not yet nulled. End thread.
                    break;
                }

                lock (_eventLock) {
                    if (resetEvent != _notifyResetEvent)
                    {
                        // A new thread has started with another reset event instance
                        // or DisableNotifications has been called, setting
                        // _notifyResetEvent to null. In both cases end this thread.
                        break;
                    }

                    if (_readHandle == IntPtr.Zero)
                    {
                        break;
                    }

                    int oldest_entry = OldestEventLogEntry;
                    if (_lastEntryWritten < oldest_entry)
                    {
                        _lastEntryWritten = oldest_entry;
                    }
                    int current_entry = _lastEntryWritten - oldest_entry;
                    int last_entry    = EntryCount + oldest_entry;
                    for (int i = current_entry; i < (last_entry - 1); i++)
                    {
                        EventLogEntry entry = GetEntry(i);
                        CoreEventLog.OnEntryWritten(entry);
                    }
                    _lastEntryWritten = last_entry;
                }
            }
        }
Esempio n. 14
0
        private static void Output(EventLogEntry entry, EvTailConfigurationModel configuration, StreamWriter outputFile)
        {
            var msg = string.Format("{0} {1} {2}", entry.TimeGenerated, entry.Source, entry.Message);

            if (configuration.outputToConsole)
            {
                Console.Write(msg);
            }

            outputFile?.Write(msg);
            outputFile?.Flush();

            if (!entry.Message.EndsWith(Environment.NewLine))
            {
                Console.Write(Environment.NewLine);
                outputFile?.Write(Environment.NewLine);
            }
        }
Esempio n. 15
0
        internal List <EventLogEntryEx> GetMatchingEventLogEntries()
        {
            List <EventLogEntryEx> list = new List <EventLogEntryEx>();

            using (diag.EventLog log = new diag.EventLog(EventLog, Computer))
            {
                DateTime currentTime = DateTime.Now;
                int      counter     = 0;
                int      listSize    = log.Entries.Count - 1;

                for (int i = listSize; i >= 0; i--)
                {
                    diag.EventLogEntry entry = log.Entries[i];
                    if (WithInLastXEntries > 0 && WithInLastXEntries <= counter)
                    {
                        break;
                    }
                    if (WithInLastXMinutes > 0 && entry.TimeGenerated.AddMinutes(WithInLastXMinutes) < currentTime)
                    {
                        break;
                    }

                    EventLogEntryEx newentry = new EventLogEntryEx();
                    newentry.Category       = entry.Category;
                    newentry.EntryType      = entry.EntryType;
                    newentry.EventId        = (int)(entry.InstanceId & 65535);
                    newentry.MachineName    = entry.MachineName;
                    newentry.LogName        = EventLog;
                    newentry.Message        = entry.Message;
                    newentry.MessageSummary = newentry.Message.Length > 80 ? newentry.Message.Substring(0, 80) : newentry.Message;
                    newentry.Source         = entry.Source;
                    newentry.TimeGenerated  = entry.TimeGenerated;
                    newentry.UserName       = entry.UserName;

                    if (MatchEntry(newentry))
                    {
                        list.Add(newentry);
                    }
                    counter++;
                }
            }
            return(list);
        }
Esempio n. 16
0
 private static string GetUserName( EventLogEntry entry )
 {
     switch (entry.InstanceId)
     {
         case 682:
         case 683:
         case 4779:
         case 4778:
             return entry.ReplacementStrings[0];
         case 528:
             return "1";
         case 538:
             return "2";
         case 4624:
             return entry.ReplacementStrings[5];
         case 4647:
         case 4634:
             return entry.ReplacementStrings[1];
         default:
             throw new Exception( "Did you forget to add the new event here?" );
     }
 }
Esempio n. 17
0
        public bool Equals(EventLogEntry otherEntry)
        {
            if (otherEntry == this)
            {
                return(true);
            }

            return(
                (otherEntry.Category == category) &&
                (otherEntry.CategoryNumber == categoryNumber) &&
                (otherEntry.Data.Equals(data)) &&
                (otherEntry.EntryType == entryType) &&
                (otherEntry.InstanceId == instanceId) &&
                (otherEntry.Index == index) &&
                (otherEntry.MachineName == machineName) &&
                (otherEntry.Message == message) &&
                (otherEntry.ReplacementStrings.Equals(replacementStrings)) &&
                (otherEntry.Source == source) &&
                (otherEntry.TimeGenerated.Equals(timeGenerated)) &&
                (otherEntry.TimeWritten.Equals(timeWritten)) &&
                (otherEntry.UserName == userName)
                );
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            Console.Write("Geben sie den Namen der Maschine ein: ");
            var log = new EventLog("Security", Console.ReadLine());

            var ele = new EventLogEntry[log.Entries.Count];
            log.Entries.CopyTo(ele, 0);

            var deletions = ele.Where(o => o != null && o.InstanceId == 5145)
                .Where(o => o.ReplacementStrings[11].Contains("%%1537"))
                .ToArray();

            foreach(var eventLogEntry in deletions)
                Console.WriteLine("Die Ressource {0} wurde gelöscht am {1} von {2}\\{3} von {4}",
                    eventLogEntry.ReplacementStrings[9], // Dateiname
                    eventLogEntry.TimeGenerated, //Zeit
                    eventLogEntry.ReplacementStrings[2], //Domaine
                    eventLogEntry.ReplacementStrings[1], // Username
                    GetHostname(eventLogEntry.ReplacementStrings[5])); // IP

            Console.WriteLine();
            Console.WriteLine("Es wurden {0} Events ausgewertet", deletions.Length);
            Console.ReadKey();
        }
Esempio n. 19
0
        // Write an entry to this event log.
        private void WriteEntryToLog(String source, String message,
                                     EventLogEntryType type, int eventID,
                                     short category, byte[] rawData)
        {
            // Change to the new source.
            if (source != this.source)
            {
                Source = source;
            }

            // Create the entry.
            EventLogEntry entry = new EventLogEntry();

            entry.category           = category.ToString();
            entry.categoryNumber     = category;
            entry.data               = rawData;
            entry.entryType          = type;
            entry.eventID            = eventID;
            entry.index              = 0;
            entry.machineName        = this.machineName;
            entry.message            = message;
            entry.replacementStrings = null;
            entry.source             = this.source;
            entry.timeWritten        = entry.timeGenerated = DateTime.Now;
            entry.userName           = Environment.UserName;

            // Write the entry to the log.
            entries.Add(entry);

            // Notify the listening event handlers for local events.
            if (enableRaisingEvents && machineName == "." &&
                EntryWritten != null)
            {
                EntryWritten(null, new EntryWrittenEventArgs(entry));
            }
        }
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void CopyTo(EventLogEntry[] entries, int index) {
     ((ICollection)this).CopyTo((Array)entries, index);
 }       
Esempio n. 21
0
        /// <summary>
        /// Send event to syslog server
        /// </summary>
        /// <param name="message">Message to send</param>
        /// <param name="evebntLogName">EventLog name</param>
        /// <param name="eventLogEntry">Event to transfert to syslog server</param>
        /// <param name="filter">Filter with Syslog facility and level</param>
        /// <param name="debug">Debug object</param>
        /// <returns>True if any error appear</returns>
        private Boolean SendEventByUDP(String message, String eventLogName, EventLogEntry eventLogEntry, Filter filter)
        {
            IPAddress[] ServersAddress;

            // Create syslog tag and remove syslog message accents
            Int32 pri = (int)Facility[filter.SyslogFacility.ToLower()] * 8 + (int)Level[filter.SyslogLevel.ToLower()];
            String body = "<" + pri + ">" + eventLogEntry.MachineName + " " + message;

            // Convert final message in bytes
            byte[] rawMsg = Encoding.Default.GetBytes(body);

            try
            {
                ServersAddress = Dns.GetHostAddresses(this._ServerAddress);

                String temp = ServersAddress.GetValue(0).ToString();

                for (int i = 0; i < ServersAddress.Length; i++)
                {
                    UdpClient udp = new UdpClient(ServersAddress.GetValue(i).ToString(), this._ServerPort);

                    udp.Send(rawMsg, rawMsg.Length);
                    this._Debug.Write("Syslog Server", "Event send to: " + ServersAddress.GetValue(i).ToString() + " with message: " + message, DateTime.Now, 2);
                    udp.Close();
                    udp = null;
                }
            }
            catch (SocketException e)
            {
                this._Debug.Write("Syslog Server", "SocketException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (ArgumentNullException e)
            {
                this._Debug.Write("Syslog Server", "ArgumentNullException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (ArgumentOutOfRangeException e)
            {
                this._Debug.Write("Syslog Server", "ArgumentOutOfRangeException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (ObjectDisposedException e)
            {
                this._Debug.Write("Syslog Server", "ObjectDisposedException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (InvalidOperationException e)
            {
                this._Debug.Write("Syslog Server", "InvalidOperationException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }

            return true;
        }
Esempio n. 22
0
        /// <summary>
        /// Transform EventLogEntry to String
        /// </summary>
        /// <param name="evebntLogName">EventLog name</param>
        /// <param name="eventLogEntry">Event to transfert to syslog server</param>
        /// <param name="debug">Debug object</param>
        /// <returns>String of syslog event to transfert</returns>
        private String PrepareSyslogEvent(String evebntLogName, EventLogEntry eventLogEntry)
        {
            // Prepare message will sent to syslog server
            String body = eventLogEntry.Source.Replace(" ", "_") + " Type: " + eventLogEntry.EntryType.ToString();

            if (eventLogEntry.Category != null)
                body = body + ", Category: " + eventLogEntry.Category;

            if (eventLogEntry.EventID != 0)
                body = body + ", Event ID: " + eventLogEntry.EventID;

            if (eventLogEntry.UserName != null)
                body = body + ", User: "******", Description: " + eventLogEntry.Message;

            body = body.Replace('\r', ' ');
            body = body.Replace('\n', ' ');

            return body;
        }
Esempio n. 23
0
 public EntryWrittenEventArgs(System.Diagnostics.EventLogEntry entry)
 {
 }
		public void Entries_Source_Null ()
		{
			if (EventLogImplType == NULL_IMPL)
				// test cannot pass with NULL implementation
				return;

			if (EventLog.SourceExists ("monotempsource", "."))
				Assert.Ignore ("Event log source 'monotempsource' should not exist.");

			if (EventLog.Exists ("monologtemp", "."))
				Assert.Ignore ("Event log 'monologtemp' should not exist.");

			EventLog.CreateEventSource ("monotempsource", "monologtemp", ".");
			try {
				using (EventLog eventLog = new EventLog ("monologtemp", ".", null)) {
					Assert.IsNotNull (eventLog.Entries, "#A1");
					Assert.AreEqual (0, eventLog.Entries.Count, "#A2");
					EventLog.WriteEntry ("monotempsource", "Entries_Source_Null1");
					Assert.AreEqual (1, eventLog.Entries.Count, "#A3");

					IEnumerator enumerator = eventLog.Entries.GetEnumerator ();
					Assert.IsNotNull (enumerator, "#B");

					try {
						object current = enumerator.Current;
						Assert.Fail ("#C1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2");
						Assert.IsNotNull (ex.Message, "#C3");
						Assert.IsNull (ex.InnerException, "#C4");
					}

					Assert.IsTrue (enumerator.MoveNext (), "#D1");
					Assert.IsNotNull (enumerator.Current, "#D2");
					Assert.IsFalse (enumerator.MoveNext (), "#D3");

					EventLogEntry [] entries = new EventLogEntry [1];
					eventLog.Entries.CopyTo (entries, 0);

					EventLogEntry entry = entries [0];
					Assert.IsNotNull (entry, "#E1");
					Assert.IsNotNull (entry.Source, "#E2");
					Assert.AreEqual ("monotempsource", entry.Source, "#E3");
					Assert.IsNotNull (entry.ReplacementStrings, "#E4");
					Assert.AreEqual (1, entry.ReplacementStrings.Length, "#E5");
					Assert.AreEqual ("Entries_Source_Null1", entry.ReplacementStrings [0], "#E6");

					try {
						object current = enumerator.Current;
						Assert.Fail ("#E1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");
						Assert.IsNotNull (ex.Message, "#E3");
						Assert.IsNull (ex.InnerException, "#E4");
					}

					try {
						object current = enumerator.Current;
						Assert.Fail ("#F1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#F2");
						Assert.IsNotNull (ex.Message, "#F3");
						Assert.IsNull (ex.InnerException, "#F4");
					}

					EventLog.WriteEntry ("monotempsource", "Entries_Source_Null2");

#if NET_2_0
					try {
						object current = enumerator.Current;
						Assert.Fail ("#G1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#G2");
						Assert.IsNotNull (ex.Message, "#G3");
						Assert.IsNull (ex.InnerException, "#G4");
					}
#else
					entry = (EventLogEntry) enumerator.Current;
					Assert.IsNotNull (entry, "#G1");
					Assert.IsNotNull (entry.Source, "#G2");
					Assert.AreEqual ("monotempsource", entry.Source, "#G3");
					Assert.IsNotNull (entry.ReplacementStrings, "#G4");
					Assert.AreEqual (1, entry.ReplacementStrings.Length, "#G5");
					Assert.AreEqual ("Entries_Source_Null2", entry.ReplacementStrings [0], "#G6");
#endif

					Assert.IsFalse (enumerator.MoveNext (), "#H1");
					Assert.AreEqual (2, eventLog.Entries.Count, "#H2");

					entries = new EventLogEntry [1];
					try {
						eventLog.Entries.CopyTo (entries, 0);
						Assert.Fail ("#I1");
					} catch (ArgumentException ex) {
						// Destination array was not long enough. Check destIndex
						// and length, and the array's lower bounds
						Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#I2");
						Assert.IsNotNull (ex.Message, "#I3");
						Assert.IsNull (ex.InnerException, "#I4");
#if NET_2_0
						Assert.AreEqual ("", ex.ParamName, "#I5");
#else
						Assert.IsNull (ex.ParamName, "#I5");
#endif
					}

					entries = new EventLogEntry [2];
					eventLog.Entries.CopyTo (entries, 0);

					entry = entries [0];
					Assert.IsNotNull (entry, "#J1");
					Assert.IsNotNull (entry.Source, "#J2");
					Assert.AreEqual ("monotempsource", entry.Source, "#J3");
					Assert.IsNotNull (entry.ReplacementStrings, "#J4");
					Assert.AreEqual (1, entry.ReplacementStrings.Length, "#J5");
					Assert.AreEqual ("Entries_Source_Null1", entry.ReplacementStrings [0], "#J6");

					entry = entries [1];
					Assert.IsNotNull (entry, "#K1");
					Assert.IsNotNull (entry.Source, "#K2");
					Assert.AreEqual ("monotempsource", entry.Source, "#K3");
					Assert.IsNotNull (entry.ReplacementStrings, "#K4");
					Assert.AreEqual (1, entry.ReplacementStrings.Length, "#K5");
					Assert.AreEqual ("Entries_Source_Null2", entry.ReplacementStrings [0], "#K6");

					Assert.IsFalse (enumerator.MoveNext (), "#L1");
					enumerator.Reset ();
					Assert.IsTrue (enumerator.MoveNext (), "#L2");
					Assert.IsNotNull (enumerator.Current, "#L3");
					Assert.IsTrue (enumerator.MoveNext (), "#L4");
					Assert.IsNotNull (enumerator.Current, "#L5");

					Assert.IsFalse (enumerator.MoveNext (), "#M1");
					enumerator.Reset ();
					Assert.IsTrue (enumerator.MoveNext (), "#M2");
					eventLog.Clear ();
#if NET_2_0
					Assert.IsNotNull (enumerator.Current, "#M3");
#else
					try {
						object current = enumerator.Current;
						Assert.Fail ("#M3a: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#M3b");
						Assert.IsNotNull (ex.Message, "#M3c");
						Assert.IsNull (ex.InnerException, "#M3d");
					}
#endif
					Assert.IsFalse (enumerator.MoveNext (), "#M4");

					try {
						object current = enumerator.Current;
						Assert.Fail ("#N1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#N2");
						Assert.IsNotNull (ex.Message, "#N3");
						Assert.IsNull (ex.InnerException, "#N4");
					}

					Assert.IsFalse (enumerator.MoveNext (), "#O1");
					enumerator.Reset ();
					Assert.IsFalse (enumerator.MoveNext (), "#O2");
				}
			} finally {
				if (EventLog.Exists ("monologtemp"))
					EventLog.Delete ("monologtemp");
			}
		}
 /// <include file='doc\EntryWrittenEventArgs.uex' path='docs/doc[@for="EntryWrittenEventArgs.EntryWrittenEventArgs1"]/*' />
 /// <devdoc>
 ///    <para>
 ///       Initializes a new instance of the <see cref='System.Diagnostics.EntryWrittenEventArgs'/> class with the
 ///       specified event log entry.
 ///    </para>
 /// </devdoc>
 public EntryWrittenEventArgs(EventLogEntry entry)
 {
     this.entry = entry;
 }
Esempio n. 26
0
 private void MakeErrorMessage(EventLogEntry entry, string log)
 {
     // Takes an entry and then formats and makes it look nice for the email
     errors.Append("Event Type: \t" + entry.EntryType + "\nEvent Log: \t\t" + log + "\nEvent Source:\t" + entry.Source
                 + "\nEvent Category:\t" + entry.Category + "\nEvent ID: \t\t" + entry.InstanceId + "\nDate: \t\t"
                 + entry.TimeGenerated + "\nUser: \t\t" + entry.UserName + "\nServer: \t\t" + server
                 + "\nDescription:\n" + entry.Message + "\n\n");
 }
	// Determine if two event log entries are equal.
	public bool Equals(EventLogEntry otherEntry)
			{
				if(otherEntry == null)
				{
					return false;
				}
				if(category != otherEntry.category)
				{
					return false;
				}
				if(categoryNumber != otherEntry.categoryNumber)
				{
					return false;
				}
				if(data == null)
				{
					if(otherEntry.data != null)
					{
						return false;
					}
				}
				else if(otherEntry.data == null)
				{
					return false;
				}
				else if(otherEntry.data.Length != data.Length)
				{
					return false;
				}
				else
				{
					int dposn;
					for(dposn = 0; dposn < data.Length; ++dposn)
					{
						if(data[dposn] != otherEntry.data[dposn])
						{
							return false;
						}
					}
				}
				if(entryType != otherEntry.entryType)
				{
					return false;
				}
				if(eventID != otherEntry.eventID)
				{
					return false;
				}
				if(index != otherEntry.index)
				{
					return false;
				}
				if(machineName != otherEntry.machineName)
				{
					return false;
				}
				if(message != otherEntry.message)
				{
					return false;
				}
				if(replacementStrings == null)
				{
					if(otherEntry.replacementStrings != null)
					{
						return false;
					}
				}
				else if(otherEntry.replacementStrings == null)
				{
					return false;
				}
				else if(otherEntry.replacementStrings.Length
							!= replacementStrings.Length)
				{
					return false;
				}
				else
				{
					int rposn;
					for(rposn = 0; rposn < replacementStrings.Length; ++rposn)
					{
						if(replacementStrings[rposn] !=
						   otherEntry.replacementStrings[rposn])
						{
							return false;
						}
					}
				}
				if(source != otherEntry.source)
				{
					return false;
				}
				if(timeGenerated != otherEntry.timeGenerated)
				{
					return false;
				}
				if(timeWritten != otherEntry.timeWritten)
				{
					return false;
				}
				if(userName != otherEntry.userName)
				{
					return false;
				}
				return true;
			}
Esempio n. 28
0
 public EventLogEntry(System.Diagnostics.EventLogEntry entry)
 {
     entry.ThrowIfNull(nameof(entry));
     Entry = entry;
 }
 public bool MoveNext()
 {
     num++;
     cachedEntry = entries.GetEntryAtNoThrow(num);
     return(cachedEntry != null);
 }
Esempio n. 30
0
 public EntryWrittenEventArgs(EventLogEntry entry)
 {
     throw new NotImplementedException();
 }
Esempio n. 31
0
 // Parse the byte[] as an event log record
 private unsafe EventLogEntry ReadEntry(byte[] buff)
 {
     EventLogEntry entry;
     try
     {
         fixed (byte* ptr = buff)
         {
             entry = new EventLogEntry();
             entry.rec = new EventLogRecord(buff);
             // Read SourceName
             uint start = (uint)sizeof(EventLogRecord);
             // Get the Source Name
             entry.SourceName = ReadString(ptr, ref start);
             // Get the Computer Name
             entry.Computername = ReadString(ptr, ref start);
             // Get the User Name
             byte[] uname = new byte[entry.rec.UserSidLength];
             Copy(ptr, ref start, uname, uname.Length);
             entry.UserSid = GetUserInfo(uname);
             // read the strings
             entry.Strings = ReadString(ptr, ref start, (int)(entry.rec.DataOffset - entry.rec.StringOffset) / 2);
             // read the data
             entry.Data = new byte[(int)entry.rec.DataLength];
             Copy(ptr, ref start, entry.Data, entry.Data.Length);
             //
         }
     }
     catch (Exception)
     {
         entry = null;
     }
     return entry;
 }
Esempio n. 32
0
		public bool Equals (EventLogEntry otherEntry)
		{
			if (otherEntry == this)
				return true;

			return (
				(otherEntry.Category == category) &&
				(otherEntry.CategoryNumber == categoryNumber) &&
				(otherEntry.Data.Equals (data)) &&
				(otherEntry.EntryType == entryType) &&
				(otherEntry.InstanceId == instanceId) &&
				(otherEntry.Index == index) &&
				(otherEntry.MachineName == machineName) &&
				(otherEntry.Message == message) &&
				(otherEntry.ReplacementStrings.Equals (replacementStrings)) &&
				(otherEntry.Source == source) &&
				(otherEntry.TimeGenerated.Equals (timeGenerated)) &&
				(otherEntry.TimeWritten.Equals (timeWritten)) &&
				(otherEntry.UserName == userName)
				);
		}
Esempio n. 33
0
 // Add an entry to this collection.
 internal void Add(EventLogEntry entry)
 {
     list.Add(entry);
 }
Esempio n. 34
0
 public bool MoveNext()
 {
     this.num++;
     this.cachedEntry = this.entries.GetEntryAtNoThrow(this.num);
     return(this.cachedEntry != null);
 }
		public void Entries_Log_Empty ()
		{
			if (EventLogImplType == NULL_IMPL)
				// test cannot pass with NULL implementation
				return;

			if (EventLog.SourceExists ("monotempsource", "."))
				Assert.Ignore ("Event log source 'monotempsource' should not exist.");

			if (EventLog.SourceExists ("monoothersource", "."))
				Assert.Ignore ("Event log source 'monoothersource' should not exist.");

			if (EventLog.Exists ("monologtemp", "."))
				Assert.Ignore ("Event log 'monologtemp' should not exist.");

			EventLog.CreateEventSource ("monotempsource", "monologtemp", ".");
			try {
				using (EventLog eventLog = new EventLog (string.Empty, ".")) {
					Assert.IsNotNull (eventLog.Entries, "#A1");

					try {
						Assert.Fail ("#B1: " + eventLog.Entries.Count);
					} catch (ArgumentException ex) {
						// Log property value has not been specified
						Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
						Assert.IsNotNull (ex.Message, "#B3");
						Assert.IsNull (ex.InnerException, "#B4");
						Assert.IsNull (ex.ParamName, "#B5");
					}

					IEnumerator enumerator = eventLog.Entries.GetEnumerator ();
					Assert.IsNotNull (enumerator, "#C");

					try {
						object current = enumerator.Current;
						Assert.Fail ("#D1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");
						Assert.IsNotNull (ex.Message, "#D3");
						Assert.IsNull (ex.InnerException, "#D4");
					}

					try {
						enumerator.MoveNext ();
						Assert.Fail ("#E1");
					} catch (ArgumentException ex) {
						// Log property value has not been specified
						Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#E2");
						Assert.IsNotNull (ex.Message, "#E3");
						Assert.IsNull (ex.InnerException, "#E4");
						Assert.IsNull (ex.ParamName, "#E5");
					}

					try {
						EventLogEntry [] entries = new EventLogEntry [0];
						eventLog.Entries.CopyTo (entries, 0);
						Assert.Fail ("#F1");
					} catch (ArgumentException ex) {
						// Log property value has not been specified
						Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#F2");
						Assert.IsNotNull (ex.Message, "#F3");
						Assert.IsNull (ex.InnerException, "#F4");
						Assert.IsNull (ex.ParamName, "#F5");
					}

					enumerator.Reset ();

					// set non-existing source
					eventLog.Source = "monoothersource";

					try {
						Assert.Fail ("#G1: " + eventLog.Entries.Count);
					} catch (ArgumentException ex) {
						// Log property value has not been specified
						Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#G2");
						Assert.IsNotNull (ex.Message, "#G3");
						Assert.IsNull (ex.InnerException, "#G4");
						Assert.IsNull (ex.ParamName, "#G5");
					}

					enumerator = eventLog.Entries.GetEnumerator ();
					Assert.IsNotNull (enumerator, "#H");

					try {
						object current = enumerator.Current;
						Assert.Fail ("#I1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#I2");
						Assert.IsNotNull (ex.Message, "#I3");
						Assert.IsNull (ex.InnerException, "#I4");
					}

					try {
						enumerator.MoveNext ();
						Assert.Fail ("#J1");
					} catch (ArgumentException ex) {
						// Log property value has not been specified
						Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#J2");
						Assert.IsNotNull (ex.Message, "#J3");
						Assert.IsNull (ex.InnerException, "#J4");
						Assert.IsNull (ex.ParamName, "#J5");
					}

					try {
						EventLogEntry [] entries = new EventLogEntry [0];
						eventLog.Entries.CopyTo (entries, 0);
						Assert.Fail ("#K1");
					} catch (ArgumentException ex) {
						// Log property value has not been specified
						Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#K2");
						Assert.IsNotNull (ex.Message, "#K3");
						Assert.IsNull (ex.InnerException, "#K4");
						Assert.IsNull (ex.ParamName, "#K5");
					}

					enumerator.Reset ();

					// set existing source
					eventLog.Source = "monotempsource";

					Assert.AreEqual (0, eventLog.Entries.Count, "#L1");
					enumerator = eventLog.Entries.GetEnumerator ();
					Assert.IsNotNull (enumerator, "#L2");

					try {
						object current = enumerator.Current;
						Assert.Fail ("#M1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#M2");
						Assert.IsNotNull (ex.Message, "#M3");
						Assert.IsNull (ex.InnerException, "#M4");
					}

					Assert.IsFalse (enumerator.MoveNext ());

					try {
						object current = enumerator.Current;
						Assert.Fail ("#N1: " + current);
					} catch (InvalidOperationException ex) {
						// No current EventLog entry available, cursor is located
						// before the first or after the last element of the
						// enumeration
						Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#N2");
						Assert.IsNotNull (ex.Message, "#N3");
						Assert.IsNull (ex.InnerException, "#N4");
					}

					enumerator.Reset ();
				}
			} finally {
				if (EventLog.Exists ("monologtemp"))
					EventLog.Delete ("monologtemp");
			}
		}
Esempio n. 36
0
 public Log(EventLogEntry eventLog)
 {
     this.GetInfo(eventLog);
 }
Esempio n. 37
0
 public bool Equals(System.Diagnostics.EventLogEntry otherEntry)
 {
     throw null;
 }
Esempio n. 38
0
 public void GetInfo(EventLogEntry eventLog)
 {
     try
     {
         this.Category = eventLog.Category;
         this.DateTime = eventLog.TimeGenerated.ToShortDateString() + " " + eventLog.TimeGenerated.ToLongTimeString();
         this.EventID = eventLog.InstanceId;
         this.Level = eventLog.EntryType.ToString();
         this.Message = eventLog.Message;
         this.Source = eventLog.Source;
     }
     catch (Exception e)
     {
         ErrorDialogue errorReporter = new ErrorDialogue(e);
     }
 }
Esempio n. 39
0
 /// <summary>
 /// Send event to syslog server using UDP protocol
 /// </summary>
 /// <param name="evebntLogName">EventLog name</param>
 /// <param name="eventLogEntry">Event to transfert to syslog server</param>
 /// <param name="filter">Filter with Syslog facility and level</param>
 /// <param name="debug">Debug object</param>
 public void SendEvent(String eventLogName, EventLogEntry eventLogEntry, Filter filter)
 {
     String message = PrepareSyslogEvent(eventLogName, eventLogEntry);
     if (_Protocol.CompareTo("udp") == 0)
     {
         SendEventByUDP(message, eventLogName, eventLogEntry, filter);
     }
     else if (_Protocol.CompareTo("tcp") == 0)
     {
         SendEventByTCP(message, eventLogName, eventLogEntry, filter);
     }
 }
        /// <summary>
        /// Checks to see if the string is present on the first line of the file.
        /// </summary>
        /// <param name="written">The string to check for.</param>
        private void CheckForString(string written)
        {
            EventLog ea=new EventLog(LOG_NAME, ".", LOG_NAME);

            EventLogEntry[] entries=new EventLogEntry[ea.Entries.Count];
            ea.Entries.CopyTo(entries,0);

            Assertion.AssertEquals("String not written to log.", written, entries[0].Message);
        }
Esempio n. 41
0
        /// <summary>
        /// Send event to syslog server using TCP protocol
        /// </summary>
        /// <param name="message">Message to send</param>
        /// <param name="evebntLogName">EventLog name</param>
        /// <param name="eventLogEntry">Event to transfert to syslog server</param>
        /// <param name="filter">Filter with Syslog facility and level</param>
        /// <param name="debug">Debug object</param>
        /// <returns>True if any error appear</returns>
        private Boolean SendEventByTCP(String message, String eventLogName, EventLogEntry eventLogEntry, Filter filter)
        {
            IPAddress[] ServersAddress;

            // Create syslog tag and remove syslog message accents
            Int32 pri = (int)Facility[filter.SyslogFacility.ToLower()] * 8 + (int)Level[filter.SyslogLevel.ToLower()];

            string month = eventLogEntry.TimeWritten.ToString("MMM", DateTimeFormatInfo.InvariantInfo);
            string day = eventLogEntry.TimeWritten.ToString("dd", DateTimeFormatInfo.InvariantInfo);
            if (Convert.ToInt32(day) < 10)
            {
                day = " " + Convert.ToInt32(day);
            }
            string date = month + " " + day + " " + eventLogEntry.TimeWritten.ToString("HH:mm:ss", DateTimeFormatInfo.InvariantInfo);

            String body = "<" + pri + ">" + date + " " + eventLogEntry.MachineName + " " + message + "\n";

            // Convert final message in bytes
            byte[] rawMsg = Encoding.Default.GetBytes(body);

            try
            {
                ServersAddress = Dns.GetHostAddresses(this._ServerAddress);

                //String temp = ServersAddress.GetValue(0).ToString();

                for (int i = 0; i < ServersAddress.Length; i++)
                {
                    //Try to send message by TCP
                    TcpClient tcp;
                    NetworkStream flux;
                    try
                    {
                        tcp = new TcpClient(ServersAddress.GetValue(i).ToString(), this._ServerPort);
                        if (tcp.Connected)
                        {
                            flux = tcp.GetStream();
                            if (flux.CanWrite)
                            {
                                flux.Write(rawMsg, 0, rawMsg.Length);

                                this._Debug.Write("Syslog Server", "Event send to: " + ServersAddress.GetValue(i).ToString() + " with message: " + message, DateTime.Now, 2);
                                flux.Close();
                                tcp.Close();
                                tcp = null;
                            }
                            else
                            {
                                SetMessageInBuffer(body);
                            }
                        }
                        else
                        {
                            SetMessageInBuffer(body);
                        }
                    }
                    catch (SocketException e)
                    {
                        SetMessageInBuffer(body);
                    }
                    catch (ArgumentNullException e)
                    {
                        this._Debug.Write("Syslog Server", "ArgumentNullException caught because: " + e.Message, DateTime.Now, 1);
                        return false;
                    }
                    catch (ArgumentOutOfRangeException e)
                    {
                        this._Debug.Write("Syslog Server", "ArgumentOutOfRangeException caught because: " + e.Message, DateTime.Now, 1);
                        return false;
                    }
                    catch (ObjectDisposedException e)
                    {
                        this._Debug.Write("Syslog Server", "ObjectDisposedException caught because: " + e.Message, DateTime.Now, 1);
                        return false;
                    }
                    catch (System.IO.IOException e)
                    {
                        SetMessageInBuffer(body);
                    }
                }
            }
            catch (SocketException e)
            {
                this._Debug.Write("Syslog Server", "SocketException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (ArgumentNullException e)
            {
                this._Debug.Write("Syslog Server", "ArgumentNullException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (ArgumentOutOfRangeException e)
            {
                this._Debug.Write("Syslog Server", "ArgumentOutOfRangeException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (ObjectDisposedException e)
            {
                this._Debug.Write("Syslog Server", "ObjectDisposedException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }
            catch (InvalidOperationException e)
            {
                this._Debug.Write("Syslog Server", "InvalidOperationException caught because: " + e.Message, DateTime.Now, 1);
                return false;
            }

            return true;
        }
        /// <summary>
        /// Checks to see if the string is present on the first line of the file.
        /// </summary>
        /// <param name="written">The string to check for.</param>
        private void CheckStringNotExist(string written)
        {
            if (!EventLog.Exists(LOG_NAME))
                return;

            EventLog ea=new EventLog(LOG_NAME, ".", LOG_NAME);
            if (ea.Entries.Count == 0)
                return;

            EventLogEntry[] entries=new EventLogEntry[ea.Entries.Count];
            ea.Entries.CopyTo(entries, 0);

            Assertion.Assert("String written to log.", entries[0].Message.IndexOf(written) == -1);
        }
Esempio n. 43
0
 public bool Equals(EventLogEntry otherEntry)
 {
     throw new NotImplementedException();
 }
 private static bool EventIsFromLogger(EventLogEntry entry, DistributorEventLogger logger)
 {
     return entry.Source == logger.EventSource;
 }
 /// <devdoc>
 ///    <para>
 ///       Advances the enumerator to the next entry in the event log.
 ///    </para>
 /// </devdoc>
 public bool MoveNext() {
     num++;
     cachedEntry = entries.GetEntryAtNoThrow(num);
     
     return cachedEntry != null;
 }            
        private EventLogEntry GetEntryWithOldest(int index) {
            EventLogEntry entry = null;
            int entryPos = GetCachedEntryPos(index);
            if (entryPos >= 0) {
                entry = new EventLogEntry(cache, entryPos, this);
                return entry;
            }

            string currentMachineName = this.machineName;

            // if we haven't seen the one after this, we were probably going
            // forwards.
            int flags = 0;
            if (GetCachedEntryPos(index+1) < 0) {
                flags = NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ;
                boolFlags[Flag_forwards] = true;
            }
            else {
                flags = NativeMethods.BACKWARDS_READ | NativeMethods.SEEK_READ;
                boolFlags[Flag_forwards] = false;
            }

            cache = new byte[BUF_SIZE];
            int bytesRead;
            int minBytesNeeded;
            bool success = UnsafeNativeMethods.ReadEventLog(readHandle, flags, index,
                                                  cache, cache.Length, out bytesRead, out minBytesNeeded);
            if (!success) {
                int error = Marshal.GetLastWin32Error();
                // NOTE, [....]: ERROR_PROC_NOT_FOUND used to get returned, but I think that
                // was because I was calling GetLastError directly instead of GetLastWin32Error.
                // Making the buffer bigger and trying again seemed to work. I've removed the check
                // for ERROR_PROC_NOT_FOUND because I don't think it's necessary any more, but
                // I can't prove it...
                Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Error from ReadEventLog is " + error.ToString(CultureInfo.InvariantCulture));
                if (error == NativeMethods.ERROR_INSUFFICIENT_BUFFER || error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) {
                    if (error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) {
                        // Reset() sets the cache null.  But since we're going to call ReadEventLog right after this,
                        // we need the cache to be something valid.  We'll reuse the old byte array rather
                        // than creating a new one.
                        byte[] tempcache = cache;
                        Reset(currentMachineName);
                        cache = tempcache;
                    } else {
                        // try again with a bigger buffer.
                        if (minBytesNeeded > cache.Length) {
                            cache = new byte[minBytesNeeded];
                        }
                    }
                    success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ, index,
                                                     cache, cache.Length, out bytesRead, out minBytesNeeded);
                }

                if (!success) {
                    throw new InvalidOperationException(SR.GetString(SR.CantReadLogEntryAt, index.ToString(CultureInfo.CurrentCulture)), SharedUtils.CreateSafeWin32Exception());
                }
            }
            bytesCached = bytesRead;
            firstCachedEntry = index;
            lastSeenEntry = index;
            lastSeenPos = 0;
            return new EventLogEntry(cache, 0, this);
        }
Esempio n. 47
0
 //
 // Summary:
 //     Performs a comparison between two event log entries.
 //
 // Parameters:
 //   otherEntry:
 //     The System.Diagnostics.EventLogEntry to compare.
 //
 // Returns:
 //     true if the System.Diagnostics.EventLogEntry objects are identical; otherwise,
 //     false.
 public bool Equals(EventLogEntry otherEntry)
 {
     //TODO: ALACHISOFT
     throw new NotImplementedException();
 }
        internal EventLogEntry[] GetAllEntries() {
            // we could just call getEntryAt() on all the entries, but it'll be faster
            // if we grab multiple entries at once.
            string currentMachineName = this.machineName;

            if (!IsOpenForRead)
                OpenForRead(currentMachineName);

            EventLogEntry[] entries = new EventLogEntry[EntryCount];
            int idx = 0;
            int oldestEntry = OldestEntryNumber;

            int bytesRead;
            int minBytesNeeded;
            int error = 0;
            while (idx < entries.Length) {
                byte[] buf = new byte[BUF_SIZE];
                bool success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ,
                                                      oldestEntry+idx, buf, buf.Length, out bytesRead, out minBytesNeeded);
                if (!success) {
                    error = Marshal.GetLastWin32Error();
                    // NOTE, [....]: ERROR_PROC_NOT_FOUND used to get returned, but I think that
                    // was because I was calling GetLastError directly instead of GetLastWin32Error.
                    // Making the buffer bigger and trying again seemed to work. I've removed the check
                    // for ERROR_PROC_NOT_FOUND because I don't think it's necessary any more, but
                    // I can't prove it...
                    Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Error from ReadEventLog is " + error.ToString(CultureInfo.InvariantCulture));
#if !RETRY_ON_ALL_ERRORS
                    if (error == NativeMethods.ERROR_INSUFFICIENT_BUFFER || error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) {
#endif
                        if (error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) {
                            // somewhere along the way the event log file changed - probably it
                            // got cleared while we were looping here. Reset the handle and
                            // try again.
                            Reset(currentMachineName);
                        }
                        // try again with a bigger buffer if necessary
                        else if (minBytesNeeded > buf.Length) {
                            Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Increasing buffer size from " + buf.Length.ToString(CultureInfo.InvariantCulture) + " to " + minBytesNeeded.ToString(CultureInfo.InvariantCulture) + " bytes");
                            buf = new byte[minBytesNeeded];
                        }
                        success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ,
                                                         oldestEntry+idx, buf, buf.Length, out bytesRead, out minBytesNeeded);
                        if (!success)
                            // we'll just stop right here.
                            break;
#if !RETRY_ON_ALL_ERRORS
                    }
                    else {
                        break;
                    }
#endif
                    error = 0;
                }
                entries[idx] = new EventLogEntry(buf, 0, this);
                int sum = IntFrom(buf, 0);
                idx++;
                while (sum < bytesRead && idx < entries.Length) {
                    entries[idx] = new EventLogEntry(buf, sum, this);
                    sum += IntFrom(buf, sum);
                    idx++;
                }
            }
            if (idx != entries.Length) {
                if (error != 0)
                    throw new InvalidOperationException(SR.GetString(SR.CantRetrieveEntries), SharedUtils.CreateSafeWin32Exception(error));
                else
                    throw new InvalidOperationException(SR.GetString(SR.CantRetrieveEntries));
            }
            return entries;
        }
Esempio n. 49
0
        private SystemLogEntry CreateLogEntry(EventLogEntry logEntry, bool includeMessage)
        {
            SystemLogEntry entry = new SystemLogEntry();
            switch (logEntry.EntryType)
            {
                case EventLogEntryType.Error: entry.EntryType = SystemLogEntryType.Error; break;
                case EventLogEntryType.Warning: entry.EntryType = SystemLogEntryType.Warning; break;
                case EventLogEntryType.Information: entry.EntryType = SystemLogEntryType.Information; break;
                case EventLogEntryType.SuccessAudit: entry.EntryType = SystemLogEntryType.SuccessAudit; break;
                case EventLogEntryType.FailureAudit: entry.EntryType = SystemLogEntryType.FailureAudit; break;
            }

            entry.Created = logEntry.TimeGenerated;
            entry.Source = logEntry.Source;
            entry.Category = logEntry.Category;
            entry.EventID = logEntry.InstanceId;
            entry.UserName = logEntry.UserName;
            entry.MachineName = logEntry.MachineName;

            if (includeMessage)
                entry.Message = logEntry.Message;

            return entry;
        }
		public void Entries_Log_DoesNotExist ()
		{
			if (EventLogImplType == NULL_IMPL)
				// test cannot pass with NULL implementation
				return;

			if (EventLog.Exists ("monologtemp", "."))
				Assert.Ignore ("Event log 'monologtemp' should not exist.");

			using (EventLog eventLog = new EventLog ("monologtemp", ".")) {
				Assert.IsNotNull (eventLog.Entries, "#A1");

				try {
					Assert.Fail ("#B1: " + eventLog.Entries.Count);
				} catch (InvalidOperationException ex) {
					// The event log 'monologtemp' on computer '.' does not exist
					Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
					Assert.IsNotNull (ex.Message, "#B3");
					Assert.IsTrue (ex.Message.IndexOf ("'monologtemp'") != -1, "#B4");
					Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#B5");
					Assert.IsNull (ex.InnerException, "#B6");
				}
				Assert.IsFalse (EventLog.Exists ("monologtemp", "."), "#B7");

				IEnumerator enumerator = eventLog.Entries.GetEnumerator ();
				Assert.IsNotNull (enumerator, "#C");

				try {
					object current = enumerator.Current;
					Assert.Fail ("#D1: " + current);
				} catch (InvalidOperationException ex) {
					// No current EventLog entry available, cursor is located
					// before the first or after the last element of the
					// enumeration.
					Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");
					Assert.IsNotNull (ex.Message, "#D3");
					Assert.IsNull (ex.InnerException, "#D4");
				}

				try {
					enumerator.MoveNext ();
					Assert.Fail ("#E1");
				} catch (InvalidOperationException ex) {
					// The event log 'monologtemp' on computer '.' does not exist
					Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");
					Assert.IsNotNull (ex.Message, "#E3");
					Assert.IsTrue (ex.Message.IndexOf ("'monologtemp'") != -1, "#E4");
					Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#E5");
					Assert.IsNull (ex.InnerException, "#E6");
				}

				try {
					EventLogEntry [] entries = new EventLogEntry [0];
					eventLog.Entries.CopyTo (entries, 0);
					Assert.Fail ("#F1");
				} catch (InvalidOperationException ex) {
					// The event log 'monologtemp' on computer '.' does not exist
					Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#F2");
					Assert.IsNotNull (ex.Message, "#F3");
					Assert.IsTrue (ex.Message.IndexOf ("'monologtemp'") != -1, "#F4");
					Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#F5");
					Assert.IsNull (ex.InnerException, "#F6");
				}

				enumerator.Reset ();
			}
		}
 public EntryWrittenEventArgs(EventLogEntry entry)
 {
 }
 public bool Equals(EventLogEntry otherEntry)
 {
     return(default(bool));
 }