Link to home
Start Free TrialLog in
Avatar of NewMom2Brandon
NewMom2Brandon

asked on

Help I am pulling hair out!!!! Stuck with Arraylists

  I have two problem areas which I marked below. The problem I am having is when searching my document for a certain phrase i.e "Search For Me". If it is found twice in the document it does the "iXMLErrorMsgIndex++;" setting it to 2. However the arraylist collections are showing 1. What can I do to solve this. I have tried so many things over 3 days and I am still having issues.

Thank you for you help

  //Check to see if the file exists
   if (File.Exists(sDirectory + sCurrentFileName))
   {    
       // Save any messages found in the error log.
      ArrayList CurrentErrorLogDateAL = new ArrayList();

     //Initialize the array lists containing the messages found in the errorlog.
     //Current Error Log File Date
     XmlNodeMessageChild = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.ErrorLogFileDate);
     CurrentErrorLogDateAL.Add(XmlNodeMessageChild.InnerText);

     // Get timestamp of Current errorlog file.
     DateTime dCurrentErrorLogFileDate = File.GetLastWriteTime(sDirectory + sCurrentFileName);
     String sCurrentErrorLogFileDate = dCurrentErrorLogFileDate.ToString
             ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
     dCurrentErrorLogFileDate = Convert.ToDateTime(sCurrentErrorLogFileDate).Date;

     if ((dCurrentErrorLogFileDate == dDayBefore) || (dCurrentErrorLogFileDate == dToday))
     {
           if (dDateTimeCurrent > dRunLast)
           {
                foreach (string sLogMsgLookingFor in LogMsgLookingFor)
     {
          bool bFound = false;

         //open the file for reading                                    
                    StreamReader objReader = new StreamReader(sDirectory + sCurrentFileName);

         string sCurrentLine = objReader.ReadLine();
         string sPreviousLine = "";
**********************************************************************************
    Should I really terminate this while loop if the log message you are looking for has been found?
    see next note). Could this be part of the index problem.? "bFound = true;
**********************************************************************************
         while(sCurrentLine != null)
         {
             if(sCurrentLine.IndexOf(sLogMsgLookingFor) > -1)
             {                                                            
                 if (sPreviousLine != null)
                 {      
                    bFound = true;
                 }
             }

             if (bFound == true)
             {                                                            
                 //Change previous line to when even happened time                                    
                 DateTime dErrorTime = Convert.ToDateTime(sPreviousLine).Date;
                 DateTime dPreviousLine = Convert.ToDateTime(sPreviousLine);
                String sErrorDateTime = dPreviousLine.ToString("dd-MMM-yyyy HH:mm:ss");

                 //Get the LogErrorTime from XML File
                XmlNode xmlLogErrorTime = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LogErrorTime);
                DateTime dLogErrorTime = Convert.ToDateTime(xmlLogErrorTime.InnerText);
                String sLogErrorTime = dLogErrorTime.ToString("dd-MMM-yyyy HH:mm:ss");    
               
               //Set the LastFoundTime to today in xml file.                                        
               XmlNode xmlNodeLastFoundTime = xmlNodeErrorLogMessage.SelectSingleNode (TAGS.LastFoundTime);
                  xmlNodeLastFoundTime.InnerText = dDateTimeCurrent.ToString
                                  ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);      

**********************************************************************************
if bFound == true twice (because "sLogMsgLookingFor" is in errorlog.txt twice), then iXMLErrorMsgIndex will = 2, and LastFoundTimeAL.Count will still = 1, causing the else block to be executed. I believe this is where the index error is happening. I don't know if it is happening else where since it stops here
**********************************************************************************
                 if(iXMLErrorMsgIndex < LastFoundTimeAL.Count)
                 {                                                                  
                      //Upgrade the array lists.
                        LastFoundTimeAL[iXMLErrorMsgIndex] = dDateTimeCurrent.ToString  
                                       ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);    
                  }
                  else
                  {
                          xmlError.InnerText =
                                      CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE + "LastFoundTimeAL";
                          xmlErrorTime.InnerText = dDateTimeCurrent.ToString  
                                     ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                   }
             
                   if ((dErrorTime == dToday) && (sErrorDateTime != sLogErrorTime))                            
                   {  
                         //Change from string to datetime to use
                           DateTime dTimeFromLog = Convert.ToDateTime(sPreviousLine);
           
                           //Set the LogErrorTime to what was found in the errlog.txt file for the error.
                            xmlLogErrorTime = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LogErrorTime);
                            xmlLogErrorTime.InnerText = dTimeFromLog.ToString
                              ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);
                                                                 
                            //Set LastErrorFoundIn to sCurrentFileName
                            XmlNode xmlLastErrorFoundIn = xmlNodeErrorLogMessage.SelectSingleNode                
                             (TAGS.LastErrorFoundIn);
                            xmlLastErrorFoundIn.InnerText = sCurrentFileName;

                            //Set LastSentTime to current date time.
                            XmlNode xmlLastSentTime = xmlNodeErrorLogMessage.SelectSingleNode  
                             (TAGS.LastSentTime);
                            xmlLastSentTime.InnerText = dDateTimeCurrent.ToString  
                                         ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                                                                 
                           //Set ErrorLogFileDate in XML
                           XmlNode xmlErrorLogFileDate = xmlNodeErrorLogMessage.SelectSingleNode    
                             (TAGS.ErrorLogFileDate);
                           xmlErrorLogFileDate.InnerText = sCurrentErrorLogFileDate;  

                if(iXMLErrorMsgIndex < LastSentTimeAL.Count)
                 {
                     // Upgrade the array lists.
                       LastSentTimeAL[iXMLErrorMsgIndex] = dDateTimeCurrent.ToString();
                 }                                                  
                 else                                                              
                {                                                                      
                      xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE    
                           + "LastSentTimeAL";
                     xmlMessageErrorTime.InnerText = dDateTimeCurrent.ToString                                                  
                         ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);                                  
                  }
         
                  if(iXMLErrorMsgIndex < LogErrorTimeAL.Count)
                  {
                       // Upgrade the array lists.
                        LogErrorTimeAL[iXMLErrorMsgIndex] = dTimeFromLog.ToString();
                  }
                 else                                                            
                {
              xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE + "LogErrorTimeAL";
                                xmlMessageErrorTime.InnerText = dDateTimeCurrent.ToString
                                          ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                }

                if(iXMLErrorMsgIndex < LastErrorFoundInAL.Count)
                {
                   // Upgrade the array lists.
                     LastErrorFoundInAL[iXMLErrorMsgIndex] = sCurrentFileName;
                }
                           else
                {
                    xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE  
                   + "LastErrorFoundInAL";
                     xmlMessageErrorTime.InnerText = dDateTimeCurrent.ToString
                         ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                }

               if(iXMLErrorMsgIndex < CurrentErrorLogDateAL.Count)
               { // Upgrade the array lists.
                      CurrentErrorLogDateAL[iXMLErrorMsgIndex] = dCurrentErrorLogFileDate.ToString();
                }
                else
                {
                 xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE
                      + "CurrentErrorLogDateAL";
                  xmlMessageErrorTime.InnerText =  dDateTimeCurrent.ToString
                       ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                }

                sDetails[0] = CONSTANTS.ERRORLOG_ERROR_FOUND;                                        
                sValues[0] =  "Error: " + sCurrentLine + " Error Occured at: " + sPreviousLine;
               iSeverityLevel = SEVERITYLEVELS.WARNING;

                //Update index into the array list.
               iXMLErrorMsgIndex++;
     }
     else if (sErrorDateTime == sLogErrorTime)
     {
          xmlError.InnerText = CONSTANTS.NO_NEW_ERRORLOG_ERRORS;
                    xmlErrorTime.InnerText = dDateTimeCurrent.ToString
                            ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  

                     //Sending an empty string so Client does not send a message
           sValues[0] = CONSTANTS.EMPTY_STRING;
     }
   }
     sPreviousLine = sCurrentLine;
     bFound = false;
     sCurrentLine = objReader.ReadLine();
          }//end while loop          
            objReader.Close();
        }
     }
  }
}
else
{
      xmlError.InnerText = ERROR.ERRORLOG_FILE_NOT_FOUND;
      xmlErrorTime.InnerText = dDateTimeCurrent.ToString            
           ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
}
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

