Question

I need assistance with gathering Active Directory data based on a table in my DB. I have an entity class that holds user requests. Each request has the user's windows name from System.Web.HttpContext.Current.User.Identity.Name. My problem is I cannot figure out how to setup a linq query to associate the AD username to the rest of the AD so I can display their full names instead of their username in my table. Here is what I have so far, any help will be appreciated.

      public partial class RequestInfo
    {
    public int RequestInfoId { get; set; }
    public string RequestByUserADId { get; set; }
    public System.DateTime RequestDateTime { get; set; }
    public string Explanation { get; set; }

    public virtual UserInfo UserInfo { get; set; } // where I define my custom roles
    }

I can query AD by using the code below. I have tried Get Active Directory User Information With Windows Authentication in MVC 4, but it did not help.

        using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
        using (UserPrincipal user = UserPrincipal.FindByIdentity(context, requestByAdId))
        {
            return user.DisplayName
        }
Était-ce utile?

La solution

I may be off here because I am not sure if you are able to successful establish a user principal or not but if you have the user principal you can get property information like the following:

user.GetProperty("propertyName")

Here is a static method that should get you the department for a user, for example.

public static String GetDepartment(UserPrincipal principal)
{
    return principal.GetProperty("department");
}

Let me know where this gets you and I can elaborate further if this isn't working.

Edit

It appears you need to go one level deeper to get the fields that aren't by default a part of the user principal. For this you will need to get the directory entry from the user principal first:

DirectoryEntry directoryEntry = (userPrincipal.GetUnderlyingObject() as DirectoryEntry);

Then you need to check if the attribute you are looking for exists, and if it does, get the value. A great way to do this is to create a helper method that you pass your directory entry to along with the string value for the property name that you want to get.

public string GetProperty(DirectoryEntry directoryEntry, string propertyName)
{
    if (directoryEntry.Properties.Contains(propertyName))
    {
        return directoryEntry.Properties[propertyName][0].ToString();
    }
    else
    {
        return string.Empty;
    }
}

Please note that going to the underlying object is expensive. I believe this operation, by default, is cached for you so subsequent use of this information can be retrieved from cache. Playing around with

directoryEntry.RefreshCache

will get you started with that.

Let me know if this does the trick for you!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top