private void GetObject(ActiveDirectoryObjectResult result, AdObject obj, bool returnObject = true, bool returnStatus = true)
    {
        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = config.Action,
            Status  = AdStatusType.Success,
            Message = "Success",
        };

        try
        {
            object adObject = GetActiveDirectoryObject(obj);
            if (returnObject)
            {
                result.Object = adObject;
            }
            if (returnStatus)
            {
                result.Statuses.Add(status);
            }
        }
        catch (AdException ex)
        {
            ProcessActiveDirectoryException(result, ex, status.Action);
        }
        catch (Exception e)
        {
            OnLogMessage("GetObject", e.Message);
            OnLogMessage("GetObject", e.StackTrace);
            AdException le = new AdException(e);
            ProcessActiveDirectoryException(result, le, status.Action);
        }
    }
    private void ProcessDelete(AdObject obj, bool returnObject = false)
    {
        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type     = obj.Type,
            Identity = obj.Identity
        };

        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = config.Action,
            Status  = AdStatusType.Success,
            Message = "Success",
        };

        try
        {
            roleManager.CanPerformActionOrException(requestUser, ActionType.Delete, obj.Identity);
            switch (obj.Type)
            {
            case AdObjectType.User:
                AdUser user = (AdUser)obj;
                DirectoryServices.DeleteUser(user.Identity);
                result.Statuses.Add(status);
                break;

            case AdObjectType.Group:
                AdGroup group = (AdGroup)obj;
                DirectoryServices.DeleteGroup(group.Identity, isDryRun);
                result.Statuses.Add(status);
                break;

            case AdObjectType.OrganizationalUnit:
                AdOrganizationalUnit ou = (AdOrganizationalUnit)obj;
                DirectoryServices.DeleteOrganizationUnit(ou.Identity);
                result.Statuses.Add(status);
                break;

            default:
                throw new AdException("Action [" + config.Action + "] Not Implemented For Type [" + obj.Type + "]", AdStatusType.NotSupported);
            }

            String message = $"{obj.Type} [{obj.Identity}] Deleted.";
            OnLogMessage("ProcessDelete", message);
        }
        catch (AdException ex)
        {
            ProcessActiveDirectoryException(result, ex, status.Action);
        }
        catch (Exception e)
        {
            OnLogMessage("ProcessDelete", e.Message);
            OnLogMessage("ProcessDelete", e.StackTrace);
            AdException le = new AdException(e);
            ProcessActiveDirectoryException(result, le, status.Action);
        }

        results.Add(result);
    }
    private void ProcessGroupAdd(AdObject obj, bool returnObject = true)
    {
        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type     = obj.Type,
            Identity = obj.Identity
        };

        AddToGroup(result, obj, returnObject);
        results.Add(result);
    }
    private void ProcessRoles(AdObject obj, bool returnObject = false)
    {
        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type     = obj.Type,
            Identity = obj.Identity
        };

        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = config.Action,
            Status  = AdStatusType.Success,
            Message = "Success",
        };

        try
        {
            roleManager.CanPerformActionOrException(requestUser, config.Action, obj.Identity);
            foreach (AdRole role in obj.Roles)
            {
                string message = string.Empty;
                switch (config.Action)
                {
                case ActionType.AddRole:
                    roleManager.AddRole(role.Principal, role.Name, obj.Identity);
                    message = $"Role [{role.Name}] Has Been Added To {obj.Type} [{obj.Identity}] For Principal [{role.Principal}].";
                    break;

                case ActionType.RemoveRole:
                    roleManager.RemoveRole(role.Principal, role.Name, obj.Identity);
                    message = $"Role [{role.Name}] Has Been Removed From {obj.Type} [{obj.Identity}] For Principal [{role.Principal}].";
                    break;
                }

                result.Statuses.Add(status);
                OnLogMessage("ProcessAccessRules", message);
            }

            if (returnObject)
            {
                result.Object = GetActiveDirectoryObject(obj);
            }
        }
        catch (AdException ade)
        {
            ProcessActiveDirectoryException(result, ade, config.Action);
        }

        results.Add(result);
    }
    private void ProcessGet(AdObject obj, bool returnObject = true)
    {
        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type     = obj.Type,
            Identity = obj.Identity
        };

        try
        {
            roleManager.CanPerformActionOrException(requestUser, ActionType.Get, obj.Identity);
            GetObject(result, obj, returnObject);
        }
        catch (AdException ade)
        {
            ProcessActiveDirectoryException(result, ade, ActionType.Get);
        }

        results.Add(result);
    }
    private object GetActiveDirectoryObject(AdObject obj)
    {
        switch (obj.Type)
        {
        case AdObjectType.User:
            AdUser user             = (AdUser)obj;
            UserPrincipalObject upo = null;
            upo = DirectoryServices.GetUser(user.Identity, config.ReturnGroupMembership, config.ReturnAccessRules, config.ReturnObjectProperties);
            if (upo == null)
            {
                throw new AdException($"User [{user.Identity}] Was Not Found.", AdStatusType.DoesNotExist);
            }
            return(upo);

        case AdObjectType.Group:
            AdGroup group            = (AdGroup)obj;
            GroupPrincipalObject gpo = null;
            gpo = DirectoryServices.GetGroup(group.Identity, config.ReturnGroupMembership, config.ReturnAccessRules, config.ReturnObjectProperties);
            if (gpo == null)
            {
                throw new AdException($"Group [{group.Identity}] Was Not Found.", AdStatusType.DoesNotExist);
            }
            return(gpo);

        case AdObjectType.OrganizationalUnit:
            AdOrganizationalUnit     ou  = (AdOrganizationalUnit)obj;
            OrganizationalUnitObject ouo = null;
            ouo = DirectoryServices.GetOrganizationalUnit(ou.Identity, config.ReturnAccessRules, config.ReturnObjectProperties);
            if (ouo == null)
            {
                throw new AdException($"Organizational Unit [{ou.Identity}] Was Not Found.", AdStatusType.DoesNotExist);
            }
            return(ouo);

        default:
            throw new AdException("Action [" + config.Action + "] Not Implemented For Type [" + obj.Type + "]", AdStatusType.NotSupported);
        }
    }
    private void AddToGroup(ActiveDirectoryObjectResult result, AdObject obj, bool returnObject = true)
    {
        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = ActionType.AddToGroup,
            Status  = AdStatusType.Success,
            Message = "Success",
        };

        try
        {
            switch (obj.Type)
            {
            case AdObjectType.User:
                AdUser user = (AdUser)obj;
                if (user.Groups != null)
                {
                    foreach (string userGroup in user.Groups)
                    {
                        try
                        {
                            roleManager.CanPerformActionOrException(requestUser, ActionType.AddToGroup, userGroup);
                            DirectoryServices.AddUserToGroup(user.Identity, userGroup, isDryRun);
                            String userMessage = $"{obj.Type} [{user.Identity}] Added To Group [{userGroup}].";
                            OnLogMessage("ProcessGroupAdd", userMessage);
                            status.Message = userMessage;
                            result.Statuses.Add(new ActiveDirectoryStatus(status));
                        }
                        catch (AdException ldeUserEx)
                        {
                            ProcessActiveDirectoryException(result, ldeUserEx, status.Action);
                        }
                    }
                }
                break;

            case AdObjectType.Group:
                AdGroup group = (AdGroup)obj;
                if (group.Groups != null)
                {
                    foreach (string groupGroup in group.Groups)
                    {
                        try
                        {
                            roleManager.CanPerformActionOrException(requestUser, ActionType.AddToGroup, groupGroup);
                            DirectoryServices.AddGroupToGroup(group.Identity, groupGroup, isDryRun);
                            String groupMessage = $"{obj.Type} [{group.Identity}] Added To Group [{groupGroup}].";
                            OnLogMessage("ProcessGroupAdd", groupMessage);
                            status.Message = groupMessage;
                            result.Statuses.Add(new ActiveDirectoryStatus(status));
                        }
                        catch (AdException ldeGroupEx)
                        {
                            ProcessActiveDirectoryException(result, ldeGroupEx, status.Action);
                        }
                    }
                }
                break;

            default:
                throw new AdException("Action [" + config.Action + "] Not Implemented For Type [" + obj.Type + "]", AdStatusType.NotSupported);
            }

            if (returnObject)
            {
                GetObject(result, obj, true, false);
            }
        }
        catch (AdException ex)
        {
            ProcessActiveDirectoryException(result, ex, status.Action);
        }
        catch (Exception e)
        {
            OnLogMessage("ProcessGroupAdd", e.Message);
            OnLogMessage("ProcessGroupAdd", e.StackTrace);
            AdException le = new AdException(e);
            ProcessActiveDirectoryException(result, le, status.Action);
        }
    }
    private void ProcessAccessRules(AdObject obj, bool returnObject = false)
    {
        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type     = obj.Type,
            Identity = obj.Identity
        };

        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = config.Action,
            Status  = AdStatusType.Success,
            Message = "Success",
        };

        try
        {
            roleManager.CanPerformActionOrException(requestUser, config.Action, obj.Identity);

            // Get Target DirectoryEntry For Rules
            DirectoryEntry de = null;
            if (obj.Type == AdObjectType.User || obj.Type == AdObjectType.Group)
            {
                Principal principal = DirectoryServices.GetPrincipal(obj.Identity);
                if (principal == null)
                {
                    throw new AdException($"Principal [{obj.Identity}] Can Not Be Found.", AdStatusType.DoesNotExist);
                }
                else if (principal.GetUnderlyingObjectType() == typeof(DirectoryEntry))
                {
                    de = (DirectoryEntry)principal.GetUnderlyingObject();
                }
                else
                {
                    throw new AdException($"AddAccessRule Not Available For Object Type [{principal.GetUnderlyingObjectType()}]", AdStatusType.NotSupported);
                }
            }
            else
            {
                de = DirectoryServices.GetDirectoryEntry(obj.Identity);
                if (de == null)
                {
                    throw new AdException($"DirectoryEntry [{obj.Identity}] Can Not Be Found.", AdStatusType.DoesNotExist);
                }
            }

            // Add Rules To Target DirectoryEntry
            foreach (AdAccessRule rule in obj.AccessRules)
            {
                String message = String.Empty;
                switch (config.Action)
                {
                case ActionType.AddAccessRule:
                    DirectoryServices.AddAccessRule(de, rule.Identity, rule.Rights, rule.Type);
                    message = $"{rule.Type} [{rule.Rights}] Rule Added To {obj.Type} [{obj.Identity}] For Identity [{rule.Identity}].";
                    break;

                case ActionType.RemoveAccessRule:
                    DirectoryServices.DeleteAccessRule(de, rule.Identity, rule.Rights, rule.Type);
                    message = $"{rule.Type} [{rule.Rights}] Rule Deleted From {obj.Type} [{obj.Identity}] For Identity [{rule.Identity}].";
                    break;

                case ActionType.SetAccessRule:
                    DirectoryServices.SetAccessRule(de, rule.Identity, rule.Rights, rule.Type);
                    message = $"{rule.Type} [{rule.Rights}] Rule Set On {obj.Type} [{obj.Identity}] For Identity [{rule.Identity}].";
                    break;

                case ActionType.PurgeAccessRules:
                    DirectoryServices.PurgeAccessRules(de, rule.Identity);
                    message = $"All Rules Purged On {obj.Type} [{obj.Identity}] For Identity [{rule.Identity}].";
                    break;

                default:
                    throw new AdException("Action [" + config.Action + "] Not Implemented For Type [" + obj.Type + "]", AdStatusType.NotSupported);
                }

                result.Statuses.Add(status);
                OnLogMessage("ProcessAccessRules", message);
            }

            if (returnObject)
            {
                result.Object = GetActiveDirectoryObject(obj);
            }
        }
        catch (AdException ex)
        {
            ProcessActiveDirectoryException(result, ex, status.Action);
        }
        catch (Exception e)
        {
            OnLogMessage("ProcessDelete", e.Message);
            OnLogMessage("ProcessDelete", e.StackTrace);
            AdException le = new AdException(e);
            ProcessActiveDirectoryException(result, le, status.Action);
        }

        results.Add(result);
    }
    private void ProcessModify(AdObject obj, bool returnObject = true)
    {
        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type     = obj.Type,
            Identity = obj.Identity
        };

        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = config.Action,
            Status  = AdStatusType.Success,
            Message = "Success",
        };

        try
        {
            string statusAction = "Modified";

            switch (obj.Type)
            {
            case AdObjectType.User:
                AdUser        user = (AdUser)obj;
                UserPrincipal up   = null;
                if (config.UseUpsert && !DirectoryServices.IsExistingUser(obj.Identity))
                {
                    if (DirectoryServices.IsDistinguishedName(obj.Identity))
                    {
                        String path = DirectoryServices.GetParentPath(obj.Identity);
                        roleManager.CanPerformActionOrException(requestUser, ActionType.Create, path);
                        up           = user.CreateUserPrincipal();
                        statusAction = "Created";
                    }
                    else
                    {
                        throw new AdException($"Identity [{obj.Identity}] Must Be A Distinguished Name For User Creation.", AdStatusType.MissingInput);
                    }
                }
                else
                {
                    roleManager.CanPerformActionOrException(requestUser, ActionType.Modify, obj.Identity);
                    up = DirectoryServices.GetUserPrincipal(obj.Identity);
                    if (up == null)
                    {
                        throw new AdException($"User [{obj.Identity}] Not Found.", AdStatusType.DoesNotExist);
                    }
                    user.UpdateUserPrincipal(up);
                }

                DirectoryServices.SaveUser(up, isDryRun);

                OnLogMessage("ProcessModify", obj.Type + " [" + obj.Identity + "] " + statusAction + ".");
                if (user.Groups != null)
                {
                    ProcessGroupAdd(user, false);
                }
                result.Statuses.Add(status);
                break;

            case AdObjectType.Group:
                AdGroup        group = (AdGroup)obj;
                GroupPrincipal gp    = null;
                if (config.UseUpsert && !DirectoryServices.IsExistingGroup(obj.Identity))
                {
                    if (DirectoryServices.IsDistinguishedName(obj.Identity))
                    {
                        String path = DirectoryServices.GetParentPath(obj.Identity);
                        roleManager.CanPerformActionOrException(requestUser, ActionType.Create, path);
                        gp           = group.CreateGroupPrincipal();
                        statusAction = "Created";
                    }
                    else
                    {
                        throw new AdException($"Identity [{obj.Identity}] Must Be A Distinguished Name For Group Creation.", AdStatusType.MissingInput);
                    }
                }
                else
                {
                    roleManager.CanPerformActionOrException(requestUser, ActionType.Modify, obj.Identity);
                    gp = DirectoryServices.GetGroupPrincipal(obj.Identity);
                    if (gp == null)
                    {
                        throw new AdException($"Group [{obj.Identity}] Not Found.", AdStatusType.DoesNotExist);
                    }
                    group.UpdateGroupPrincipal(gp);
                }

                DirectoryServices.SaveGroup(gp, isDryRun);
                OnLogMessage("ProcessModify", obj.Type + " [" + obj.Identity + "] " + statusAction + ".");
                if (group.Groups != null)
                {
                    ProcessGroupAdd(group, false);
                }
                result.Statuses.Add(status);
                break;

            case AdObjectType.OrganizationalUnit:
                AdOrganizationalUnit ou = (AdOrganizationalUnit)obj;

                // Get DistinguishedName from User or Group Identity for ManagedBy Property
                if (!String.IsNullOrWhiteSpace(ou.ManagedBy))
                {
                    if (ou.Properties == null)
                    {
                        ou.Properties = new Dictionary <string, List <string> >();
                    }

                    if (!ou.Properties.ContainsKey("managedBy"))
                    {
                        String distinguishedName = DirectoryServices.GetDistinguishedName(ou.ManagedBy);
                        if (distinguishedName == null)
                        {
                            distinguishedName = ou.ManagedBy;
                        }

                        List <String> values = new List <string>()
                        {
                            distinguishedName
                        };
                        ou.Properties.Add("managedBy", values);
                    }
                }

                if (config.UseUpsert && !DirectoryServices.IsExistingDirectoryEntry(obj.Identity))
                {
                    if (DirectoryServices.IsDistinguishedName(obj.Identity))
                    {
                        String path = DirectoryServices.GetParentPath(obj.Identity);
                        roleManager.CanPerformActionOrException(requestUser, ActionType.Create, path);
                        if (!String.IsNullOrWhiteSpace(ou.Description))
                        {
                            DirectoryServices.AddProperty(ou.Properties, "description", ou.Description);
                        }
                        DirectoryServices.CreateOrganizationUnit(obj.Identity, ou.Properties, isDryRun);
                        statusAction = "Created";
                    }
                    else
                    {
                        throw new AdException($"Identity [{obj.Identity}] Must Be A Distinguished Name For Organizational Unit Creation.", AdStatusType.MissingInput);
                    }
                }
                else
                {
                    roleManager.CanPerformActionOrException(requestUser, ActionType.Modify, obj.Identity);
                    if (!String.IsNullOrWhiteSpace(ou.Description))
                    {
                        DirectoryServices.AddProperty(ou.Properties, "description", ou.Description);
                    }
                    DirectoryServices.ModifyOrganizationUnit(ou.Identity, ou.Properties, isDryRun);
                }

                OnLogMessage("ProcessModify", obj.Type + " [" + obj.Identity + "] " + statusAction + ".");
                result.Statuses.Add(status);
                break;

            default:
                throw new AdException("Action [" + config.Action + "] Not Implemented For Type [" + obj.Type + "]", AdStatusType.NotSupported);
            }

            if (returnObject)
            {
                result.Object = GetActiveDirectoryObject(obj);
            }
        }
        catch (AdException ex)
        {
            ProcessActiveDirectoryException(result, ex, status.Action);
        }
        catch (Exception e)
        {
            OnLogMessage("ProcessCreate", e.Message);
            OnLogMessage("ProcessCreate", e.StackTrace);
            AdException le = new AdException(e);
            ProcessActiveDirectoryException(result, le, status.Action);
        }

        results.Add(result);
    }