.NET 3.5 (finally) brings some decent Active Directory support!
Back in the old days (like AD Change Password WebPart and Account locked WebPart) you had to use the "Active DS Type Library" (Interop.ActiveDs.dll) to interact with Active Directory to retrieve things like :
- Change Password
- Lockout Time
- Last password change date
- Change users password, etc
Now there is .NET 3.5 with the inclusion of System.DirectoryServices.AccountManagement! Using this piece, gone are the days when you had to invoke a property and you got a LargeInteger as a return value which you had to split up in a high and a low part and make a datetime thing out of it (see samples below to see what i'm talking about ;))
UserDiabled:
bool isDisabled; isDisabled = ((int)entry.Properties["userAccountControl"].Value & (int)ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE) != 0;
LastLogonDate:
object lastlogon = entry.InvokeGet("LastLogin");
LastPasswordChage:
LargeInteger liAcctPwdChange = entry.Properties["pwdLastSet"].Value as LargeInteger; // Convert the highorder/loworder parts of the property pulled to a long. long dateAcctPwdChange = (((long)(liAcctPwdChange.HighPart) << 32) + (long)liAcctPwdChange.LowPart); DateTime dtAcctPwdChange = DateTime.FromFileTime(dateAcctPwdChange);
Nowadays your code will look like this
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain", "DC=domain,DC=com"); // Create an in-memory user object to use as the query example. UserPrincipal u = new UserPrincipal(ctx); // Set properties on the user principal object. u.SamAccountName = "Robin"; // Create a PrincipalSearcher object to perform the search. PrincipalSearcher ps = new PrincipalSearcher(); ps.QueryFilter = u; PrincipalSearchResult<Principal> results = ps.FindAll(); foreach (UserPrincipal _user in results) { DateTime LastPasswordChange = _user.LastPasswordSet; DateTime LockoutTime = _user.AccountLockoutTime; DateTime ExpirationDate = _user.AccountExpirationDate; int FailedLogonAttempts = _user.BadLogonCount; bool UserDisabled = _user.Enabled; bool UserLockedOut = _user.IsAccountLockedOut; }
Pretty sweet eh? No more Googling to find out which property in AD you need to address in order to get things working :)

3 reacties:
Hey I wrote up a quick blog entry on how to make a custom User object to get access to fields that aren't in the basic UserPrincipal object.
Costoda's Blog
Hi Robin, thanks for the messenger chat last night... I found an example (finally) for using an extended userprincipal object :)
http://msdn2.microsoft.com/de-de/library/bb552835.aspx
Thanks for psoting this.
Brian Miller
http://www.convergepoint.com
Post a Comment