Пример #1
0
            protected override async Task HandleCore(Command message)
            {
                //Delete all roles for the employee
                _dbContext.EmployeeRole
                .RemoveRange(_dbContext
                             .EmployeeRole
                             .Where(er => er.Employee.Id == message.Id));

                await _dbContext.SaveChangesAsync();

                //Get the employee based on their id
                var employee = await _dbContext.Employee
                               .SingleOrDefaultAsync(e => e.Id == message.Id);

                foreach (var roleId in message.SelectedRoles)
                {
                    var employeeRole = new EmployeeRole
                    {
                        EmployeeId = employee.Id,
                        RoleId     = roleId,
                        Employee   = employee,
                        Role       = await _dbContext.Role.SingleOrDefaultAsync(r => r.Id == roleId)
                    };
                    _dbContext.EmployeeRole.Add(employeeRole);
                }

                await _dbContext.SaveChangesAsync();
            }
Пример #2
0
        public async Task <IActionResult> Create([Bind("Id,Name,Surname,Address,Email,PhoneNumber")] Person person)
        {
            if (ModelState.IsValid)
            {
                _context.Add(person);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(person));
        }
        public async Task CreateDeveloperEntry(DeveloperDirectoryBindingModel model)
        {
            var directory = Mapper.Map <Developer>(model);

            var category = await _context.Categories.FindAsync(model.CategoryId);

            if (category == null)
            {
                throw new Exception("Category Doesn't exist");
            }

            _context.Developers.Add(directory);
            await _context.SaveChangesAsync();
        }
Пример #4
0
            protected override async Task HandleCore(Command message)
            {
                var employee = await _dbContext.Employee
                               .SingleOrDefaultAsync(e => e.Id == message.Id);

                Mapper.Map(message, employee);

                await _dbContext.SaveChangesAsync();
            }
