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;
            }
        }
예제 #2
0
        protected virtual uint getMostRecentRemoteLogonTime()
        {
            uint mostRecentRemoteLogonTickCount = 0;

            string logonEventID = "1149";
            string RemoteConnectionLogSource = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";
            string remoteLogonsQuery         = "*[System/EventID=" + logonEventID + "]";

            DateTime?mostRecentLogon = null;

            var elQuery  = new EventLogQuery(RemoteConnectionLogSource, PathType.LogName, remoteLogonsQuery);
            var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery);

            for (EventRecord record = elReader.ReadEvent(); record != null; record = elReader.ReadEvent())
            {
                if (!mostRecentLogon.HasValue || mostRecentLogon.Value < record.TimeCreated)
                {
                    mostRecentLogon = record.TimeCreated;
                }
            }

            if (mostRecentLogon.HasValue)
            {
                uint     nowTickCount             = getEnvironmentTickCount();
                TimeSpan mostRecentRemoteLogonAge = Utils.Calculations.NowTime - mostRecentLogon.Value;
                mostRecentRemoteLogonTickCount = nowTickCount - (uint)mostRecentRemoteLogonAge.TotalMilliseconds;
            }
            return(mostRecentRemoteLogonTickCount);
        }
예제 #3
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {

                var result ="unknown issue";
                var query = new EventLogQuery("Application", PathType.LogName, Query);
                using (var reader = new EventLogReader(query))
                {
                    var nextEvent = reader.ReadEvent();
                    while (nextEvent != null)
                    {
                        result = GetDescriptionFromEntry(nextEvent.FormatDescription());
                        nextEvent = reader.ReadEvent();
                    }
                }

                result = GetDescriptionFromEntry(result);
                SettingsManager.SetTemporarySettingString(SettingKey, result);
                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
예제 #4
0
        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            if (tabControl1.SelectedIndex == 1 && dataGridView1.Rows.Count == 0)
            {
                Cursor.Current = Cursors.WaitCursor;

                EventLogQuery elQuery = new EventLogQuery("Application", PathType.LogName, "*[System/Provider/@Name=\"Raccine\"]");
                elQuery.ReverseDirection = true;

                using (var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery))
                {
                    List <EventRecord> eventList     = new List <EventRecord>();
                    EventRecord        eventInstance = elReader.ReadEvent();
                    try
                    {
                        while (eventInstance != null)
                        {
                            eventInstance = elReader.ReadEvent();
                            if (eventInstance != null)
                            {
                                if (eventInstance.TimeCreated != null)
                                {
                                    TimeSpan ts = ((DateTime)eventInstance.TimeCreated - DateTime.Now);
                                    if (ts.TotalDays < 1)
                                    {
                                        eventList.Add(eventInstance);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (eventInstance != null)
                        {
                            eventInstance.Dispose();
                        }
                    }
                    dataGridView1.Columns.Add("TimeCreated", "TimeCreated");
                    dataGridView1.Columns.Add("EventData", "EventData");
                    foreach (EventRecord evt in eventList)
                    {
                        int rowId = dataGridView1.Rows.Add();

                        // Grab the new row!
                        DataGridViewRow row = dataGridView1.Rows[rowId];

                        // Add the data
                        row.Cells["TimeCreated"].Value = evt.TimeCreated;
                        row.Cells["EventData"].Value   = evt.FormatDescription();
                    }
                }
                Cursor.Current = Cursors.Default;
            }
        }
예제 #5
0
        private void compute_time()
        {
            date_now.Text = DateTime.Now.Date.Date.ToString();
            string query = "*[System/EventID=12]";
            EventLogQuery event_query = new EventLogQuery("System", PathType.LogName, query);
            try
            {
                EventLogReader reader = new EventLogReader(event_query);
                for (EventRecord eventdetail = reader.ReadEvent();
                     eventdetail != null;
                     eventdetail = reader.ReadEvent())
                {
                    DateTime log_created = eventdetail.TimeCreated.Value;
                    if (log_created.Date.ToString() == DateTime.Now.Date.ToString())
                    {
                        double logout_hour = 0.0;
                        double login_hour = log_created.TimeOfDay.TotalHours;
                        if (login_hour < minimum_login_hour)
                        {
                            logout_hour = minimum_login_hour + working_hours;
                        }
                        else if (login_hour > maximum_login_hour)
                        {
                            logout_hour = maximum_login_hour + working_hours;
                        }
                        else
                        {
                            logout_hour = login_hour + working_hours;
                        }
                        TimeSpan span = TimeSpan.FromHours(logout_hour);
                        login_time = eventdetail.TimeCreated.Value;
                        logout_time = DateTime.Today.Add(span);
                        login.Text = login_time.ToString("hh:mm tt");
                        logout.Text = logout_time.ToString("hh:mm tt");

                        double time_now = DateTime.Now.TimeOfDay.TotalHours;
                        double countdown_hour = logout_hour - time_now;
                        if (countdown_hour < 0)
                        {
                            countdown_hour = 0;
                        }
                        TimeSpan t = TimeSpan.FromHours(countdown_hour);
                        hours = t.Hours;
                        minutes = t.Minutes;
                        seconds = t.Seconds;
                    }
                }
            }
            catch (EventLogNotFoundException e)
            {
                Console.WriteLine("Error while readig event logs");
            }
        }
        private DataTable GetStartupShutdownLogs(int NoofEventstoGet)
        {

            DataTable dtLogs = new DataTable("SystemLogs");
            dtLogs.Columns.Add("Message");
            dtLogs.Columns.Add("TimeGenerated");
            dtLogs.Columns.Add("ID");
            DataRow dr;
            try
            {
                string query = "*[System/EventID=6005 or System/EventID=6006]";
                EventLogQuery eventsQuery = new EventLogQuery("System", PathType.LogName, query);

                try
                {
                    EventLogReader logReader = new EventLogReader(eventsQuery);
                    int i = 1;
                    for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent())
                    {
                        dr = dtLogs.NewRow();
                        dr["Message"] = eventdetail.Id == 6005 ? "System Startup" : "System Shutdown";
                        dr["TimeGenerated"] = eventdetail.TimeCreated.ToString();
                        dr["ID"] = i++;
                        dtLogs.Rows.Add(dr);

                    }
                    if (dtLogs.Rows.Count > NoofEventstoGet)
                    {

                        DataView dview = dtLogs.DefaultView;
                        dview.RowFilter = "ID <=" + i + " AND ID >=" + (i - NoofEventstoGet);
                        dview.Sort = "ID Desc";
                        dtLogs = dview.ToTable();

                    }

                }
                catch (EventLogNotFoundException ex)
                {
                    LogManager.WriteLog("Error while reading the event logs" + ex.Message, LogManager.enumLogLevel.Error);
                }


            }
            catch (Exception ex)
            {
                LogManager.WriteLog("GetSystemLogs:" + ex.Message, LogManager.enumLogLevel.Error);
            }
            return dtLogs;
        }
예제 #7
0
        private object[] DisplayEventAndLogInformation(EventLogReader logReader)
        {
            ArrayList eventlog_json_arraylist = new ArrayList();
            for (EventRecord eventInstance = logReader.ReadEvent();
                null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                string eventlog_json = JsonConvert.SerializeObject(eventInstance);
                eventlog_json_arraylist.Add(eventlog_json);

                var serializer = new YamlSerializer();
                String yaml = serializer.Serialize(eventInstance);

                var serializer2 = new YamlDotNet.Serialization.Serializer();
                serializer2.Serialize(System.Console.Out, eventInstance);
                if (Verbose)
                {
                    Console.WriteLine("-----------------------------------------------------");
                    Console.WriteLine("Event ID: {0}", eventInstance.Id);
                    Console.WriteLine("Level: {0}", eventInstance.Level);
                    Console.WriteLine("LevelDisplayName: {0}", eventInstance.LevelDisplayName);
                    Console.WriteLine("Opcode: {0}", eventInstance.Opcode);
                    Console.WriteLine("OpcodeDisplayName: {0}", eventInstance.OpcodeDisplayName);
                    Console.WriteLine("TimeCreated: {0}", eventInstance.TimeCreated);
                    Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                }
                try
                {
                    if (Verbose)
                    {
                        Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                    }
                }
                catch (EventLogException)
                {
                    // The event description contains parameters, and no parameters were 
                    // passed to the FormatDescription method, so an exception is thrown.
                }
                // Cast the EventRecord object as an EventLogRecord object to 
                // access the EventLogRecord class properties
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                if (Verbose)
                {
                    Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog);
                }
            }
            object[] result = eventlog_json_arraylist.ToArray();
            return result;
        }
        public List<IEvent> ReadEventLogData()
        {
            List<IEvent> coll = new List<IEvent>();
            string queryString =
                "<QueryList>" +
                "  <Query Id='0' Path='Microsoft-Windows-Diagnostics-Performance/Operational'>" +
                "    <Select Path='Microsoft-Windows-Diagnostics-Performance/Operational'>*[System[(EventID=100)]]</Select>" +
                "  </Query>" +
                "</QueryList>";
            try
            {
                EventLogQuery eventsQuery = new EventLogQuery("System", PathType.LogName, queryString);
                EventLogReader logReader = new EventLogReader(eventsQuery);

                //create an array of strings for xpath enum.
                String[] xPathRefs = new String[4];
                xPathRefs[0] = "Event/EventData/Data[@Name='BootEndTime']";
                xPathRefs[1] = "Event/EventData/Data[@Name='BootTime']";
                xPathRefs[2] = "Event/EventData/Data[@Name='MainPathBootTime']";
                xPathRefs[3] = "Event/EventData/Data[@Name='BootPostBootTime']";
                IEnumerable<String> xPathEnum = xPathRefs;
                EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

                for (EventRecord eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
                {
                    IList<object> logEventProps;
                    // Cast the EventRecord into an EventLogRecord to retrieve property values.
                    // This will fetch the event properties we requested through the
                    // context created by the EventLogPropertySelector
                    logEventProps = ((EventLogRecord)eventDetail).GetPropertyValues(logPropertyContext);
                    if (eventDetail.Id == 100)
                    {
                        int boot = Convert.ToInt32(logEventProps[1]);
                        int mainPath = Convert.ToInt32(logEventProps[2]);
                        int postBoot = Convert.ToInt32(logEventProps[3]);
                        DateTime date = (DateTime)logEventProps[0];
                        coll.Add(new StartupEvent(date, boot, mainPath, postBoot, (int)eventDetail.Level));
                    }
                }
            }
            catch (EventLogNotFoundException e)
            {
                Console.WriteLine("Error while reading the event logs");
            }
            return coll;
        }
예제 #9
0
 private static IEnumerable<EventLogRecord> LogRecordCollection(string filename, string xpathquery = "*")
 {
     var eventLogQuery = new EventLogQuery(filename, PathType.FilePath, xpathquery);
     using (var eventLogReader = new EventLogReader(eventLogQuery))
     {
         EventLogRecord eventLogRecord;
         while ((eventLogRecord = (EventLogRecord) eventLogReader.ReadEvent()) != null)
             yield return eventLogRecord;
     }
 }
예제 #10
0
        public static int Main(string[] argv)
        {
            EventLogQuery evtQuery;
            EventLogReader evtReader;

            if (argv.Length < 1)
            {
                Console.Error.WriteLine("Event2Text version " + VERSION_MAJOR + "." + VERSION_MINOR);
                Console.Error.WriteLine("USAGE: evt2txt.exe infile");

                return ERROR_ARGUMENTS;
            }

            if (!File.Exists(argv[0]))
            {
                Console.Error.WriteLine("Input file not found: " + argv[0]);

                return ERROR_FILE_NOT_FOUND;
            }

            try
            {
                evtQuery = new EventLogQuery(argv[0], PathType.FilePath);
                evtReader = new EventLogReader(evtQuery);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Input file specified is not a valid log file!");
                Console.Error.WriteLine(e);

                return ERROR_BAD_EVENT_FILE;
            }

            for (EventRecord record = evtReader.ReadEvent();
                null != record;
                record = evtReader.ReadEvent())
            {
                Console.WriteLine(record.ToXml());
            }

            return 0;
        }
 public void ReadEvents(string query = "*[System/EventID=903]")
 {
     var eventsQuery = new EventLogQuery("Application", PathType.LogName, query);
     try
     {
         var logReader = new EventLogReader(eventsQuery);
         // This is a crazy f*****g for loop.  Took me a while to realize what was going on.
         for (EventRecord eventdetail = logReader.ReadEvent();
             eventdetail != null;
             eventdetail = logReader.ReadEvent())
         {
             // Read Event details
             eventdetail.ToXml();
         }
     }
     catch (EventLogNotFoundException e)
     {
         Console.WriteLine(Resources.EventViewerReader_Thing_Error_while_reading_the_event_logs);
     }
 }
예제 #12
0
        public static IEnumerable<EventRecord> GetEvents(string remoteComputer, string domain, string username, string password, string path, string queryString)
        {
            EventLogQuery query = GetQuery(remoteComputer, domain, username, password, path, queryString);
            query.ReverseDirection = true;
            EventLogReader reader = null;
            try
            {

                reader = new EventLogReader(query);
            }
            catch (EventLogException e)
            {
                Console.WriteLine("Could not query the remote computer! " + e.Message);
            }
            var eventLog = reader.ReadEvent();
            while (eventLog != null)
            {
                yield return eventLog;
                eventLog = reader.ReadEvent();
            }
        }
예제 #13
0
        /// <param name="startDate">yyyy-MM-dd</param>
        /// <param name="endDate">yyyy-MM-dd</param>
        public DataTable EventLogGet(string siteId, string startDate, string endDate, int pageNumber, int pageSize, out int recordAmount, out int pageAmount)
        {
            recordAmount = 0;
            pageAmount = 0;

            Regex regex = new Regex(@"<Data Name='SiteID'>(\d+)</Data>", RegexOptions.Compiled);

            string path = "System";
            string query = "*[System/Provider/@EventSourceName='W3SVC']";

            EventLogQuery eventLogQuery = new EventLogQuery(path, PathType.LogName, query);
            EventLogReader eventLogReader = new EventLogReader(eventLogQuery);

            List<string> listLog = new List<string>();

            EventRecord eventInstance;
            while ((eventInstance = eventLogReader.ReadEvent()) != null)
            {
                string createDate = eventInstance.TimeCreated.Value.ToString("yyyy-MM-dd");

                if (string.Compare(createDate, startDate) >= 0 && string.Compare(createDate, endDate) <= 0)
                {
                    Match match = regex.Match(eventInstance.ToXml());
                    if (siteId == match.Groups[1].ToString())
                    {
                        listLog.Add(eventInstance.FormatDescription());
                    }
                }
            }

            DataTable dtLogPage = new DataTable();
            dtLogPage.Columns.Add("LogContent", typeof(string));

            if (listLog.Count == 0)
            {
                return dtLogPage;
            }

            recordAmount = listLog.Count;
            pageAmount = (int)Math.Ceiling(recordAmount * 1.0 / pageSize);
            List<string> listLogPage = Tools.GetPage(listLog, pageNumber, pageSize, pageAmount);

            DataRow newRow;
            foreach (string log in listLogPage)
            {
                newRow = dtLogPage.NewRow();
                newRow["LogContent"] = log;
                dtLogPage.Rows.Add(newRow);
            }

            return dtLogPage;
        }
예제 #14
0
파일: Program.cs 프로젝트: Ams627/EventLog1
        private static void Main(string[] args)
        {
            try
            {
                string eventID1  = "6005";
                string eventID2  = "6006";
                string LogSource = "System";
                string sQuery    = $"*[System/EventID=\"{eventID1}\" or System/EventID=\"{eventID2}\"]";

                Console.WriteLine($"Query {sQuery}");

                var elQuery  = new EventLogQuery(LogSource, PathType.LogName, sQuery);
                var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery);
                List <EventRecord> eventList = new List <EventRecord>();
                for (EventRecord eventInstance = elReader.ReadEvent();
                     null != eventInstance; eventInstance = elReader.ReadEvent())
                {
                    eventList.Add(eventInstance);
                    string eventName = "No event";
                    if (eventInstance.Id == 6005)
                    {
                        eventName = "Computer startup";
                    }
                    else if (eventInstance.Id == 6006)
                    {
                        eventName = "Computer shutdown";
                    }
                    Console.WriteLine($"{eventName}: {eventInstance.TimeCreated}");
                }
            }
            catch (Exception ex)
            {
                var codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
                var progname = Path.GetFileNameWithoutExtension(codeBase);
                Console.Error.WriteLine(progname + ": Error: " + ex.Message);
            }
        }
예제 #15
0
파일: Program.cs 프로젝트: vjohnson01/Tools
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: GetEventLog activityId machines");
                Console.WriteLine("Example: GetEventLog \"0724A8D0-D873-4CB3-8762-C9A70084DD98\" \"server1.company.com,server2.company.com\"");
                return;
            }

            string activityId = args[0];
            string machineNames = args[1];
            
            string adfsAdminLogName = "AD FS 2.0/Admin";

            string[] machineNamesArray = machineNames.Split(new char[1] { ',' });
            foreach (string machineName in machineNamesArray)
            {
                Console.WriteLine();
                Console.WriteLine("--------------------------------------------------------------------------------");
                Console.WriteLine("Getting AD FS event logs with correlation activity ID " + activityId + " from " + machineName);

                string query = "*[System/Correlation/@ActivityID=\"{" + activityId + "}\"]";
                EventLogQuery eventLogQuery = new EventLogQuery(adfsAdminLogName, PathType.LogName, query);
                eventLogQuery.Session = new EventLogSession(machineName);
                EventLogReader eventLogReader = new EventLogReader(eventLogQuery);

                for (EventRecord eventRecord = eventLogReader.ReadEvent(); eventRecord != null; eventRecord = eventLogReader.ReadEvent())
                {
                    //Console.WriteLine("eventRecord.ActivityId=" + eventRecord.ActivityId);
                    Console.WriteLine();
                    Console.WriteLine("--------------------------------------------------------------------------------");
                    Console.WriteLine("Event ID: " + eventRecord.Id);
                    Console.WriteLine("Logged: " + eventRecord.TimeCreated);
                    Console.WriteLine(eventRecord.FormatDescription());
                }
            }
        }
