Handling AD Error When Not Connected

272 views Asked by At

I'm using the below code to get the logge don user's logon name. This works fine when connected to the network/domain. But when offline, I get an error on the 3rd line:

PrincipalServerDownException was unhandled

The server could not be contacted.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
    currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
    Dim DisplayName As String = currentADUser.GivenName & " " & currentADUser.Surname
    Label5.Text = DisplayName
    Label4.Text = GetUserProperties()
End Sub

How can I get this to check, and return a userful error to the user, such as "Not on network" or "not connected to domain", then exit? I've tried the below, but this just gives the same error:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
    If System.DirectoryServices.AccountManagement.UserPrincipal.Current Is Nothing Then
        MsgBox("Network Error: No Connection to Domain")
        Application.Exit()
    Else ....
    End if
End Sub
1

There are 1 answers

1
andrejke On BEST ANSWER

Use try/catch

    Try
        Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
        currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
        Dim DisplayName As String = currentADUser.GivenName & " " & currentADUser.Surname
        Label5.Text = DisplayName
        Label4.Text = GetUserProperties()
    Catch ex As Exception
        MsgBox(...)
    End Try