Exemple #1
0
        public async Task UpdateGroupCommandHandler_ShouldUpdateGroup()
        {
            // Arrange
            UpdateGroupCommand request = new UpdateGroupCommand
            {
                GroupId     = 1,
                Name        = "Some updated name",
                Description = "Some updated description"
            };

            IEnumerable <Group> expectedGroup = new[]
            {
                new Group {
                    GroupId = 1
                }
            };

            IQueryable <Group> queryableMock = expectedGroup
                                               .AsQueryable()
                                               .BuildMock()
                                               .Object;

            _unitOfWork
            .Setup(m => m.Groups.GetById(request.GroupId))
            .Returns(queryableMock);

            UpdateGroupCommand.Handler handler = new UpdateGroupCommand.Handler(_unitOfWork.Object);

            // Act
            await handler.Handle(request);

            // Assert
            _unitOfWork.Verify(m => m.Groups.Update(It.IsAny <Group>()), Times.Once);
            _unitOfWork.Verify(m => m.CommitAsync(It.IsAny <CancellationToken>()), Times.Once);
        }
Exemple #2
0
        public void UpdateGroup(UpdateGroupCommand command)
        {
            var entity = this
                         .GetValidGroups(command.OrganizationId)
                         .FirstOrDefault(g => g.GroupEntityId.Equals(command.GroupId));

            var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            entity.UpdatedAt = now;

            if (!string.IsNullOrWhiteSpace(command.Name))
            {
                entity.Name = command.Name;
            }

            if (!string.IsNullOrWhiteSpace(command.Description))
            {
                entity.Description = command.Description;
            }

            if (command.ParentGroupId > 0 || command.ParentGroupId == null)
            {
                entity.ParentGroupId = command.ParentGroupId;
            }

            context.Groups.Update(entity);
            this.context.SaveChanges();
        }
Exemple #3
0
        public async Task <ActionResult> UpdateGroup([FromRoute] int groupId, [FromBody] UpdateGroupBody model, CancellationToken cancellationToken = default)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            GroupExistsQuery existsQuery = new GroupExistsQuery {
                GroupId = groupId
            };

            bool exists = await _mediator.Send(existsQuery, cancellationToken);

            if (!exists)
            {
                return(NotFound(new ErrorResource
                {
                    StatusCode = StatusCodes.Status404NotFound,
                    Message = $"Group with ID '{groupId}' does not exist"
                }));
            }

            UpdateGroupCommand updateCommand = new UpdateGroupCommand
            {
                GroupId     = groupId,
                Name        = model.Name,
                Description = model.Description
            };

            await _mediator.Send(updateCommand, cancellationToken);

            return(NoContent());
        }
Exemple #4
0
        public Result <EmptyResult> UpdateGroup(UpdateGroupCommand command)
        {
            if (command.OrganizationId <= 0)
            {
                return(new Result <EmptyResult>(GroupServiceErrors.InvalidUpdateGroupDataError(nameof(command.OrganizationId))));
            }

            if (command.GroupId <= 0)
            {
                return(new Result <EmptyResult>(GroupServiceErrors.InvalidUpdateGroupDataError(nameof(command.GroupId))));
            }

            if (!groupRepository.GroupExists(command.GroupId, command.OrganizationId))
            {
                return(new Result <EmptyResult>(GroupServiceErrors.GroupNotFoundError()));
            }

            if (groupRepository.GroupNameExists(command.GroupId, command.Name, command.OrganizationId))
            {
                return(new Result <EmptyResult>(GroupServiceErrors.GroupAlreadyExistsError()));
            }

            groupRepository.UpdateGroup(command);

            return(new Result <EmptyResult>());
        }
Exemple #5
0
        public async Task <GroupResponseModel> PutGroup(
            int groupId,
            [FromForm] GroupRequestModel model,
            CancellationToken cancellationToken
            )
        {
            cancellationToken.ThrowIfCancellationRequested();

            var command = new UpdateGroupCommand(
                groupId,
                model.Name,
                model.FacultyId,
                model.CourseNumber
                );

            await _mediator.Send(command, cancellationToken);

            var query = new FindGroupByIdQuery(groupId);

            var group = await _mediator.Send(query, cancellationToken);

            var response = _mapper.Map <GroupResponseModel>(group);

            return(response);
        }
