Updating user via System.DirectoryServices.AccountManagement library randomly results in 'Attempted to access an unloaded appdomain.' exceptions

75 views Asked by At

We've implemented logic using System.DirectoryServices.AccountManagement (.NET Framework 4.5.2) to update user's Enabled flag. The issue is that we are sporadically receiving the following exception on user update:

System.AppDomainUnloadedException: Attempted to access an unloaded appdomain. (Exception from HRESULT: 0x80131014)
   at System.StubHelpers.StubHelpers.InternalGetCOMHRExceptionObject(Int32 hr, IntPtr pCPCMD, Object pThis, Boolean fForWinRT)
   at System.StubHelpers.StubHelpers.GetCOMHRExceptionObject(Int32 hr, IntPtr pCPCMD, Object pThis)
   at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.PutEx(Int32 lnControlCode, String bstrName, Object vProp)
   at System.DirectoryServices.PropertyValueCollection.OnClearComplete()
   at System.DirectoryServices.PropertyValueCollection.set_Value(Object value)
   at System.DirectoryServices.AccountManagement.SDSUtils.AccountControlToDirectoryEntry(Principal p, String propertyName, DirectoryEntry de, String suggestedProperty, Boolean isSAM, Boolean isUnpersisted)
   at System.DirectoryServices.AccountManagement.SAMStoreCtx.UserFlagsToWinNTConverter(Principal p, String propertyName, DirectoryEntry de, String suggestedWinNTProperty, Boolean isLSAM)
   at System.DirectoryServices.AccountManagement.SAMStoreCtx.PushChangesToNative(Principal p)
   at System.DirectoryServices.AccountManagement.SDSUtils.ApplyChangesToDirectory(Principal p, StoreCtx storeCtx, GroupMembershipUpdater updateGroupMembership, NetCred credentials, AuthenticationTypes authTypes)
   at System.DirectoryServices.AccountManagement.SAMStoreCtx.Update(Principal p)

Code that throws that exception:

using (PrincipalContext context = new PrincipalContext(ContextType.Machine, Environment.MachineName))
{
    UserPrincipal toUpdate = UserPrincipal.FindByIdentity(context, IdentityType.Name, username);

    if (toUpdate.Enabled != active)
    {
        toUpdate.Enabled = active;
        toUpdate.Save();
    }                
}

That code runs on Windows Server 2012 R2

We are expecting that code to run consistently without sporadic exceptions.

0

There are 0 answers