Пример #5
0
        public async Task <IActionResult> PutPerson(Guid id, Person person)
        {
            if (id != person.PersonId)
            {
                return(BadRequest());
            }

            if (person.FamilyRoles.Any(familyPerson => familyPerson.PersonId != person.PersonId))
            {
                return(BadRequest());
            }

            var personOld = await _context.People.FindAsync(id);

            await _context.Entry(personOld).Collection(p => p.FamilyRoles).LoadAsync();

            personOld.Notes        = person.Notes;
            personOld.EmailAddress = person.EmailAddress;
            personOld.Name         = person.Name;
            personOld.PhoneNumber  = person.PhoneNumber;
            personOld.FamilyRoles  = person.FamilyRoles;
            _context.People.Update(personOld);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PersonExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> UpdateBrother(int brotherId, [FromBody] Brother newBrotherModel)
        {
            Brother brother = await _dbContext.Brother.FindBrotherByIdAsync(brotherId);

            if (brother == null)
            {
                return(NotFound());
            }

            if (newBrotherModel.Id != brotherId)
            {
                return(BadRequest());
            }

            string?subject = _principal.GetSubjectId();

            if (string.IsNullOrEmpty(subject))
            {
                // Well, this shouldn't happen, but just to be sure.
                return(Unauthorized());
            }

            IEnumerable <string> scopes = _principal.GetScopes();

            // TODO: I think there's a better way to do this (and the bit above), having the authorization filter do it instead, though this requires several things:
            // (1) the route to be consistent; (2) the parameter to either be obtained from the route in the authorization handler or obtainable
            // there via an injected service; and (3) access to the claims principal.
            // However, doing this would prevent this boilerplate every time. It should also be its own authorization policy so that it doesn't apply everywhere.
            if (!subject.Equals(brother.Id.ToString()))
            {
                // If the user isn't the brother they're trying to update and doesn't have the administrator scope, reject the request.
                if (!scopes.Contains(Constants.Scopes.Administrator))
                {
                    _logger.LogInformation("Rejecting request from user with identifier {subject} attempting to modify {brotherFirst} {brotherLast}: the user is not an administrator.",
                                           subject, brother.FirstName, brother.LastName);
                    return(Unauthorized());
                }

                // User is an administrator
                _logger.LogTrace("Administrator (subject {subjectId}) updating {first} {last}.", subject,
                                 brother.FirstName, brother.LastName);
            }

            try {
                _dbContext.Entry(brother).CurrentValues.SetValues(newBrotherModel);

                await _dbContext.SaveChangesAsync();
            } catch (DbUpdateConcurrencyException) {
                return(Conflict());
            }

            return(Ok());
        }
Пример #7
0
        public async Task ReplacePicture_ControllerConcurrencyConflict_ReturnsConflict()
        {
            await _dbContext.Database.EnsureDeletedAsync();

            using DirectoryContext dbContext = new DirectoryContext(new DbContextOptionsBuilder <DirectoryContext>()
                                                                    .UseInMemoryDatabase("directory")
                                                                    .EnableSensitiveDataLogging()
                                                                    .EnableDetailedErrors()
                                                                    .Options);
            await dbContext.Database.EnsureCreatedAsync();

            await dbContext.Brother.AddRangeAsync(new[] {
                new Brother {
                    Id = 1, Picture = new byte[] { 1, 2, 3 }
                },
                new Brother {
                    Id = 2
                }
            });

            await dbContext.SaveChangesAsync();

            Mock <DirectoryContext> mockedContext = new Mock <DirectoryContext>();

            mockedContext.SetupGet(m => m.Brother).Returns(dbContext.Brother);
            mockedContext.Setup(m => m.SaveChangesAsync(It.IsAny <CancellationToken>())).Throws <DBConcurrencyException>();

            ClaimsPrincipal principal = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new[] {
                new Claim(JwtClaimTypes.Scope, Constants.Scopes.Administrator),
                new Claim(JwtClaimTypes.Subject, "1")
            },
                    "Bearer"));
            PictureController controller = new PictureController(mockedContext.Object,
                                                                 Mock.Of <IDefaultPictureProvider>(),
                                                                 principal,
                                                                 Mock.Of <ILogger <PictureController> >());

            byte[]    picture = { 5 };
            IFormFile file    = new FormFile(new MemoryStream(picture), 0, picture.Length, "file", "file");

            IActionResult result = await controller.ReplacePicture(1, file);

            Assert.Multiple(() => {
                Assert.That(result, Is.Not.Null);
                Assert.That(result, Is.InstanceOf <ConflictResult>());
                // Make sure the picture is still what it was before
                Assert.That(_dbContext.Brother.First(b => b.Id.Equals(1)).Picture, Is.EqualTo(new byte[] { 1, 2, 3 }));
            });
        }
        public async Task <IActionResult> PutFamily(Guid id, Family family)
        {
            if (id != family.FamilyId)
            {
                return(BadRequest());
            }

            if (family.FamilyMembers.Any(familyMember => familyMember.FamilyId != family.FamilyId))
            {
                return(BadRequest());
            }

            var familyOld = await _context.Families.FindAsync(id);

            await _context.Entry(familyOld).Collection(f => f.FamilyMembers).LoadAsync();

            familyOld.Notes         = family.Notes;
            familyOld.FamilyMembers = family.FamilyMembers;
            _context.Families.Update(familyOld);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FamilyExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #9
0
        public async Task <IActionResult> ReplacePicture(int brotherId, [FromForm] IFormFile?picture)
        {
            string? subjectId = _principal.GetSubjectId();
            Brother brother   = await _dbContext.Brother.FindBrotherByIdAsync(brotherId);

            if (brother == null)
            {
                _logger.LogInformation("Received request to modify picture for brother {id} but they do not exist.", brotherId);
                return(NotFound());
            }

            _logger.LogInformation("Received request to modify picture for brother {brotherId} ({first} {last}).", brotherId, brother.FirstName, brother.LastName);

            // TODO: The subject id is not necessarily the same as the brother id. They should be linked by a column in the Brother table that does not yet exist.
            IEnumerable <string> scopes = _principal.GetScopes();

            if (!brotherId.ToString().Equals(subjectId, StringComparison.OrdinalIgnoreCase))
            {
                if (!scopes.Contains(Constants.Scopes.Administrator))
                {
                    _logger.LogTrace("Rejecting request to modify another user's picture from non-administrator user {subject}.", subjectId);
                    return(Unauthorized());
                }

                // User is an administrator
                _logger.LogTrace("Administrator replacing picture for {brother}.", brotherId);
            }

            if (picture == null || picture.Length == 0)
            {
                _logger.LogTrace("Clearing picture.");
                brother.Picture = null;
            }
            else
            {
                brother.Picture = new byte[picture.Length];
                await picture.OpenReadStream().ReadAsync(brother.Picture, 0, (int)picture.Length);
            }

            try {
                await _dbContext.SaveChangesAsync();
            } catch (DBConcurrencyException) {
                return(Conflict());
            }

            return(Ok());
        }
Пример #10
0
        public async Task ActiveBrother_IsReturned()
        {
            int id = _dbContext.Brother.Add(new Brother {
                FirstName = "First", LastName = "Last"
            }).Entity.Id;
            await _dbContext.SaveChangesAsync();

            BrotherController  controller = new BrotherController(_dbContext, null, null);
            BrotherDetailModel result     = ((OkObjectResult)await controller.GetBrother(id)).Value as BrotherDetailModel;

            Assert.Multiple(() => {
                Assert.That(result, Is.Not.Null);
                Assert.That(result.Id, Is.EqualTo(id));
                Assert.That(result.FirstName, Is.EqualTo("First"));
                Assert.That(result.LastName, Is.EqualTo("Last"));
            });
        }
 public Task <int> SaveChangesAsync(string user) => _context.SaveChangesAsync(user);
Пример #12
0
        public async Task ActiveBrothers_AreInCorrectOrder()
        {
            await _dbContext.Database.EnsureDeletedAsync();

            _dbContext.SaveChanges();

            DateTime       sameDate    = DateTime.Now;
            List <Brother> brotherList = new List <Brother> {
                // Should be 1 (Zeta number)
                new Brother {
                    FirstName = "FName", LastName = "LName", ExpectedGraduation = DateTime.MaxValue, ZetaNumber = 1
                },
                // Should be 2 (Zeta number)
                new Brother {
                    FirstName = "FName1", LastName = "LName1", ExpectedGraduation = DateTime.MaxValue, ZetaNumber = 2
                },
                // Should be 3 (Join date)
                new Brother {
                    FirstName = "FName2", LastName = "LName2", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate.AddDays(-5)
                },
                // Should be 4 (Join date)
                new Brother {
                    FirstName = "FName3", LastName = "LName3", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate.AddDays(-3)
                },
                // Should be 5 (Last name)
                new Brother {
                    FirstName = "ZFirst", LastName = "ALast", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate
                },
                // Should be 6 (First name)
                new Brother {
                    FirstName = "AFirst", LastName = "ZLast", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate
                },
                // Should be 7 (First name)
                new Brother {
                    FirstName = "ZFirst", LastName = "ZLast", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate
                }
            };

            DirectoryContext dbContext = new DirectoryContext(new DbContextOptionsBuilder <DirectoryContext>()
                                                              .UseInMemoryDatabase("directory")
                                                              .Options);
            await dbContext.Brother.AddRangeAsync(brotherList);

            await dbContext.SaveChangesAsync();

            BrotherController controller = new BrotherController(dbContext, new ClaimsPrincipal(), Mock.Of <ILogger <BrotherController> >());

            Assert.Multiple(() => {
                OkObjectResult result = controller.GetBrothers() as OkObjectResult;
                Assert.That(result, Is.Not.Null);

                IEnumerable <MinimalBrother> brothers = (result.Value as ContentModel <MinimalBrother>)?.Content;
                Assert.That(brothers, Is.Not.Null);

                Assert.That(brothers.Count(), Is.EqualTo(7));

                for (int i = 0; i < brotherList.Count; i++)
                {
                    MinimalBrother actual = brothers.ElementAt(i);
                    Brother expected      = brotherList[i];

                    Assert.That(actual.LastName, Is.EqualTo(expected.LastName));
                    Assert.That(actual.FirstName, Is.EqualTo(expected.FirstName));
                    Assert.That(actual.ZetaNumber, Is.EqualTo(expected.ZetaNumber));
                    Assert.That(actual.DateJoined, Is.EqualTo(expected.DateJoined));
                }
            });
        }