Home > ASP.NET, Uncategorized > Updating Active Directory using ASP.NET 3.5

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

Advertisements
Categories: ASP.NET, Uncategorized
  1. shrikant
    January 24, 2011 at 7:42 pm

    Hi,
    I have a web page through this page when I try to add a new user then users created successfully but when try resetting their password then I am getting errors’

    add New user successfully

    public static void AddUser(ADUser adUser)
    {
    // Local variables
    DirectoryEntry oDE = null;
    DirectoryEntry oDENewUser = null;
    DirectoryEntries oDEs = null;

    try
    {
    oDE = GetDirectoryEntry(GetADPath(PROD, adUser.UserType));

    // 1. Create user account
    oDEs = oDE.Children;
    oDENewUser = oDEs.Add(“CN=” + adUser.UserName, “user”);

    // 2. Set properties
    SetProperty(oDENewUser, “givenName”, adUser.FirstName);
    SetProperty(oDENewUser, “sn”, adUser.LastName);
    SetProperty(oDENewUser, “mail”, adUser.Email);
    SetProperty(oDENewUser, “sAMAccountName”, adUser.UserName);
    oDENewUser.CommitChanges();

    /// 4. Enable account
    EnableAccount(oDENewUser);

    // 3. Set password
    //SetPassword(oDENewUser, adUser.Password);
    SetPassword1(oDENewUser.Path, adUser.Password);
    oDENewUser.CommitChanges();

    oDENewUser.Close();
    oDE.Close();
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    I have try the following 2 SetPassword methods but getting error.
    Method 1.
    internal static void SetPassword1(string path, string userPassword)
    {
    //Local variables
    DirectoryEntry usr = null;

    try
    {
    usr = new DirectoryEntry();
    usr.Path = path;
    usr.AuthenticationType = AuthenticationTypes.Secure;
    object ret = usr.Invoke(“SetPassword”, userPassword);
    usr.CommitChanges();
    usr.Close();
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    The exception raised (Error Code 80072035: The server is unwilling to process the request)
    Method 2.
    internal static void SetPassword(DirectoryEntry de, string userPassword)
    {
    //Local variables
    //DirectoryEntry usr = null;
    string quotePwd;
    byte[] pwdBin;

    try
    {
    quotePwd = String.Format(@”””{0}”””, userPassword);
    pwdBin = System.Text.Encoding.Unicode.GetBytes(quotePwd);
    de.Properties[“unicodePwd”].Value = pwdBin;
    de.CommitChanges();
    //usr.Close();
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    The exception raised (“Exception has been thrown by the target of an invocation.”)
    Is there an easy way to tell if there is a problem with changing a password?
    Please reply me as soon as possible.
    Thanks.

    • February 4, 2011 at 7:17 pm

      It seems the account performing this action does not have the necessary rights to perform a password change, or there is some group policy blocking this password change

  2. shrikant12
    April 13, 2011 at 12:12 am

    Hi All,
    We are able to create new user successfully on the active directory but the SetPassword method is taking around 1.5 minutes to complete the process. Below is the code of the snippet of SetPassword. Is there any better approach to set the password of new user?
    #region SetPassword
    ///
    /// This function is used to set user password
    ///
    ///
    ///
    ///

    ///
    internal static void SetPassword(string path, string userPassword)
    {
    if (_logger.IsDebugEnabled)
    _logger.Debug(“ADHelper.cs : Enter SetPassword”);

    try
    {
    using (DirectoryEntry usr = GetDirectoryEntry(path))
    {
    object ret = usr.Invoke(“SetPassword”, userPassword);
    usr.CommitChanges();
    usr.Close();
    }

    if (_logger.IsDebugEnabled)
    _logger.Debug(“ADHelper.cs : Exit SetPassword”);
    }
    catch (Exception ex)
    {
    if (_logger.IsErrorEnabled)
    _logger.Error(“ADHelper.cs : Exception occurred in SetPassword. Message: “, ex);

    throw ex;
    }
    }

    #endregion
    Here is our production environment type.
    • IIS 7
    • ASP.NET 3.5 (C#)
    • Active Directory
    • Windows Server 2008 R2

    Add user snippet
    #region AddUser

    ///
    /// This function is used to add user to active directory
    ///
    /// Active Directory
    /// directory entry object
    ///
    ///
    public static void AddUser(ADUser adUser)
    {
    if (_logger.IsDebugEnabled)
    _logger.Debug(“ADHelper.cs : Enter AddUser”);

    // Local variables
    DirectoryEntry oDE = null;
    DirectoryEntry oDENewUser = null;
    DirectoryEntries oDEs = null;

    try
    {
    oDE = GetDirectoryEntry(GetADPath(Constants.EnvironmentType.PROD, adUser.UserType));

    // 1. Create user account
    oDEs = oDE.Children;
    oDENewUser = oDEs.Add(string.Format(“{0}=”, Constants.ADAttributes.CN) + adUser.UserName, “user”);

    // 2. Set properties
    SetProperty(oDENewUser, Constants.ADAttributes.givenName, adUser.FirstName);
    SetProperty(oDENewUser, Constants.ADAttributes.sn, adUser.LastName);
    SetProperty(oDENewUser, Constants.ADAttributes.mail, adUser.Email);
    SetProperty(oDENewUser, Constants.ADAttributes.sAMAccountName, adUser.UserName);
    oDENewUser.CommitChanges();

    // 3. Set password
    SetPassword(oDENewUser.Path, adUser.Password);

    // 4. Enable account
    EnableAccount(oDENewUser);

    oDENewUser.Close();
    oDE.Close();

    if (_logger.IsDebugEnabled)
    _logger.Debug(“ADHelper.cs : Exit AddUser”);
    }
    catch (Exception ex)
    {
    if (_logger.IsErrorEnabled)
    _logger.Error(“ADHelper.cs : Exception occurred in AddUser. Message: “, ex);

    throw ex;
    }
    finally
    {
    if (oDENewUser != null)
    {
    oDENewUser.Dispose();
    oDENewUser = null;
    }

    if (oDEs != null)
    {
    oDEs = null;
    }

    if (oDE != null)
    {
    oDE.Dispose();
    oDE = null;
    }
    }
    }

    #endregion

    THANKS IN ADVANCE!!!

    • April 13, 2011 at 11:26 pm

      just wondering, why not just set the password directly to oDENewUser instead of calling setpassword function which needs to search the AD again for the account?

      alternatively you time each of the function calls in setpassword to see exactly which is taking the longest

      • shrikant
        April 15, 2011 at 5:49 pm

        hi kwanann

        please tell me how can set password directly to oDENewUser.

  3. April 18, 2011 at 11:14 am

    meaning, instead of

    // 3. Set password
    SetPassword(oDENewUser.Path, adUser.Password);

    change to

    // 3. Set password
    oDENewUser.Invoke(“SetPassword”, userPassword);
    oDENewUser.CommitChanges();

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: