Comment #2 on issue 81 by
jather...@northpennlegal.org: Access Denied error
This is the code I used based on the code used in Issue 34, No matter what
combination I try it still shows access denied, Firewall is off at the
moment. As I stated, I am an administrator from the remote development pc
as well as the actual Terminal Server. Any help would be appreciated...
Private Sub btnConnectRemote_Click(sender As Object, e As EventArgs)
Handles btnConnectRemote.Click
Dim serverName As String = InputBox("Connect to Server")
Dim usrName As String = String.Empty
Dim token As IntPtr
If Not NativeMethods.LogonUser("Administrator",
serverName, "adminpassword", NativeMethods.LogonType.NewCredentials,
NativeMethods.LogonProvider.Default, token) Then
Throw New Win32Exception
End If
Try
Dim tokenDuplicate As IntPtr
If Not NativeMethods.DuplicateToken(token,
NativeMethods.SecurityImpersonationLevel.Impersonation, tokenDuplicate) Then
Throw New Win32Exception()
End If
Try
Using impersonationContext As WindowsImpersonationContext =
New WindowsIdentity(tokenDuplicate).Impersonate
Using serverInstance = iTSM.GetRemoteServer(serverName)
serverInstance.Open()
rtbList.Text = "Retreiving User List..."
For Each session As ITerminalServicesSession In
serverInstance.GetSessions
If session.ConnectionState =
ConnectionState.Disconnected Then
usrName = session.UserName
session.Logoff(True)
rtbList.Text &= String.Concat(usrName, "
has been logged off...")
End If
Next
For Each session As ITerminalServicesSession In
server.GetSessions
rtbList.Text &=
String.Concat(session.UserAccount, vbTab, vbTab, " Session ID: ",
session.SessionId, vbTab, vbTab, " Connection State:",
session.ConnectionState, vbCrLf)
Next
serverInstance.Close()
End Using
impersonationContext.Undo()
End Using
Catch ex As Exception
rtbList.Text &= String.Concat("Error Occured:", ex.ToString)
Finally
If tokenDuplicate <> IntPtr.Zero Then
NativeMethods.CloseHandle(tokenDuplicate)
End If
End Try
Catch ex As Exception
Finally
If token <> IntPtr.Zero Then
NativeMethods.CloseHandle(token)
End If
End Try
End Sub