예제 #16
0
        static IEnumerable<EventRecord> FromFile(string logFile)
        {
            long eventCount = 0; // for debugging
            using (EventLogReader reader = new EventLogReader(logFile, PathType.FilePath))
            {
                for (; ; )
                {
                    EventRecord record = reader.ReadEvent();
                    if (record == null)
                        yield break;

                    eventCount++;
                    yield return record;
                }
            }
        }
예제 #17
0
        public static string GetIP(int session_id)
        {
            var query_str = $"*[System[(EventID=21 or EventID=25)]] and *[UserData[EventXML[@xmlns='Event_NS'][(SessionID='{session_id}')]]]";
            var query_log = new EventLogQuery("Microsoft-Windows-TerminalServices-LocalSessionManager/Operational", PathType.LogName, query_str);

            query_log.ReverseDirection = true;

            var         reader        = new System.Diagnostics.Eventing.Reader.EventLogReader(query_log);
            EventRecord eventInstance = reader.ReadEvent();

            if (eventInstance.Properties.Count > 2)
            {
                return((string)eventInstance.Properties[2].Value);
            }
            return(string.Empty);
        }
예제 #18
0
        public static ApplicationError GetById(int eventLogId)
        {
            var query = string.Format(@"<QueryList>
                                            <Query Id=""0"" Path=""Application"">
                                            <Select Path=""Application"">*[System[(EventRecordID={0})]]</Select>
                                            </Query>
                                        </QueryList>", eventLogId);

            var elq = new EventLogQuery("Application", PathType.LogName, query);
            using (var elr = new EventLogReader(elq))
            {
                var eventInstance = elr.ReadEvent();
                return eventInstance == null
                    ? null
                    : ParseEntry(eventInstance);
            }
        }
예제 #19
0
 // ReadLocal
 public EventRecord DisplayEventAndLogInformation(EventRecord eventInstance, string fileName, EventLogReader logReader)
 {
     //EventRecord eventInstance = null;
     //for (eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent())
     //{
     //    #region Gerçek
     //    //_eventId = eventInstance.Id;
     //    //_eventType = eventInstance.TaskDisplayName;
     //    //_description = eventInstance.FormatDescription();
     //    //_eventCategory = eventInstance.LevelDisplayName;
     //    //_computerName = eventInstance.MachineName;
     //    //DateTime dtCreate = Convert.ToDateTime(eventInstance.TimeCreated);
     //    //_dateTimeCreate = dtCreate.ToString(DateFormat);
     //    //DateTime dtNow = DateTime.Now;
     //    //_dateTimeNow = dtNow.ToString(DateFormat);
     //    #endregion
     //}
     eventInstance = logReader.ReadEvent();
     return eventInstance;
 }
예제 #20
0
        public static void DoWork()
        {
            EventLogQuery elQuery = new EventLogQuery("Application", PathType.LogName, "*[System/Provider/@Name=\"Raccine\"]");

            elQuery.ReverseDirection = true;
            using (var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery))
            {
                EventRecord eventInstance = null;
                try
                {
                    eventInstance = elReader.ReadEvent();
                    if (eventInstance != null)
                    {
                        if (eventInstance.TimeCreated != null)
                        {
                            TimeSpan ts = ((DateTime)eventInstance.TimeCreated - DateTime.Now);
                            if (ts.TotalDays < 2)  // it should be recent
                            {
                                // if we already saw an event, don't show it again. wait for a new one.
                                if ((WatcherThread.lastEventTimeGenerated == null) ||
                                    WatcherThread.lastEventTimeGenerated != null &&
                                    (((TimeSpan)(WatcherThread.lastEventTimeGenerated - (DateTime)eventInstance.TimeCreated)).TotalMinutes > 0))
                                {
                                    frmAlert frmAlertInstance = new frmAlert(eventInstance);
                                    //WatcherThread.lastEventTimeGenerated = eventInstance.TimeCreated;
                                    frmAlertInstance.ShowDialog();
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (eventInstance != null)
                    {
                        eventInstance.Dispose();
                    }
                }
            }
        }
예제 #21
0
        public async Task <int> ReadEvents(string eventSource, DateTime fromTime, DateTime toTime, IProgress <ProgressInfo> progress)
        {
            using (cts = new CancellationTokenSource())
            {
                // Event records to be sent to the ViewModel
                var    eventRecords = new List <EventRecord>();
                string errMsg       = "";
                int    count        = 0;
                bool   isFirst      = true;
                try
                {
                    string sQuery = string.Format(" *[System[TimeCreated[@SystemTime > '{0}' and @SystemTime <= '{1}']]]",
                                                  fromTime.ToUniversalTime().ToString("s"),
                                                  toTime.ToUniversalTime().ToString("s"));

                    var elQuery = new EventLogQuery(eventSource, PathType.LogName, sQuery)
                    {
                        ReverseDirection = true
                    };
                    var reader      = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery);
                    var eventRecord = reader.ReadEvent();
                    Debug.WriteLine("Begin Reading");
                    await Task.Run(() =>
                    {
                        for (; eventRecord != null; eventRecord = reader.ReadEvent())
                        {
                            cts.Token.ThrowIfCancellationRequested();

                            eventRecords.Add(eventRecord);
                            ++count;
                            if (count % 100 == 0)
                            {
                                var info = new ProgressInfo(eventRecords.ConvertAll(e => new EventItem(e)), false, isFirst);
                                cts.Token.ThrowIfCancellationRequested();
                                progress.Report(info);
                                isFirst = false;
                                eventRecords.Clear();
                            }
                        }
                    });
                }
                catch (OperationCanceledException ex)
                {
                    errMsg = ex.Message;
                }
                catch (EventLogNotFoundException ex)
                {
                    errMsg = ex.Message;
                }
                catch (UnauthorizedAccessException)
                {
                    errMsg = "Unauthorized access to the channel. Try Run as Administrator.";
                }
                finally
                {
                    var info_comp = new ProgressInfo(eventRecords.ConvertAll(e => new EventItem(e)), true, isFirst, errMsg);
                    progress.Report(info_comp);
                    Debug.WriteLine("End Reading");
                }
                return(count);
            }
        }
예제 #22
0
        void Run(Options options)
        {
            string level = "Message";
            string provider = String.Empty;
            string eventHtml = String.Empty;

            //Query the event log for the event record.
            Trace.WriteLine($"Fetching event log record {options.EventSource} {options.EventId}.");
            EventLogQuery query = new EventLogQuery($"{options.EventSource}", PathType.LogName, $"*[System/EventRecordID = {options.EventId}]");
            using (EventLogReader reader = new EventLogReader(query))
            {
                EventRecord record = reader.ReadEvent();

                // If we found the record, add the event message to the email body.
                // If we didn't find the record, we'll still send the email, but it won't include any of the event data.
                if (record != null)
                {
                    if (record.LevelDisplayName.Equals("Information", StringComparison.OrdinalIgnoreCase) && options.IgnoreInformation)
                    {
                        Trace.TraceInformation("Ignoring information message");
                        return;
                    }
                    else if (record.LevelDisplayName.Equals("Warning", StringComparison.OrdinalIgnoreCase) && options.IgnoreWarning)
                    {
                        Trace.TraceInformation("Ignoring warning message");
                        return;
                    }
                    else if (record.LevelDisplayName.Equals("Error", StringComparison.OrdinalIgnoreCase) && options.IgnoreError)
                    {
                        Trace.TraceInformation("Ignoring error message");
                        return;
                    }

                    if (IsKnownRecord(options, record))
                    {
                        Trace.TraceInformation("Ignoring known message");
                        return;
                    }

                    Trace.WriteLine($"Received event data.");

                    level = record.LevelDisplayName;
                    provider = record.ProviderName;

                    eventHtml += $"<div>MESSAGE: <br/>{HttpUtility.HtmlEncode(record.FormatDescription()).Replace("\n", "<br/>")}</div>";
                }
            }

            // This will be the email body text.
            string line1 = $"{level} message from {Environment.MachineName}";
            string line2 = $"    Source: {options.EventSource}/{provider}";
            string line3 = $"    EventRecordID: {options.EventId}";

            string messageText = $"<div>{HttpUtility.HtmlEncode(line1)}</div>";
            messageText += $"<div>&nbsp;&nbsp;&nbsp;&nbsp;{HttpUtility.HtmlEncode(line2)}</div>";
            messageText += $"<div>&nbsp;&nbsp;&nbsp;&nbsp;{HttpUtility.HtmlEncode(line3)}</div>";
            messageText += $"<div>&nbsp;</div>";
            messageText += eventHtml;

            // Send the email
            MailMessage message = new MailMessage();
            message.From = new MailAddress(options.EmailFrom.Trim());
            foreach (string emailTo in options.EmailTo.Split(',', ';'))
            {
                message.To.Add(new MailAddress(emailTo.Trim()));
            }
            message.Subject = $"{options.EventSource} Service {level} message #{options.EventId}";
            message.Body = messageText;
            message.IsBodyHtml = true;

            SmtpClient client = new SmtpClient(options.EmailSmtp);
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(options.EmailFrom, options.EmailFromPassword);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;
            client.Send(message);

            Trace.WriteLine($"Sent email to {options.EmailTo}.");
        }
예제 #23
0
        public static IEnumerable<ApplicationError> GetByDateTimeDescending(int max = 0)
        {
            var query = @"<QueryList>
                              <Query Id=""0"" Path=""Application"">
                                <Select Path=""Application"">*[System[Provider[@Name='ASP.NET 2.0.50727.0' or @Name='ASP.NET 4.0.30319.0'] and (Level=2 or Level=3 or Level=4)]]</Select>
                              </Query>
                            </QueryList>";

            var elq = new EventLogQuery("Application", PathType.LogName, query) {ReverseDirection = true};
            using (var elr = new EventLogReader(elq))
            {
                var events = new List<EventRecord>();

                max = (max == 0) ? int.MaxValue : max;
                var i = 0;
                var entries = 0;

                for (var eventInstance = elr.ReadEvent(); null != eventInstance && entries < max; eventInstance = elr.ReadEvent(), i++)
                {
                    var parsedEvent = ParseEntry(eventInstance);
                    if (parsedEvent != null && parsedEvent.SiteIisId != 0)
                    {
                        entries++;
                        yield return parsedEvent;
                    }
                }
            }
        }
예제 #24
0
        private void read_single_log_thread(log_info log) {
            string query_string = "*";
            if (provider_name != "")
                query_string = "*[System/Provider/@Name=\"" + provider_name + "\"]";

            int max_event_count = int.MaxValue;
            // debugging - load much less, faster testing
            if (util.is_debug)
                max_event_count = 250;

            try {
                // we can read the number of entres only for local logs
                if (provider_name == "" && log.remote_machine_name == "") {
                    var dummy_log = new EventLog(log.log_type);
                    lock(this)
                        log.full_log_count_ = dummy_log.Entries.Count;
                    dummy_log.Dispose();
                }

                // waiting for user to set the password
                if ( log.remote_machine_name != "")
                    while ( remote_password_ == "")
                        Thread.Sleep(100);

                SecureString pwd = new SecureString();
                foreach ( char c in remote_password_)
                    pwd.AppendChar(c);
                EventLogSession session = log.remote_machine_name != "" ? new EventLogSession(log.remote_machine_name, remote_domain_name, remote_user_name, pwd, SessionAuthentication.Default) : null;
                pwd.Dispose();

                EventLogQuery query = new EventLogQuery(log.log_type, PathType.LogName, query_string);
                query.ReverseDirection = reverse_;
                if ( session != null)
                    query.Session = session;

                EventLogReader reader = new EventLogReader(query);
                int read_idx = 0;
                for (EventRecord rec = reader.ReadEvent(); rec != null && !log.disposed_ && read_idx++ < max_event_count ; rec = reader.ReadEvent())
                    lock (this) {
                        log.last_events_.Add(rec);
                        ++log.cur_log_count_;
                    }

                lock (this)
                    log.listening_for_new_events_ = true;

                // at this point, listen for new events
                if (reverse_) {
                    // if reverse, I need to create another query, or it won't allow watching
                    query = new EventLogQuery(log.log_type, PathType.LogName, query_string);                
                    if ( session != null)
                        query.Session = session;                    
                }
				using (var watcher = new EventLogWatcher(query))
				{
					watcher.EventRecordWritten += (o, e) => {
                        lock(this)
                            log.new_events_.Add(e.EventRecord);
					};
					watcher.Enabled = true;

                    while ( !log.disposed_)
                        Thread.Sleep(100);
				}

            } catch (Exception e) {
                logger.Error("can't create event log " + log.log_type + "/" + remote_machine_name + " : " + e.Message);
                errors_.add("Can't create Log " + log.log_type + " on machine " + remote_machine_name + ", Reason=" + e.Message);
            }
            
        }
예제 #25
0
        public static IEnumerable<ApplicationError> GetBySite(int siteIisId, StatsRange range)
        {
            Int64 msLookback = 0;

            switch (range)
            {
                case StatsRange.LastMonth:
                    msLookback = 2592000000;
                    break;
                case StatsRange.LastWeek:
                    msLookback = 604800000;
                    break;
                case StatsRange.Last24Hours:
                    msLookback = 86400000;
                    break;
            }

            var query = string.Format(@"<QueryList>
                              <Query Id=""0"" Path=""Application"">
                                <Select Path=""Application"">*[System[Provider[@Name='ASP.NET 2.0.50727.0' or @Name='ASP.NET 4.0.30319.0'] and (Level=2 or Level=3){0}]]</Select>
                              </Query>
                            </QueryList>", (msLookback == 0) ? null : "and TimeCreated[timediff(@SystemTime) &lt;= " + msLookback + "]");

            var elq = new EventLogQuery("Application", PathType.LogName, query) { ReverseDirection = true};

            using (var elr = new EventLogReader(elq))
            {
                var events = new List<EventRecord>();
                for (var eventInstance = elr.ReadEvent(); null != eventInstance; eventInstance = elr.ReadEvent())
                {
                    if (eventInstance.Properties.Count() > 9 && eventInstance.Properties[8].Value.ToString().StartsWith("/LM/W3SVC/" + siteIisId + "/"))
                        events.Add(eventInstance);
                }
                return events.Select(ParseEntry);
            }
        }
예제 #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            DataTable datatable = new DataTable();

            datatable.Clear();
            DataRow datarow;

            datatable.Columns.Add("EventRecordID");
            datatable.Columns.Add("ProcessId");
            datatable.Columns.Add("ProcessName");
            datatable.Columns.Add("AccessList");
            datatable.Columns.Add("ObjectName");
            datatable.Columns.Add("TimeCreated");

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            watch.Start();
            //int count = 0;
            // int x = 0;
            var query = new EventLogQuery("C:\\Windows\\System\\winevt\\Logs\\Security.evtx", PathType.FilePath, "*[System/EventID=4663]");

            using (var reader = new System.Diagnostics.Eventing.Reader.EventLogReader(query))
            {
                List <EventRecord> eventList = new List <EventRecord>();
                for (EventRecord eventInstance = reader.ReadEvent();
                     null != eventInstance; eventInstance = reader.ReadEvent())
                {
                    eventInstance.FormatDescription();
                    if ((eventInstance.Id == 4663))
                    {
                        XmlDocument xmlDoc   = new XmlDocument();
                        String      eventXml = eventInstance.ToXml(); //we can read Event data from xml, Like xml file reading ;)


                        xmlDoc.LoadXml(eventXml);
                        XmlElement root = xmlDoc.DocumentElement;
                        XmlElement el   = (XmlElement)root.SelectSingleNode("Event");
                        xmlDoc.DocumentElement.SetAttribute("xmlns", "");
                        xmlDoc.LoadXml(xmlDoc.InnerXml);

                        datarow = datatable.NewRow();
                        XmlNode node_EventRecordID = xmlDoc.SelectSingleNode("Event/System/EventRecordID");
                        datarow["EventRecordID"] = node_EventRecordID.InnerText;

                        XmlNodeList nodeList = (xmlDoc.SelectNodes("Event/System/TimeCreated"));
                        foreach (XmlNode elem in nodeList)
                        {
                            datarow["TimeCreated"] = elem.Attributes["SystemTime"].Value;
                        }

                        XmlNode node_ProcessId = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='ProcessId']");
                        datarow["ProcessId"] = node_ProcessId.InnerText;

                        XmlNode node_ProcessName = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='ProcessName']");
                        datarow["ProcessName"] = node_ProcessName.InnerText;

                        XmlNode node_ObjectName = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='ObjectName']");
                        datarow["ObjectName"] = node_ObjectName.InnerText;

                        XmlNode node_AccessList = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='AccessList']");
                        if (node_AccessList.InnerText.Substring(0, 6) == "%%4423")
                        {
                            datarow["AccessList"] = "ReadAttributes";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%1538")
                        {
                            datarow["AccessList"] = "READ_CONTROL";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4416")
                        {
                            datarow["AccessList"] = "ReadData (or ListDirectory)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4416")
                        {
                            datarow["AccessList"] = "ReadData (or ListDirectory)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4417")
                        {
                            datarow["AccessList"] = "WriteData (or AddFile)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4418")
                        {
                            datarow["AccessList"] = "AppendData (or AddSubdirectory or CreatePipeInstance)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%1537")
                        {
                            datarow["AccessList"] = "DELETE";
                        }
                        else
                        {
                            datarow["AccessList"] = node_AccessList.InnerText;
                        }

                        datatable.Rows.InsertAt(datarow, 0);
                    }
                    //x = x + 1;
                }
            }
            dataGridView1.DataSource = datatable;
            timer1.Enabled           = true;
        }
예제 #27
0
        private string DisplayEventInformation(EventLogReader logReader)
        {
            StringBuilder rString = new StringBuilder();
            for (EventRecord eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                rString.AppendLine("------------------------------------------------------");
                rString.AppendLine("Event ID: " + eventInstance.Id.ToString());
                rString.AppendLine("Publisher: " + eventInstance.ProviderName);

                try
                {
                    rString.AppendLine("Description: " + eventInstance.FormatDescription());
                }
                catch (EventLogException)
                {

                }
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                rString.AppendLine("Container Event Log: " + logRecord.ContainerLog);
            }
            return rString.ToString();
        }
 // ReadLocal
 public EventRecord DisplayEventAndLogInformation(EventRecord eventInstance, string fileName, EventLogReader logReader)
 {
     eventInstance = logReader.ReadEvent();
     return eventInstance;
 }
        public GatherResult GatherLogs()
        {
            var logEntries = new List<dynamic>();

            var logQuery = string.Format(WindowsLogQuery, LastLogEntrySent.ToString("o"));
            var eventQuery = new EventLogQuery("Application", PathType.LogName, logQuery);
            var eventReader = new EventLogReader(eventQuery);
            var record = eventReader.ReadEvent();
            DateTime? lastLogEntryTime = null;
            while (record != null)
            {
                if (record.TimeCreated.HasValue && record.TimeCreated.Value.ToUniversalTime() > LastLogEntrySent)
                {
                    lastLogEntryTime = record.TimeCreated.Value.ToUniversalTime();
                }
                logEntries.Add(CreateDynamic(record));
                record = eventReader.ReadEvent();
            }

            return new GatherResult
                {
                    Logs = logEntries,
                    LastLogEntryTime = lastLogEntryTime
                };
        }
예제 #30
0
 private static IEnumerable<EventRecord> GetEventRecords(string logName)
 {
     var query = new EventLogQuery(logName, PathType.LogName) { ReverseDirection = true };
     using (var reader = new EventLogReader(query))
         for (var eventInstance = reader.ReadEvent(); eventInstance != null; eventInstance = reader.ReadEvent())
             yield return eventInstance;
 }
예제 #31
0
        public static void Main(string[] args)
        {
            int exitCode = 0;
            String path = "";
            String query = "*";
            bool reverseDirection = false;
            UInt32 count = UInt32.MaxValue;
            String format = "xml";
            PathType pathType =  PathType.LogName;

            try
            {
                //
                // Parse the command line.
                //
                if (args.Length == 0)
                {
                    Console.WriteLine("Error: No parameters provided.");
                    PrintUsage();
                    Environment.Exit(1);
                }
                if (args[0] == "/?" || args[0] == "-?")
                {
                    PrintUsage();
                    Environment.Exit(1);
                }

                path = args[0];
                char[] delimiters = {':'};

                for (int i=1 ; i < args.Length; i++)
                {
                    String option = args[i].Substring(1);
                    String[] words = option.Split(delimiters, 2);
                    words[0] = words[0].ToLower(CultureInfo.InvariantCulture);

                    switch (words[0])
                    {
                        case "logfile":
                        case "lf":
                            pathType = PathType.FilePath;
                            break;

                        case "query":
                        case "q":
                            query = words[1];
                            break;

                        case "reversedirection":
                        case "rd":
                            reverseDirection = true;
                            break;

                        case "count":
                        case "c":
                            count = Convert.ToUInt32(words[1], CultureInfo.InvariantCulture);
                            break;

                        case "format":
                        case "f":
                            format = words[1].ToLower(CultureInfo.InvariantCulture);
                            if (format != "text" && format != "xml")
                            {
                                throw (new Exception(String.Format(CultureInfo.InvariantCulture, "Unrecognized format option: {0}.", format)));
                            }
                            break;

                        default:
                            throw (new Exception( String.Format(CultureInfo.InvariantCulture, "Unrecognized parameter option: {0}.", words[0]) ));
                    }
                }

                //
                // Query the event log.
                //
                EventLogQuery queryObj = new EventLogQuery(path, pathType, query);
                queryObj.ReverseDirection = reverseDirection;
                queryObj.TolerateQueryErrors = true;  // Continue to read events even if an error occurs.

                EventLogReader reader = new EventLogReader(queryObj);
                TimeSpan timeout = new TimeSpan(0, 0, 5);

                EventRecord eventRecord = null;
                UInt32 eventsRead = 0;
                while (((eventRecord = reader.ReadEvent(timeout)) != null) && (eventsRead++ < count))
                {
                    if (format == "xml")
                    {
                        Console.WriteLine("\n" + eventRecord.ToXml());
                    }
                    else if (format == "text")
                    {
                        Console.WriteLine("Source:\t\t" + eventRecord.ProviderName);
                        Console.WriteLine("Description:\t" + eventRecord.FormatDescription() + "\n");
                    }
                }
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("You do not have the correct permissions. " +
                                  "Try re-running the sample with administrator privileges.\n" + e.ToString());
                exitCode = 1;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
                exitCode = 1;
            }
            Environment.Exit(exitCode);
        }
예제 #32
0
        //
        // ReadEvents helper.
        //
        private void ReadEvents(EventLogReader readerObj)
        {
            Int64 numEvents = 0;
            EventRecord evtObj = null;

            while (true)
            {
                try
                {
                    evtObj = readerObj.ReadEvent();
                }
                catch (Exception exc)
                {
                    WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null));
                    continue;
                }
                if (evtObj == null)
                {
                    break;
                }
                if (_maxEvents != -1 && numEvents >= _maxEvents)
                {
                    break;
                }

                PSObject outputObj = new PSObject(evtObj);

                string evtMessage = _resourceMgr.GetString("NoEventMessage");
                try
                {
                    evtMessage = evtObj.FormatDescription();
                }
                catch (Exception exc)
                {
                    WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null));
                }
                outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage));


                //
                // Enumerate the object one level to get to event payload
                //
                WriteObject(outputObj, true);
                numEvents++;
            }

            if (numEvents == 0)
            {
                string msg = _resourceMgr.GetString("NoMatchingEventsFound");
                Exception exc = new Exception(msg);
                WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null));
            }
        }
