Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Active Directory Account is Locked out (WPF C#)

Hello everyone (this is my first post) I have some simple AD code that i pulled from Codeplex http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C) and i am able to get all of our end user's information from said code. Now, I have been searching and searching and have found some interesting code snippets from here, and around the web regarding "Is the user locked out?"

I would like to use my code that I have been using for 2 years now, and just add a little bit more to it to add in the locked out part... I would be happy if there was a text box that gave me my info, or a check box, or something that just said "user locked" and then I would notify my Exchange team and have the user unlocked...

The code that I have is the following:

string eid = this.tbEID.Text;
string user = this.tbUserName.Text.ToString();
string path = "PP://dc=ds,dc=SorryCantTellYou,dc=com";

DirectoryEntry de = new DirectoryEntry(path);

DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectCategory=person)(sAMAccountName=" + eid + "))";

SearchResultCollection src = ds.FindAll();

//AD results
if (src.Count > 0)
{
   if (src[0].Properties.Contains("displayName"))
   {
      this.tbUserName.Text = src[0].Properties["displayName"][0].ToString();
   }
}

So, if I can figure out how to use the same directory entry, and searcher to show me the account lockout status that would be amazing.. please assist

like image 277
user1762132 Avatar asked Oct 20 '12 20:10

user1762132


1 Answers

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SamAccountName");

if(user != null)
{
    string displayName = user.DisplayName;

    if(user.IsAccountLockedOut())
    {       
        // do something here....    

    }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

like image 108
marc_s Avatar answered Oct 15 '22 22:10

marc_s