public void GivenGenerateViewModelThrowsValidationExceptionOnPostedRoles_WhenCreateRole_ThenPartialViewResultIsReturned_AndModelStateContainsPostedRolesErrors()
        {
            UserRoleModel viewModel = new UserRoleModel { UserId = 1 };
            MockAccountManager.Expect(m => m.Create(viewModel, User)).Throw(new ValidationException(new ValidationResult("fake error happened!", new string[] { "PostedRoles" }), null, null));

            PartialViewResult result = Target.CreateRole(viewModel) as PartialViewResult;

            Assert.IsNotNull(result);
            Assert.IsTrue(Target.ModelState["PostedRoles"].Errors.Count > 0);
        }
 private void EditRoles(User user, IEnumerable<int> PostedRoles, UserRoleModel viewModel, EducationSecurityPrincipal requestor)
 {
     var rolesToEdit = user.UserRoles.Select(u => u.RoleId).Intersect(PostedRoles).ToList();
     foreach (int roleId in rolesToEdit)
     {
         var role = RoleRepository.Items.Where(r => r.Id == roleId).SingleOrDefault();
         if (role != null)
         {
             var schools = GetSelectedSchools(viewModel.allSchoolsSelected, role, viewModel.SelectedSchoolIds).ToList();
             var providers = GetSelectedProviders(role, viewModel.SelectedProviderIds).ToList();
             var updatedUserRole = user.UserRoles.Where(u => u.RoleId == roleId).Single();
             var schoolsToRemove = updatedUserRole.Schools.Except(schools).ToArray();
             foreach (School school in schoolsToRemove)
             {
                 UserRoleRepository.DeleteLink(updatedUserRole, school);
             }
             var schoolsToAdd = schools.Except(updatedUserRole.Schools).ToList();
             foreach (School school in schoolsToAdd)
             {
                 UserRoleRepository.AddLink(updatedUserRole, school);
             }
             var providersToRemove = updatedUserRole.Providers.Except(providers).ToArray();
             foreach (Provider provider in providersToRemove)
             {
                 UserRoleRepository.DeleteLink(updatedUserRole, provider);
             }
             var providersToAdd = providers.Except(updatedUserRole.Providers).ToList();
             foreach (Provider provider in providersToAdd)
             {
                 UserRoleRepository.AddLink(updatedUserRole, provider);
             }
             updatedUserRole.LastModifyingUser = requestor.Identity.User;
             updatedUserRole.LastModifyTime = DateTime.Now;
             UserRoleRepository.Update(updatedUserRole);
         }
     }
 }
 public void PopulateViewModel(UserRoleModel viewModel)
 {
     if (viewModel == null)
     {
         throw new ArgumentNullException("viewModel");
     }
     viewModel.Schools = new MultiSelectList(SchoolRepository.Items.OrderBy(s => s.Name), "Id", "Name", viewModel.SelectedSchoolIds);
     viewModel.Providers = new MultiSelectList(ProviderRepository.Items.Where(p => p.IsActive).OrderBy(p => p.Name), "Id", "Name", viewModel.SelectedProviderIds);
     viewModel.AvailableRoles = RoleRepository.Items;
 }
 public UserRoleModel GenerateCreateViewModel(int id)
 {
     var user = UserRepository.Items.SingleOrDefault(u => u.Id == id);
     if (user == null)
     {
         throw new EntityNotFoundException("User does not exist.");
     }
     UserRoleModel viewModel = new UserRoleModel();
     viewModel.CopyFrom(user);
     PopulateViewModel(viewModel);
     return viewModel;
 }
 public void Create(UserRoleModel viewModel, EducationSecurityPrincipal user)
 {
     if (viewModel == null)
     {
         throw new ArgumentNullException("viewModel");
     }
     if (viewModel.PostedRoles == null)
     {
         throw new ValidationException(new ValidationResult("You must select at least 1 role", new string[] { "PostedRoles" }), null, null);
     }
     var item = UserRepository.Items.
                                     Include("UserRoles.Role").
                                     Include("UserRoles.Schools").
                                     Include("UserRoles.Providers").
                                     SingleOrDefault(u => u.Id == viewModel.UserId);
     if (item == null)
     {
         throw new EntityNotFoundException("User does not exist.");
     }
     item.Active = true;
     item.Comments = viewModel.Comments;
     AddRoles(item, viewModel.PostedRoles, viewModel, user);
     UserRepository.Update(item);
     UserAccessChangeEventRepository.Add(Auditor.CreateAccessChangeEvent(item, user.Identity.User));
     RepositoryContainer.Save();
 }
        public void WhenEditRolePostedWithoutSchoolsAsSiteCoordinator_ThenJsonResultReturned()
        {
            int userId = 1;
            var expectedUpdate = Data.Users.Single(u => u.Id == userId);
            int newRoleId = 2;
            var expectedRemove = expectedUpdate.UserRoles.Single(ur => ur.RoleId != newRoleId);
            var viewModel = new UserRoleModel
            {
                UserId = userId,
                Comments = "Testing",
                PostedRoles = new int[] { newRoleId }
            };
            AddAdditionalUsers();

            Target.Edit(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(u => u.Remove(expectedRemove));
            Repositories.MockUserRepository.AssertWasCalled(u => u.Update(expectedUpdate));
            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void WhenCreate_ThenChangesSaved_AndUserRoleIsUpdatedCorrectly()
        {
            AddAdditionalUsers();
            var expectedUser = Repositories.MockUserRepository.Items.Where(u => u.Id == 1).SingleOrDefault();
            var expectedRole = Repositories.MockRoleRepository.Items.Where(r => r.Id == 1).SingleOrDefault();
            var expectedComments = "Test Comments";
            var expectedSchools = Repositories.MockSchoolRepository.Items.Where(s => s.Id == 1).ToList();
            var viewModel = new UserRoleModel
            {
                UserId = 3,
                Comments = expectedComments,
                SelectedProviderIds = new List<int>(),
                SelectedSchoolIds = new List<int> { 1 },
                PostedRoles = new int[] { 2 }
            };

            Target.Create(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(u => u.Add(null), options => options.IgnoreArguments().Do(new Action<UserRole>(u =>
            {
                Assert.AreEqual(expectedUser, u.User);
                Assert.AreEqual(expectedRole, u.Role);
                Assert.AreEqual(expectedSchools, u.Schools);
            })));
            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void GivenViewModel_WhenPopulateViewModelIsCalled_ThenListsArePopulatedOrderedByName()
        {
            var expectedSchools = Repositories.MockSchoolRepository.Items.OrderBy(s => s.Name);
            var actual = new UserRoleModel();

            Target.PopulateViewModel(actual);

            Assert.AreEqual(Repositories.MockRoleRepository.Items, actual.AvailableRoles);
            CollectionAssert.AreEqual(expectedSchools.ToList(), actual.Schools.Items.Cast<School>().ToList());
        }
        public void WhenIRemoveAllOfMyUserRoles_ThenIWillNotHaveAnyUserRoles()
        {
            var users = Data.Users;
            var userId = users[0].Id;
            var viewModel = new UserRoleModel
            {
                UserId = userId
            };
            var expectedRemove = users[0].UserRoles.Single();
            Repositories.MockUserRepository.Expect(m => m.Items).Return(users.AsQueryable());

            Target.Edit(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(u => u.Remove(expectedRemove));
        }
        public void WhenGenerateEditViewModel_ThenAPartialViewIsReturned()
        {
            var user = Users.Where(u => u.Id == 1).SingleOrDefault();
            UserRoleModel expectedViewModel = new UserRoleModel();
            expectedViewModel.CopyFrom(user);
            expectedViewModel.UserRoleIds = user.UserRoles.Select(u => u.Id);
            expectedViewModel.AvailableRoles = Repositories.MockRoleRepository.Items;
            expectedViewModel.SelectedRoles = user.UserRoles.Select(u => u.Role);
            AddAdditionalUsers();

            UserRoleModel actual = Target.GenerateEditViewModel(1);

            Assert.IsNotNull(actual);
            CollectionAssert.AreEqual(expectedViewModel.AvailableRoles.ToList(), actual.AvailableRoles.ToList());
            Assert.AreEqual(expectedViewModel.Comments, actual.Comments);
            Assert.AreEqual(expectedViewModel.PostedRoles, actual.PostedRoles);
            CollectionAssert.AreEqual(expectedViewModel.SelectedRoles.ToList(), actual.SelectedRoles.ToList());
            CollectionAssert.AreEqual(expectedViewModel.SelectedSchoolIds.ToList(), actual.SelectedSchoolIds.ToList());
            Assert.AreEqual(expectedViewModel.UserId, actual.UserId);
            CollectionAssert.AreEqual(expectedViewModel.UserRoleIds.ToList(), actual.UserRoleIds.ToList());
        }
        public void GivenLogicManagerReturnsViewModel_WhenIEditRole_ThenPartialViewResultContainsViewModel()
        {
            int expectedId = 878797;
            UserRoleModel expected = new UserRoleModel();
            MockAccountManager.Expect(m => m.GenerateEditViewModel(expectedId)).Return(expected);

            var result = Target.EditRole(expectedId) as PartialViewResult;

            result.AssertGetViewModel(expected);
        }
 public ActionResult CreateRole(UserRoleModel viewModel)
 {
     try
     {
         LogicManager.Create(viewModel, (EducationSecurityPrincipal)User);
     }
     catch (ValidationException e)
     {
         ModelState.AddModelErrors(e);
         LogicManager.PopulateViewModel(viewModel);
         return PartialView(viewModel);
     }
     return Json(true);
 }
 public ActionResult EditRole(UserRoleModel viewModel)
 {
     LogicManager.Edit(viewModel, (EducationSecurityPrincipal)User);
     return Json(true);
 }
 public void InitializeTest()
 {
     Target = new UserRoleModel();
 }
        public void GivenRoleAssignmentDoesNotChange_WhenEditRoleIsPostedWithSchoolsAsSiteCoordinator_ThenUserRoleMappingAudited()
        {
            int userId = 1;
            var expectedUpdate = Data.Users.Single(u => u.Id == userId).UserRoles.Single();
            var viewModel = new UserRoleModel
            {
                UserId = userId,
                Comments = "Testing",
                PostedRoles = new int[] { expectedUpdate.RoleId }
            };
            AddAdditionalUsers();

            Target.Edit(viewModel, User);

            Assert.AreEqual(User.Identity.User, expectedUpdate.LastModifyingUser);
            Assert.IsTrue(expectedUpdate.LastModifyTime.Value.WithinTimeSpanOf(TimeSpan.FromSeconds(1), DateTime.Now));
        }
        public void GivenViewModel_WhenEdit_ThenAuditorCreatesChangeEvent_AndEventAddedToRepository()
        {
            AddAdditionalUsers();
            var viewModel = new UserRoleModel
            {
                UserId = 3,
                PostedRoles = new int[] { 2 }
            };
            var expectedAuditEvent = new UserAccessChangeEvent();
            MockUserAuditor.Expect(m => m.CreateAccessChangeEvent(Data.Users.Single(u => u.Id == viewModel.UserId), User.Identity.User)).Return(expectedAuditEvent);

            Target.Edit(viewModel, User);

            Repositories.MockUserAccessChangeEventRepository.AssertWasCalled(m => m.Add(expectedAuditEvent));
        }
        public void GivenUserHasMultipleRoles_WhenEditUserProfile_ThenErrorThrown()
        {
            User notExpected = Users[3];
            var expectedState = new UserRoleModel { UserId = notExpected.Id, PostedRoles = notExpected.UserRoles.Select(u => u.Id) };

            TestExtensions.ExpectException<ValidationException>(() => Target.Edit(expectedState, User));
        }
        public void WhenCreate_ThenChangesSaved()
        {
            var viewModel = new UserRoleModel
            {
                UserId = 3,
                Comments = "Test Comments",
                SelectedSchoolIds = new List<int> { 1 },
                SelectedProviderIds = new List<int>(),
                PostedRoles = new int[] { 2 }
            };
            AddAdditionalUsers();

            Target.Create(viewModel, User);

            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void GivenUserRemovesProvider_WhenIEditRoles_ThenJsonResultReturned()
        {
            UserRoleModel viewModel = new UserRoleModel
            {
                UserId = 3,
                Comments = "Testing",
                PostedRoles = new int[] { Repositories.MockRoleRepository.Items.Where(m => m.Name.Equals(SecurityRoles.Provider)).Select(p => p.Id).SingleOrDefault() },
                SelectedProviderIds = new List<int> { 1 }
            };
            AddAdditionalUsers();

            Target.Edit(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(u => u.DeleteLink(Data.UserRoles[2], Data.Providers[2]));
            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void WhenEditRoleIsPosted_ThenJsonResultReturned()
        {
            AddAdditionalUsers();
            var viewModel = new UserRoleModel { UserId = 1, PostedRoles = new int[] { } };

            Target.Edit(viewModel, User);

            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void GivenUserRoleWithProvider_WhenCreate_ThenChangesSaved_AndAddedToUserRole()
        {
            AddAdditionalUsers();
            var expectedUser = Repositories.MockUserRepository.Items.Where(u => u.Id == 1).SingleOrDefault();
            var expectedRole = Repositories.MockRoleRepository.Items.Where(r => r.Name.Equals(SecurityRoles.Provider)).SingleOrDefault();
            var expectedComments = "Test Comments";
            var expectedProviders = Repositories.MockProviderRepository.Items.Where(p => p.Id == 1).SingleOrDefault();
            var expectedSchools = new List<School>();
            var viewModel = new UserRoleModel
            {
                UserId = 2,
                Comments = expectedComments,
                PostedRoles = new int[] { expectedRole.Id },
                SelectedProviderIds = new List<int> { 1 }
            };

            Target.Create(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(u => u.Add(null), options => options.IgnoreArguments().Do(new Action<UserRole>(u =>
            {
                Assert.AreEqual(expectedUser, u.User);
                Assert.AreEqual(expectedRole, u.Role);
                Assert.AreEqual(expectedProviders, u.Providers);
                Assert.AreEqual(true, u.User.Active);
            })));
            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void WhenEditRolePostedWithUserWhoHasNoUserRoles_ThenJsonResultReturned()
        {
            AddAdditionalUsers();
            var viewModel = new UserRoleModel
            {
                UserId = 5,
                Comments = "Testing",
                PostedRoles = new int[] { 2 }
            };

            Target.Edit(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(u => u.Add(null), options => options.IgnoreArguments());
            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void GivenUserRoleWithSiteCoordinatorAndNoPostedSchools_WhenCreate_ThenChangesSaved_AndAllSchoolsAreAddedToUserRole()
        {
            AddAdditionalUsers();
            var expectedUser = Repositories.MockUserRepository.Items.Where(u => u.Id == 1).SingleOrDefault();
            var expectedRole = Repositories.MockRoleRepository.Items.Where(r => r.Id == 1).SingleOrDefault();
            var expectedComments = "Test Comments";
            var expectedSchools = Repositories.MockSchoolRepository.Items.ToList();
            var viewModel = new UserRoleModel
            {
                UserId = 3,
                Comments = expectedComments,
                PostedRoles = new int[] { 2 },
                allSchoolsSelected = true
            };

            Target.Create(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(u => u.Add(null), options => options.IgnoreArguments().Do(new Action<UserRole>(u =>
            {
                Assert.AreEqual(expectedUser, u.User);
                Assert.AreEqual(expectedRole, u.Role);
                Assert.AreEqual(expectedSchools, u.Schools);
                Assert.AreEqual(true, u.User.Active);
            })));
            Repositories.MockRepositoryContainer.AssertWasCalled(u => u.Save());
        }
        public void Edit(UserRoleModel viewModel, EducationSecurityPrincipal user)
        {
            if (viewModel.PostedRoles != null && viewModel.PostedRoles.Count() > 1)
            {
                throw new ValidationException(new ValidationResult("You can't have more than 1 role", new string[] { "PostedRoles" }), null, null);
            }
            var item = UserRepository.Items.
                                            Include("UserRoles.Role").
                                            Include("UserRoles.Schools").
                                            Include("UserRoles.Providers").
                                            SingleOrDefault(u => u.Id == viewModel.UserId);
            if (item == null)
            {
                throw new EntityNotFoundException("User does not exist.");
            }
            item.Comments = viewModel.Comments;
            if (viewModel.PostedRoles == null || !viewModel.PostedRoles.Any())
            {
                //in case someone decides to manually remove all roles associated with the user
                RemoveRoles(item, Enumerable.Empty<int>().ToList());
            }
            else
            {
                //remove any roles the user does not want anymore
                RemoveRoles(item, viewModel.PostedRoles);

                //check to see if any of the roles and schools associated need to be edited
                EditRoles(item, viewModel.PostedRoles, viewModel, user);

                //add roles that the user has selected. if it's a site coordinator we need to link the role to the proper schools
                AddRoles(item, viewModel.PostedRoles, viewModel, user);
            }
            UserRepository.Update(item);
            UserAccessChangeEventRepository.Add(Auditor.CreateAccessChangeEvent(item, user.Identity.User));
            RepositoryContainer.Save();
        }
        public void GivenUserRoleWithUserUserRole_WhenCreate_ThenCreatedUserRoleHasExpectedCreateTime()
        {
            AddAdditionalUsers();
            var viewModel = new UserRoleModel
            {
                UserId = 3,
                Comments = string.Empty,
                PostedRoles = new int[] { 2 }
            };

            Target.Create(viewModel, User);

            DateTime completeTime = DateTime.Now;
            TimeSpan maxDelta = TimeSpan.FromMilliseconds(5);
            Repositories.MockUserRoleRepository.AssertWasCalled(m => m.Add(Arg<UserRole>.Matches(u => u.CreateTime.WithinTimeSpanOf(maxDelta, completeTime))));
        }
 public UserRoleModel GenerateEditViewModel(int id)
 {
     var user = UserRepository.Items
                                    .Include("UserRoles.Role")
                                    .Include("UserRoles.Schools")
                                    .Include("UserRoles.Providers")
                                    .SingleOrDefault(u => u.Id == id);
     if (user == null)
     {
         throw new EntityNotFoundException("User does not exist.");
     }
     UserRoleModel viewModel = new UserRoleModel();
     viewModel.CopyFrom(user);
     viewModel.UserRoleIds = user.UserRoles.Select(u => u.Id);
     viewModel.SelectedRoles = user.UserRoles.Select(u => u.Role);
     PopulateViewModel(viewModel);
     return viewModel;
 }
        public void GivenViewModelHasNullPostedRoles_WhenCreate_ThenThrowValidationException()
        {
            AddAdditionalUsers();
            var viewModel = new UserRoleModel { UserId = 977878787, PostedRoles = null };

            Target.ExpectException<ValidationException>(() => Target.Create(viewModel, User));
        }
 private void AddRoles(User user, IEnumerable<int> PostedRoles, UserRoleModel viewModel, EducationSecurityPrincipal requestor)
 {
     var rolesToAdd = PostedRoles.Except(user.UserRoles.Select(u => u.RoleId)).ToList();
     foreach (int roleId in rolesToAdd)
     {
         var role = RoleRepository.Items.SingleOrDefault(r => r.Id == roleId);
         if (role != null)
         {
             var schools = GetSelectedSchools(viewModel.allSchoolsSelected, role, viewModel.SelectedSchoolIds).ToList();
             var providers = GetSelectedProviders(role, viewModel.SelectedProviderIds).ToList();
             var newUserRole = new UserRole
             {
                 RoleId = roleId,
                 UserId = viewModel.UserId,
                 CreatingUser = requestor.Identity.User
             };
             user.UserRoles.Add(newUserRole);
             UserRoleRepository.Add(newUserRole);
             foreach (School school in schools)
             {
                 UserRoleRepository.AddLink(newUserRole, school);
             }
             foreach (Provider provider in providers)
             {
                 UserRoleRepository.AddLink(newUserRole, provider);
             }
         }
     }
 }
        public void GivenViewModel_WhenCreate_ThenUserRoleHasCreatingUserInfo()
        {
            AddAdditionalUsers();
            var viewModel = new UserRoleModel
            {
                UserId = 3,
                PostedRoles = new int[] { 2 }
            };

            Target.Create(viewModel, User);

            Repositories.MockUserRoleRepository.AssertWasCalled(m => m.Add(Arg<UserRole>.Matches(u => u.CreatingUser == User.Identity.User)));
        }
 public void InitializeTest()
 {
     Target = new UserRoleModel();
 }
        public void GivenValidViewModel_WhenEdit_ThenSucceed()
        {
            EducationSecurityPrincipal user = new EducationSecurityPrincipal(EducationContext.Users.First());
            UserRoleModel viewModel = new UserRoleModel { UserId = 1, PostedRoles = new[] { 1 } };

            Target.Edit(viewModel, user);
        }