I had a college professor that would get very mad if any program had procedures with >24 lines in them.  Now, I understand why.  It makes it very difficult to read.


Are you parsing an error log for a specific message?  What would a few of the lines in the file look like (not all of them if the file is large)?

It may be quite a bit easier to accomplish this task, but I need to make sure that I understand the requirement.

Bob
Avatar of NewMom2Brandon
NewMom2Brandon

ASKER

I am looking in an error log for a message that is defined in a XML file.

Believe me initially this was a short easy program...until the arraylist stuff had to be added. I am willing to try any other way.

the errlog sample would be this

___
June 1, 2005 1:24:31 PM
MESSAGE I AM SEARCHING FOR
line here
line here
line here
___
June 1, 2005 1:24:31 PM
Additional Message
line here
line here
line here
___
June 1, 2005 3:24:31 PM
MESSAGE I AM LOOKING FOR (second occurance possible)
line here
line here
line here
___


XML file is this

    <Type>ErrorLog Reader</Type>
    <RunEvery>1</RunEvery>
    <RunSpan>Hour</RunSpan>
    <RunLast>2001-01-01T00:00:00</RunLast>
    <LastSentTime>2001-01-01T00:00:00</LastSentTime>
    <!--THIS IS THE FILE INFORMATION -->
    <Directory>c:\\</Directory>
    <FileName>errlog.txt</FileName>
    <LastErrorTime>2001-01-01T00:00:00</LastErrorTime>
    <LastError></LastError>
    <ErrorLogMessage>
      <!-- Just add another whole ErrorLogMessage block
         and put the next MessageId consecutive i.e
         next would be 2..3..4 and so on.-->
      <MessageId>1</MessageId>
      <LogMsgLookingFor>Message I am Searching For</LogMsgLookingFor>
      <LastFoundTime>2001-01-01T00:00:00</LastFoundTime>
      <LogErrorTime>2001-01-01T00:00:00</LogErrorTime>
      <LastErrorFoundIn>errlog.txt</LastErrorFoundIn>
      <ErrorLogFileDate>2001-01-01T00:00:00</ErrorLogFileDate>
      <LastMessageErrorTime>2001-01-01T00:00:00</LastMessageErrorTime>
      <LastMessageError>
      </LastMessageError>
    </ErrorLogMessage>
  </Task>
