Reputation: 1692
I've tried multiple ways to set the flag "User cannot change password" in active directory from c#.
The following haven't worked:
The first three each give the exact same, highly cryptic error message, "Constraint Violation" with the extended message:
0000051B: AtrErr: DSID-030F20BA, #1:
0: 0000051B: DSID-030F20BA, problem 1005 (CONSTRAINT_ATT_TYPE), data 0, Att 20119 (nTSecurityDescriptor)
Here is the simplest case code that should have worked (option 1):
using (var context = new PrincipalContext(ContextType.Domain, myDomain, myAccountOperatorUsername, myAccountOperatorPassword))
{
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userNameToChange))
{
if (user != null)
{
user.UserCannotChangePassword = true;
user.Save()
}
}
}
The powershell way of doing this works perfectly fine, using the same credentials from the same machine. In fact, it works so well I can automate it in the code and it succeeds:
using (var PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("Import-Module Active-Directory");
PowerShellInstance.AddScript("$password = ConvertTo-SecureString \"" + myAccountOperatorPassword + "\" -AsPlainText -Force");
PowerShellInstance.AddScript("$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist \"" + myAccountOperatorUsername + "\", $password");
PowerShellInstance.AddScript("Set-ADAccountControl -Identity " + usernameToChange + " -CannotChangePassword $true -Credential $cred");
var PSOutput = PowerShellInstance.Invoke();
}
However the powershell way makes the deployment more complicated for something that should be accomplishable in pure c#.
Is this a problem with the domain, the environment the code is running in, or the code itself?
Upvotes: 3
Views: 2671
Reputation: 11
I had the exact same problem using a very similar C# code. In my case, the account we were using to set the "User cannot change password" flag had that option marked itself. When we removed the flag from the account, the code started working.
This is something that, apparently, only affected C#. Other implementations of the solution worked fine, including PowerShell.
Upvotes: 1