Return to Snippet

Revision: 40539
at February 3, 2011 10:00 by lance


Initial Code
public UserPrincipal GetLoggedInUser()
        {
            try
            {
                //Get the principal logged in user
                WindowsPrincipal principal = System.Threading.Thread.CurrentPrincipal as WindowsPrincipal;

                //split the principal identity name from the domain and put them in an array
                string delimiter = "\\";
                string userAndDomain = principal.Identity.Name.ToString();
                string[] arrayName = userAndDomain.Split(delimiter.ToCharArray());
            
                //Get the context of this action based on the first item in the arrayName which is the domain
                PrincipalContext pc = new PrincipalContext(ContextType.Domain, arrayName[0]);
                
                //Get the userprincipal (user) by matching the username in active directory and the name in the array
                UserPrincipal p = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, arrayName[1]);

           
                //make sure the userprincipal is a directoryentry then get the user
                if (p.GetUnderlyingObjectType() == typeof(DirectoryEntry))
                {
                    DirectoryEntry user = (DirectoryEntry)p.GetUnderlyingObject();

                    //The EmpID is located in the wwwHomePage field in AD
                    if (user.Properties["wwwHomePage"].Count > 0)
                    {
                        //set a variable to the wwwHomePage property so we can return it
                        empID = Convert.ToInt32(user.Properties["wwwHomePage"].Value);
                    }
                    else
                    {
                        empID = 0;
                    }
                }
                return p;
            }
            catch (Exception ex)
            {
                
                return null;
            }
        }

Initial URL

                                

Initial Description

                                

Initial Title
Get logged in user from Active Directory and then get some of their AD attributes

Initial Tags
directory

Initial Language
C#