</TaskConfiguration>
there is a potential for there to be two of the messages that I am searching for to be in the file with a small time difference between them say about a half hour.

So I only want to send 1 message out but to make sure the message that goes out is the one with the most recent occurance.
Hmm i wrote a search program once.

I discovered that the "filename" functions  contained the pathname as well. The Directory functions only had the the path name.

e.g

Directory: c:\yahoo\spam

File: C:\yahoo\spam\porn.jpg


Maybe this is a little too simply, but do you think you can simply create an array of strings to "house" each error code and then search through the string array?

also is LastFoundTimeAL.Count  a global variable? static?(if not maybe you shoudl make it that way)

The last peice i can offer right now is to just go ahead and scrap everything you have done and start over...maybe you will know what you did wrong :)

In all that code, is there something that I am missing?  Are you just reading in a log file, and searching for a particular phrase?  Or, are you looking for more information?

Bob

I am just reading in a text file. Searching for the one phrase that was entered via the XML file. Then once that line is found I am also pulling the line before it. The line before it contains the date and time that the error happend.

Prior to adding the Arraylist stuff. The code functioned correctly. It read the file and pulled the line before it. Everything went haywire the minute I added the Arraylist stuff. I don't know if maybe there is a way to do this with out adding the Arraylist stuff. The code still reads the errorlog the way it should I am just getting a exception...index must be non-negative and larger than the size of the collection.

See the way the code needs to function would be like this....

