Exemple #1
0
        public DataSet QueryRemoteComputer(string querystring, Queryobj o)
        {
            string queryString = querystring; // XPATH Query


            EventLogSession session = new EventLogSession(
                o.IP,
                o.domain,
                o.username,
                o.password,
                SessionAuthentication.Default);



            // Query the Application log on the remote computer.
            EventLogQuery query = new EventLogQuery(o.logname, PathType.LogName, queryString);

            query.Session = session;

            try
            {
                EventLogReader logReader = new EventLogReader(query);

                // Display event info
                DisplayEventAndLogInformation(logReader);
            }
            catch (EventLogException e)
            {
                Console.WriteLine("Could not query the remote computer! " + e.Message);
            }
            return(data);
        }
Exemple #2
0
        public IEnumerable <EventRecord> ReadEvents(string path, int minutes, bool reverseDirection = true)
        {
            string queryString =
                "<QueryList>" +
                $" <Query Id=\"0\" Path=\"{path}\">" +
                $" <Select Path=\"{path}\">" +
                $" *[System[TimeCreated[timediff(@SystemTime) &lt;= {minutes * 60}000]]]" +
                " </Select>" +
                " </Query>" +
                "</QueryList>";

            EventLogSession session = new EventLogSession(this._computerName);
            EventLogQuery   query   = new EventLogQuery(path, PathType.LogName, queryString)
            {
                Session          = session,
                ReverseDirection = reverseDirection
            };

            var result = new List <EventRecord>();

            try
            {
                EventLogReader logReader = new EventLogReader(query);

                for (EventRecord eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent())
                {
                    result.Add(eventInstance);
                }
            }
            catch (EventLogException) { }

            return(result);
        }
Exemple #3
0
        public void QueryRemoteComputer()
        {
            string       queryString = "*[System/Level=2]"; // XPATH Query
            SecureString pw          = GetPassword();

            EventLogSession session = new EventLogSession(
                "RemoteComputerName",                      // Remote Computer
                "Domain",                                  // Domain
                "Username",                                // Username
                pw,
                SessionAuthentication.Default);

            pw.Dispose();

            // Query the Application log on the remote computer.
            EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);

            query.Session = session;

            try
            {
                EventLogReader logReader = new EventLogReader(query);

                // Display event info
                DisplayEventAndLogInformation(logReader);
            }
            catch (EventLogException e)
            {
                Console.WriteLine("Could not query the remote computer! " + e.Message);
                return;
            }
        }
        //If you don't want completed tasks remove the second part in the where clause
        private static List <EventRecord> GetCompletedScheduledTaskEventRecords(EventLogSession session)
        {
            //Below logName is very important since out windows Task Scheduler writes logs to the below
            var logName = "Microsoft-Windows-TaskScheduler/Operational";

            var logquery =
                new EventLogQuery(logName, PathType.LogName)
            {
                Session = session
            };

            //the userId associated to the Tasks Scheduled in the Task Scheduler
            var userId = "USER_ID"; //ex: S-1-5-18

            //name of the task we want to get the history for
            //we can remove this filtering from below to get logs for all tasks
            var taskName = "NAME_OF_THE_TASK_YOU_WANT_GET_HISTORY";

            //we can update the query here to only get the completed Tasks etc by
            //adding the TaskID (ex: 102 is Task Completed, 201 is Action Completed)
            //shown in the commented code as below
            return(GetRecords(logquery, x =>
                              x.TimeCreated > DateTime.Today.AddDays(-2) &&
                              x.Properties.Select(p => p.Value).Contains(taskName)
                              //&& x.Id == <<TaskId>>
                              && x.UserId.Value == userId
                              ).ToList());
        }