예제 #33
0
        private List<EventSummary> GetEvents(string query)
        {
            int numberOfEvents = 0;
            List<EventSummary> eventSummaries = new List<EventSummary>(100);
            EventSummary eventSummary;
            
            EventLogQuery logQuery = new EventLogQuery(eventFilters.log.ToString(), PathType.LogName, query);
            logQuery.Session = new EventLogSession(eventFilters.MachineName);
            EventLogReader logReader = new EventLogReader(logQuery);

            if (eventFilters.maxRecords < 100)
            {
                eventFilters.maxRecords = 100;
            }
            // For each event returned from the query
            for (EventRecord eventInstance = logReader.ReadEvent();
                    eventInstance != null;
                    eventInstance = logReader.ReadEvent())
            {

                try
                {
                    // Cast the EventRecord into an EventLogRecord to retrieve property values.

                    eventSummary = new EventSummary();
                    eventSummary.EventID = eventInstance.Id;
                    eventSummary.EventRecordID = eventInstance.RecordId;
                    eventSummary.Description = eventInstance.FormatDescription();
                    eventSummary.LevelDisplayName = ((LogLevel)eventInstance.Level).ToString();
                    eventSummary.LogLevel = eventInstance.Level;
                    eventSummary.ProviderName = eventInstance.ProviderName;
                    eventSummary.TimeCreated = eventInstance.TimeCreated;

                    eventSummaries.Add(eventSummary);
                    if (++numberOfEvents == eventFilters.maxRecords)
                    {
                        break;
                    }

                }
                catch (Exception e)
                {
                    Debug.Print("Couldn't render event!");
                    Debug.Print(string.Format("Exception: Event {0} may not have an XML representation \n\n", ++numberOfEvents));
                    Debug.Print(e.Message);
                }


            }
            return eventSummaries;
        }
