Click here to Skip to main content
15,941,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ,
I Stuck in Somthing :

I wanna Read an attribute which is related with logged on user which is Employee ID ,
My Code is :
Importing two libraries :

Imports System.Security.Principal
Imports System.DirectoryServices.AccountManagement

Then Reading Parameter EmployeeID :

Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current

Session("UserEmpID") = currentADUser.EmployeeId

When I Run this on visual studio , it works Perfectly , but when I Published it on IIS , this Error Shown :

Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'

When I searched deep I find out that this website should have a credential to access Active Directory database , but how I couldn't know.

Please help I Am Stuck.


1 solution

I found the solution:
First : IIS authentication should be Windows Authentication
Second : a Domain user should be inserted in web.config in this format :
   <add key="LDAPsvcAcct" value="domain\username" />
   <add key="LDAPsvcPass" value="user_password" />

Third : then you can use this code:

Dim Username As String = ""
       Dim identityName = User.Identity.Name

       Using HostingEnvironment.Impersonate()
           Using context = New PrincipalContext(ContextType.Domain, "", Nothing, ContextOptions.Negotiate Or ContextOptions.SecureSocketLayer)
               Using userPrincipal__1 = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, identityName)
                   EmpID = userPrincipal__1.EmployeeId
                   Session("EmpID") = userPrincipal__1.EmployeeId 'To Read attributes
                   Username = userPrincipal__1.DisplayName
               End Using
           End Using
       End Using
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900