0
votes

I am trying to make a bool property that would toggle the pwdLastSet property.

public bool UserMustChangePassword
{
    get { return (long)Entry.Properties["pwdLastSet"].Value == 0; }
    set
    {
        if (value) 
        {
            Entry.Properties["pwdLastSet"].Value = 0; 
        }
        else 
        { 
            Entry.Properties["pwdLastSet"].Value = -1; 
        }
    }                                                                                   
}

I can set the property successfully however I cant read the property. I keep getting the following casting error.

System.InvalidCastException: 'Specified cast is not valid.'

Is there a specific way to read this property. I know it may be possible to UserPrincipal, however I would like to use DirectoryEntry to keep the code consistent.

Edit: check null before casting

public bool UserMustChangePassword
{
    get
    {
        var value = Entry.Properties["pwdLastSet"].Value;

        if (value != null)
            return (long)Entry.Properties["pwdLastSet"].Value == 0;

        return false;
    }
    set
    {
        if (value) 
        {
            Entry.Properties["pwdLastSet"].Value = 0; 
        }
        else 
        { 
            Entry.Properties["pwdLastSet"].Value = -1; 
        }
    }                                                                                   
}
1
Need a null check in the getter, you cannot cast null to long. - kennyzx
@kennyzx I had thought about that. Unfortunately I still get the same error. I also cannot cast it to a (long?) - Dblock247
Show how do you check against null before casting. - kennyzx
And what is the type of the Value property? Can it be something other than a long? - kennyzx
@kennyzx see above - Dblock247

1 Answers

0
votes

You need to check its Count property to make sure there is a value. Try this,

if (Entry.Properties["pwdLastSet"].Count > 0)
{
    return (Entry.Properties["pwdLastSet"][0] == 0)
}
else 
    return false;

Edit:

Seems the problem comes from that you are querying Properties of DirectoryEntry instead of SearchResult. See this question. I have a copy of working code that is also querying SearchResult.