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 ProcessActiveDirectoryException(ActiveDirectoryObjectResult result, AdException ex, ActionType action)
    {
        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = action,
            Status  = ex.Type,
            Message = ex.Message,
        };

        OnLogMessage("Exception", ex.Message);
        result.Statuses.Add(status);
    }
    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 ProcessSearchRequest(AdSearchRequest request)
    {
        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = ActionType.Search,
            Status  = AdStatusType.Success,
            Message = "Success",
        };


        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type = AdObjectType.SearchResults,
        };

        try
        {
            string searchBase = request.SearchBase;
            if (String.IsNullOrWhiteSpace(request.SearchBase))
            {
                searchBase = DirectoryServices.GetDomainDistinguishedName();
            }
            roleManager.CanPerformActionOrException(requestUser, ActionType.Search, searchBase);

            String filter = request.Filter;
            if (request.Parameters != null)
            {
                foreach (RegexParameters param in request.Parameters)
                {
                    filter = Regex.Replace(filter, param.Find, param.ReplaceWith);
                }
            }

            OnLogMessage("ProcessSearchRequest", $"Executing Search.  Filter String: [{filter}].  Search Base: [{searchBase}].");
            SearchResultsObject searchResults = DirectoryServices.Search(searchBase, filter, request.ReturnAttributes?.ToArray());
            result.Object = searchResults;
            result.Statuses.Add(status);
        }
        catch (AdException ade)
        {
            ProcessActiveDirectoryException(result, ade, ActionType.Search);
        }

        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 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);
    }
    private ActiveDirectoryHandlerResults CallPlan(string planName, StartPlanEnvelope planEnvelope)
    {
        IExecuteController ec = GetExecuteControllerInstance();
        StartPlanEnvelope  pe = planEnvelope;

        if (pe == null)
        {
            pe = new StartPlanEnvelope()
            {
                DynamicParameters = new Dictionary <string, string>()
            }
        }
        ;

        // Add Query String values into Plan Envelope Exactly As Provided
        IEnumerable <KeyValuePair <string, string> > queryString = this.Request.GetQueryNameValuePairs();

        foreach (KeyValuePair <string, string> kvp in queryString)
        {
            pe.DynamicParameters.Add(kvp.Key, kvp.Value);
        }

        object reply = ec.StartPlanSync(pe, planName, setContentType: false);
        ActiveDirectoryHandlerResults result = null;
        Type replyType = reply.GetType();

        if (replyType == typeof(Dictionary <object, object>))
        {
            String str = YamlHelpers.Serialize(reply);
            result = YamlHelpers.Deserialize <ActiveDirectoryHandlerResults>(str);
        }
        else if (replyType == typeof(XmlDocument))
        {
            XmlDocument doc = (XmlDocument)reply;
            result = XmlHelpers.Deserialize <ActiveDirectoryHandlerResults>(doc.InnerXml);
        }
        else
        {
            try
            {
                result = YamlHelpers.Deserialize <ActiveDirectoryHandlerResults>(reply.ToString());
            }
            catch (Exception)
            {
                try
                {
                    // Reply was not Json or Yaml.  See if Xml
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(reply.ToString());
                    result = XmlHelpers.Deserialize <ActiveDirectoryHandlerResults>(doc.InnerXml);
                }
                catch (Exception)
                {
                    // Reply was of unknown type.  Put Raw Output In Return Object
                    result = new ActiveDirectoryHandlerResults();
                    ActiveDirectoryObjectResult error  = new ActiveDirectoryObjectResult();
                    ActiveDirectoryStatus       status = new ActiveDirectoryStatus();

                    status.StatusId = AdStatusType.NotSupported;
                    status.Message  = $"Unable To Parse ObjectType [{replyType}].";
                    status.ActionId = ActionType.None;
                    error.Statuses.Add(status);

                    error.TypeId = AdObjectType.None;
                    error.Object = reply;
                    result.Add(error);
                }
            }
        }

        return(result);
    }