[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

Howto get a Windows eventlog EventID

Posted on 2008-02-04
9
Medium Priority
?
4,772 Views
Last Modified: 2013-12-17
Hello,

   I need to get the Eventlog EventID out of the InstanceID. Below is some code I found that does it perfectly, but sometimes it does not return the correct value. Does this code look right?
private void ValidateEventID (long instanceID)
		{
			int eventID = GetEventID (instanceID);
			if (eventID < ushort.MinValue || eventID > ushort.MaxValue)
				throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
					"Invalid eventID value '{0}'. It must be in the range between"
					+ " '{1}' and '{2}'.", instanceID, ushort.MinValue, ushort.MaxValue));
		}
 
		internal static int GetEventID (long instanceID)
		{
			long inst = (instanceID < 0) ? -instanceID : instanceID;
 
			// MSDN: eventID equals the InstanceId with the top two bits masked
			int eventID = (int) (inst & 0x3fffffff);
			return (instanceID < 0) ? -eventID : eventID;
		}

Open in new window

0
Comment
Question by:pyrokin
  • 5
  • 4
9 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20823449
You would need to show where this fails to work, because it worked for me.  Also, I have learned that just because the EventLogEntry.EventId property is marked as Obsolete, you can still use it (since it is just a warning).

Test code:
           Dictionary<string, EventLog> logList = new Dictionary<string, EventLog>();
            foreach (EventLog log in EventLog.GetEventLogs())
                logList.Add(log.LogDisplayName, log);
 
            foreach (EventLogEntry entry in logList["Application"].Entries)
            {
                long instanceID = entry.InstanceId;
                long eventID = entry.EventID;
                long calculatedEventID = entry.InstanceId & 0x3fffffff;
                if (eventID != calculatedEventID)
                    Console.WriteLine("{0}, {1}, {2}", eventID, instanceID, calculatedEventID);
            }

Open in new window

0
 
LVL 1

Author Comment

by:pyrokin
ID: 20823678
TheLearnedOne,

  When the InstanceID = 1101, I get 1101. When the InstanceID = 3223978043, I get
2752571, when the eventid should be "59".  What is interesting is that the EventID property returns 2752571 as well. Any Ideas?

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20823838
Why do you think that the event ID should be 59?

Bob
Binary math:
 
11000000001010100000000000111011
00111111111111111111111111111111
--------------------------------
00000000001010100000000000111011 = 2752571

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
LVL 1

Author Comment

by:pyrokin
ID: 20825030
When I look in the eventlog and match the event text, TimeGen, Source, Type, etc. The EventID in the EventViewer is "59", also aren't eventIDs suppose to be between 0-65535?
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 20825287
Yeah, that is true.  You could use WMI to get event log information:
using System;
using System.Collections.Generic;
using System.Management;
 
public class Win32_NTLogEvent
{
 
    public enum EventType
    {
        Unknown,
        Error,
        Warning,
        Information,
        SecurityAuditSuccess,
        SecurityAuditFailure
    }
 
    public int Category;
    public string CategoryString = "";
    string ComputerName = "";
    public int EventCode;
    public long EventIdentifier;
    public string Message = "";
    public int RecordNumber;
    public string SourceName = "";
    public DateTime TimeWritten;
    public string User = "";
    public EventType Type;
 
    public static List<Win32_NTLogEvent> GetList(string logName)
    {
 
        string queryString = string.Format("Select * from Win32_NTLogEvent where LogFile='{0}' ", logName);
 
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(queryString);
 
        List<Win32_NTLogEvent> list = new List<Win32_NTLogEvent>();
 
        foreach (ManagementObject obj in searcher.Get())
        {
 
            Win32_NTLogEvent entry = new Win32_NTLogEvent();
 
            entry.Category = int.Parse(obj["Category"].ToString());
 
            if (obj["CategoryString"] != null)
            {
                entry.CategoryString = obj["CategoryString"].ToString();
            }
 
            entry.ComputerName = obj["ComputerName"].ToString();
            entry.EventCode = int.Parse(obj["EventCode"].ToString());
            entry.EventIdentifier = long.Parse(obj["EventIdentifier"].ToString());
            entry.Message = obj["Message"].ToString();
            entry.RecordNumber = int.Parse(obj["RecordNumber"].ToString());
            entry.SourceName = obj["SourceName"].ToString();
            entry.TimeWritten = ConvertTime(obj["TimeWritten"].ToString());
            entry.Type = (EventType)int.Parse(obj["EventType"].ToString());
 
            list.Add(entry);
        }
 
        return list;
    }
 
    private static DateTime ConvertTime(string time)
    {
        time = time.Remove(time.LastIndexOf('-'));
        return DateTime.ParseExact(time, "yyyyMMddHHmmss.ffffff", null);
    }
}

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20825290
Sample usage:

            List<Win32_NTLogEvent> list = Win32_NTLogEvent.GetList("Application");

Bob
0
 
LVL 1

Author Comment

by:pyrokin
ID: 20837114
TheLearnedOne,

   Thanks for the info. After using your example code I get the correct EventID for the entry in question. Is there any chance of getting this info from Eventlog InstanceID? Is this normal?
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20840844
I would have to do some more investigation.  I don't go into that much detail with event log processing.  I am more of a WMI guy, so I don't go beyond what is already working for me (unless I have to).

Bob
0
 
LVL 1

Author Closing Comment

by:pyrokin
ID: 31427774
Can you recommend any zones to figure out how to get this to work with the Eventlog dotnet component?
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
The PowerShell Core 6.0 of .NET release is just the beginning. The upcoming PowerShell Core 6.1 would have artificial intelligence and internet of things capabilities. So many things to look forward to in the upcoming release.
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

612 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question