Right now every hour the code would run and check to see if the errorlog was written to. If it was then it would open the file and search for the "LogMsgLookingFor" (defined in the XML) say it would be "Broken Part A".  As soon as it finds it  then it would fill in XML detail listed below(****FILL IN THIS ONE). Then it would move on to the second message to search for "BROKEN PART B".

     <ErrorLogMessage>
      <!-- Just add another whole ErrorLogMessage block
         and put the next MessageId consecutive i.e
         next would be 2..3..4 and so on.-->
      <MessageId>1</MessageId>
      <LogMsgLookingFor>BROKEN PART A</LogMsgLookingFor>
      <LastFoundTime>2001-01-01T00:00:00</LastFoundTime>****FILL IN THIS ONE
      <LogErrorTime>2001-01-01T00:00:00</LogErrorTime>****FILL IN THIS ONE
      <LastErrorFoundIn>errlog.txt</LastErrorFoundIn>****FILL IN THIS ONE
      <ErrorLogFileDate>2001-01-01T00:00:00</ErrorLogFileDate>****FILL IN THIS ONE
      <LastMessageErrorTime>2001-01-01T00:00:00</LastMessageErrorTime>
      <LastMessageError>
      </LastMessageError>
    </ErrorLogMessage>
*****SECOND MESSAGE TO LOOK FOR
     <ErrorLogMessage>
      <!-- Just add another whole ErrorLogMessage block
         and put the next MessageId consecutive i.e
         next would be 2..3..4 and so on.-->
      <MessageId>1</MessageId>
      <LogMsgLookingFor>BROKEN PART B</LogMsgLookingFor>
      <LastFoundTime>2001-01-01T00:00:00</LastFoundTime>****FILL IN THIS ONE
      <LogErrorTime>2001-01-01T00:00:00</LogErrorTime>****FILL IN THIS ONE
      <LastErrorFoundIn>errlog.txt</LastErrorFoundIn>****FILL IN THIS ONE
      <ErrorLogFileDate>2001-01-01T00:00:00</ErrorLogFileDate>****FILL IN THIS ONE
      <LastMessageErrorTime>2001-01-01T00:00:00</LastMessageErrorTime>
      <LastMessageError>
      </LastMessageError>
    </ErrorLogMessage>

The problem I am running into is say BROKEN PART A is listed 2 times in the errorlog like this

___
June 2, 2005 1:24:31 PM
BROKEN PART A
line here
line here
line here
___
June 2, 2005 1:50:31 PM
BROKEN PART A (second occurance possible)
line here
line here
line here
___

The only one I am really concerned about is the second one "June 2, 2005 1:50:31 PM" This is the one that needs to be used. So the June 2nd date and time would be placed in the XML file and an email would be sent.


I put these in just to find out where the code was having problems which pin pointed to the LastFountTimeAL.Count. But I have a feeling it would stop at every one but since the first one was LastFoundTime it stops there.

              if(iXMLErrorMsgIndex < LastSentTimeAL.Count)
                 {
                     // Upgrade the array lists.
                       LastSentTimeAL[iXMLErrorMsgIndex] = dDateTimeCurrent.ToString();
                 }                                                  
                 else                                                              
                {                                                                      
                      xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE    
                           + "LastSentTimeAL";
                     xmlMessageErrorTime.InnerText = dDateTimeCurrent.ToString                                                  
                         ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);                                  
                  }
Is this a console application?

If it is please post ALL of the code you have.

If it is not a console app, go ahead and post ALL the code you have and also a little text at the end stating that you need Listbox1 named mylist..ect..

and after that post an example error log.
I don't see where iXMLErrorMsgIndex is defined or initialized.

Bob
I can not post all of the code...since it is a windows service and has multiple files but I can post the whole .cs file for this task..

There is an example of how the errorlog is set up listed in a previous post. It is took big of a file for me to put in here since it is constantly being written too.

Sorry if the alignment is not right. I added the code to the orginal post.

ErrorLogReader.cs
using System;
using System.Globalization;
using System.Xml;
using System.IO;
using System.Collections;
using Microsoft.Win32;
using QTI.Monitor.Configuration;
using System.Windows.Forms;

