コード例 #1
0
        public IActionResult Post([FromBody] MessageAddDTO message)
        {
            try
            {
                if (message == null || message.Text == null || message.Text == "")
                {
                    return(BadRequest(new ResponseVM("Message object is not filled correct")));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(new ResponseVM("Invalid model object")));
                }

                int userId = _repoWrapper.User.GetUserByUserNameAsync(_userClaimsPrincipal.GetUserName(HttpContext?.User)).Result;

                int messageId = _repoWrapper.Message.CreateMessageAsync(new Message(), message, userId).Result;
                _repoWrapper.Save();

                return(CreatedAtRoute("MessageById", new { id = messageId }, new { id = messageId }));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside CreateMessage action: {ex.Message}");
                return(StatusCode(500, new ResponseVM("Internal server error")));
            }
        }
コード例 #2
0
        public void Should_AddEmptyMessageMockFunction_With_Return_BadRequest()
        {
            //Arrange
            var newMessage = new MessageAddDTO()
            {
                Text = ""
            };

            var message = new Message()
            {
                Id     = 4,
                Text   = "New Message",
                UserId = 1,
            };

            var _mockRepo      = new Mock <IRepositoryWrapper>();
            var _mockPrincipal = new Mock <IUserClaimsPrincipal>();
            var _mockLogger    = new Mock <ILoggerManager>();

            _mockRepo.Setup(x => x.Message.CreateMessageAsync(message, newMessage, 1)).ReturnsAsync(4);
            _mockPrincipal.Setup(x => x.GetUserName(It.IsAny <ClaimsPrincipal>())).Returns("admin");
            _mockRepo.Setup(x => x.User.GetUserByUserNameAsync("admin")).ReturnsAsync(1);

            var controller = new MessageController(_mockRepo.Object, _mockLogger.Object, _mockPrincipal.Object);

            //Act
            var actual       = controller.Post(newMessage);
            var actualResult = ((BadRequestObjectResult)actual);

            //Assert
            Assert.Same(typeof(BadRequestObjectResult), actualResult.GetType());
            Assert.Equal("Message object is not filled correct", (((ResponseVM)actualResult.Value).Title));
        }
コード例 #3
0
        public async Task <int> CreateMessageAsync(Message dbMessage, MessageAddDTO message, int userId)
        {
            Create(dbMessage.MapForAdd(message, userId));
            await SaveAsync();

            return(dbMessage.Id);
        }
コード例 #4
0
ファイル: MessagesController.cs プロジェクト: Olya73/Chat
        public async Task <IActionResult> Post(MessageAddDTO messageAddDTO)
        {
            ServiceResponse <MessageGetDTO> serviceResponse = await _messageService.CreateMessageAsync(messageAddDTO);

            if (serviceResponse.Success == false)
            {
                return(BadRequest(serviceResponse.Message));
            }
            return(Ok(serviceResponse));
        }
コード例 #5
0
ファイル: MessageServiceTests.cs プロジェクト: Olya73/Chat
        public async Task CreateMessageAsyncReturnsServiceResponseWithExMessage_IfErrorOccurs()
        {
            MessageAddDTO messageAddDTO = new MessageAddDTO();

            _dbContextMock.Setup(r => r.SaveChangesAsync(CancellationToken.None)).Callback(() => throw new Exception());

            ServiceResponse <MessageGetDTO> serviceResponse = await _service.CreateMessageAsync(messageAddDTO);

            Assert.False(serviceResponse.Success);
            Assert.NotNull(serviceResponse.Message);
        }