Exemple #5
0
        public EventLogReader GetEventLogReader(string path, string query)
        {
            // TODO: investigate https://docs.microsoft.com/en-us/previous-versions/windows/desktop/eventlogprov/win32-ntlogevent

            var eventsQuery = new EventLogQuery(path, PathType.LogName, query)
            {
                ReverseDirection = true
            };

            if (!string.IsNullOrEmpty(ComputerName))
            {
                //EventLogSession session = new EventLogSession(
                //    ComputerName,
                //    "Domain",                                  // Domain
                //    "Username",                                // Username
                //    pw,
                //    SessionAuthentication.Default); // TODO password specification! https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.eventlogsession.-ctor?view=dotnet-plat-ext-3.1#System_Diagnostics_Eventing_Reader_EventLogSession__ctor_System_String_System_String_System_String_System_Security_SecureString_System_Diagnostics_Eventing_Reader_SessionAuthentication_

                var session = new EventLogSession(ComputerName);
                eventsQuery.Session = session;
            }

            var logReader = new EventLogReader(eventsQuery);

            return(logReader);
        }
 public void ClearLog_LogExists_Success()
 {
     using (var session = new EventLogSession())
     {
         string log    = "Log_" + nameof(ClearLog_LogExists_Success);
         string source = "Source_" + nameof(ClearLog_LogExists_Success);
         try
         {
             EventLog.CreateEventSource(source, log);
             using (EventLog eventLog = new EventLog())
             {
                 eventLog.Source = source;
                 Helpers.Retry(() => eventLog.WriteEntry("Writing to event log."));
                 Assert.NotEqual(0, Helpers.Retry((() => eventLog.Entries.Count)));
                 session.ClearLog(logName: log);
                 Assert.Equal(0, Helpers.Retry((() => eventLog.Entries.Count)));
             }
         }
         finally
         {
             EventLog.DeleteEventSource(source);
         }
         session.CancelCurrentOperations();
     }
 }
        public static List <KeyValuePair <int, string> > GetEventTasks(string computerName, IEnumerable <string> providers)
        {
            bool isLocal = (string.IsNullOrEmpty(computerName) || computerName == "." || computerName.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase));
            var  ret     = new Dictionary <int, string>();

            try
            {
                using (EventLogSession session = isLocal ? new EventLogSession() : new EventLogSession(computerName))
                {
                    foreach (var item in providers)
                    {
                        var md = new ProviderMetadata(item, session, System.Globalization.CultureInfo.CurrentUICulture);
                        foreach (var t in md.Tasks)
                        {
                            if (!ret.ContainsKey(t.Value))
                            {
                                ret.Add(t.Value, t.DisplayName);
                            }
                        }
                    }
                }
            }
            catch { }
            return(new List <KeyValuePair <int, string> >(ret));
        }
Exemple #8
0
        public static object[] GetEventLogDisplayObjects(string computerName, bool filterForTasks = true)
        {
            var ret = new List <ELObj>();

            try
            {
                using (EventLogSession session = GetEventLogSession(computerName))
                {
                    foreach (var s in session.GetLogNames())
                    {
                        try
                        {
                            var cfg = new EventLogConfiguration(s, session);
                            if (!filterForTasks || IsValidTaskLog(cfg))
                            {
                                ret.Add(new ELObj(session.GetLogDisplayName(s), s));
                            }
                        }
                        catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Couldn't get display name for event log '{s}': {e.Message}"); }
                    }
                    ret.Sort();
                }
            }
            catch { }
            return(ret.ToArray());
        }
        public static string QueryRemoteComputer(string username, string domain, string dc, string dauser, string dapass)
        {
            string       queryString = "*[System[(EventID=4624)] and EventData[Data[@Name='TargetUserName']='******']]"; // XPATH Query
            SecureString pw          = GetPassword(dapass);

            EventLogSession session = new EventLogSession(
                dc,                               // Remote Computer
                domain,                           // Domain
                dauser,                           // Username
                pw,
                SessionAuthentication.Default);

            pw.Dispose();

            // Query the Application log on the remote computer.
            EventLogQuery query = new EventLogQuery("Security", PathType.LogName, queryString);

            query.Session = session;
            EventLogReader reader = new EventLogReader(query);
            EventRecord    eventRecord;
            string         result = String.Empty;

            while ((eventRecord = reader.ReadEvent()) != null)
            {
                result = eventRecord.FormatDescription();
            }
            // Display event info
            return(result);
        }
Exemple #10
0
 private void LoadProvider()
 {
     if (string.IsNullOrEmpty(this.providerName))
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("ProviderNotSpecified"), new object[0]), "ProviderName");
     }
     using (EventLogSession session = new EventLogSession())
     {
         foreach (string str in session.GetProviderNames())
         {
             if (string.Equals(str, this.providerName, StringComparison.OrdinalIgnoreCase))
             {
                 try
                 {
                     this.providerMetadata = new ProviderMetadata(str);
                     goto Label_00D2;
                 }
                 catch (EventLogException exception)
                 {
                     throw new Exception(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("ProviderMetadataUnavailable"), new object[] { str, exception.Message }), exception);
                 }
             }
         }
     }
     Label_00D2:
     if (this.providerMetadata == null)
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("NoProviderFound"), new object[] { this.providerName }));
     }
 }
