Example #1
0
        public static RawEvents ToDto(this EventLogEntry entry, string logName)
        {
            return(new RawEvents
            {
                Events = new[]
                {
                    new RawEvent
                    {
                        Timestamp = entry.TimeGenerated,
                        Level = MapLogLevel(entry.EntryType),
                        MessageTemplate = entry.Message,
                        Properties = new Dictionary <string, object>
                        {
                            { "MachineName", entry.MachineName },
#pragma warning disable 618
                            { "EventId", entry.EventID },
#pragma warning restore 618
                            { "InstanceId", entry.InstanceId },
                            { "Source", entry.Source },
                            { "Category", entry.CategoryNumber },
                            { "EventLogName", logName }
                        }
                    },
                }
            });
        }
Example #2
0
        public static List <Tuple <string, EventLogEntry> > ReadLog(int numLastRecords)
        {
            List <Tuple <string, EventLogEntry> > result = new List <Tuple <string, EventLogEntry> >();

            int LastLogToShow = myLog.Entries.Count;

            if (LastLogToShow < 0)
            {
                MessageBox.Show("Лог Пустой");
            }
            else
            {
                int j = numLastRecords < LastLogToShow ? numLastRecords : LastLogToShow;
                for (int i = LastLogToShow - 1; i >= LastLogToShow - j; i--)
                {
                    EventLogEntry currentEntry = myLog.Entries[i];
                    result.Add(new Tuple <string, EventLogEntry>(currentEntry.Message, currentEntry));
                }
            }
            // Event ID   currentEntry.InstanceId
            // Entry Type
            myLog.Close();

            return(result);
        }
