Howto get a Windows eventlog EventID

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

LVL 1
pyrokinAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
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
pyrokinAuthor Commented:
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
Bob LearnedCommented:
Why do you think that the event ID should be 59?

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

Open in new window

0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

pyrokinAuthor Commented:
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
Bob LearnedCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bob LearnedCommented:
Sample usage:

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

Bob
0
pyrokinAuthor Commented:
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
Bob LearnedCommented:
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
pyrokinAuthor Commented:
Can you recommend any zones to figure out how to get this to work with the Eventlog dotnet component?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.