Exemple #11
0
        public static string ExtractLogByPeriod(string directoryFullPath, string clientCode, int hourFromNow)
        {
            string query = "*[System[TimeCreated[@SystemTime >= '" + DateTime.Now.AddHours(-1 * hourFromNow).ToUniversalTime().ToString("o") + "']]]";
            //    "(Provider/@Name=\"AD FS 2.0 Auditing\") and " +
            //    "(TimeCreated/@SystemTime <= \"" + toDate.ToString("yyyy-MM-ddTHH:mm:ss") + "\") and " +
            //"(TimeCreated/@SystemTime >= " + DateTime.Now.AddHours(-10).ToString("o") + ")" +
            //"]]";
            //" and (TimeCreated/@SystemTime <= " + toDate.Ticks + ")]]";
            //" and TimeCreated[timediff(@SystemTime) <= 86400000]]]";

            string eventLogFile = clientCode + ".EventLog." + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss", new CultureInfo("en-AU"));

            if (!Directory.Exists(directoryFullPath))
            {
                Directory.CreateDirectory(directoryFullPath);
            }

            string fileNameWithFullPath = (directoryFullPath + @"\" + eventLogFile + ".evtx").Replace(@"\\", @"\");

            using (var logSession = new EventLogSession())
            {
                if (File.Exists(fileNameWithFullPath))
                {
                    File.Delete(fileNameWithFullPath);
                }
                logSession.ExportLogAndMessages("System", PathType.LogName, query, fileNameWithFullPath, true, CultureInfo.CurrentCulture);
            }

            return(fileNameWithFullPath);
        }
Exemple #12
0
        public static List <EventLogConfiguration> GetEventLogs(string computerName, bool filterForTasks = true)
        {
            var ret = new List <EventLogConfiguration>();

            try
            {
                using (EventLogSession session = GetEventLogSession(computerName))
                {
                    foreach (var s in session.GetLogNames())
                    {
                        try
                        {
                            var cfg = new EventLogConfiguration(s, session);
                            if (!filterForTasks || IsValidTaskLog(cfg))
                            {
                                ret.Add(cfg);
                            }
                        }
                        catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Couldn't get config for event log '{s}': {e.Message}"); }
                    }
                }
            }
            catch { }
            return(ret);
        }
Exemple #13
0
        public static void ExtractLog(string query, string dirName, string fileName)
        {
            string fileNameFullPath = string.Empty;

            try
            {
                //query = "*[System[TimeCreated[@SystemTime >= '" + DateTime.Now.AddHours(-1).ToUniversalTime().ToString("o") + "']]]";

                //    "(Provider/@Name=\"AD FS 2.0 Auditing\") and " +
                //    "(TimeCreated/@SystemTime <= \"" + toDate.ToString("yyyy-MM-ddTHH:mm:ss") + "\") and " +
                //"(TimeCreated/@SystemTime >= " + DateTime.Now.AddHours(-10).ToString("o") + ")" +
                //"]]";
                //" and (TimeCreated/@SystemTime <= " + toDate.Ticks + ")]]";
                //" and TimeCreated[timediff(@SystemTime) <= 86400000]]]";

                fileNameFullPath = (dirName + @"\" + fileName).Replace(@"\\", @"\");
                //query = "*";

                if (File.Exists(fileNameFullPath))
                {
                    File.Delete(fileNameFullPath);
                }

                using (var logSession = new EventLogSession())
                {
                    logSession.ExportLogAndMessages("Application", PathType.LogName, query, fileNameFullPath, true, CultureInfo.CurrentCulture);
                    logSession.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw new RMSAppException("ExtractLog failed. " + ex.Message, ex, false);
            }
        }
Exemple #14
0
        protected /*override*/ void OnStart(string[] args)
        {
            var remoteComputer = null;
            var domain         = null;
            var password       = null;
            var userName       = null;

            EventLogSession session = new EventLogSession(
                remoteComputer,                          // Remote Computer
                domain,                                  // Domain
                userName,                                // Username
                password,
                SessionAuthentication.Default);

            String xpath = "*[System[EventID=4624 or EventID=4634]]";

            var query = new EventLogQuery("Security", PathType.LogName, xpath);

            query.Session = session;

            var watcher = new EventLogWatcher(query);

            watcher.EventRecordWritten += OnEntryWritten;
            watcher.Enabled             = true;
        }
        private static bool remote_event_log_exists(string log, string remote_machine_name, string remote_domain_name, string remote_user_name, string remote_password_name)
        {
            try {
                SecureString pwd = new SecureString();
                foreach (char c in remote_password_name)
                {
                    pwd.AppendChar(c);
                }
                EventLogSession session = remote_machine_name.Trim() != ""
                    ? new EventLogSession(remote_machine_name, remote_domain_name, remote_user_name, pwd, SessionAuthentication.Default)
                    : null;
                pwd.Dispose();
                EventLogQuery query = new EventLogQuery(log, PathType.LogName);
                if (session != null)
                {
                    query.Session = session;
                }

                EventLogReader reader = new EventLogReader(query);
                if (reader.ReadEvent(TimeSpan.FromMilliseconds(500)) != null)
                {
                    return(true);
                }
            } catch (Exception e) {
                logger.Error("can't login " + e.Message);
            }
            return(false);
        }
        public void SetProperties_SaveChanges_NotAdmin_Throws()
        {
            const string LogName = "Application";

            using (var session = new EventLogSession())
            {
                EventLogConfiguration configuration = null;
                try
                {
                    configuration = new EventLogConfiguration(LogName, session);
                }
                catch (EventLogNotFoundException)
                {
                    configuration?.Dispose();
                    return;
                }

                configuration.IsEnabled          = false;
                configuration.SecurityDescriptor = string.Empty;
                configuration.LogFilePath        = null;
                configuration.LogMode            = EventLogMode.Retain;
                configuration.ProviderLevel      = 1;
                configuration.ProviderKeywords   = 1;
                configuration.MaximumSizeInBytes = long.MaxValue;
                Assert.Throws <UnauthorizedAccessException>(() => configuration.SaveChanges());

                configuration.Dispose();
                session.CancelCurrentOperations();
            }
        }
Exemple #17
0
        private void LoadProvider()
        {
            if (string.IsNullOrEmpty(_providerName))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderNotSpecified")), "ProviderName");
            }

            using (EventLogSession session = new EventLogSession())
            {
                foreach (string providerName in session.GetProviderNames())
                {
                    if (string.Equals(providerName, _providerName, StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            _providerMetadata = new ProviderMetadata(providerName);
                        }
                        catch (EventLogException exc)
                        {
                            string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderMetadataUnavailable"), providerName, exc.Message);
                            throw new Exception(msg, exc);
                        }
                        break;
                    }
                }
            }

            if (_providerMetadata == null)
            {
                string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), _providerName);
                throw new ArgumentException(msg);
            }
        }
