tags:

views:

660

answers:

2

Hi guys,

I just want to Add a new method on an existing code below. Method is a simply check a given User_ID if it is exists on the AD.

It's my 1st time dealing with AD.

public class AD
{
    // Fields
    private static string ADPassword = ConfigurationManager.AppSettings["ADPassword"].ToString();
    private static string ADPath = ConfigurationManager.AppSettings["ADConnection"].ToString();
    private static string ADServerName = ConfigurationManager.AppSettings["ADServerName"].ToString();
    private static string ADUserName = ConfigurationManager.AppSettings["ADUserName"].ToString();

    // Methods
    public static string GetLogin(string sUserName, string sPassword)
    {
        try
        {
            DirectoryEntry entry = new DirectoryEntry(ADPath, ADServerName + sUserName, sPassword);
            object nativeObject = entry.NativeObject;
            return string.Empty;
        }
        catch
        {
            return "Invalid Username or Password";
        }
    }

    public static string Update(string sUserName, string sOldPassword, string sNewPassword)
    {
        string message;
        try
        {
            DirectoryEntry searchRoot = new DirectoryEntry();
            searchRoot.Path = ADPath;
            searchRoot.Username = ADServerName + ADUserName;
            searchRoot.Password = ADPassword;
            DirectorySearcher searcher = new DirectorySearcher(searchRoot);
            searcher.Filter = "(SAMAccountName=" + sUserName + ")";
            DirectoryEntry directoryEntry = searcher.FindOne().GetDirectoryEntry();
            directoryEntry.Invoke("ChangePassword", new object[] { sOldPassword, sNewPassword });
            directoryEntry.CommitChanges();
            directoryEntry.Close();
            message = string.Empty;
        }
        catch (Exception exception)
        {
            try
            {
                message = exception.InnerException.Message;
            }
            catch
            {
                message = exception.Message;
            }
        }
        return message;
    }
}
A: 

If it's your first AD experience, it might be worth taking a look at this codeproject article: Howto: (Almost) Everything In Active Directory via C#. It contains lots of examples that might help you.

What do you mean exactly by User_ID? Account name? LDAP distinguished name?

Paolo Tedesco
User_ID is a UserName
No Body
A: 

Which version of the .NET Framework are you on??

In .NET before 3.5, you could probably do a DirectorySearch on the whole server (or alternatively a more constrained subtree):

public bool UserExists(string userName)
{
  DirectoryEntry searchRoot = new DirectoryEntry("LDAP://dc=yourcompany,dc=com", userName, password);
  DirectorySearcher searchForUser = new DirectorySearcher(searchRoot);

  searchForUser.SearchScope = SearchScope.SubTree;
  searchForUser.Filter = string.Format("(&(objectCategory=Person)(anr={0}))", userName);

  if(searchForUser.FindOne() != null)
  {  
     return true;
  } 
  else
  {
     return false;
  }
}

This is just off the top of my head, can't test it right now. This will search in your entire domain - check the LDAP path for the searchRoot - it would have to be something like

LDAP://dc=yourcompany,dc=com

or if you want to search just inside the "Users" container:

LDAP://cn=Users,dc=yourcompany,dc=com

With .NET 3.5 things got a lot easier - see this MSDN Article for a lot of useful info on how to search and find users and groups in .NET 3.5 using the new System.DirectoryServices.AccountManagement namespace. You can basically now do a FindByIdentity call:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

UserPrincipal foundUser = UserPrincipal.FindByIdentity(ctx, "your user name");

and that's all there is.

Marc

marc_s
using the code above:Unknown error (0x80005000) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: Unknown error (0x80005000)Source Error: Line 88: Line 89: bool _return;Line 90: if (searchForUser.FindOne() != null)Line 91: {Line 92: _return = true;
No Body
Then most likely your "ADServerName" isn't a valid LDAP name - what does it look like?? Your base LDAP path has to be something like `LDAP://dc=yourcompany,dc=com` or something similar.
marc_s
=> "LDAP://ip address/DC=ourDomain, DC=com"using the above code, yields => Logon failure: unknown user name or bad password.
No Body
well, in that case, you'll need to supply user name and password in the constructor of the DirectoryEntry
marc_s
No Body
well, it seems your current code also uses username+password, so I guess you'll just have to do the same in this method, too.
marc_s
it's a different scenario from the existing code. =), anyway,seems I don't have any choice at the moment, The code above works fine, how can i filtered out those username that are disabled,?
No Body