namespace QTI.Monitor.Tasks
{
    public class TaskErrorLogReader : TaskInterface
   {
        public void DoTask(XmlNode xmlNode, ref int iSeverityLevel,
      ref String[] sValues, ref String[] sDetails)
        {
      string sCurrentFileName = CONSTANTS.NULL;
      string sOldFileName = CONSTANTS.NULL;
      string sDirectory = CONSTANTS.NULL;
                  
      //Sending an empty string so Client does not send a message
      sValues[0] = CONSTANTS.EMPTY_STRING;

      //Today's date for comparisons
      System.DateTime dToday = System.DateTime.Today.Date;

      //Yesterday's date for comparisons
      System.DateTime dDayBefore = dToday.AddDays(-1);

      //Used to update the Date/Time in XML
      DateTime dDateTimeCurrent = DateTime.Now;

      //Get the RunLast from XML File
      XmlNode xmlRunLast = xmlNode.SelectSingleNode(TAGS.RunLast);
      DateTime dRunLast = Convert.ToDateTime(xmlRunLast.InnerText).Date;

      // Get directory from XML File
      XmlNode xmlDirectory = xmlNode.SelectSingleNode(TAGS.Directory);
      sDirectory = xmlDirectory.InnerText;

      //Get CurrentFileName (errorlog.txt) from XML File
      XmlNode xmlCurrentFileName = xmlNode.SelectSingleNode(TAGS.FileName);
      sCurrentFileName = xmlCurrentFileName.InnerText;

      //Get OldFileName (errorlog.txt.old) from XML File
      XmlNode xmlOldFileName = xmlNode.SelectSingleNode(TAGS.OldFileName);
      sOldFileName = xmlOldFileName.InnerText;

      //Get Message Error node from XML file
      XmlNode xmlMessageError = xmlNode.SelectSingleNode(TAGS.LastMessageError);

      //Get the Message Error Time node from XML file
      XmlNode xmlMessageErrorTime = xmlNode.SelectSingleNode (TAGS.LastMessageErrorTime);

      //Get Error node from XML file
      XmlNode xmlError = xmlNode.SelectSingleNode(TAGS.LastError);

      //Get the Error Time node from XML file
      XmlNode xmlErrorTime = xmlNode.SelectSingleNode(TAGS.LastErrorTime);
            
      try
      {
      // Save any messages found in the error log.
      ArrayList LastFoundTimeAL       = new ArrayList();
      ArrayList LastSentTimeAL        = new ArrayList();
      ArrayList LogErrorTimeAL        = new ArrayList();
      ArrayList LastErrorFoundInAL    = new ArrayList();
                        
      int iXMLErrorMsgIndex = 0;

      // Loop through all errorlog messages,saving any messages that are found in an array.
      XmlNodeList nodeListErrorMessages = xmlNode.SelectNodes(TAGS.ErrorLogMessage);
      foreach (XmlNode xmlNodeErrorLogMessage in nodeListErrorMessages)
      {
            // Message Id.
        XmlNode XmlNodeMessageChild = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.MessageId);
       double dXMLMessageId = 0;
       if (XmlNodeMessageChild.InnerText.Trim().Length > 0)
      {
             dXMLMessageId = Convert.ToDouble(XmlNodeMessageChild.InnerText);
      }

      // List for the Log message source.
      ArrayList LogMsgLookingFor = new ArrayList();
      XmlNodeList nodeListLogMsgLookingFor = xmlNodeErrorLogMessage.SelectNodes
               (TAGS.LogMsgLookingFor);
      foreach (XmlNode NodeLogMsgLookingFor in nodeListLogMsgLookingFor)
      {
         LogMsgLookingFor.Add(NodeLogMsgLookingFor.InnerText);
      }

      //Initialize the array lists containing the messages found in the errorlog.
                              
      //Last Found Time.
      XmlNodeMessageChild = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LastFoundTime);
      LastFoundTimeAL.Add(XmlNodeMessageChild.InnerText);

      //Last Sent Time
      XmlNodeMessageChild = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LastSentTime);
      LastSentTimeAL.Add(XmlNodeMessageChild.InnerText);

      //Log Error Time
      XmlNodeMessageChild = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LogErrorTime);
      LogErrorTimeAL.Add(XmlNodeMessageChild.InnerText);