Exemple #18
0
        private void querySecHistoricLocalServerEvents()
        {
            Thread thloadSecH = new Thread(() =>
            {
                Thread.CurrentThread.Name = "thloadSecH";

                TimeSpan span      = DateTime.UtcNow.Subtract(DateTime.UtcNow.AddDays(-1));
                string queryString = "<QueryList>" +
                                     @"<Query Id = ""0"" Path = ""ForwardedEvents"">" +
                                     @"<Select Path = ""ForwardedEvents""> *[System[(EventID=4740) and TimeCreated[timediff(@SystemTime) &lt;= " + span.TotalMilliseconds + "]]]</Select>" +
                                     @"</Query>" +
                                     @"</QueryList>";

                SecureString pw = new SecureString();
                foreach (char c in frmMain.domainAccountData[2])
                {
                    pw.AppendChar(c);
                }
                EventLogSession session = new EventLogSession("corp1042", frmMain.domainAccountData[0], frmMain.domainAccountData[1], pw, SessionAuthentication.Default);
                pw.Dispose();

                // Query the Application log on the remote computer.
                EventLogQuery query = new EventLogQuery("ForwardedEvents", PathType.LogName, queryString);
                query.Session       = session;

                try
                {
                    EventLogReader logReader = new EventLogReader(query);
                    DisplayEventAndLogInformation(logReader);
                }
                catch (EventLogException ex)
                {
                    Console.WriteLine("Could not query the remote computer! " + ex.Message);
                    return;
                }
                session.Dispose();
                try
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        pBoxProgressSecH.Visible = false;
                    });
                }
                catch { Thread.CurrentThread.Abort(); }
            });

            string nOFDays;
            int    nOFDaysInt;

            nOFDays = txtBoxDays.Text;
            if (int.TryParse(nOFDays, out nOFDaysInt))
            {
                pBoxProgressSecH.Visible = true;
                thloadSecH.Start();
            }
            else
            {
                MessageBox.Show("Please enter only Numbers on field: Days", "Information!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemple #19
0
        private void check_log(string name)
        {
            try {
                SecureString pwd = new SecureString();
                foreach (char c in remote_passw_)
                {
                    pwd.AppendChar(c);
                }
                EventLogSession session = remote_machine_name_ != "" ? new EventLogSession(remote_machine_name_, remote_domain_, remote_username_, pwd, SessionAuthentication.Default) : null;
                pwd.Dispose();
                string        query_string = "*";
                EventLogQuery query        = new EventLogQuery(name, PathType.LogName, query_string);

                using (EventLogReader reader = new EventLogReader(query))
                    for (EventRecord rec = reader.ReadEvent(); rec != null; rec = reader.ReadEvent())
                    {
                        lock (this)
                            --log_names_[name];
                    }
            } catch (Exception e) {
                logger.Error("error checking log " + name + " on " + remote_machine_name_ + " : " + e.Message);
            }

            // mark log as fully read
            lock (this) {
                log_names_[name] = -log_names_[name];
                if (log_names_[name] == 0)
                {
                    // convention - 0 entries
                    log_names_[name] = int.MinValue;
                }
            }
        }
Exemple #20
0
 public static void Export(string path)
 {
     using (var log = new EventLogSession())
     {
         log.ExportLogAndMessages("Application", PathType.LogName, Query, path);
     }
 }
Exemple #21
0
            public static DataTable SearchEventLogsForLockouts(string[] DomainControllers, DateTime LastScan)
            {
                DataTable table = new DataTable(); //Build a table to house the results

                table.Columns.Add("Date", typeof(DateTime));
                table.Columns.Add("User");
                table.Columns.Add("Machine");
                table.Columns.Add("DC");

                foreach (string dc in DomainControllers)
                {
                    EventLogQuery   eventsQuery = new EventLogQuery("Security", PathType.LogName, "*[System/EventID=4740]"); //Create an eventlog query to find 4740 events in the security log
                    EventLogSession session     = new EventLogSession(dc);                                                   //Create an eventlog session on the target machine
                    eventsQuery.Session = session;                                                                           //Invoke the session

                    try
                    {
                        EventLogReader logReader = new EventLogReader(eventsQuery);                                                                                 //start the eventlog reader

                        for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent())                             //foreach the results of the reader
                        {
                            if (eventdetail.TimeCreated > LastScan)                                                                                                 //find entries newer than the date specified
                            {
                                table.Rows.Add(eventdetail.TimeCreated, eventdetail.Properties[0].Value, eventdetail.Properties[1].Value, eventdetail.MachineName); //add the specific columns to the table
                            }
                        }
                    }
                    catch { }
                }
                return(table); //return the table
            }
Exemple #22
0
        public static void ExtractLog(string query, string dirName, string fileName, string serverName, string domainName, string userName, string password)
        {
            string fileNameFullPath = string.Empty;

            try
            {
                fileNameFullPath = (dirName + @"\" + fileName).Replace(@"\\", @"\");
                //query = "*";

                if (File.Exists(fileNameFullPath))
                {
                    File.Delete(fileNameFullPath);
                }

                var secureString = new SecureString();
                password.ToCharArray().ToList().ForEach(p => secureString.AppendChar(p));

                using (var logSession = new EventLogSession(serverName, domainName, userName, secureString, SessionAuthentication.Default))
                {
                    logSession.ExportLogAndMessages("Application", PathType.LogName, query, fileNameFullPath, true, CultureInfo.CurrentCulture);
                    logSession.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw new RMSAppException("ExtractLog failed. " + ex.Message, ex, false);
            }
        }
Exemple #23
0
        static void Main(string[] args)
        {
            {
                Console.Out.WriteLine("Available Logs:");
                var session = new EventLogSession();
                foreach (var log in session.GetLogNames())
                {
                    Console.Out.WriteLine("    " + log);
                }
                Console.Out.WriteLine();
            }

            if (!EventLog.SourceExists("TestEventLog"))
            {
                EventSourceCreationData eventSourceData = new EventSourceCreationData("TestEventLog", "TestEventLog");
                EventLog.CreateEventSource(eventSourceData);
            }

            using (var testEventLogListener = new Listener("TestEventLog", "*"))
                using (var applicationListener = new Listener("Application", "*"))
                    using (var testEventLogger = new EventLog("TestEventLog", ".", "TestEventLog"))
                        using (var timer = new System.Threading.Timer(
                                   _ => testEventLogger.WriteEntry("Test message", EventLogEntryType.Information),
                                   null,
                                   TimeSpan.FromSeconds(1),
                                   TimeSpan.FromSeconds(1)
                                   ))
                        {
                            while (Console.ReadLine().Trim().ToLower() != "exit")
                            {
                                Console.WriteLine("  exit↵ to Exit");
                            }
                        }
        }
        public static void Main(string[] args)
        {
            //Establish a connection to the Event Log Session for the given computer name
            var computerName = "<<NAME_OF_YOUR_COMPUTER>>"; //name of your computer

            using (var session = new EventLogSession(computerName))
            {
                //getting the list of event logs from the session
                var result = GetCompletedScheduledTaskEventRecords(session);

                //Filtering the data more and getting what ever is required, you can change this code
                //to get more information or in a different format
                var response = result
                               .OrderByDescending(x => x.TimeCreated)
                               .Select(r => new
                {
                    EventId       = r.Id,
                    Publisher     = r.ProviderName,
                    CompletedTime = r.TimeCreated,
                    r.TaskDisplayName,
                    Props = string.Join(" | ", r.Properties.Select(p => p.Value))
                }).ToList();

                //Writing the response to a text file, with a delimiter which I then exported to Excel
                string fileName = "PATH_TO_FILE_TO_WRITE_THE_LOGS.TXT";
                using (var fs = new StreamWriter(fileName))
                {
                    foreach (var item in response)
                    {
                        fs.WriteLine(item.EventId + "||" + item.TaskDisplayName + "||" + item.CompletedTime + "||" + item.Props);
                    }
                }
            }
        }
Exemple #25
0
        public void GetLogInformation_UsingLogName_DoesNotThrow(string logName)
        {
            using (var session = new EventLogSession())
            {
                EventLogConfiguration configuration;
                try
                {
                    configuration = new EventLogConfiguration(logName, session);
                }
                catch (EventLogNotFoundException)
                {
                    throw new SkipTestException(nameof(EventLogNotFoundException));
                }

                using (configuration)
                {
                    EventLogInformation logInfo = session.GetLogInformation(configuration.LogName, PathType.LogName);

                    Assert.Equal(logInfo.CreationTime, logInfo.CreationTime);
                    Assert.Equal(logInfo.LastAccessTime, logInfo.LastAccessTime);
                    Assert.Equal(logInfo.LastWriteTime, logInfo.LastWriteTime);
                    Assert.Equal(logInfo.FileSize, logInfo.FileSize);
                    Assert.Equal(logInfo.Attributes, logInfo.Attributes);
                    Assert.Equal(logInfo.RecordCount, logInfo.RecordCount);
                    Assert.Equal(logInfo.OldestRecordNumber, logInfo.OldestRecordNumber);
                    Assert.Equal(logInfo.IsLogFull, logInfo.IsLogFull);
                }
            }
        }
Exemple #26
0
        public IEnumerable <XElement> ProvideInfo(XElement root)
        {
            foreach (var element in root.Elements("Log"))
            {
                var name     = (string)element.Attribute("Name");
                var filename = (string)element.Attribute("Filename");
                var query    = (string)element.Attribute("Query") ?? "*";

                var temp    = Path.GetTempPath();
                var success = false;
                try
                {
                    using (var session = new EventLogSession())
                    {
                        session.ExportLogAndMessages(name, PathType.LogName, query, temp + filename);
                    }

                    _host.AddFile(temp + filename, filename, true);
                    success = true;
                }
                catch (Exception ex)
                {
                    _log.Warn($"Error: {ex.Message}");
                    continue;
                }
                if (success)
                {
                    yield return(new XElement("Log",
                                              new XAttribute("Name", name),
                                              new XAttribute("Filename", filename),
                                              new XAttribute("Query", query)));
                }
            }
        }
        public void GetPropertyValues_MatchProviderIdUsingProviderMetadata_Success()
        {
            Dictionary <string, Guid> providerNameAndIds = new Dictionary <string, Guid>();

            string logName     = "Application";
            string queryString = "*[System/Level=4]";
            var    xPathEnum   = new List <string>()
            {
                "Event/System/EventID", "Event/System/Provider/@Name"
            };
            var logPropertyContext = new EventLogPropertySelector(xPathEnum);
            var eventsQuery        = new EventLogQuery(logName, PathType.LogName, queryString);

            try
            {
                using (var logReader = new EventLogReader(eventsQuery))
                {
                    for (EventLogRecord eventRecord = (EventLogRecord)logReader.ReadEvent();
                         eventRecord != null;
                         eventRecord = (EventLogRecord)logReader.ReadEvent())
                    {
                        IList <object> logEventProps;
                        logEventProps = eventRecord.GetPropertyValues(logPropertyContext);
                        int eventId;
                        Assert.True(int.TryParse(string.Format("{0}", logEventProps[0]), out eventId));
                        string providerName = (string)logEventProps[1];
                        if (!providerNameAndIds.ContainsKey(providerName) && eventRecord.ProviderId.HasValue)
                        {
                            providerNameAndIds.Add(providerName, eventRecord.ProviderId.Value);
                        }
                    }
                }
            }
            catch (EventLogNotFoundException) { }

            if (providerNameAndIds.Count > 0)
            {
                using (var session = new EventLogSession())
                {
                    foreach (var nameAndId in providerNameAndIds)
                    {
                        ProviderMetadata providerMetadata = null;
                        try
                        {
                            providerMetadata = new ProviderMetadata(nameAndId.Key);
                            Assert.Equal(providerMetadata.Id, nameAndId.Value);
                        }
                        catch (EventLogException)
                        {
                            continue;
                        }
                        finally
                        {
                            providerMetadata?.Dispose();
                        }
                    }
                }
            }
        }
Exemple #28
0
        public void ProviderNameTests(bool noProviderName)
        {
            string log    = "Application";
            string source = "Source_" + nameof(ProviderNameTests);

            using (var session = new EventLogSession())
            {
                try
                {
                    EventLog.CreateEventSource(source, log);

                    string providerName = noProviderName ? "" : source;
                    using (var providerMetadata = new ProviderMetadata(providerName))
                    {
                        Assert.Null(providerMetadata.DisplayName);
                        Assert.Equal(providerName, providerMetadata.Name);
                        Assert.Equal(new Guid(), providerMetadata.Id);
                        Assert.Empty(providerMetadata.Events);
                        Assert.Empty(providerMetadata.Keywords);
                        Assert.Empty(providerMetadata.Levels);
                        Assert.Empty(providerMetadata.Opcodes);
                        Assert.Empty(providerMetadata.Tasks);
                        Assert.NotEmpty(providerMetadata.LogLinks);
                        if (!string.IsNullOrEmpty(providerName))
                        {
                            foreach (var logLink in providerMetadata.LogLinks)
                            {
                                Assert.True(logLink.IsImported);
                                Assert.Equal(log, logLink.LogName);
                                Assert.NotEmpty(logLink.DisplayName);
                                if (CultureInfo.CurrentCulture.Name.Split('-')[0] == "en")
                                {
                                    Assert.Equal("Application", logLink.DisplayName);
                                }
                                else if (CultureInfo.CurrentCulture.Name.Split('-')[0] == "es")
                                {
                                    Assert.Equal("Aplicación", logLink.DisplayName);
                                }
                            }
                            Assert.Contains("EventLogMessages.dll", providerMetadata.MessageFilePath);
                            Assert.Contains("EventLogMessages.dll", providerMetadata.HelpLink.ToString());
                        }
                        else
                        {
                            Assert.Null(providerMetadata.MessageFilePath);
                            Assert.Null(providerMetadata.HelpLink);
                        }
                        Assert.Null(providerMetadata.ResourceFilePath);
                        Assert.Null(providerMetadata.ParameterFilePath);
                    }
                }
                finally
                {
                    EventLog.DeleteEventSource(source);
                }
                session.CancelCurrentOperations();
            }
        }
        public void ResolveLocalEventsWorks()
        {
            // Arrange
            var session   = new EventLogSession();
            var providers = new List <string>(session.GetProviderNames().Distinct().OrderBy(name => name));

            // Act
            var providerData = new Dictionary <string, ProviderDetails>();

            foreach (var providerName in providers)
            {
                var p = new EventMessageProvider(providerName, _output.WriteLine);
                providerData.Add(providerName, p.LoadProviderDetails());
            }

            var reader = new EventLogReader("Application", PathType.LogName)
            {
                BatchSize = 1000
            };
            EventRecord evt;

            var found    = 0;
            var notfound = 0;
            var total    = 0;

            while (null != (evt = reader.ReadEvent()))
            {
                total += 1;

                if (!providerData.TryGetValue(evt.ProviderName, out var provider))
                {
                    _output.WriteLine("Could not find provider: " + evt.ProviderName);
                    continue;
                }

                if (provider.Events?.FirstOrDefault(e => e.Id == evt.Id) == null)
                {
                    if (provider.Messages.FirstOrDefault(m => m.RawId == evt.Id) == null)
                    {
                        if (provider.Messages.FirstOrDefault(m => m.ShortId == evt.Id) == null)
                        {
                            notfound += 1;
                            _output.WriteLine($"Could not find event matching id {evt.Id} for provider {evt.ProviderName}");
                        }
                    }
                }

                found += 1;
            }

            _output.WriteLine($"Total: {total}");
            _output.WriteLine($"Found: {found}");
            _output.WriteLine($"Not found: {notfound}");

            // Assert
            // Must find at least 90% to pass this test
            Assert.True(found > total * .9);
        }
    /// <summary>
    /// Gets provider data for the specified provider.
    /// </summary>
    /// <param name="providerName">The name of the provider.</param>
    /// <returns>A String with info.</returns>
    public static String getEventProvider(String providerName)
    {
        EventLogSession session = new EventLogSession();
        String          providerMessageFilePath   = String.Empty;
        String          providerParameterFilePath = String.Empty;
        String          providerResourceFileName  = String.Empty;
        String          providerHelpLink          = String.Empty;
        String          providerDisplayName       = String.Empty;
        //IList<EventLogLink> eventLogLinks = null;
        StringBuilder sb = new StringBuilder();

        try {
            sb.AppendLine("Provider: " + providerName);
            ProviderMetadata metaData = new ProviderMetadata(providerName,                //Provider name to look up
                                                             session,                     //The session
                                                             CultureInfo.CurrentCulture); //Culture of active thread

            if (metaData != null)
            {
                providerDisplayName = metaData.DisplayName;             //Display Name of the provider
                if (metaData.HelpLink != null)
                {
                    providerHelpLink = metaData.HelpLink.ToString();    //Link to external help on event
                }
                providerMessageFilePath   = metaData.MessageFilePath;   //Source of provider metadata
                providerParameterFilePath = metaData.ParameterFilePath; //Source of provider metadata
                providerResourceFileName  = metaData.ResourceFilePath;  //Resource with provider metadata
                //eventLogLinks = metaData.LogLinks;
            }
            //sb.AppendLine("HelpLink: " + providerHelpLink);
            //sb.AppendLine("MessageFilePath: " + providerMessageFilePath);
            //sb.AppendLine("ParameterFilePath: " + providerParameterFilePath);
            //sb.AppendLine("ResourceFilePath: " + providerResourceFileName);

            sb.AppendLine();
            sb.AppendLine("This provider has the following logs:");
            foreach (EventLogLink eventLink in metaData.LogLinks)
            {
                sb.AppendLine(SEPARATOR_LINE);
                sb.AppendFormat("Display Name: {0}" + LF, eventLink.DisplayName);
                sb.AppendFormat("LogName: {0}" + LF, eventLink.LogName);
            }
            sb.AppendLine(SEPARATOR_LINE);

            sb.AppendLine();
            sb.AppendLine("This provider publishes the following events:");
            foreach (EventMetadata eventData in metaData.Events)
            {
                sb.AppendLine(SEPARATOR_LINE);
                sb.AppendLine("Event ID " + eventData.Id);
                sb.AppendLine(eventData.Description);
            }
            sb.AppendLine(SEPARATOR_LINE);
        } catch (Exception ex) {
            sb.Append(excMsgLocal("Error in getEventProviders", ex));
        }
        return(sb.ToString());
    }
Exemple #31
0
        public EventLogQuery(string path, PathType pathType, string query)
        {
            _session = EventLogSession.GlobalSession;
            _path = path;   // can be null
            _pathType = pathType;

            if (query == null)
            {
                if (path == null)
                    throw new ArgumentNullException("path");
            }
            else
            {
                _query = query;
            }
        }
        internal EventLogInformation(EventLogSession session, string channelName, PathType pathType)
        {
            EventLogHandle logHandle = NativeWrapper.EvtOpenLog(session.Handle, channelName, pathType);

            using (logHandle)
            {
                _creationTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogCreationTime);
                _lastAccessTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastAccessTime);
                _lastWriteTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastWriteTime);
                _fileSize = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFileSize));
                _fileAttributes = (int?)((uint?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogAttributes));
                _recordCount = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogNumberOfLogRecords));
                _oldestRecordNumber = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogOldestRecordNumber));
                _isLogFull = (bool?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFull);
            }
        }