Tuesday, August 19, 2008

Windows Event Helper C# "Integration with EventLog"

for the people whom need to control and watch windows event viewer its to hard to watch all windows event.we will try to find solution to get only the error entry and avoid to open all category and know more about event viewer.
There is to important logs in windows event viewer one of it called System and the other category called Application logs all event whether the entry type is Error or SuccessAudit , there is a lot of event entry type we will discuss it in this article.
Here we will use important namespace called "System.Diagnostics" which  namespace provides classes that allow you to interact with system processes, event logs, and performance counters.
From this namespace we will expose The EventLog component which provides functionality to write to event logs, read event log entries, and create and delete event logs and event sources on the network. The EntryWrittenEventHandler provides a way to interact with event logs asynchronously. Supporting classes provide access to more detailed control, including: permission restrictions, the ability to specify event log types (which controls the type of default data that is written with an event log entry), and iterate through collections of event log entries. For more information about these tasks, see the EventLogPermission, EventLogEntryType, and EventLogEntryCollection classes.
Windows Event Helper ver1.0 :
1- Create a simple class called EventItem to help us in serialize the event entry details: this class will be as this example:

public class EventItem
 {
     private string  _Category;
     public string  Category
     {  get { return _Category; }set { _Category = value; }   }
    private string _Data;
    public string Data
    {  get { return _Data; }set { _Data = value; }   }
    private string _EntryTypr;
    public string EntryType
    { get { return _EntryTypr; } set { _EntryTypr = value; }}
    private string _InstancedId;
    public string MyProperty
    { get { return _InstancedId; }set { _InstancedId = value; } }
    private string _MachineName;
    public string MachineName
    {get { return _MachineName; } set { _MachineName = value; }}
    private string _Message;
    public string Message
    { get { return _Message; }set { _Message = value; }}
    private string _ReplacemetString;
    public string ReplacemetString
    {get { return _ReplacemetString; } set { _ReplacemetString = value; } }
    private string _Source;
    public string Source
    { get { return _Source; } set { _Source = value; }}
    private DateTime _TimeGenerated;
    public DateTime TimeGenerated
    {get { return _TimeGenerated; } set { _TimeGenerated = value; } }
    private DateTime _TimeWritten;
    public DateTime TimeWritten
    {get { return _TimeWritten; } set { _TimeWritten = value; }  }
    private string _UserName;
    public string UserName
    {get { return _UserName; } set { _UserName = value; }      }
 }

2-our main class is WindowsEventHelper Contain the main functionality of our solution:
a) Connect with Windows Event logs and get all Logs

public EventLog[] GetAllLogs()
        {  return EventLog.GetEventLogs(); // or return EventLog.GetEventLogs("Machine Name");}

This method use EventLog Class to Creates an array of the event logs.
GetEventLogs()
Searches for all event logs on the local computer and creates an array of EventLog objects that contain the list.
GetEventLogs(String)
Searches for all event logs on the given computer and creates an array of EventLog objects that contain the list.

b) Create method to get specific Logs with a specific LogDisplayName

public EventLogEntryCollection GetLogCollection(string logDisplayName)
       {
           foreach (EventLog evLog in GetAllLogs())
           {               
               if (evLog.LogDisplayName ==  logDisplayName)
                   return evLog.Entries;
           }
           return null;
       }

// Log Display Name Can be :
     ///////////////////////////////////////////////////////////////////////////////////
     //Application-Internet Explorer - Microsoft Office Diagnostics - Microsoft Office Sessions
     // Security -  System
     //--------------------------------------------------------------------------------
     // the most important for me in this case is Application and System

c) we need now to collect event entry in a given date and from a specific type , .net help us in this case with enum called EventLogEntryType contain all entry types.

public List<EventItem> GetLogEntryList(string logDisplayName, EventLogEntryType eventLogEntryType)
       {
           List<EventItem> EventItemList = new List<EventItem>();
           EventLogEntryCollection logColection =  GetLogCollection(logDisplayName) ; 
 
           foreach (EventLogEntry logEntry in logColection)
           {
               if (logEntry.TimeWritten.Date == DateTime.Today.Date)
               {
                   if (logEntry.EntryType == eventLogEntryType)
                   {
                       EventItem eventItem = new EventItem();
                       eventItem.Category = logEntry.Category;
                       eventItem.Data = Encoding.ASCII.GetString(logEntry.Data);
                       eventItem.EntryType = "" + logEntry.EntryType;
                       eventItem.MachineName = logEntry.MachineName;
                       eventItem.Message = logEntry.Message;
                       foreach (string rMsg in logEntry.ReplacementStrings)
                       {
                           eventItem.ReplacemetString += rMsg;
                       }
                       eventItem.Source = logEntry.Source;
                       eventItem.TimeGenerated = logEntry.TimeGenerated;
                       eventItem.TimeWritten = logEntry.TimeWritten;
                       eventItem.UserName = logEntry.UserName;
 
                       EventItemList.Add(eventItem);
                   }
               }
           }
           if (EventItemList.Count > 0)
               return EventItemList;
 
           return null;
       }

now we have a list of error entity help you to reduce your time we will in our Administration helper trying to use this to make it more useful by sending mail to the administrator with error only but now I make a method to serialize these error objects and expose it in XML.

public void GetEventLogFile(string logDisplayName, EventLogEntryType eventLogEntryType)
        {
            if (GetLogEntryList(logDisplayName, eventLogEntryType) != null)
            {
                List<EventItem> eventItems = GetLogEntryList(logDisplayName, eventLogEntryType);
                XmlSerializer xmlSerializer = new XmlSerializer(eventItems.GetType());
              
                StreamWriter sw = new StreamWriter("e:\\log.xml") ; 
                xmlSerializer.Serialize(sw , eventItems) ; 
            }
        }
hope this be useful for you and send me your ideas in the subject.