VB.Net: Impersonation in a threaded Class with Param

Imports System.Security.Principal

Module SimplePerformanceMonitor

    'Sub Main is the starting point

    'of the application and starts the thread.

    Public lstServers As New SortedList

    Public iAlertThreshold As Integer = 50

    Public bStop As Boolean = False

    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal un As String, ByVal domain As String, ByVal pw As String, ByVal LogonType As Integer, ByVal LogonProvider As Integer, ByRef Token As IntPtr) As Boolean

    Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

    Sub Main()

        Dim serv As New PerfMonCall

        Dim TH1 As System.Threading.Thread

        subReadFile()  'READS a file, having 1 server per line to monitor

        For Each i As String In lstServers.Keys()

            If i.Trim.Length > 0 Then

                'Console.WriteLine("Starting: " & i.ToString)


                'Since we have params, we must instantiate the class,

                 pass it the server and then thread on the instantiated object

                serv = New PerfMonCall

                serv.server = i.Trim.ToString  '"crh0s19"

                'This sets up a global variable thread

                TH1 = New _

                  System.Threading.Thread(AddressOf serv.DoServiceCall) 'Start our thread


            End If


    End Sub

    Public Sub PerformancMonitor(server As String)

        Dim bForever As Boolean = False

        Dim iFrequency As Integer = 1000

        Dim pCounter As System.Diagnostics.PerformanceCounter


        '***These variables can be interchanged depending

        '   on which performance object to watch. ***

        '***Open the windows performance monitor, right click

        '   and add counter to see a list of options.***


        Dim tokenHandle As New IntPtr(0)

        '' generate our idenity once

        Dim identity As WindowsIdentity = Login(tokenHandle)  ' LOGIN Using the impersonation, Admin Account

        identity.Impersonate()  'Start the impersonation


        'This is the Perfomance Object.

        Dim sCategory As String = "MSMQ Queue"

        'This represents the counter

        Dim sCounter As String = "Messages in Queue"

        'This represents the instance of the counter

        Dim sInstance As String = "\private$\stentorin"

        Dim Sample As System.Diagnostics.CounterSample


        'Setting up the performance counter.

        pCounter = New PerformanceCounter

        pCounter.CategoryName = sCategory

        pCounter.CounterName = sCounter

        pCounter.MachineName = server.ToString

        pCounter.InstanceName = pCounter.MachineName.ToString & sInstance

        'Sets the baseline


        Sample = pCounter.NextSample

        'This is an endless loop controlled by the thread TH1

        Console.WriteLine("Starting Server: " & pCounter.MachineName.ToString)

        Do While bForever = False And bStop = False


                'Retrieves the calculated data.

                Dim nv As Single = pCounter.NextValue()

                'Retrieves the Raw data

                Dim Sample2 As CounterSample = pCounter.NextSample()

                'Keeps rolling avg

                Dim avg As Single = CounterSample.Calculate(Sample, Sample2)

                Console.WriteLine(pCounter.MachineName.ToString & " is " & sCategory.ToString & " = " & nv.ToString & " -- " &

                                  "Avg %  = " & avg.ToString &

                                  " , " & Date.Now.ToString)

            Catch e As Exception

                Console.WriteLine(pCounter.MachineName.ToString & " " & e.Message.ToString)


                Threading.Thread.Sleep(5 * 60000) ' Wait 5 minutes before allowing thread to continue

            End Try

            Threading.Thread.Sleep(10000) 'Sleep for 10 seconds

            'Pauses loop for 1 second.



    End Sub

    Public Class PerfMonCall  ' This is the wrapper class for when you have params to pass in

        Public server As String  'This var is passed in by the instatatiated object before

                                 'it is threaded

        Public Sub DoServiceCall() 'Threaded function

            Call PerformancMonitor(server)

        End Sub

        Public Sub New()

        End Sub

    End Class

    Sub subReadFile()

        Dim sLines As String = vbCrLf & System.IO.File.ReadAllText("\\cswis001\il\YOUR TABLE HERE\tools\iSiteMonitor_ServiceRestart\allowed.txt")

        Dim sLine As String = ""

        '#The format is:



        'Services    c:\windows\system32\mmc.exe    c:\windows\system32\services.msc    c:\windows\system32

        'EventViewer    c:\windows\system32\mmc.exe    c:\windows\system32\eventvwr.msc    c:\windows\system32

        'Notepad    C:\Windows\System32\notepad.exe        c:\


        For Each sLine In sLines.Split(vbCrLf)


            Debug.Print("[" & sLine & "]")

            If sLine.Length > 0 Then

                lstServers.Add(sLine.Trim.ToString, sLine.Trim.ToString)

            End If


        Console.WriteLine("# Servers to Monitor: # " & lstServers.Count)

    End Sub

    Sub WriteFile(sText As String, sFile As String)


            If System.IO.File.Exists("c:\temp\logme") Then

                System.IO.File.AppendAllText(sFile.ToString, sText.ToString & vbCrLf)

            End If


        End Try

    End Sub

    Public Function Login(ByVal tokenHandle As IntPtr) As WindowsIdentity

        '' initialize it

        Dim identity As WindowsIdentity = Nothing


            '' generate our identity and set it if it works

            If LogonUser("<admin account>", "domain", "<admin password", 2, 0, tokenHandle) Then

                identity = New WindowsIdentity(tokenHandle)


                Debug.Print("!! LOG ON FAILED")

            End If

        Catch ex As UnauthorizedAccessException

            Debug.Print("!! UNAUTHORIZED: " + ex.Message())

        Catch ex As Exception

            Debug.Print("!! EXCEPTION: " + ex.Message())

        End Try

        '' return it

        Return identity

    End Function

End Module

This is a simple example that is monitoring Performance Counters on servers