Exemple #6
0
        public void UpdateGroup(Guid id, string name, string description, bool isDisabled, string externalGroupName)
        {
            userContext.CheckPermission(Permissions.UserMaintenance);

            var command = new UpdateGroupCommand(id, name, description, isDisabled, externalGroupName);

            commandBus.Value.Send(Envelope.Create(command));
        }
Exemple #7
0
        public void TestInitialize()
        {
            var commandFactory = AssemblyConfiguration.Kernel.Get <CommandFactory>();
            var queryFactory   = AssemblyConfiguration.Kernel.Get <QueryFactory>();

            _mapper             = AssemblyConfiguration.Kernel.Get <IMapper>();
            _createGroupCommand = commandFactory.GetInstance <CreateGroupCommand>();
            _getGroupQuery      = queryFactory.GetInstance <GetGroupsQuery>();
            _sut = commandFactory.GetInstance <UpdateGroupCommand>();
        }
Exemple #8
0
        public void ShouldRequireMinimumFields()
        {
            var command = new UpdateGroupCommand
            {
                Capacity = 0
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
Exemple #9
0
        public async Task <IActionResult> Update([FromBody] UpdateGroupCommand updateGroup)
        {
            var result = await Mediator.Send(updateGroup);

            if (result.Success)
            {
                return(Ok(result.Message));
            }
            return(BadRequest(result.Message));
        }
Exemple #10
0
        public async Task <IActionResult> Update(
            [FromRoute] int id,
            [FromBody] UpdateGroupCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest());
            }

            return(Ok(await Mediator.Send(command)));
        }
Exemple #11
0
        public async Task <ActionResult> Update(int id, UpdateGroupCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest());
            }

            await Mediator.Send(command);

            return(NoContent());
        }
Exemple #12
0
        void AndGivenRequest()
        {
            var content = new UpdateGroupCommand
            {
                Id            = 1,
                Name          = "group2",
                LanguageFront = 2,
                LanguageBack  = 1
            };

            Request.Content = new StringContent(JsonSerializer.Serialize(content), Encoding.UTF8, "application/json");
        }
Exemple #13
0
        public async Task <IActionResult> PutGroup(Guid id, GroupUpdateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var command = new UpdateGroupCommand
            {
                Id    = id,
                Input = model
            };

            return(await ExecuteRequest(command).ConfigureAwait(false));
        }
        public CommandResult Update(Guid id, [FromBody] UpdateGroupCommand command)
        {
            command.setGroupId(id);
            command.setRequestHost(HttpContext.Request.Host.ToString());

            _loggingService.Log(this.GetType(), ELogType.Input, ELogLevel.Info, new { Group = this.User.Identity.Name, Path = this.Request.Path, Method = this.Request.Method });

            CommandResult result = (CommandResult)_groupHandler.Handle(command);

            _loggingService.Log(this.GetType(), ELogType.Output, ELogLevel.Info, new { Group = this.User.Identity.Name, Path = this.Request.Path, Method = this.Request.Method, Code = this.Response.StatusCode });

            HttpContext.Response.StatusCode = result.Code;

            return(result);
        }
Exemple #15
0
        public IActionResult Update([FromBody] UpdateGroupCommand command)
        {
            if (command == null)
            {
                return(BadRequest());
            }

            var result = _mediator.Send(command).Result;

            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                return(StatusCode(200, result));
            }

            return(Ok(result));
        }
        public ICommandResult Handle(UpdateGroupCommand command)
        {
            ICommandResult result = new CommandResult();

            _loggingService.Log(this.GetType(), ELogType.Neutral, ELogLevel.Debug, new { command.Id, command.Name, command.Description, command.RequestHost }, "GroupCommandHandler.Handle(Update)");

            try
            {
                Group group = new Group(command.Name, command.Description);

                if (group.Valid)
                {
                    if (_groupRepository.CheckExists(command.Id))
                    {
                        if (!_groupRepository.CheckExists(group.Name))
                        {
                            if (_groupRepository.Update(command.Id, group))
                            {
                                result = new CommandResult(200);
                            }
                        }

                        else if (_groupRepository.Valid)
                        {
                            result = new CommandResult(400, new Notification("Name", "Already in Use"));
                        }
                    }

                    else if (_groupRepository.Valid)
                    {
                        result = new CommandResult(400, new Notification("Group", "Could not be found"));
                    }
                }

                else
                {
                    result = new NewGroupCommandResult(400, group.Notifications);
                }
            }
            catch (Exception e)
            {
                _loggingService.Log(this.GetType(), ELogType.Neutral, ELogLevel.Error, new { command.Id, command.Name, command.Description, command.RequestHost }, e);
            }

            return(result);
        }