      //Last Error Found In
      XmlNodeMessageChild = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LastErrorFoundIn);
      LastErrorFoundInAL.Add(XmlNodeMessageChild.InnerText);

  //Check to see if the file exists
   if (File.Exists(sDirectory + sCurrentFileName))
   {    
       // Save any messages found in the error log.
      ArrayList CurrentErrorLogDateAL = new ArrayList();

     //Initialize the array lists containing the messages found in the errorlog.
     //Current Error Log File Date
     XmlNodeMessageChild = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.ErrorLogFileDate);
     CurrentErrorLogDateAL.Add(XmlNodeMessageChild.InnerText);

     // Get timestamp of Current errorlog file.
     DateTime dCurrentErrorLogFileDate = File.GetLastWriteTime(sDirectory + sCurrentFileName);
     String sCurrentErrorLogFileDate = dCurrentErrorLogFileDate.ToString
             ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
     dCurrentErrorLogFileDate = Convert.ToDateTime(sCurrentErrorLogFileDate).Date;

     if ((dCurrentErrorLogFileDate == dDayBefore) || (dCurrentErrorLogFileDate == dToday))
     {
           if (dDateTimeCurrent > dRunLast)
           {
                foreach (string sLogMsgLookingFor in LogMsgLookingFor)
     {
          bool bFound = false;

         //open the file for reading                                    
                    StreamReader objReader = new StreamReader(sDirectory + sCurrentFileName);

         string sCurrentLine = objReader.ReadLine();
         string sPreviousLine = "";
**********************************************************************************
    Should I really terminate this while loop if the log message you are looking for has been found?
    see next note). Could this be part of the index problem.? "bFound = true;
**********************************************************************************
         while(sCurrentLine != null)
         {
             if(sCurrentLine.IndexOf(sLogMsgLookingFor) > -1)
             {                                                            
                 if (sPreviousLine != null)
                 {      
                    bFound = true;
                 }
             }

             if (bFound == true)
             {                                                            
                 //Change previous line to when even happened time                                    
                 DateTime dErrorTime = Convert.ToDateTime(sPreviousLine).Date;
                 DateTime dPreviousLine = Convert.ToDateTime(sPreviousLine);
                String sErrorDateTime = dPreviousLine.ToString("dd-MMM-yyyy HH:mm:ss");

                 //Get the LogErrorTime from XML File
                XmlNode xmlLogErrorTime = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LogErrorTime);
                DateTime dLogErrorTime = Convert.ToDateTime(xmlLogErrorTime.InnerText);
                String sLogErrorTime = dLogErrorTime.ToString("dd-MMM-yyyy HH:mm:ss");    
               
               //Set the LastFoundTime to today in xml file.                                        
               XmlNode xmlNodeLastFoundTime = xmlNodeErrorLogMessage.SelectSingleNode (TAGS.LastFoundTime);
                  xmlNodeLastFoundTime.InnerText = dDateTimeCurrent.ToString
                                  ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);      

**********************************************************************************
if bFound == true twice (because "sLogMsgLookingFor" is in errorlog.txt twice), then iXMLErrorMsgIndex will = 2, and LastFoundTimeAL.Count will still = 1, causing the else block to be executed. I believe this is where the index error is happening. I don't know if it is happening else where since it stops here
**********************************************************************************
                 if(iXMLErrorMsgIndex < LastFoundTimeAL.Count)
                 {                                                                  
                      //Upgrade the array lists.
                        LastFoundTimeAL[iXMLErrorMsgIndex] = dDateTimeCurrent.ToString  
                                       ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);    
                  }
                  else
                  {
                          xmlError.InnerText =
                                      CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE + "LastFoundTimeAL";
                          xmlErrorTime.InnerText = dDateTimeCurrent.ToString  
                                     ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                   }
             
                   if ((dErrorTime == dToday) && (sErrorDateTime != sLogErrorTime))                            
                   {  
                         //Change from string to datetime to use
                           DateTime dTimeFromLog = Convert.ToDateTime(sPreviousLine);
           
                           //Set the LogErrorTime to what was found in the errlog.txt file for the error.
                            xmlLogErrorTime = xmlNodeErrorLogMessage.SelectSingleNode(TAGS.LogErrorTime);
                            xmlLogErrorTime.InnerText = dTimeFromLog.ToString
                              ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);
                                                                 
                            //Set LastErrorFoundIn to sCurrentFileName
                            XmlNode xmlLastErrorFoundIn = xmlNodeErrorLogMessage.SelectSingleNode                
                             (TAGS.LastErrorFoundIn);
                            xmlLastErrorFoundIn.InnerText = sCurrentFileName;

                            //Set LastSentTime to current date time.
                            XmlNode xmlLastSentTime = xmlNodeErrorLogMessage.SelectSingleNode  
                             (TAGS.LastSentTime);
                            xmlLastSentTime.InnerText = dDateTimeCurrent.ToString  
                                         ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                                                                 
                           //Set ErrorLogFileDate in XML
                           XmlNode xmlErrorLogFileDate = xmlNodeErrorLogMessage.SelectSingleNode    
                             (TAGS.ErrorLogFileDate);
                           xmlErrorLogFileDate.InnerText = sCurrentErrorLogFileDate;  

                if(iXMLErrorMsgIndex < LastSentTimeAL.Count)
                 {
                     // Upgrade the array lists.
                       LastSentTimeAL[iXMLErrorMsgIndex] = dDateTimeCurrent.ToString();
                 }                                                  
                 else                                                              
                {                                                                      
                      xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE    
                           + "LastSentTimeAL";
                     xmlMessageErrorTime.InnerText = dDateTimeCurrent.ToString                                                  
                         ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);                                  
                  }
         
                  if(iXMLErrorMsgIndex < LogErrorTimeAL.Count)
                  {
                       // Upgrade the array lists.
                        LogErrorTimeAL[iXMLErrorMsgIndex] = dTimeFromLog.ToString();
                  }
                 else                                                            
                {
              xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE + "LogErrorTimeAL";
                                xmlMessageErrorTime.InnerText = dDateTimeCurrent.ToString
                                          ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                }

                if(iXMLErrorMsgIndex < LastErrorFoundInAL.Count)
                {
                   // Upgrade the array lists.
                     LastErrorFoundInAL[iXMLErrorMsgIndex] = sCurrentFileName;
                }
                           else
                {
                    xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE  
                   + "LastErrorFoundInAL";
                     xmlMessageErrorTime.InnerText = dDateTimeCurrent.ToString
                         ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                }

               if(iXMLErrorMsgIndex < CurrentErrorLogDateAL.Count)
               { // Upgrade the array lists.
                      CurrentErrorLogDateAL[iXMLErrorMsgIndex] = dCurrentErrorLogFileDate.ToString();
                }
                else
                {
                 xmlMessageError.InnerText = CONSTANTS.ERRORLOG_INDEX_OUT_OF_RANGE
                      + "CurrentErrorLogDateAL";
                  xmlMessageErrorTime.InnerText =  dDateTimeCurrent.ToString
                       ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
                }

                sDetails[0] = CONSTANTS.ERRORLOG_ERROR_FOUND;                                        
                sValues[0] =  "Error: " + sCurrentLine + " Error Occured at: " + sPreviousLine;
               iSeverityLevel = SEVERITYLEVELS.WARNING;

                //Update index into the array list.
               iXMLErrorMsgIndex++;
     }
     else if (sErrorDateTime == sLogErrorTime)
     {
          xmlError.InnerText = CONSTANTS.NO_NEW_ERRORLOG_ERRORS;
                    xmlErrorTime.InnerText = dDateTimeCurrent.ToString
                            ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  

                     //Sending an empty string so Client does not send a message
           sValues[0] = CONSTANTS.EMPTY_STRING;
     }
   }
     sPreviousLine = sCurrentLine;
     bFound = false;
     sCurrentLine = objReader.ReadLine();
          }//end while loop          
            objReader.Close();
        }
     }
  }
}
else
{
      xmlError.InnerText = ERROR.ERRORLOG_FILE_NOT_FOUND;
      xmlErrorTime.InnerText = dDateTimeCurrent.ToString            
           ("s",System.Globalization.DateTimeFormatInfo.InvariantInfo);  
}

 catch (Exception e)
 {
   System.Diagnostics.EventLog.WriteEntry(this.ToString(),
        ERROR.FAILED_TO_READ_ERROR_LOG + e.ToString(),
        System.Diagnostics.EventLogEntryType.Error);
   sValues[0] = ERROR.FAILED_TO_READ_ERROR_LOG;
   iSeverityLevel = SEVERITYLEVELS.INFORMATIONAL;
   m_iMsgNum = MESSAGENUMBERS.CODE_ERROR_FOUND;      

 }
}
  public  string GetMsgId() {return m_sMsgId;}
  public  int GetMsgNum() {return m_iMsgNum;}
  private static string m_sMsgId = MESSAGETYPES.ERROR_LOG_READER;
  private static int m_iMsgNum = MESSAGENUMBERS.ERROR_LOG_READER;
}
}