예제 #34
0
        private static void LogTimeStamp(string direction)
        {
            Direction dir = Direction.In;

            if (direction.Trim().ToLowerInvariant() == "lock")
            {
                dir = Direction.Out;
            }

            TimeStamp stamp = new TimeStamp()
            {
                Direction = dir,
                Stamp     = DateTime.Now,
                User      = Environment.UserName
            };

            //EventHandling for EnergySave
            var                s = new System.Diagnostics.Eventing.Reader.EventLogReader("Microsoft-Windows-TaskScheduler/Operational"); //EventLog.GetEventLogs(".").ToArray();// Single(x => x.Log == "Application").Entries.OfType<EventLogEntry>().ToArray().Where(x=>x.EventID==1532);
            EventRecord        record;
            List <EventRecord> records = new List <EventRecord>();

            while ((record = s.ReadEvent()) != null)
            {
                if (record.Id == 108 && (string)record.Properties[0].Value == "\\__percip.io__energysave_pc")
                {
                    records.Add(record);
                }
            }
            string set = (string)Settings.Default["lastenergysave"];

            while (set != "" && records.First().ActivityId.ToString() != set)
            {
                records.RemoveAt(0);
            }

            int lastid = records.FindIndex(i => i.ActivityId.ToString() == set);
            TimeStampCollection col = null;

            if (File.Exists(dbFile))
            {
                try
                {
                    col = Saver.Load <TimeStampCollection>(dbFile);
                }
                catch (CryptographicException ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    Environment.Exit(2);
                }
            }
            else
            {
                col = new TimeStampCollection();
            }

            foreach (var rec in records)
            {
                if (rec.ActivityId.ToString() != set)
                {
                    TimeStamp repair = new TimeStamp()
                    {
                        Direction = Direction.Out,
                        Stamp     = rec.TimeCreated.GetValueOrDefault(),
                        User      = Environment.UserName
                    };
                    col.TimeStamps.Add(repair);
                }
            }
            Settings.Default.lastenergysave = records.Last().ActivityId.ToString();
            Settings.Default.Save();
            col.TimeStamps.Sort();
            col.TimeStamps.Add(stamp);
            Saver.Save(dbFile, col);
            Console.WriteLine("Saved: {0}|{1}|{2}", stamp.Stamp, stamp.User, stamp.Direction);
        }