Example #3
0
        public void TraceEventTest(TraceEventType eventType, EventLogEntryType expectedType, int id, int expectedId)
        {
            string log    = "TraceEvent";
            string source = "Source" + nameof(TraceEventTest);

            try
            {
                EventLog.CreateEventSource(source, log);
                using (var listener = new EventLogTraceListener(source))
                {
                    string message = "One simple message to trace";
                    listener.TraceEvent(null, source, eventType, id, message);
                    EventLogEntry eventLogEntry = ValidateLastEntryMessage(listener, message, source);

                    if (eventLogEntry != null)
                    {
                        Assert.Equal(expectedType, eventLogEntry.EntryType);
                        Assert.Equal(expectedId, eventLogEntry.InstanceId);
                    }
                }
            }
            finally
            {
                EventLog.DeleteEventSource(source);
                Helpers.RetrySilently(() => EventLog.Delete(log));
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="event"></param>
 /// <param name="expires">消息过期时间</param>
 public static void WithNoRetry(this EventLogEntry @event)
 {
     @event.Headers["x-first-death-queue"] = $"{@event.EventTypeName}@Failed";   //死信队列名称
     @event.Headers.Remove("x-message-ttl");
     @event.Headers["x-dead-letter-exchange"]    = @event.Headers["x-exchange"]; //过期消息转向路由
     @event.Headers["x-dead-letter-routing-key"] = @event.EventTypeName;         //过期消息转向路由相匹配routingkey
 }
        public void EventLogEntryWrittenWhenLoggingConfigurationIsCorrupt()
        {
            //corrupt the logging configuration
            System.Configuration.Configuration config      = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            LoggingSettings rwLoggingSettings              = (LoggingSettings)config.GetSection(LoggingSettings.SectionName);
            string          originalFirstTraceListenerName = rwLoggingSettings.TraceListeners.Get(0).Name;

            rwLoggingSettings.TraceSources.Get(0).TraceListeners.Get(0).Name = "wrongName";
            config.Save(ConfigurationSaveMode.Full);
            ConfigurationManager.RefreshSection(LoggingSettings.SectionName);

            try
            {
                Logger.Write("SomeMessage");
            }
            catch (ConfigurationErrorsException)
            {
                using (EventLog applicationLog = new EventLog("Application"))
                {
                    EventLogEntry lastEntry = applicationLog.Entries[applicationLog.Entries.Count - 1];

                    Assert.AreEqual("Enterprise Library Logging", lastEntry.Source);
                    Assert.IsTrue(lastEntry.Message.Contains("wrongName"));
                }
            }
            finally
            {
                //restore the logging configuration
                rwLoggingSettings.TraceSources.Get(0).TraceListeners.Get(0).Name = originalFirstTraceListenerName;
                config.Save(ConfigurationSaveMode.Full);
                ConfigurationManager.RefreshSection(LoggingSettings.SectionName);
            }
        }
        static void Main(string[] args)
        {
            string logType = "System";

            //use this if your are are running the app on the server
            //EventLog ev = new EventLog(logType, System.Environment.MachineName);
            //use this if you are running the app remotely
            EventLog ev = new EventLog(logType, "[youservername]");

            if (ev.Entries.Count <= 0)
            {
                Console.WriteLine("No Event Logs in the Log :" + logType);
            }

            // Loop through the event log records.
            for (int i = 0; i < ev.Entries.Count; i++)
            {
                EventLogEntry CurrentEntry = ev.Entries[i];

                //use DateTime type to compare on CurrentEntry.TimeGenerated

                if (CurrentEntry.Source.ToUpper() == "USER32")
                {
                    Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
                    Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
                    Console.WriteLine("Message :  " + CurrentEntry.Message + "\n");
                }
            }
            ev.Close();
        }
Example #7
0
        private string getEventString(EventLogEntry entry)
        {
            string loggingEvent;

            if (_appendFieldNames)
            {
                loggingEvent  = "Message: " + entry.Message;
                loggingEvent += "\tCategory: " + entry.Category;
                loggingEvent += "\tEntryType: " + entry.EntryType.ToString();
                loggingEvent += "\tEventID: " + entry.InstanceId.ToString();
                loggingEvent += "\tSource: " + entry.Source;
                loggingEvent += "\tTimeWritten: " + entry.TimeWritten.ToLongTimeString();
                loggingEvent += "\tUserName: "******"\t" + entry.Category;
                loggingEvent += "\t" + entry.EntryType.ToString();
                loggingEvent += "\t" + entry.InstanceId.ToString();
                loggingEvent += "\t" + entry.Source;
                loggingEvent += "\t" + entry.TimeWritten.ToLongTimeString();
                loggingEvent += "\t" + entry.UserName;
            }

            return(loggingEvent);
        }
Example #8
0
        private void button2_Click(object sender, EventArgs e)
        {
            //logType может быть Application, Security, System или собственный журнал событий
            string logType = "MyNewLog";

            EventLog ev            = new EventLog(logType, System.Environment.MachineName);
            int      LastLogToShow = ev.Entries.Count;

            if (LastLogToShow <= 0)
            {
                MessageBox.Show("Нет записей в журнале событий: " + logType);
            }
            else
            {
                // Read the last 2 records in the specified log.
                int i;
                for (i = ev.Entries.Count - 1; i >= LastLogToShow - 2; i--)
                {
                    EventLogEntry CurrentEntry = ev.Entries[i];
                    listBox1.Items.Add("Event ID : " + CurrentEntry.InstanceId);
                    listBox1.Items.Add("Entry Type : " + CurrentEntry.EntryType.ToString());
                    listBox1.Items.Add("Message :  " + CurrentEntry.Message);
                }
                ev.Close();
            }
        }
Example #9
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);
        }
        static void Main()
        {
            if (!EventLog.SourceExists("MySource"))
            {
                EventLog.CreateEventSource("MySource", "MyNewLog");
                Console.WriteLine("CreatedEventSource");
                Console.WriteLine("Please restart application");
                Console.ReadKey();
                return;
            }
            EventLog myLog = new EventLog();

            myLog.Source = "MySource";
            myLog.WriteEntry("Log event!");

            EventLog log = new EventLog("MyNewLog");

            Console.WriteLine("Total entries: " + log.Entries.Count);
            EventLogEntry last = log.Entries[log.Entries.Count - 1];

            Console.WriteLine("Index: " + last.Index);
            Console.WriteLine("Source: " + last.Source);
            Console.WriteLine("Type: " + last.EntryType);
            Console.WriteLine("Time: " + last.TimeWritten);
            Console.WriteLine("Message: " + last.Message);
            Console.ReadKey();
        }
Example #11
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?");
            }
        }
