Thursday, January 10, 2008

Getting information from Active Directory in .NET 3.5

I can first of all say that .NET 3.5 rocks when it comes to getting or putting information into Active Directory. Gone are the old days of DirectoryEntry and DirectorySearch objects. They have been replaced with a much nicer Principal Framework. Robin Meure has an awesome write up on this on his blog that I recommend you read. After talking to him, we both came up with the question on how do you read in schema properties that aren't attached to the UserPrincipal object. Well, Robin found an awesome article on MSDN that explains this.

Here is an example of a quick dirty object I put together to get the IpPhone and Department properties. Make sure you reference System.DirectoryServices.AccountManagement properly:

[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
public class ADUser:UserPrincipal
{
public ADUser(PrincipalContext context) : base(context) { }
public ADUser(PrincipalContext context, string samAccountName, string password, bool enabled) : base(context, samAccountName, password, enabled) { }

[DirectoryProperty("IpPhone")]
public string IpPhone
{
get
{
object[] result = this.ExtensionGet("IpPhone");
if (result != null && result.Length > 0)
return (string)result[0];
else
return null;
}
set
{
this.ExtensionSet("IpPhone", value);
}
}

[DirectoryProperty("Department")]
public string Department
{
get
{
object[] result = this.ExtensionGet("department");
if (result != null && result.Length > 0)
return (string)result[0];
else
return null;
}
set
{
this.ExtensionSet("department", value);
}
}
}



I hope that helps out anyone that had the same question I did.

-Costoda

7 comments:

Paul said...

Costa, do you have an example of finding a current AD user and returning the custom userprincipal object?

Robin Meuré said...

Thanks for the lovelink mate :)

Paul said...

Hi Costada, found the following example http://msdn2.microsoft.com/de-de/library/bb552835.aspx
Regards Paul

Владимир said...

Hi! Do you know that your "awesome article on MSDN" link above does not work? Apparently they rearranged that stuff on MSDN. What was the name of that article and who wrote it? Thanks!

Paul said...

this link worked for me...

http://msdn.microsoft.com/en-us/library/bb552835.aspx

try googling for Principal Extensions, it was the first item on the results.

Владимир said...

I found it too, thanks.

Preston Gallwas said...

This is awesome. I was a bit disappointed that 'yet again' we have another way to manage DS but it didn't include all that is necessary. Now all I have to do is get this bad-boy shaped up to do all the attributes that we need. Totally sweet!