예제 #35
0
파일: Program.cs 프로젝트: JimJinn/iTest
        /// <summary>
        /// Displays the event information and log information on the console for 
        /// all the events returned from a query.
        /// </summary>
        private void DisplayEventAndLogInformation(EventLogReader logReader)
        {
            for (EventRecord eventInstance = logReader.ReadEvent();
                null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                Console.WriteLine("-----------------------------------------------------");
                Console.WriteLine("Event ID: {0}", eventInstance.Id);
                Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);

                try
                {
                    Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                }
                catch (EventLogException)
                {
                    // The event description contains parameters, and no parameters were 
                    // passed to the FormatDescription method, so an exception is thrown.

                }

                // Cast the EventRecord object as an EventLogRecord object to 
                // access the EventLogRecord class properties
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog);
            }
        }
예제 #36
0
        private static void LogTimeStamp(string direction)
        {
            Direction dir = Direction.In;
            if (direction.Trim().ToLowerInvariant() == "lock")
                dir = Direction.Out;

            TimeStamp stamp = new TimeStamp()
            {
                Direction = dir,
                Stamp = DateTime.Now,
                User = Environment.UserName
            };

            //EventHandling for EnergySave
            var s = new System.Diagnostics.Eventing.Reader.EventLogReader("Microsoft-Windows-TaskScheduler/Operational"); //EventLog.GetEventLogs(".").ToArray();// Single(x => x.Log == "Application").Entries.OfType<EventLogEntry>().ToArray().Where(x=>x.EventID==1532);
            EventRecord record;
            List<EventRecord> records = new List<EventRecord>();
            while ((record = s.ReadEvent()) != null)
            {
                if (record.Id == 108 && (string)record.Properties[0].Value == "\\__percip.io__energysave_pc")
                {
                    records.Add(record);
                }

            }
            string set = (string)Settings.Default["lastenergysave"];
            while (set != "" && records.First().ActivityId.ToString() != set)
            {
                records.RemoveAt(0);
            }

            int lastid = records.FindIndex(i => i.ActivityId.ToString() == set);
            TimeStampCollection col = null;
            if (File.Exists(dbFile))
            {
                try
                {
                    col = Saver.Load<TimeStampCollection>(dbFile);
                }
                catch (CryptographicException ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    Environment.Exit(2);
                }
            }
            else
                col = new TimeStampCollection();

            foreach (var rec in records)
            {
                if (rec.ActivityId.ToString() != set)
                {
                    TimeStamp repair = new TimeStamp()
                    {
                        Direction = Direction.Out,
                        Stamp = rec.TimeCreated.GetValueOrDefault(),
                        User = Environment.UserName
                    };
                    col.TimeStamps.Add(repair);
                }
            }
            Settings.Default.lastenergysave = records.Last().ActivityId.ToString();
            Settings.Default.Save();
            col.TimeStamps.Sort();
            col.TimeStamps.Add(stamp);
            Saver.Save(dbFile, col);
            Console.WriteLine("Saved: {0}|{1}|{2}", stamp.Stamp, stamp.User, stamp.Direction);
        }