Example #12
0
        // Send Eventlog
        private long sendEventlogFromIndex(long startIndex)
        {
            long lastIndex  = 0;
            bool readActive = false; // Activated when last index found

            try
            {
                // Send entries from startPos
                int i;
                for (i = 0; i < ev.Entries.Count; i++)
                {
                    if (readActive)
                    {
                        EventLogEntry CurrentEntry = ev.Entries[i];
                        lastIndex = CurrentEntry.Index;
                        // print("Index: "+CurrentEntry.Index.ToString());
                        verifiedSend(CurrentEntry.TimeGenerated + "\t" + CurrentEntry.InstanceId + "\t" + CurrentEntry.Source + "\t" + CurrentEntry.Message);
                    }
                    if (ev.Entries[i].Index == startIndex && !readActive)
                    {
                        readActive = true;
                    }
                }
                eventlogPos = i;
            }
            catch (Exception ex)
            {
                showErrorAndExit("Eventlog with name " + eventlogType + " not found or not accessible. " + ex.ToString());
            }

            return(lastIndex);
        }
Example #13
0
 public XEv(EventLogEntry ent)
 {
     this.id      = ((int)ent.InstanceId) & 0x3fffffff;
     this.dt      = ent.TimeGenerated;
     this.al      = ent.ReplacementStrings;
     this.message = ent.Message;
 }
Example #14
0
 private EventLogEntry GetEventLogEntryFiltered(int i)   //get linkNode from sytem (with filtering is enabled)
 {
     if (i >= 0 || i < eventlog.Entries.Count)
     {
         EventLogEntry entry = eventlog.Entries[i];
         if (rdoAll.Checked)
         {
             return(entry);
         }
         else //help
         {
             if (entry.Source.Length > 1 && entry.Source[0] == 'H' || entry.Source[0] == 'h')   //All help event start with 'H'
             {
                 if (HV2Source.Contains(entry.Source.ToUpper()))
                 {
                     return(entry);
                 }
                 else if (cbxIncludeHV1.Checked && HV1Source.Contains(entry.Source.ToUpper()))
                 {
                     return(entry);
                 }
             }
         }
     }
     return(null);
 }
Example #15
0
        public async Task <string> Test1()
        {
            var item1 = new EventLogEntry("TestEventHandler", new Events.TestEvent()
            {
                EventType = "Test1",
            });
            var item2 = new EventLogEntry("TestEventHandler", 0, new Events.TestEvent()
            {
                EventType = "Test1",
            });

            item2.EventId = 1;

            var item3 = new EventLogEntry("TestEventHandler", 1, new
            {
                EventType = "Test2"
            });


            var events = new List <EventLogEntry>()
            {
                item1, item2, item3
            };

            var ret = await eventBus.PublishAsync(events);

            return(ret.ToString());
        }
Example #16
0
        public void ConfigurationErrorsOnUpdateKeepExistingSetupAndLogError()
        {
            LogWriter logWriter = new LogWriterFactory(configurationSource).Create();

            Assert.IsNotNull(logWriter);

            {
                Assert.AreEqual(2, logWriter.TraceSources.Count);
                IEnumerator <LogSource> sources = logWriter.TraceSources.Values.GetEnumerator();
                sources.MoveNext();
                Assert.AreEqual("blocking", sources.Current.Name);
            }

            settings.TraceSources.Get(0).Name = "new source";
            settings.TraceSources.Get(0).TraceListeners.Get(0).Name = "invalid listener";

            using (EventLog eventLog = new EventLog("Application", ".", "Enterprise Library Logging"))
            {
                int    previousEventCount = eventLog.Entries.Count;
                Thread notificationThread = new Thread(FireConfigurationSectionChangedNotification);
                notificationThread.Start();
                notificationThread.Join(1000);

                Assert.IsTrue(eventLog.Entries.Count > 0);
                EventLogEntry lastEntry = eventLog.Entries[eventLog.Entries.Count - 1];
                Assert.AreEqual("Enterprise Library Logging", lastEntry.Source);
            }

            {
                Assert.AreEqual(2, logWriter.TraceSources.Count);
                IEnumerator <LogSource> sources = logWriter.TraceSources.Values.GetEnumerator();
                sources.MoveNext();
                Assert.AreEqual("blocking", sources.Current.Name);
            }
        }
        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);
        }
