BlueBarren BlueBarren - 7 days ago 5
C# Question

Extended UserPrincipal Only Returning an Empty String

I was trying to find a way to get some of the attributes from an active directory user that aren't in the

UserPrincipal
object by default. While searching for my answer I came across this question. I'm sure the answer posted by @marc_s is right, it at least is very useful. Because of it's usefulness I have created a
UserPrincipalEx
class and done everything like @marc_s suggested in his answer. The class itself seems to be defined properly aside from that fact that my extended attribute, in this case
title
is always returning an empty string. I double checked in AD that the attribute is called
title
so I should be grabbing the right attribute I'm just not getting any content for it. @marc_s also mentions that the class is a skeleton but if that's why I can't get it to work what more would I need to add?

I defined his two classes in their own
.cs
class called
UserPrincipalEx.cs
and I have both the
UserPrincipalExSearchFilter
and
UserPrincipalEx
classes defined in that file. When I create my object in my code however it always returns an empty string.

UserPrincipalEx user = new UserPrincipalEx(principal.Context);
if (user == null) return false;
return user.Title == "A value other than empty" | (user.Title == "" || user.Title == null);


What more do I need to do to grab the value of
title
from AD?

Update:

If I follow the retrieving of the
title
attribute the
UserPrincipalEx
always says it's null, which continues to make me feel like I did something wrong with
UserPrincipalEx.cs


[DirectoryProperty("title")]
public string Title
{
get
{
if (ExtensionGet("title").Length != 1)
return string.Empty;

return (string)ExtensionGet("title")[0];
}
set { ExtensionSet("title", value); }
}


It always hits the
return string.Empty;
and like the lines says, returns an empty string

Update 2:

From what I can tell it doesn't matter what extended attribute you're looking for UserPrincipalEx will always return a null and make the string empty.

Answer

Instead of using the extended UserPrincipal I ended up just using a DictionaryEntry to find the value and compare it instead like so.

UserPrincipal user = new UserPrincipal(principal.Context);
if (user == null) return false;
DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
string title = "";
if (directoryEntry.Properties.Contains("title"))
{
    title = directoryEntry.Properties["title"].Value.ToString();
}
return title == "Comparison Value" | (title == "" || title == null);