event log watcher

   Public Sub ApplicationLog_OnEntryWritten(ByVal [source] As Object, ByVal e As EntryWrittenEventArgs)

        'm_LogWatcherLog.WriteEntry("LogWacther:Application Log " & e.Entry.Message, EventLogEntryType.Information)

        'WriteFile(e.Entry.Message & vbCrLf & "---", "c:\temp\servicefailed.txt")

        'https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventID=4625

        If e.Entry.EventID = 4625 Then

            Dim y As Integer = 0

            'For Each x As String In e.Entry.ReplacementStrings

            WriteFile(y & ">>Account > " & e.Entry.ReplacementStrings(5) & vbCrLf, "c:\temp\servicefailed.txt")

            WriteFile(y & " >SourceIP> " & e.Entry.ReplacementStrings(19) & vbCrLf & "---", "c:\temp\servicefailed.txt")

            Dim sType As String = "?"

            Dim ent = FindEntry("(&(sAMAccountName=" & e.Entry.ReplacementStrings(5) & ")(objectClass=user))")

            'Dim dn = "" & ent.Properties("sAMAccountName").Value

            Try

                If ent IsNot Nothing Then

                    DictionaryAdd(dictValuesLDAP, e.Entry.ReplacementStrings(5), e.Entry.ReplacementStrings(19), Now)

                    sType = "AD"

                Else

                    DictionaryAdd(dictValues, e.Entry.ReplacementStrings(5), e.Entry.ReplacementStrings(19), Now)

                    sType = "NonAD"

                End If

                funSendMail("RDPGuardRichStyle@crouse.org", "richlemmermann@crouse.org", "#4625: " & sType, ">>Account > " & e.Entry.ReplacementStrings(5) & vbCrLf & " >SourceIP> "

                   e.Entry.ReplacementStrings(19) & vbCrLf & "---", False)


            Catch ex As Exception

                funSendMail("RDPGuardRichStyle@crouse.org", "richlemmermann@crouse.org", "#Error: ", ex.Message.ToString & vbCrLf & "---", False)

            End Try

        End If

        ' y += 1

        ' 5 = account

        ' 19 = source IP

        'Next

        'Status And Sub Status Codes     Description (Not checked against "Failure Reason:")

        '0xC0000064 user name does Not exist

        '0xC000006A user name Is correct but the password Is wrong

        '0xC0000234 user Is currently locked out

        '0xC0000072 account Is currently disabled

        '0xC000006F user tried to logon outside his day of week Or time of day restrictions

        '0xC0000070 workstation restriction, Or Authentication Policy Silo violation (look for event ID 4820 on domain controller)

        '0xC0000193 account expiration

        '0xC0000071 expired password

        '0xC0000133 clocks between DC And other computer too far out of sync

        '0xC0000224 user Is required to change password at next logon

        '0xC0000225 evidently a bug in Windows And Not a risk

        '0xc000015b The user has Not been granted the requested logon type (aka logon right) at this machine

    End Sub

    Sub StartWatch()

        WriteFile("Started (StartWatch): " & Now & " #" & Thread.CurrentThread.ManagedThreadId.ToString, "c:\temp\servicefailed.txt")

        m_ApplicationLog = New EventLog()

        m_ApplicationLog.Log = "Security"

        AddHandler m_ApplicationLog.EntryWritten, AddressOf ApplicationLog_OnEntryWritten

        m_ApplicationLog.EnableRaisingEvents = True

        While Not m_bMustStop

            Thread.Sleep(2000)

        End While

        WriteFile("Stopped (StartWatch): " & Now & " #" & Thread.CurrentThread.ManagedThreadId.ToString, "c:\temp\servicefailed.txt")

    End Sub

Folder/File watcher...Open File watcher


'This variable helps eliminate the duplicate/multiple firing of the event
Dim oRunningFiles As New Dictionary(Of String, Threading.Thread)