Example #18
0
        //---------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Determines whether [is watcher set] [the specified log name].
        /// </summary>
        /// <param name="logName">Name of the log.</param>
        /// <param name="logEntry">The log entry.</param>
        /// <returns>
        ///     <c>true</c> if [is watcher set] [the specified log name]; otherwise, <c>false</c>.
        /// </returns>
        private bool AddEvent(string logName, EventLogEntry logEntry)
        {
            int count = 0;

            count = (from crashInfo in configManager.SystemAnalyzerInfo.ListCrashReportInfo
                     where crashInfo.LogName == logName
                     select crashInfo).ToList <PMAEventReportInfo>().Count;

            if (count > 0)
            {
                count = (from crashInfo in configManager.SystemAnalyzerInfo.ListCrashReportInfo
                         where
                         crashInfo.EventType == logEntry.EntryType.ToString()
                         &&
                         (crashInfo.EventSource == logEntry.Source || crashInfo.EventSource == "*")
                         &&
                         (logEntry.Message.Contains(crashInfo.EventMessage) || crashInfo.EventMessage == "*")
                         select crashInfo).ToList <PMAEventReportInfo>().Count;
            }
            if (count > 0)
            {
                configManager.Logger.Debug(EnumMethod.START);
                configManager.Logger.Message("Event ID :" + logEntry.EventID + "\r\n" + "Logname : " + logName + " : " + logEntry.EntryType + " : " + logEntry.Source + " : \r\n" + logEntry.Message);
                listEntryLog.Add(logEntry);
                configManager.Logger.Debug(EnumMethod.END);
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public override LogEntry GetEntry(int idx)
        {
            EventLogEntry eventLogEntry = alphaEventLog.Entries[idx];
            LogEntry      logEntry      = new LogEntry(eventLogEntry.Message);

            return(logEntry);
        }
Example #20
0
        public void CheckingEntryInEquality()
        {
            string log    = "InEqualityTest";
            string source = "Source_" + nameof(CheckingEntryInEquality);

            try
            {
                EventLog.CreateEventSource(source, log);
                using (EventLog eventLog = new EventLog())
                {
                    eventLog.Source = source;
                    Helpers.Retry(() => eventLog.WriteEntry(message));
                    Helpers.Retry(() => eventLog.WriteEntry(message));
                    Helpers.WaitForEventLog(eventLog, 2);
                    EventLogEntry entry       = Helpers.Retry(() => eventLog.Entries[eventLog.Entries.Count - 1]);
                    EventLogEntry secondEntry = Helpers.Retry(() => eventLog.Entries[eventLog.Entries.Count - 2]);
                    Assert.False(entry.Equals(secondEntry));
                }
            }
            finally
            {
                EventLog.DeleteEventSource(source);
                Helpers.RetrySilently(() => EventLog.Delete(log));
            }
        }
 /// <summary>
 /// 设置延时策略
 /// </summary>
 /// <param name="event"></param>
 /// <param name="TTL">延时时间(秒)</param>
 /// <returns></returns>
 public static void WithWait(this EventLogEntry @event, int TTL)
 {
     @event.Headers["x-first-death-queue"]       = $"{@event.EventTypeName}@Delay#{TTL}"; //死信队列名称
     @event.Headers["x-message-ttl"]             = TTL * 1000;                            //当一个消息被推送在该队列的时候 可以存在的时间 单位为ms,应小于队列过期时间
     @event.Headers["x-dead-letter-exchange"]    = @event.Headers["x-exchange"];          //过期消息转向路由
     @event.Headers["x-dead-letter-routing-key"] = @event.EventTypeName;                  //过期消息转向路由相匹配routingkey
 }
Example #22
0
        public void CopyingEventLogEntryCollection()
        {
            string log    = "CopyCollection";
            string source = "Source_" + nameof(CopyingEventLogEntryCollection);

            try
            {
                EventLog.CreateEventSource(source, log);
                using (EventLog eventLog = new EventLog())
                {
                    eventLog.Source = source;
                    Helpers.Retry(() => eventLog.WriteEntry(message));
                    Helpers.Retry(() => eventLog.WriteEntry("Further Testing"));

                    EventLogEntryCollection entryCollection       = eventLog.Entries;
                    EventLogEntry[]         entryCollectionCopied = new EventLogEntry[entryCollection.Count];

                    Helpers.Retry(() => entryCollection.CopyTo(entryCollectionCopied, 0));
                    int i = 0;
                    foreach (EventLogEntry entry in entryCollection)
                    {
                        Assert.Equal(entry.Message, Helpers.Retry(() => entryCollectionCopied[i].Message));
                        i += 1;
                    }
                }
            }
            finally
            {
                EventLog.DeleteEventSource(source);
                Helpers.RetrySilently(() => EventLog.Delete(log));
            }
        }
Example #23
0
        public void run()
        {
            //_form.UpdateUI_DataGridGrid(_form.events_grid, "clear", "", "", -1);
            //string eventLogName = "Application";
            //"Application"
            System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
            eventLog.Log = "Application";
            //eventLog.Log = eventLogName;
            int     step = 0;
            DataRow row  = dt.NewRow();

            //_form.my.file_put_contents(_form.my.pwd() + "\\log\\events.txt", _form.my.json_encode(eventLog.Entries));
            //_form.my.file_put_contents(_form.my.pwd() + "\\log\\events.txt", "");
            for (int i = eventLog.Entries.Count - 1; i >= 0; i--)
            {
                EventLogEntry log = eventLog.Entries[i];
                //Dictionary<string, string> d = new Dictionary<string, string>();
                //d["Index"] = log.Index.ToString();
                //d["Category"] = log.Category;
                //d["Message"] = log.Message;
                //d["DateTime"] = log.TimeGenerated.ToString("yyyy-MM-dd HH:mm:ss");
                //var twtzinfo = TimeZoneInfo.FindSystemTimeZoneById("Taipei Standard Time");
                string eventDateTime = log.TimeGenerated.ToString("yyyy-MM-dd HH:mm:ss");

                //_form.my.file_put_contents(_form.my.pwd() + "\\log\\events.txt", eventDateTime, true);
                //改成現在時間跟上一次回報的時間之間才傳
                if (Convert.ToInt64(_form.my.strtotime(eventDateTime)) < Convert.ToInt64(_form.my.time()) - Convert.ToInt64(_form.my.getSystemKey("LOOP_MINUTE")) * 60)
                {
                    continue;
                }

                /*
                 * _form.UpdateUI_DataGridGrid(_form.events_grid, "add", "", "", -1);
                 * int lastId = _form.events_grid.Rows.Count - 1;
                 * _form.UpdateUI_DataGridGrid(_form.events_grid, "set_cell", "eventsID", (lastId + 1).ToString(), lastId);
                 * _form.UpdateUI_DataGridGrid(_form.events_grid, "set_cell", "eventsIndex", log.Index.ToString(), lastId);
                 * _form.UpdateUI_DataGridGrid(_form.events_grid, "set_cell", "eventsCategory", log.Category, lastId);
                 * _form.UpdateUI_DataGridGrid(_form.events_grid, "set_cell", "eventsMessage", log.Message, lastId);
                 * _form.UpdateUI_DataGridGrid(_form.events_grid, "set_cell", "eventsDateTime", eventDateTime, lastId);
                 */

                row                   = dt.NewRow();
                row["eventsID"]       = ++step;
                row["eventsIndex"]    = log.Index.ToString();
                row["eventsCategory"] = log.Category;
                row["eventsMessage"]  = log.Message;
                row["eventsDateTime"] = eventDateTime;
                dt.Rows.Add(row);

                //my.echo(log.Message + "\n");
                //step++;
                //if (step >= 200)
                //{
                //    break;
                //}
            }
            _form.updateDGVUI(_form.events_grid, dt);
            _form.setStatusBar("就緒", 0);
            is_running = false;
        }
Example #24
0
        public void CheckingEntryEqualityAndIndex()
        {
            string log    = "IndexTest";
            string source = "Source_" + nameof(CheckingEntryEqualityAndIndex);

            try
            {
                EventLog.CreateEventSource(source, log);
                using (EventLog eventLog = new EventLog())
                {
                    eventLog.Source = source;
                    Helpers.Retry(() => eventLog.WriteEntry(message));
                    Helpers.WaitForEventLog(eventLog, 1);  //There is latency between writing and getting the entry
                    EventLogEntry entry = Helpers.Retry(() => eventLog.Entries[eventLog.Entries.Count - 1]);
                    Assert.True(entry.Equals(entry));

                    Helpers.Retry(() => eventLog.WriteEntry(message));
                    Helpers.WaitForEventLog(eventLog, 2);
                    EventLogEntry secondEntry = Helpers.Retry(() => eventLog.Entries[eventLog.Entries.Count - 1]);
                    Assert.Equal(entry.Index + 1, secondEntry.Index);
                }
            }
            finally
            {
                EventLog.DeleteEventSource(source);
                Helpers.RetrySilently(() => EventLog.Delete(log));
            }
        }
Example #25
0
        /// <summary>
        /// Logs the given object into the DB.
        /// </summary>
        /// <param name="logEntry"></param>
        public static void Log(EventLogEntryBase logEntry)
        {
            //Serialize the object into a string
            XmlSerializer serializer          = new XmlSerializer(logEntry.GetType());
            StringBuilder outputStringBuilder = new StringBuilder();
            StringWriter  stringWriter        = new StringWriter(outputStringBuilder);

            serializer.Serialize(stringWriter, logEntry);

            //Create a database record around the string and write it to the DB
            //The record is a hybrid: the common fields are stored as SQL columns for quick access,
            //the log entry specific columns are stored in XML for flexibility.
            EventLogEntry dbEntry = new EventLogEntry()
            {
                Error     = logEntry.Error,
                EventType = logEntry.GetType().Name,
                Guid      = logEntry.Guid,
                Player    = logEntry.Player,
                Timestamp = logEntry.Timestamp,
                Xml       = outputStringBuilder.ToString()
            };

            db.EventLogEntries.InsertOnSubmit(dbEntry);
            db.SubmitChanges();
        }
Example #26
0
        internal void HandleEventLogNotification(EventLogEntry entry)
        {
            try
            {
                int       pid          = int.Parse(GetReplacementString(entry, 0));
                Direction direction    = GetReplacementString(entry, 2) == @"%%14593" ? Direction.Out : Direction.In;
                int       protocol     = int.Parse(GetReplacementString(entry, 7));
                string    targetIp     = GetReplacementString(entry, 5);
                int       targetPort   = int.Parse(GetReplacementString(entry, 6));
                string    sourceIp     = GetReplacementString(entry, 3);
                int       sourcePort   = int.Parse(GetReplacementString(entry, 4));
                string    friendlyPath = GetReplacementString(entry, 1) == "-" ? "System" : Common.IO.Files.PathResolver.GetFriendlyPath(GetReplacementString(entry, 1));
                string    fileName     = System.IO.Path.GetFileName(friendlyPath);

                // try to get the servicename from pid (works only if service is running)
                string serviceName = AsyncTaskRunner.GetServicName(pid);

                LogHelper.Info($"Handle {direction.ToString().ToUpper(CultureInfo.InvariantCulture)}-going connection for '{fileName}', service: {serviceName} ...");
                if (!AddItem(pid, friendlyPath, targetIp, protocol: protocol, targetPort: targetPort, localPort: sourcePort))
                {
                    //This connection is blocked by a specific rule. No action necessary.
                    LogHelper.Info($"{direction}-going connection for '{fileName}' is blocked by a rule - ignored.");
                    return;
                }

                //if (notifierWindow.WindowState == WindowState.Minimized)
                //{
                //    notifierWindow.ShowActivityTrayIcon($"Notifier blocked connections - click tray icon to show");  // max 64 chars!
                //}
            }
            catch (Exception e)
            {
                LogHelper.Error("HandleEventLogNotification exception", e);
            }
        }
Example #27
0
        private LoggedOn.LogonType ParseLogonType(EventLogEntry entry)
        {
            LoggedOn.LogonType result = LoggedOn.LogonType.Unknown;

            string value_str = GetReplacementString(entry, New_Logon_Type);

            if (value_str.Length > 0)
            {
                uint value = 0;
                if (UInt32.TryParse(value_str, out value))
                {
                    try
                    {
                        result = (LoggedOn.LogonType)value;
                    }
                    catch (Exception e)
                    {
                        Debug.Write(e.Message);
                    }
                }
            }

            // and return nicely
            return(result);
        }
Example #28
0
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            if (listView1.SelectedIndices.Count <= 0)
            {
                return;
            }
            int iSel = listView1.SelectedIndices[0];

            EventLogEntry entry = GetEventLogEntryFromCache(iSel);

            if (entry != null)
            {
                RichTextBoxFuncs rtf = new RichTextBoxFuncs(richTextBox1);
                rtf.WriteLine("Id:\t", entry.InstanceId.ToString());
                rtf.WriteLine("Index: ", entry.Index.ToString());
                rtf.WriteLine("EntryType: ", GetErrorType(entry.EntryType));

                rtf.WriteLine("TimeWritten: ", entry.TimeWritten.ToString());
                rtf.WriteLine("Source: ", entry.Source);
                //rtf.WriteLine("Category: ", zipEntry.Category);
                //rtf.WriteLine("CategoryNumber: ", zipEntry.CategoryNumber.ToString());
                rtf.WriteLine("MachineName: ", entry.MachineName);
                rtf.WriteLine("UserName: "******"Message: ", entry.Message);
            }
        }
 public static void Main()
 {
     try
     {
         EventLog myNewLog = new EventLog();
         myNewLog.Log    = "MyNewLog";
         myNewLog.Source = "MySource";
         // Create the source if it does not exist already.
         if (!EventLog.SourceExists("MySource"))
         {
             // An event log source should not be created and immediately used.
             // There is a latency time to enable the source, it should be created
             // prior to executing the application that uses the source.
             // Execute this sample a second time to use the new source.
             EventLog.CreateEventSource("MySource", "MyNewLog");
             Console.WriteLine("CreatingEventSource");
             Console.WriteLine("Exiting, execute the application a second time to use the source.");
             // The source is created.  Exit the application to allow it to be registered.
             return;
         }
         // Write an entry to the EventLog.
         myNewLog.WriteEntry("The Latest entry in the Event Log");
         int                   myEntries        = myNewLog.Entries.Count;
         EventLogEntry         entry            = myNewLog.Entries[myEntries - 1];
         EntryWrittenEventArgs myEntryEventArgs =
             new EntryWrittenEventArgs();
         MyOnEntry(myNewLog, myEntryEventArgs);
     }
     catch (Exception e)
     {
         Console.WriteLine("Exception Raised" + e.Message);
     }
 }
Example #30
0
 /// <summary>
 /// Creates a new instance of the <see cref="LogMessageEventlog"/> object.
 /// </summary>
 /// <param name="rawData">The data <see cref="Array"/> the new <see cref="LogMessageEventlog"/> represents.</param>
 /// <param name="index">The index of the <see cref="LogMessage"/>.</param>
 public LogMessageEventlog(EventLogEntry rawData, int index) : base(rawData, index)
 {
     if (!ParseData(rawData))
     {
         throw new ApplicationException("Unable to parse the logger data.");
     }
 }
Example #31
0
    private static SqlDataRecord buildRecord(SqlMetaData[] metadata,EventLogEntry entry)
    {
        SqlDataRecord record     = new SqlDataRecord(metadata);

        record.SetSqlInt32(0, entry.Index);
        record.SetSqlInt64(1, entry.InstanceId);
        record.SetSqlDateTime(2, entry.TimeWritten);
        record.SetSqlString(3, entry.MachineName);
        record.SetSqlString(4, entry.Source);
        record.SetSqlString(5, entry.UserName);
        record.SetSqlString(6, entry.Message);

        return record;
    }
	// Methods
	public void CopyTo(EventLogEntry[] entries, int index) {}
	// Methods
	public bool Equals(EventLogEntry otherEntry) {}
	public EntryWrittenEventArgs(EventLogEntry entry) {}
	public EntryWrittenEventArgs(EventLogEntry entry)
			{
				this.entry = entry;
			}
	// Constructor.
	public EntryWrittenEventArgs()
			{
				this.entry = null;
			}