Exemple #17
0
        public IHttpActionResult UpdateGroup(Guid groupId, UpdateGroupCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }
            if (groupId == Guid.Empty)
            {
                throw new ArgumentException("groupId must be defined.");
            }
            if (string.IsNullOrWhiteSpace(command.Name))
            {
                throw new ArgumentException("Group name must be defined.");
            }

            identityManagementService.UpdateGroup(groupId, command.Name, command.Description, command.IsDisabled, command.ExternalGroupName);
            return(Ok());
        }
        public async Task ThrowNotFoundException_WhenGroupIsNotExists()
        {
            var request = new UpdateGroupCommand
            {
                Id                  = 100,
                Name                = "Test Group Edited",
                SpecialityId        = 1,
                StudentsCount       = 10,
                EducationalDegreeId = 1,
                Year                = 1
            };

            var handler = new UpdateGroupCommandHandler(Context);

            var exception = Assert.ThrowsAsync <NotFoundException>(async() => await handler.Handle(request, CancellationToken.None));

            Assert.AreEqual(exception.Message, ExceptionMessagesBuilderHelper.GetNotFoundExceptionMessage(nameof(Group), request.Id));
        }
        public async Task ThrowDuplicateException_WhenGroupNameExists()
        {
            var request = new UpdateGroupCommand
            {
                Id                  = 1,
                Name                = "Group 2",
                StudentsCount       = 10,
                SpecialityId        = 1,
                Year                = 1,
                EducationalDegreeId = 1
            };

            var handler = new UpdateGroupCommandHandler(Context);

            var exception = Assert.ThrowsAsync <DuplicateException>(async() => await handler.Handle(request, CancellationToken.None));

            Assert.AreEqual(exception.Message, ExceptionMessagesBuilderHelper.GetDuplicateExceptionMessage(nameof(Group), "Name", request.Name));
        }
Exemple #20
0
        public async Task ShouldUpdateGroup()
        {
            var group = await AddGroupAsync();

            var command = new UpdateGroupCommand
            {
                GroupId  = group.Id,
                Capacity = 10,
                Name     = "Den Hague"
            };

            await SendAsync(command);

            var list = await FindAsync <Group>(group.Id);

            list.Should().NotBeNull();
            list.Name.Should().Be(command.Name);
            list.Capacity.Should().Be(command.Capacity);
        }
        public void When_UpdateGroupName_Expect_GroupUpdate()
        {
            var errorMessage    = string.Empty;
            var guid            = Guid.NewGuid().ToString();
            var newGroupCommand = new CreateGroupCommand()
            {
                Group = new Group()
                {
                    Name = guid, CurrentCapacity = 100M
                }
            };
            var actionResult = _groupController.Create(newGroupCommand);

            var createdGroup = ActionResultParser.ParseCreatedResult <Group>(actionResult, out errorMessage);

            CheckErrorMessage(errorMessage);

            if (createdGroup.Id == 0)
            {
                Assert.Fail();
            }

            var newGuid            = Guid.NewGuid().ToString();
            var groupUpdateCommand = new UpdateGroupCommand()
            {
                Group = new Group()
                {
                    Id = createdGroup.Id, CurrentCapacity = createdGroup.CurrentCapacity, Name = newGuid
                }
            };

            actionResult = _groupController.Update(groupUpdateCommand);

            var updatedGroup = ActionResultParser.ParseOkObjectResult <Group>(actionResult, out errorMessage);

            CheckErrorMessage(errorMessage);

            Assert.AreEqual(newGuid, updatedGroup.Name);

            DeleteGroup(updatedGroup);
        }
Exemple #22
0
        public CredentialGroup UpdateGroup(CredentialGroup toBeUpdated, CredentialGroup updated)
        {
            if (String.IsNullOrWhiteSpace(updated.Name))
            {
                throw new InvalidOperationException("Der Name darf nicht leer sein.");
            }
            else if (_currentData.Any(g => g.Name == updated.Name))
            {
                throw new InvalidOperationException("Eine Gruppe mit diesem Namen existiert bereits.");
            }

            ICommand command = new UpdateGroupCommand()
            {
                ToBeUpdated       = toBeUpdated,
                UpdatedCredential = updated
            };

            toBeUpdated = (CredentialGroup)ExecuteCommand(command);

            return(toBeUpdated);
        }
        public async Task UpdateGroup()
        {
            var request = new UpdateGroupCommand
            {
                Id                  = 1,
                Name                = "Test Group 1 edited",
                StudentsCount       = 10,
                SpecialityId        = 1,
                EducationalDegreeId = 1,
                Year                = 1
            };

            var handler = new UpdateGroupCommandHandler(Context);

            await handler.Handle(request, CancellationToken.None);

            Assert.IsTrue(Context.Groups.Where(x => x.Id == request.Id &&
                                               x.Name == request.Name &&
                                               x.EducationalDegreeId == request.EducationalDegreeId &&
                                               x.SpecialityId == request.SpecialityId &&
                                               x.Year == request.Year).Count() == 1);
        }