Dim oFileSystemADT As FileSystemWatcher

 Sub StartIt()
        oRunningFiles.Clear()
        dLastError = "1900-01-01 00:00:00"

        oFileSystemADT = New FileSystemWatcher("\\filepath\OneC_transagt_ADT$")
        AddHandler oFileSystemADT.Created, AddressOf OnCreated
        AddHandler oFileSystemADT.Changed, AddressOf OnChanged
        AddHandler oFileSystemADT.Error, AddressOf OnError
        oFileSystemADT.IncludeSubdirectories = True
        oFileSystemADT.EnableRaisingEvents = True
        Dim myFile = Directory.GetFiles("\\filepath\OneC_transagt_ADT$").OrderByDescending(Function(f) New FileInfo(f).LastWriteTime).First()
        If Len(myFile) > 0 Then
            'FunWatchFile(myFile)
            OnChanged(Nothing, New FileSystemEventArgs(WatcherChangeTypes.Changed, My.Computer.FileSystem.GetParentPath(myFile), Path.GetFileName(myFile)))

        Else
            oFileSystemADT.WaitForChanged(WatcherChangeTypes.Created Or
        WatcherChangeTypes.Changed)
        End If

    End Sub

  Public Sub OnCreated(ByVal source As Object, ByVal e As FileSystemEventArgs)
        'Console.WriteLine("File created: " & e.FullPath & " change type: " & e.ChangeType)
        'Dim oThread As Threading.Thread

        'oThread = New Threading.Thread(Sub() FunWatchFile(e.FullPath))
        'oThread.Name = e.FullPath
        'oThread.Start()
        'oThreads.Add(oThread)
        Console.WriteLine("File created: " & e.FullPath & " change type: " & e.ChangeType)
        OnChanged(source, e)
        'Dim oThread As Threading.Thread

        'oThread = New Threading.Thread(Sub() FunWatchFile(e.FullPath))
        'oThread.Name = e.FullPath
        'oThread.Start()
        'oThreads.Add(oThread)


    End Sub

        Private Sub OnError(source As Object, e As ErrorEventArgs)

        'If e.GetException.GetType() = TypeOf (InternalBufferOverflowException) Then

        '    txtResults.Text += "Error: File System Watcher internal buffer overflow at " + DateTime.Now + "\r\n"

        'Else

        '    txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "\r\n"
        'End If
        iErrorCount += 1
        RemoveHandler oFileSystemADT.Created, AddressOf OnCreated
        RemoveHandler oFileSystemADT.Changed, AddressOf OnChanged
        RemoveHandler oFileSystemADT.Error, AddressOf OnError
        funSendMail("MonitorADT@crouse.org""richlemmermann@crouse.org""MPF ADT OnError (live mode)""Going to restart the Handler momentarily. Error count =  " & iErrorCount & " minutes", False)

        oFileSystemADT.IncludeSubdirectories = False
        oFileSystemADT.EnableRaisingEvents = False
        oFileSystemADT.Dispose()

        Threading.Thread.Sleep(2000)

        StartIt()


    End Sub


    '    DateTime lastRead = DateTime.MinValue;

    'void OnChanged(Object source, FileSystemEventArgs a)
    '{
    '    DateTime lastWriteTime = File.GetLastWriteTime(Uri);
    '    If (lastWriteTime!= lastRead)
    '    {
    '        doStuff();
    '        lastRead = lastWriteTime;
    '    }
    '    // else discard the (duplicated) OnChanged event
    '}

    Dim lastRead = DateTime.MinValue


    Public Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
        ' oFileSystemADT.EnableRaisingEvents = False

        Console.WriteLine("File changed: " & e.FullPath & " change type: " & e.ChangeType)
        'Are we already processing it?
        '    DateTime lastWriteTime = File.GetLastWriteTime(Uri);
        Dim lastWriteTime As DateTime = File.GetLastWriteTime(e.FullPath)

        'If Not bAlreadyRUnning(e.FullPath) And Not bInProgress Then
        bInProgress = True
        'OnCreated(source, e)

        Dim oThread As Threading.Thread

        oThread = New Threading.Thread(Sub() FunWatchFile(e.FullPath))
        oThread.Name = e.FullPath
        Try
            Console.WriteLine("e.Name: " & e.Name)
            oRunningFiles.Add(e.Name, oThread)
            oThread.Start()
        Catch ex As Exception
            Console.WriteLine("** Dup? " & e.FullPath)

        End Try
        '  oFileSystemADT.EnableRaisingEvents = True

        'oThreads.Add(oThread)


        bInProgress = False
        lastRead = lastWriteTime

        'bInProgress
        'Threading.Thread.Sleep(1000)

        '  End If
    End Sub



    Function FunWatchFile(sFile As String)
        Console.WriteLine("Watching: " & sFile)
        'While IsFileOpen(New FileInfo(sFile))
        '    Threading.Thread.Sleep(2000)

        'End While
        'If bAlreadyRUnning(sFile) Then
        '    Console.WriteLine("Duplicate, returning")
        '    Return ""
        'End If


        Dim sLastFile As String = ""

        Try

            Using reader As StreamReader = New StreamReader(New FileStream(sFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                Console.WriteLine("sFile: " & sFile)
                Dim lastMaxOffset As Long = reader.BaseStream.Length
                lastMaxOffset = reader.BaseStream.Length
                While True And Not bSelfDestruct
                    System.Threading.Thread.Sleep(100)
                    If (reader.BaseStream.Length = lastMaxOffset) Then
                    Else
                        reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin)
                        '        //read out of the file until the EOF
                        Dim line As String = ""

                        Do
                            line = reader.ReadLine()




                            If InStr(line, "no mapping d", CompareMethod.Text) > 0 Then
                                'funSendMail("MonitorADT@crouse.org", "richlemmermann@crouse.org", "MPF ADT Error (debug mode)", "", False)
                                Console.WriteLine("RTL> " & line)
                                If dLastError = "1900-01-01 00:00:00" Then dLastError = Now

                                If DateDiff(DateInterval.Minute, dLastNotified, Now) > iNotifiyInMins Then
                                    funSendMail("MonitorADT@crouse.org""dlrevcycle@crouse.org;dlitinterfaces@crouse.org;dlsysadmin@crouse.org;dlithelpdesk@crouse.org""MPF ADT Error (live mode)""Hi all" & vbCrLf & "   This message is saying that there is a problem with the ADT feed and OneContent. Server is: 'CRH19VMPFagent1' and Service is: 'OneC_transagt_ADT'" & vbCrLf & vbCrLf & "  Please restart that service so that the error clears." & vbCrLf & "** If service hangs, run from Admin Command Prompt = 'taskkill /F /IM transagt.exe'" & vbCrLf & vbCrLf & "Interfaces will have to replay the ADT" & vbCrLf & vbCrLf & "Mel's team can provide the pertinent information" & vbCrLf & vbCrLf & "Line that started this is: " & vbCrLf & vbCrLf & line & vbCrLf & vbCrLf & "FileName: " & sFile & vbCrLf & vbCrLf & "First Error Time: " & dLastError & vbCrLf & vbCrLf, False)
                                    dLastNotified = Now

                                Else
                                End If

                            ElseIf InStr(line, "0:INFO Transaction Agent Stopped", CompareMethod.Text) > 0 Then
                                dLastError = "1900-01-01 00:00:00"

                            End If

                            If InStr(line, "0:TRANEND", CompareMethod.Text) > 0 Then
                                Console.WriteLine("RTL> " & Path.GetFileName(sFile) & "," & line)
                            End If
                            'Loop While Len(line) > 0 And Not bSelfDestruct
                            oListOfLinesForWebPage.Add(line)

                        Loop While Not reader.EndOfStream And Not bSelfDestruct


                        lastMaxOffset = reader.BaseStream.Position
                        iListOffset = lastMaxOffset

                        '            Console.WriteLine(line);
                        'If InStr(line, "0:TRANEND", CompareMethod.Text) > 0 Then
                        '    Console.WriteLine("RTL#2> " & Path.GetFileName(sFile) & "," & line)
                        'End If

                    End If
                End While


            End Using
        Catch ex As Exception
            Console.WriteLine("** Error (" & sFile & "): " & ex.Message.ToString)
        End Try

        '    Using (StreamReader reader = New StreamReader(New FileStream(fileName, 
        '                     FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) )
        '{
        '    //start at the end of the file
        '    Long lastMaxOffset = reader.BaseStream.Length;

        '    While (True)
        '    {
        '        System.Threading.Thread.Sleep(100);

        '        //if the file size has Not changed, idle
        '        If (reader.BaseStream.Length == lastMaxOffset)
        '    Continue Do;

        '        //seek to the last max offset
        '        reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);

        '        //read out of the file until the EOF
        '        String line = "";
        '        While ((line = reader.ReadLine())!= null)
        '            Console.WriteLine(line);

        '        //update the last max offset
        '        lastMaxOffset = reader.BaseStream.Position;
        '    }
        '}
        Console.WriteLine("**Thread Aborting: " & Threading.Thread.CurrentThread.ManagedThreadId)
        'This line causes a crash. Cannot reset the name
        'Threading.Thread.CurrentThread.Name = "Aborted: " & Now
        Threading.Thread.CurrentThread.Abort()

    End Function