Friday, October 05, 2007

Account locked WebPart

And while I'm at it.. I created another webpart that tells an administrator whether or not an useraccount is locked out in Active Directory. Further I provide the admin with information about the last logon time and when the password will expire. There is a lot to be found on what you can extract from Active Directory using System.DirectoryServices and ActiveDs :)

Here is the code to get the informatio to check whether an account is locked:

 object o = entry.InvokeGet("IsAccountLocked");
 if (o != null)
 {
     bool locked = (bool)o;
     output.Text += "Account Locked : <b>" + locked.ToString() + "</b>";
 };
 

Here is the code to check whether an account is disabled :

bool isDisabled;
isDisabled = ((int)entry.Properties["userAccountControl"].Value &
(int)ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE) != 0;
output.Text += "<BR>Account Disabled: <b>" + isDisabled.ToString() + "</b>";

Here is the code to see when the successful logon was :

object lastlogon = entry.InvokeGet("LastLogin");
if (lastlogon != null)
{
      DateTime LastLogon = (DateTime)lastlogon;
      output.Text += "<BR> Last Logon was at : " + LastLogon.ToString("d", ci) + "  " + LastLogon.ToShortTimeString();
}

And to determine when the password is about to expire use this code :

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);

// Convert FileTime to DateTime and get what today's date is. 
DateTime dtNow = DateTime.Now;
// I added 90 days because I know what my password expiration is set to, if not you need to pull that information and add the number of days it is set for. 
DateTime dtAcctPwdChange = DateTime.FromFileTime(dateAcctPwdChange).AddDays(180);
string strAcctPwdChange = DateTime.FromFileTime(dateAcctPwdChange).ToString("d", ci);
string strAcctPwdExpires = DateTime.FromFileTime(dateAcctPwdChange).AddDays(180).ToString("d", ci);

// Calculate the difference between the date the pasword was changed, and what day it is now and display the # of days. 
TimeSpan time;
time = dtAcctPwdChange - dtNow;

output.Text += "<BR>Password will expire in " + time.Days + " days";

You can reuse the code from the previous post to get things working

 

3 comments:

Anonymous said...

It is extremely interesting for me to read the article. Thanx for it. I like such topics and everything that is connected to this matter. BTW, try to add some images :).

Anonymous said...

Hi Robin,

how come, that in my case

DateTime.FromFileTime(dateAcctPwdChange)

does not display the corect value? There is always a couple of minutes difference (about 7minutes and 10 sec)..

Any Ideas?

KR said...

Hi Robin,

This is very useful, could you please share the full source code. Thanks.