ActiveDirectoryBlogPost.DisableUserMicroservice.Repository.ActiveDirectory.DisableUserRepository.DisableBySamAccountName C# (CSharp) Method

DisableBySamAccountName() public method

Disables a user with a specific ID.
public DisableBySamAccountName ( string customerName, string samAccountName ) : void
customerName string The name of the customer the user belongs to.
samAccountName string The id of the user to disable.
return void
        public void DisableBySamAccountName(string customerName, string samAccountName)
        {
            using (var activeDirectorySearcher = ActiveDirectoryConnector.GetDirectorySearcher(customerName))
            {
                activeDirectorySearcher.Filter = "(&(sAMAccountName=" + samAccountName + "))";
                activeDirectorySearcher.PropertiesToLoad.Add("userAccountControl");

                var result = activeDirectorySearcher.FindOne();

                if (result == null)
                {
                    throw new UserNotFoundException("The user with the sAMAccountName " + samAccountName + " could not be found.");
                }

                var entryToUpdate = result.GetDirectoryEntry();

                // Perform the Block
                var val = (int)entryToUpdate.Properties["userAccountControl"].Value;
                entryToUpdate.Properties["userAccountControl"].Value = val | (int)UserAccountControl.UF_ACCOUNT_DISABLE;

                entryToUpdate.CommitChanges();
                entryToUpdate.Close();
            }
        }
    }
DisableUserRepository