Friday, May 25, 2012

Setting LDAP parameter to invalid value caused strange error

I was working on a web based application using C# and ran into a bit of a strange error.  I'm using an LDAP to try and set the option "Require user to change password at next login"  for an Active Directory account.  A small typo resulted in a strange error that lead me to waste some time today.  Thought I'd share to hopefully prevent others from having the same issue.  The error I received was:


A device attached to the system is not functioning. (Exception from HRESULT: 0x8007001F)

The snippet of relevant code:


    public bool RequireUserToChangePwd(bool force)
    {
        bool success = false;

        try
        {
            DirectoryEntry user = loadSpecificEntry();
                
            if (user != null)
            {
                if (force)
                    user.Properties["pwdLastSet"].Value = 0;
                else
                    user.Properties["pwdLastSet"].Value = 1;
                        
                user.CommitChanges();
                user.Close();
                success = true;
            }
        }
        catch (Exception ex)
        {
            tossFormattedExceptionMessage("Unhandled error requiring force password change",ex);
        }

        return success;
    }


The exception was happening on the call to CommitChanges();   It was happening because the "pwdLastSet" property only has two valid values  0  and  -1  so when I called this method with force = false the exception was being tossed.   Needless to say the error message "A device attached to the system is not functioning" is a bit misleading.   Changing the code to supply the proper value of -1 resolved the issue.  I imagine this error could potentially show up in when using invalid values for other properties being modified using LDAP.  If you're reading this, hopefully I've saved you some time.

References
https://groups.google.com/forum/?fromgroups#!topic/microsoft.public.adsi.general/qUfqhn0qb6M