Получить Active Directory ExtensionAttribute через UserPrincipal - PullRequest
0 голосов
/ 14 декабря 2018

Я пытаюсь получить значение пользователя ExtensionAttribute4.

Это мой класс расширения до UserPrincipal:

[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("Person")]
public class UserPrincipalEx : UserPrincipal
{
    // Implement the constructor using the base class constructor. 
    public UserPrincipalEx(PrincipalContext context) : base(context)
    { }

    // Implement the constructor with initialization parameters.    
    public UserPrincipalEx(PrincipalContext context,
                         string samAccountName,
                         string password,
                         bool enabled) : base(context, samAccountName, password, enabled)
    { }

    // Create the "extensionAttribute4" property.    
    [DirectoryProperty("extensionAttribute4")]
    public string ExtensionAttribute4
    {
        get
        {
            if (ExtensionGet("extensionAttribute4").Length != 1)
                return string.Empty;

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

    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue);
    }

    // Implement the overloaded search method FindByIdentity. 
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue);
    }
}

Вот как я вызываю метод:

 UserPrincipalEx user = UserPrincipalEx.FindByIdentity(ctx, IdentityType.SamAccountName, "someuser");

Я вижу в отладке, что пользователь действительно является результатом Classes.UserPrincipalEx.FindByIdentity, но extensionAttribute4 там не указан.Совсем.Другие атрибуты есть.

Я пытался сделать то же самое с менеджером, тот же результат.Ошибка:

Ссылка на объект не установлена ​​для экземпляра объекта

Я новичок в этом, поэтому, пожалуйста, извините, если я упустил что-то очевидное.

1 Ответ

0 голосов
/ 14 декабря 2018

Документация для ExtensionGet() говорит, что она возвращает "null, если не существует атрибута с таким именем".Если атрибут пустой, считается, что он не существует, и он вернет null.Поэтому вы должны проверить это.

[DirectoryProperty("extensionAttribute4")]
public string ExtensionAttribute4
{
    get
    {
        var extensionAttribute4 = ExtensionGet("extensionAttribute4");
        if (extensionAttribute4 == null || extensionAttribute4.Length != 1)
            return string.Empty;

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

Обратите внимание, что вы можете сделать то же самое, не расширяя UserPrincipal, используя GetUnderlyingObject() и используя базовый объект DirectoryEntry:

UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "someuser");
var extensionAttribute4 = ((DirectoryEntry) user.GetUnderlyingObject())
                            .Properties["extensionAttribute4"]?.Value as string;
...