private AdUser GetUserFromEntry(DirectoryEntry di)
{
int phone = 0;
if (di.Properties["telephoneNumber"].Value != null)
{
int.TryParse(di.Properties["telephoneNumber"].Value.ToString(), out phone);
}
DateTime created = DateTime.MinValue;
if (di.Properties["whenCreated"].Value != null)
{
// DateTime.ParseExact(di.Properties["whenCreated"].Value.ToString())
created = (DateTime)di.Properties["whenCreated"].Value;
}
int flags = (int)di.Properties["userAccountControl"][0];
string manager = di.Properties["manager"].Value != null
? GetCnFromString(di.Properties["manager"].Value.ToString())
: string.Empty;
DateTime? lastLogon = null;
//if (di.Properties.Contains("lastLogon"))
//{
// var largeInt = (LargeInteger)di.Properties["lastLogon"][0];
// Int64 liTicks = largeInt.HighPart * 0x100000000 + largeInt.LowPart;
// if (DateTime.MaxValue.Ticks >= liTicks && DateTime.MinValue.Ticks <= liTicks)
// {
// lastLogon = DateTime.FromFileTime(liTicks);
// }
//}
var user = new AdUser()
{
Login = di.Properties["sAMAccountName"].Value != null ? di.Properties["sAMAccountName"].Value.ToString() : string.Empty,
CN = di.Properties["cn"].Value != null ? di.Properties["cn"].Value.ToString() : string.Empty,
FullName = di.Properties["displayName"].Value != null ? di.Properties["displayName"].Value.ToString() : string.Empty,
Department = di.Properties["department"].Value != null ? di.Properties["department"].Value.ToString() : string.Empty,
Mobile = di.Properties["mobile"].Value != null ? di.Properties["mobile"].Value.ToString() : string.Empty,
Office = di.Properties["physicalDeliveryOfficeName"].Value != null ? di.Properties["physicalDeliveryOfficeName"].Value.ToString() : string.Empty,
Title = di.Properties["title"].Value != null ? di.Properties["title"].Value.ToString() : string.Empty,
Mail = di.Properties["mail"].Value != null ? di.Properties["mail"].Value.ToString() : string.Empty,
WhenCreated = di.Properties["whenCreated"].Value != null ? (DateTime)di.Properties["whenCreated"].Value : DateTime.Now,
OfficePhone = phone == 0 ? (int?)null : phone,
HasPicture = di.Properties["thumbnailPhoto"].Value != null,
CreatedWhen = created,
Disabled = Convert.ToBoolean(flags & UF_ACCOUNTDISABLE),
Userpic = di.Properties["thumbnailPhoto"].Value != null ? (byte[])di.Properties["thumbnailPhoto"].Value : null,
Category = di.Properties["objectCategory"].Value != null ? di.Properties["objectCategory"].Value.ToString() : string.Empty,
sAMAccountType = di.Properties["sAMAccountType"].Value != null ? (int)di.Properties["sAMAccountType"].Value : 0,
LastLogon = lastLogon,
Manager = manager,
Sid = di.Properties["objectSid"].Value != null ? new SecurityIdentifier((byte[])di.Properties["objectSid"].Value, 0).ToString() : string.Empty
};
di.Close();
di.Dispose();
return user;
}