constants.cs

here are some of the things from the constants file. Sorry I can not post the whole thing way to large

public const string FAILED_TO_READ_ERROR_LOG
  = "Failed to read errlog.txt and errlog.txt.old.";
 public const string ERRORLOG_FILE_NOT_FOUND
 = "errlog.txt File Not Found";

//ErrorLogReader Tags
 public const string OldFileName            =  "OldFileName";
 public const string LogMsgLookingFor      =  "LogMsgLookingFor";
 public const string LastSentTime            =  "LastSentTime";
public const string LogErrorTime            =  "LogErrorTime";
public const string LastErrorFoundIn      =  "LastErrorFoundIn";
public const string ErrorLogFileDate      =  "ErrorLogFileDate";
public const string OldErrorLogFileDate      =  "OldErrorLogFileDate";
public const string ErrorLogMessage          =  "ErrorLogMessage";
public const string MessageId                      =  "MessageId";
public const string LastMessageError          =  "LastMessageError";
public const string LastMessageErrorTime    =  "LastMessageErrorTime";
public const string RunLast                         =  "RunLast";
public const string Directory                       =  "Directory";
public const string FileName                       =  "FileName";
public const string LastErrorTime                =  "LastErrorTime";
public const string LastError                        =  "LastError";
public const string NULL                              =  "null";
public const string EMPTY_STRING                 =  "";
public const string XML_INITIAL_DATE           = "2001-01-01T00:00:00";
public const string NO_NEW_ERRORLOG_ERRORS  = "No new errors in errlog";
public const string ERRORLOG_INDEX_OUT_OF_RANGE  = "Index out of Range must be non-negative and less than size of collection";
SOLUTION
Avatar of topdog770
topdog770
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Bob-