예제 #37
0
        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;
        }
예제 #38
0
파일: Coloma.cs 프로젝트: Robo210/Coloma
        private static void AddLogToList(List<ColomaEvent> list, DateTime dt, Dictionary<string, KBRevision> installedUpdates)
        {
            // this retrieves the build.revision and branch for the current client
            WindowsVersion.WindowsVersionInfo wvi = new WindowsVersion.WindowsVersionInfo();
            WindowsVersion.GetWindowsBuildandRevision(wvi);

            FirstBuild firstBuildEvent = new FirstBuild { index = 0, build = wvi.build };

            KBRevision currentKb = new KBRevision();
            uint currentBuild = wvi.build;

            Guid servicingProvider = new Guid("BD12F3B8-FC40-4A61-A307-B7A013A069C1");
            string structuredQuery = string.Format(System.Globalization.CultureInfo.InvariantCulture, Coloma.structuredQueryTemplate, dt.ToUniversalTime());

            EventLogQuery query = new EventLogQuery(null, PathType.LogName, structuredQuery);
            query.ReverseDirection = false;
            EventLogReader reader = new EventLogReader(query);
            // The Event Log can only return a maximum of 2 MB at a time, but it does not actually limit itself to this when collecting <BatchSize> events.
            // If the number of requested events exceeds 2 MB of event data an exception will be throw (System.Diagnostics.Eventing.Reader.EventLogException: The data area passed to a system call is too small).
            // Since an event is at most 64 KB, 30 events is a conservative limit to ensure the 2 MB limit is never crossed.
            // Setting a smaller batch size does have a small performance impact, but not enough to notice in this scenario.
            reader.BatchSize = 30;

            EventRecord entry;
            while ((entry = reader.ReadEvent()) != null)
            {
                var entryTimeCreated = entry.TimeCreated ?? DateTime.Now;
                var entryMachineName = entry.MachineName;
                var entryLogName = entry.LogName;
                var entryId = entry.Id;
                var entryProviderName = entry.ProviderName;

                string entryLevelDisplayName = "";
                try
                {
                    entryLevelDisplayName = entry.LevelDisplayName;
                }
                catch
                {
                    if (entry.Level != null) entryLevelDisplayName = ((StandardEventLevel) entry.Level).ToString();
                }

                string entryMessage = CleanUpMessage(entry.FormatDescription());
                if (entryMessage == null && entry.Properties.Count > 0)
                {
                    string entryProperties = String.Join(", ", entry.Properties.Select(p => String.Format("'{0}'", p.Value)));
                    entryMessage = String.Format(Coloma.descNotFoundMsgTemplate, entryId, entryProviderName, entryProperties);
                }

                if (entryId == 2 && entry.ProviderId.HasValue && entry.ProviderId.Value == servicingProvider)
                {
                    if (entry.Properties.Count == 5 && entry.Properties[2].Value.ToString() == "Installed")
                    {
                        string kb = entry.Properties[0].Value.ToString();

                        KBRevision KBRev;
                        if(installedUpdates.TryGetValue(kb, out KBRev))
                        {
                            // Update InstallDate with a more precise time
                            KBRev.InstallDate = entryTimeCreated;
                            KBRev.FoundInSetupLog = true;

                            currentKb = KBRev;
                        }
                        else
                        {
                            currentKb = new KBRevision { InstallDate = entryTimeCreated, Kb = kb, FoundInSetupLog = true };
                            installedUpdates.Add(kb, new KBRevision(currentKb));
                        }
                    }
                }
                else if (entryId == 6009 && entry.ProviderName == "EventLog")
                {
                    if (firstBuildEvent.index == 0 && entry.Properties.Count == 5)
                    {
                        uint.TryParse(entry.Properties[1].Value.ToString(), out currentBuild);

                        // If the boot event indicates an earlier build, remember it so we can set all the prior events to this build number
                        if (firstBuildEvent.build != currentBuild)
                        {
                            firstBuildEvent.index = list.Count + 1;
                            firstBuildEvent.build = currentBuild;
                        }
                        // Else the event indicates no build number change, so don't bother checking later boot events either
                        else
                        {
                            firstBuildEvent.index = -1;
                        }
                    }

                    // This event doesn't go into the log file
                    continue;
                }

                list.Add(new ColomaEvent(wvi.branch, currentBuild, currentKb, entryMachineName, DeviceId,
                    Environment.UserName, entryLogName, entryLevelDisplayName, entryId,
                    entryTimeCreated, entryProviderName, entryMessage));
            }

            IEnumerable<KBRevision> orderedUpdates = installedUpdates.Select(kb => kb.Value).OrderBy(kb => kb.InstallDate);
            IEnumerable<KBRevision> missingUpdates = orderedUpdates.Where(kb => !kb.FoundInSetupLog);
            IEnumerator<KBRevision> currentMissingEnum = missingUpdates.GetEnumerator(); currentMissingEnum.MoveNext();
            IEnumerator<KBRevision> nextInstalled = orderedUpdates.GetEnumerator(); nextInstalled.MoveNext();
            DateTime nextInstallTime = DateTime.Now;

            Action getNextInstallTime = new Action(() =>
            {
                if (nextInstalled.Current != null && currentMissingEnum != null && currentMissingEnum.Current != null)
                {
                    do
                    {
                        if (nextInstalled.Current.Kb == currentMissingEnum.Current.Kb)
                        {
                            if (nextInstalled.MoveNext())
                            {
                                nextInstallTime = nextInstalled.Current.InstallDate;

                                // Install times from WMI only include the date, so skip ahead to the next install that falls on a later date or has a more precise time from a setup event
                                while (!nextInstalled.Current.FoundInSetupLog && nextInstallTime >= currentMissingEnum.Current.InstallDate && nextInstallTime < currentMissingEnum.Current.InstallDate.AddDays(1))
                                {
                                    if (nextInstalled.MoveNext())
                                    {
                                        nextInstallTime = nextInstalled.Current.InstallDate;
                                    }
                                    else
                                    {
                                        nextInstallTime = DateTime.Now;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                nextInstallTime = DateTime.Now;
                                break;
                            }

                            break;
                        }
                    }
                    while (nextInstalled.MoveNext());
                }
            });

            getNextInstallTime();

            int fixupsRemaining = (firstBuildEvent.index > 0 ? 1 : 0) + (missingUpdates.Any() ? 1 : 0);

            foreach (var evt in list)
            {
                if (fixupsRemaining == 0)
                {
                    break;
                }

                // If there was a EventLog 6009 event with a different build number, go back and set all the events before it to have that build number
                // This is highly unlikely to ever happen under the current OS-swap upgrade mechanism because the logs get cleared during each upgrade
                if (firstBuildEvent.index > 0)
                {
                    firstBuildEvent.index--;
                    if (firstBuildEvent.index <= 0)
                    {
                        fixupsRemaining--;
                    }
                    else
                    {
                        evt.Build = firstBuildEvent.build;
                    }
                }

                // If there are installed KBs found via WMI that were not in the Setup log, go back and set all the events between the KB installation time
                // and the next KB installation time to use this KB number.
                if (currentMissingEnum != null && currentMissingEnum.Current != null)
                {
                    if (evt.TimeCreated >= currentMissingEnum.Current.InstallDate && evt.TimeCreated < nextInstallTime)
                    {
                        evt.MostRecentKb = new KBRevision(currentMissingEnum.Current);

                        // Since the installations times from WMI are only accurate to the day, append a * to the KB name for any events that fall on that day, to indicate uncertainty.
                        if (evt.TimeCreated >= evt.MostRecentKb.InstallDate && evt.TimeCreated < evt.MostRecentKb.InstallDate.AddDays(1))
                        {
                            evt.MostRecentKb.Kb += "*";
                        }
                    }
                    else if (evt.TimeCreated >= nextInstallTime)
                    {
                        if (currentMissingEnum.MoveNext())
                        {
                            getNextInstallTime();
                        }
                        else
                        {
                            currentMissingEnum = null;
                            fixupsRemaining--;
                        }
                    }
                }
            }
        }