コード例 #6
0
ファイル: MessageServiceTests.cs プロジェクト: Olya73/Chat
        public async Task CreateMessageAsyncAddsChatEventCallsBotNotifier()
        {
            MessageAddDTO messageAddDTO = new MessageAddDTO();

            _messageRepositoryMock.Setup(r => r.GetUserDialogByFKIdAsync(It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(new UserDialog()));

            ServiceResponse <MessageGetDTO> serviceResponse = await _service.CreateMessageAsync(messageAddDTO);

            _chatEventRepositoryMock.Verify(r => r.Add(It.IsAny <ChatEvent>()), Times.Once);
            _botNotifierMock.Verify(r => r.NotifyAsync(), Times.Once);
        }
コード例 #7
0
        /// <summary>
        /// Genel mesaj ise studentId null olarak gelsin
        /// </summary>
        public async Task <int> AddMessage(MessageAddDTO messageAddDTO)
        {
            var teacherTc   = _unitOfWork.AppUsers.GetAsync(p => p.Id == messageAddDTO.TeacherId);
            var teacherList = _unitOfWork.Teachers.GetAsync(p => p.TCNumber == teacherTc.Result.TCNumber);

            messageAddDTO.TeacherId = teacherList.Result.Id;
            var message = _mapper.Map <MessageAddDTO, Message>(messageAddDTO);

            await _unitOfWork.Messages.AddAsync(message);

            return(await _unitOfWork.SaveAsync());
        }
コード例 #8
0
ファイル: MessageServiceTests.cs プロジェクト: Olya73/Chat
        public async Task CreateMessageAsyncAddsMessageCallsSaveChanges_and_ReturnsServiceResponseWithData()
        {
            MessageAddDTO messageAddDTO = new MessageAddDTO();

            _messageRepositoryMock.Setup(r => r.GetUserDialogByFKIdAsync(It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(new UserDialog()));

            ServiceResponse <MessageGetDTO> serviceResponse = await _service.CreateMessageAsync(messageAddDTO);

            _messageRepositoryMock.Verify(r => r.Add(It.IsAny <Message>()), Times.Once);
            _dbContextMock.Verify(r => r.SaveChangesAsync(CancellationToken.None), Times.AtLeast(1));
            Assert.IsAssignableFrom <ServiceResponse <MessageGetDTO> >(serviceResponse);
            Assert.NotNull(serviceResponse.Data);
            Assert.True(serviceResponse.Success);
        }
コード例 #9
0
        public async Task <ServiceResponse <MessageGetDTO> > CreateMessageAsync(MessageAddDTO messageDTO)
        {
            ServiceResponse <MessageGetDTO> serviceResponse = new ServiceResponse <MessageGetDTO>();

            try
            {
                UserDialog userDialog = await _messageRepository.GetUserDialogByFKIdAsync(messageDTO.UserId, messageDTO.DialogId);

                if (userDialog == null)
                {
                    serviceResponse.Success = false;
                    serviceResponse.Message = "Нет доступа";
                    return(serviceResponse);
                }
                Message message = new Message()
                {
                    Text       = messageDTO.Text,
                    UserDialog = userDialog
                };
                _messageRepository.Add(message);
                await _context.SaveChangesAsync();

                _chatEventRepository.Add(new ChatEvent()
                {
                    UserId         = messageDTO.UserId,
                    DialogId       = messageDTO.DialogId,
                    TypeOfActionId = (int)ActionTypes.NewMessage,
                    MessageId      = message.Id
                });
                await _context.SaveChangesAsync();

                _botNotifier.NotifyAsync();

                serviceResponse.Data    = _mapper.Map <MessageGetDTO>(messageDTO);
                serviceResponse.Data.Id = message.Id;
            }
            catch (Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.Message;
                return(serviceResponse);
            }

            return(serviceResponse);
        }
コード例 #10
0
        public void Should_AddMessageMockFunction_With_Return_MessageID()
        {
            //Arrange
            var newMessage = new MessageAddDTO()
            {
                Text = "New Message"
            };

            var message = new Message()
            {
                Id     = 4,
                Text   = "New Message",
                UserId = 1,
            };

            var _mockRepo      = new Mock <IRepositoryWrapper>();
            var _mockPrincipal = new Mock <IUserClaimsPrincipal>();
            var _mockLogger    = new Mock <ILoggerManager>();

            _mockRepo.Setup(x => x.Message.CreateMessageAsync(message, newMessage, 1)).ReturnsAsync(4);
            _mockPrincipal.Setup(x => x.GetUserName(It.IsAny <ClaimsPrincipal>())).Returns("admin");
            _mockRepo.Setup(x => x.User.GetUserByUserNameAsync("admin")).ReturnsAsync(1);

            var controller = new MessageController(_mockRepo.Object, _mockLogger.Object, _mockPrincipal.Object);

            //Act
            var actual = controller.Post(newMessage);

            //Assert
            var actualResult = ((CreatedAtRouteResult)actual).Value;

            System.Reflection.PropertyInfo pi = actualResult.GetType().GetProperty("id");
            int id = (int)(pi.GetValue(actualResult, null));

            Assert.Equal(0, id);
        }
コード例 #11
0
 public static Message MapForAdd(this Message dbMessage, MessageAddDTO message, int userId)
 {
     dbMessage.Text   = message.Text;
     dbMessage.UserId = userId;
     return(dbMessage);
 }