public ActionResult SaveUsers(ICollection <int> roleIds, ICollection <Guid> users, string submitButton)
        {
            if (submitButton == "Remove")
            {
                if (users != null)
                {
                    List <UserDetailsModel> model = new List <UserDetailsModel>();
                    IAdSearch searcher            = new AdSearch();

                    foreach (var user in users)
                    {
                        string displayName;
                        try
                        {
                            displayName = searcher.GetUserDisplayName(user);
                        }
                        catch (Exception)
                        {
                            displayName = "Name not found";
                        }

                        model.Add(new UserDetailsModel
                        {
                            UserDto = new UserDto {
                                AdGuid = user
                            },
                            DisplayName = displayName
                        });
                    }

                    return(View("ConfirmDeleteUsers", model));
                }
            }

            if (users != null && roleIds != null && users.Any() && roleIds.Any())
            {
                foreach (var user in users)
                {
                    IUserDto userDto = null;                     //the dto, user is just the guid
                    try
                    {
                        userDto = _userManager.GetUser(user);
                    }
                    catch (Exception)
                    {
                        /* user does not exist */
                    }

                    if (userDto == null)                     /* first add anyone new if not found above*/
                    {
                        UserDto newUser = new UserDto {
                            AdGuid = user
                        };
                        ScriptExecutor       scriptExecutor   = new ScriptExecutor();
                        ScriptFileController scriptController = new ScriptFileController();
                        try
                        {
                            var scriptGuid = scriptController.GetScript(UserId, ConfigHelper.GetDepartmentScriptId()).ScriptFile;
                            newUser.DepartmentId = (from d in _departmentController.GetDepartments(UserId)
                                                    where d.Name == scriptExecutor.GetUserDepartment(user, scriptGuid)
                                                    select d.Id).FirstOrDefault();
                            userDto = _userManager.ModifyUser(UserId, newUser, EntityModification.Create);
                        }
                        catch (Exception exception)
                        {
                            TempData["MessageType"] = WebMessageType.Failure;
                            TempData["Message"]     = $"Failed to save adding a user, error: {exception.Message}";
                            return(RedirectToAction("ManageUsers"));
                        }
                    }

                    //Remove roles from the user where all the roleIds do not match the ID
                    foreach (var role in userDto.Roles.Where(x => roleIds.All(y => y != x.Id)))
                    {
                        try
                        {
                            /* useless is a lazy loading work around */
                            var useless = _userManager.RemoveRoleFromUsers(UserId, role, new List <IUserDto> {
                                userDto
                            });
                            foreach (var unused in useless)
                            {
                                /* do nothing */
                            }
                        }
                        catch (Exception)
                        {
                            /* ignore if user did not have role somehow */
                        }
                    }
                    //add roles
                    foreach (var roleId in roleIds)
                    {
                        try
                        {
                            var useless = _userManager.AddRolesToUser(UserId, userDto.Id, new List <IRoleDto> {
                                new RoleDto {
                                    Id = roleId
                                }
                            });
                            foreach (var unused in useless)
                            {
                                /*do nothing */
                            }                             //lazy loading work around
                        }
                        catch (Exception exception)
                        {
                            TempData["MessageType"] = WebMessageType.Failure;
                            TempData["Message"]     = $"Failed to save user changes, error: {exception.Message}";
                            return(RedirectToAction("ManageUsers"));
                        }
                    }
                }

                TempData["MessageType"] = WebMessageType.Success;                 //successful assumed now
                TempData["Message"]     = "Successfully saved users";
            }
            else
            {
                TempData["MessageType"] = WebMessageType.Info;
                TempData["Message"]     = "No changes made";
            }
            return(RedirectToAction("ManageUsers"));
        }
Example #2
0
        /// <summary>
        /// Gets the AD display name of a User directly from an AD identifier
        /// </summary>
        /// <param name="userGuid"></param>
        /// <returns></returns>
        public string GetDisplayName(Guid userGuid)
        {
            IAdSearch userSearch = new AdSearch();

            return(userSearch.GetUserDisplayName(userGuid));
        }
        /// <summary>
        /// Apply a filter on the results
        /// </summary>
        /// <param name="id">role Id</param>
        /// <param name="pageId">page of results</param>
        /// <returns></returns>
        public ActionResult FilterByRole(int id, int pageId = 0)
        {
            UserControlsModel controls = new UserControlsModel {
                CurrentPage = pageId, SelectedRole = id
            };                                                                                                          /*construct model for view */
            var model = new ManageUsersModel {
                Controls = controls, ReturningSearch = false
            };

            model.Roles = _userManager.GetRoles(UserId).ToList();             //stop forgetting these roles, ok?

            controls.Roles = from r in _userManager.GetRoles(UserId) select new Tuple <int, string>(r.Id, r.Name);

            IEnumerable <IUserDto> users = new List <UserDto>();

            if (id == 0)
            {
                users = (from u in _userManager.GetUsers(UserId) select u);
            }
            else if (id > 0)
            {
                users = (from u in _userManager.GetUsers(UserId) where u.Roles.Any(role => role.Id == id) select u);
            }

            List <UserDetailsModel> modelUsers = new List <UserDetailsModel>();

            IAdSearch searcher = new AdSearch();

            foreach (var user in users)
            {
                string displayName = null;                 //debugging with no AD
                if (user.Name == null)
                {
                    try
                    {
                        displayName = searcher.GetUserDisplayName(user.AdGuid);
                    }
                    catch
                    {
                        displayName = "Name not found";
                    }
                }
                else
                {
                    displayName = user.Name;
                }


                modelUsers.Add(new UserDetailsModel {
                    UserDto = user, DisplayName = displayName
                });
            }
            modelUsers = modelUsers.OrderBy(o => o.DisplayName).ToList();

            if (modelUsers.Count() > _userPageSize)                                                     //pagination
            {
                model.Controls.TotalPages = ((modelUsers.Count() + _userPageSize - 1) / _userPageSize); //# pages
                modelUsers = modelUsers.Skip(_userPageSize * pageId).Take(_userPageSize).ToList();      //contents of the page
            }
            model.Users = modelUsers;

            return(View("ManageUsers", model));
        }