How should I do it if there are mulitple messages being searched for.
Add a While loop.  Also, I added the WordWrap = false, otherwise GetLineFromCharIndex returns incorrect values because of line wrapping.


    public void SearchForMessage(string path, string message)
    {

      // Create an instance of a RichTextBox to load a file
      // and search for text.
      RichTextBox rtfSearcher = new RichTextBox();

      // Clear word wrap so GetLineFromCharIndex returns correct value.
      rtfSearcher.WordWrap = false;

      // Load the log file.
      rtfSearcher.LoadFile(path, RichTextBoxStreamType.PlainText);

      // The date will be on the line previous to the found message.
      string messageLine = String.Empty;
      string dateLine = String.Empty;

      // Set the initial start position at the beginning.
      int start = 0;

      // Set the initial value to allow the While loop to work.
      int messageIndex = 0;

      // Search for all messages.
      while (messageIndex != -1 && start < rtfSearcher.Text.Length)
      {

        // Find the message starting at the current start index.
        messageIndex = rtfSearcher.Find(message, start, RichTextBoxFinds.NoHighlight);

        if (messageIndex != -1)
        {
          // The message was found, so get the text.

          // Convert the char index to a line number.
          int lineNumber = rtfSearcher.GetLineFromCharIndex(messageIndex);

          // Make sure the index is valid.
          if (lineNumber < rtfSearcher.Lines.Length)
          {
            // Get the message, and the date.
            messageLine = rtfSearcher.Lines[lineNumber];
            dateLine = rtfSearcher.Lines[lineNumber - 1];

            // Move the start position past the text already found.
            start += messageIndex + messageLine.Length;

          }

        }
 
      }

    }

Bob
Thank you for your help.

you guys got me really thinking about it.  I decided to try to remove all of the ArrayLists minus one

    ArrayList LogMsgLookingFor = new ArrayList();

So far the testing seems to be going good. I still have further testing to do. If what I have done does not work then Bobs solution will be the best next step.

Thanks again!!! I really appreciate your help and your sharing a little knowledge with a newbie!!