I got this from a member of our Network Team:
You can see that extensionAttribute2 has a value in it. How can I retrieve this value - I cannot see extensionAttributes anywere in UserPrincipal object - unless I am missing something.
I have went back a level further and tried the below:
UserPrincipal myUser = UserPrincipal.FindByIdentity(con, identityName);
DirectoryEntry de = (myUser.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
// go for those attributes and do what you need to do
if (de.Properties.Contains("extensionAttribute2"))
{
return de.Properties["extensionAttribute2"][0].ToString();
}
else
{
return string.Empty;
}
}
However this does not work - debugging this there are about 40 properties available but none for extensionAttribute2
If you're on .NET 3.5 and up and using the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace, you can easily extend the existing UserPrincipal
class to get at more advanced properties, like Manager
etc.
Read all about it here:
Basically, you just define a derived class based on UserPrincipal
, and then you define your additional properties you want:
[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("Person")]
public class UserPrincipalEx : UserPrincipal
{
// Inplement 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 "extensionAttribute2" property.
[DirectoryProperty("extensionAttribute2")]
public string ExtensionAttribute2
{
get
{
if (ExtensionGet("extensionAttribute2").Length != 1)
return string.Empty;
return (string)ExtensionGet("extensionAttribute2")[0];
}
set { ExtensionSet("extensionAttribute2", value); }
}
}
Now, you can use the "extended" version of the UserPrincipalEx
in your code:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// Search the directory for the new object.
UserPrincipalEx inetPerson = UserPrincipalEx.FindByIdentity(ctx, IdentityType.SamAccountName, "someuser");
// you can easily access the ExtensionAttribute2 now
string department = inetPerson.ExtensionAttribute2;
}
Using the code that marc_s used add the following:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With