Updating Active Directory using ASP.NET 3.5

It is extremely easy to use ASP.NET to manage your Active Directory Users. This article shall list some of the common scenarios which is most frequently used.

Points to ensure

  1. add the reference to System.DirectoryServices
  2. The account running the website must have the appropriate access to the AD

Get Users in Group

List<UserID_CN>
result =
new
List<UserID_CN>();

using
(var
de = getEntry())
{
object
obj = de.Properties[
“member”].Value;

if
(obj
is
string)
{

result.Add(new
UserID_CN()
{

CN = obj.ToString(),
ID = Regex.Match(obj.ToString(),
“CN=(.*?),”,
RegexOptions.IgnoreCase).Groups[1].Value

});
}
else
if (obj
is
object[])
{

foreach
(object
o
in (object[])obj)

{
result.Add(new
UserID_CN()
{

CN = o.ToString(),
ID = Regex.Match(o.ToString(),
“CN=(.*?),”,
RegexOptions.IgnoreCase).Groups[1].Value

});
}
}
else

{
}
}
result = result.OrderBy(p => p.ID).ToList();

return
result;
}

Delete Users in Group

using (var
de = getEntry())

{

foreach (UserID_CN
u
in GetUsersInGroup)

{

de.Properties[“member”].Remove(u.CN);

}

de.CommitChanges();

de.Close();

}

Add Users to Group

de.Properties[“member”].Add(userDN);

Get all properties of directory entry

foreach(string
key
in
dirEntry.Properties.PropertyNames)

{

// Each property contains a collection
of its own

// that may contain multiple values

Label1.Text += “–“
+ key +
“–<br>”;

foreach(
object propVal
in dirEntry.Properties[key]
)

{

if
(propVal.GetType() ==
typeof(System.Byte[]))

{

Label1.Text += “(“;

for (int
i=((
byte[])propVal).GetLowerBound(0);i<((byte[])propVal).GetUpperBound(0)+1;i++)

Label1.Text += (char)
((
byte[])propVal)[i];

Label1.Text += “)<br>”;

}

else
if
(propVal.GetType().ToString() ==

“System.__ComObject”
)

{

try

{

Label1.Text += “(“;

long val_int64 =
GetInt64(dirEntry, key);

//DateTime dt =
DateTime.FromFileTime(val);

try

{

if (val_int64 >
0)

{

DateTime T =
DateTime.FromFileTime(val_int64);

Label1.Text += T.ToString(“dd MMM yyyy
HH:mm:ss”
) + “)<br>”;

}

else

{

throw
new
Exception();

}

}

catch

{

Label1.Text += val_int64 + “)<br>”;

}

}

catch

{

Label1.Text += “(“
+ propVal +
“)<br>”;

}

}

else

Label1.Text += “(“
+ propVal +
“)<br>”;

}

}

Label1.Text += “—————<br>”;

Leave a Reply

Your email address will not be published. Required fields are marked *