Exemple #24
0
        public async Task ShouldNotUpdateIfTotalCurrentExceedsNewCapacity()
        {
            var group = await AddGroupAsync();

            var chargeStation = await AddChargeStationAsync(group.Id);

            await AddConnectorAsync(chargeStation.Id, 1, 30);

            var command = new UpdateGroupCommand
            {
                GroupId  = group.Id,
                Capacity = 10,
                Name     = "Den Hague"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <EntityUpdateException>();

            var list = await FindAsync <Group>(group.Id);

            list.Should().NotBeNull();
            list.Name.Should().Be(group.Name);
            list.Capacity.Should().Be(group.Capacity);
        }
 public async Task <IActionResult> UpdateGroupAsync([FromRoute] string groupId, [FromBody] UpdateGroupCommand updateGroupCommand)
 {
     return(Ok(await _mediator.Send(updateGroupCommand)));
 }
Exemple #26
0
 public async Task <ActionResult <int> > Update(UpdateGroupCommand command)
 {
     return(await Mediator.Send(command));
 }
Exemple #27
0
 public async Task <IActionResult> Update([FromBody] UpdateGroupCommand updateGroup)
 {
     return(GetResponseOnlyResultMessage(await Mediator.Send(updateGroup)));
 }
Exemple #28
0
 public async Task <ActionResult <GroupDto> > Update([FromBody] UpdateGroupCommand command)
 {
     return(Ok(await Mediator.Send(command)));
 }
Exemple #29
0
        public GroupMutation()
        {
            Name = "GroupMutation";

            this.FieldAsyncWithScope <StringGraphType, string>(
                "create",
                arguments:
                new QueryArguments
                (
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "name"
            }
                ),
                resolve: async(ctx, mediator) =>
            {
                var command = new CreateGroupCommand()
                {
                    Name = ctx.GetString("name")
                };

                var id = await mediator.Send(command);

                return(id);
            }
                );

            this.FieldAsyncWithScope <BooleanGraphType, bool>(
                "delete",
                arguments:
                new QueryArguments
                (
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "id"
            }
                ),
                resolve: async(ctx, mediator) =>
            {
                var command = new DeleteGroupCommand()
                {
                    Id = ctx.GetString("id")
                };

                await mediator.Send(command);

                return(true);
            }
                );

            this.FieldAsyncWithScope <BooleanGraphType, bool>(
                "update",
                arguments:
                new QueryArguments
                (
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "id"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "name"
            }
                ),
                resolve: async(ctx, mediator) =>
            {
                var command = new UpdateGroupCommand()
                {
                    Id   = ctx.GetString("id"),
                    Name = ctx.GetString("name")
                };

                await mediator.Send(command);

                return(true);
            }
                );

            this.FieldAsyncWithScope <BooleanGraphType, bool>(
                "addUser",
                arguments:
                new QueryArguments
                (
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "userId"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "groupId"
            }
                ),
                resolve: async(ctx, mediator) =>
            {
                var command = new AddUserToGroupCommand()
                {
                    UserId  = ctx.GetString("userId"),
                    GroupId = ctx.GetString("groupId")
                };

                await mediator.Send(command);

                return(true);
            }
                );

            this.FieldAsyncWithScope <BooleanGraphType, bool>(
                "removeUser",
                arguments:
                new QueryArguments
                (
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "userId"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "groupId"
            }
                ),
                resolve: async(ctx, mediator) =>
            {
                var command = new RemoveUserFromGroupCommand()
                {
                    UserId  = ctx.GetString("userId"),
                    GroupId = ctx.GetString("groupId")
                };

                await mediator.Send(command);

                return(true);
            }
                );
        }
Exemple #30
0
 public void Handle(UpdateGroupCommand message)
 {
     this.Handle(message.AcSession, message.Input, true);
 }