コード例 #1
0
        public void addComment(CommentDto CommentDto)
        {
            var comment = _mapper.Map <Comment>(CommentDto);

            _commentRep.Create(comment);
            _commentRep.Save();
        }
コード例 #2
0
        public void updateComment(CommentDto CommentDto)
        {
            var comment = _mapper.Map <Comment>(CommentDto);

            _commentRep.Update(comment);
            _commentRep.Save();
        }
コード例 #3
0
 public IActionResult Post([FromBody] CommentDto dto)
 {
     try
     {
         addComment.Execute(dto);
         return(StatusCode(201));
     }
     catch (EntityAlreadyExistsException e)
     {
         return(StatusCode(409, new
         {
             Errors = new List <string> {
                 e.Message
             }
         }));
     }
     catch (EntityAlreadyHasAnEntryException e)
     {
         return(StatusCode(409, new
         {
             Errors = new List <string> {
                 e.Message
             }
         }));
     }
     catch (Exception e)
     {
         return(StatusCode(500, new
         {
             Errors = new List <string> {
                 e.Message
             }
         }));
     }
 }
コード例 #4
0
        public async Task <ActionResult <CommentDto> > Add([FromBody] CommentDto comment)
        {
            comment.Id = null;
            var addedComment = await _commentsService.Add(comment);

            return(Created(addedComment.Id.ToString(), addedComment));
        }
コード例 #5
0
        public ActionResult AddComment([FromBody] CommentDto commentDto)
        {
            var currUserId = _uow.Users.GetUserId(User.Identity.Name);

            commentDto.UserId = currUserId.ToString();

            var currComment = _mapper.Map <Comment>(commentDto);


            _uow.Comments.Add(currComment);

            var currPost = _uow.Posts.Find(x => x.Id == currComment.PostId).FirstOrDefault();

            if (currPost.Comments != null)
            {
                currPost.Comments.Add(currComment.Id);
            }
            else
            {
                currPost.Comments = new List <ObjectId>();
                currPost.Comments.Add(currComment.Id);
            }

            _uow.Posts.Edit(currPost);

            return(Ok(currComment));
        }
コード例 #6
0
 public IActionResult Put(int id, [FromBody] CommentDto dto)
 {
     try
     {
         dto.Id = id;
         editComment.Execute(dto);
         return(StatusCode(204));
     }
     catch (EntityNotFoundException e)
     {
         return(NotFound(new
         {
             Errors = new List <string> {
                 e.Message
             }
         }));
     }
     catch (Exception e)
     {
         return(StatusCode(500, new
         {
             Errors = new List <string> {
                 e.Message
             }
         }));
     }
 }
コード例 #7
0
        public async Task <IActionResult> AddComment(CommentDto comment)
        {
            Comment createComment = new Comment
            {
                Text      = comment.Text,
                ArticleId = comment.ArticleId,
                ParentId  = comment.ParentId,
                Date      = DateTime.Now,
                Email     = comment.Email,
                Name      = comment.UserName
            };

            try
            {
                await _commentRep.CreateAsync(createComment);

                await _uow.Commit();

                return(Json(new JsonResponse
                {
                    Success = true,
                    Data = new
                    {
                        date = _convert.ConvertMiladiToShamsi(createComment.Date, "yyyy/MM/dd"),
                        id = createComment.Id
                    }
                }));
            }
            catch (Exception err)
            {
                return(Json(new JsonResponse {
                    Success = false, ErrorMessage = err.Message
                }));
            }
        }
コード例 #8
0
        public bool Handle(NewCommentRequest request, IOutputPort <NewCommentResponse> outputPort)
        {
            if (_userRepository.FindById(request.UserId) == null)
            {
                outputPort.Handle(new NewCommentResponse(new[] { new Error(404, "user not found") }));
                return(false);
            }
            if (_videoRepository.FindById(request.VideoId) == null)
            {
                outputPort.Handle(new NewCommentResponse(new[] { new Error(404, "video not found") }));
                return(false);
            }
            var commentInfo = new CommentDto()
            {
                PostingDate = request.PostingDate,
                Text        = request.Text,
                UserId      = request.UserId,
                VideoId     = request.VideoId,
            };
            int commentId = _commentRepository.Create(commentInfo);

            outputPort.Handle(new NewCommentResponse(commentId));

            return(true);
        }
コード例 #9
0
        /// <inheritdoc/>
        public async Task <int> UpdateAsync(CommentDto commentDto)
        {
            if (commentDto == null)
            {
                throw new ArgumentNullException(nameof(commentDto));
            }

            var comment = await _context.Comments.FindAsync(commentDto.Id);

            if (comment == null)
            {
                return(0);
            }

            // If have class context use:
            // entity = _mapper.Map<EntityDto, Entity>(entityDto);
            // _context.Entry(entity).State = EntityState.Modified;

            comment.CloudId = commentDto.CloudId;
            comment.PostId  = commentDto.PostId;
            comment.Name    = commentDto.Name;
            comment.Email   = commentDto.Email;
            comment.Body    = commentDto.Body;

            return(await _context.SaveChangesAsync());
        }
コード例 #10
0
        public async Task <IActionResult> Create([FromBody] CommentDto comment)
        {
            Guard.IsNotNull(comment, nameof(comment));
            if (!ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            try
            {
                if (string.IsNullOrWhiteSpace(comment.Commenter))
                {
                    comment.Commenter = this.username; // generated anonymous username
                }

                var result = await this.repository.AddCommentAsync(comment).ConfigureAwait(false);

                return(result.ToActionResult());
            }
            catch (Exception e)
            {
                this.logger.LogError(e, e.Message);
                return(new StatusCodeResult(500));
            }
        }
コード例 #11
0
        public void DeleteCommentTest()
        {
            // Arrange
            var expected = new CommentDto
            {
                Id     = "1",
                BookId = "1",
                Book   = new Book()
                {
                    Id          = "1",
                    Title       = "Stephen",
                    Description = "King"
                },
                UserId = "1",
                User   = new UserProfile()
                {
                    Id        = "1",
                    FirstName = "Oleksii",
                    LastName  = "Rudenko"
                },
                Message   = "Best book ever",
                TimeStamp = DateTime.Now
            };

            var repository = new Mock <IRepository <Comment> >();

            repository.Setup(r => r.Get(expected.Id)).Returns(new Comment
            {
                Id     = "1",
                BookId = "1",
                Book   = new Book()
                {
                    Id          = "1",
                    Title       = "Stephen",
                    Description = "King"
                },
                UserId = "1",
                User   = new UserProfile()
                {
                    Id        = "1",
                    FirstName = "Oleksii",
                    LastName  = "Rudenko"
                },
                Message   = "Best book ever",
                TimeStamp = DateTime.Now
            });

            var mapper = new Mock <IMapper>();

            mapper.Setup(m => m.Map <Comment, CommentDto>(It.IsAny <Comment>())).Returns(expected);
            var svc = new CommentService(repository.Object, mapper.Object);

            // Act
            svc.DeleteComment(expected);

            // Assert
            repository.Verify(r => r.Get(It.IsAny <string>()), Times.Once());
            repository.Verify(r => r.Delete(It.IsAny <string>()), Times.Once());
            repository.Verify(r => r.Save(), Times.Once());
        }
コード例 #12
0
ファイル: CommentService.cs プロジェクト: SyPham/DMRS
        public async Task <bool> Update(CommentDto model)
        {
            var articleNo = _mapper.Map <Comment>(model);

            _repoArticalNo.Update(articleNo);
            return(await _repoArticalNo.SaveAll());
        }
コード例 #13
0
        public async Task <ActionResult <CommentDto> > CreateComment([FromRoute] int forumId,
                                                                     [FromBody] CommentDto newComment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var forum = await _context.Forums
                        .Where(o => o.Id == forumId)
                        .Include(o => o.Comments)
                        .FirstOrDefaultAsync();

            if (forum == null)
            {
                return(BadRequest("Forum not found."));
            }

            var comment = new Comment
            {
                Author       = await _userManager.GetUserAsync(HttpContext.User),
                Text         = newComment.Text,
                CreationDate = DateTimeOffset.Now
            };

            forum.Comments.Add(comment);
            await _context.SaveChangesAsync();

            return(_mapper.Map <CommentDto>(comment));
        }
コード例 #14
0
ファイル: CommentService.cs プロジェクト: tRamq/InfoHub
        public void UpdateComment(CommentDto comment)
        {
            var commentMap = _mapper.Map <Comment>(comment);

            _commentRepository.Update(commentMap);
            _unitOfWork.Complete();
        }
コード例 #15
0
        public IResult DeleteComment(CommentDto commentDto)
        {
            var comment = _mapper.Map <Comment>(commentDto);

            _commentRepository.Delete(comment);
            return(new SuccessResult(string.Format(Messages.SuccessfulDelete, nameof(Picture))));
        }
コード例 #16
0
        private CommentDto CreateLinksForComment(CommentDto comment)
        {
            comment.Links.Add(new LinkDto(_urlHelper.Link("GetCommentForReview",
                                                          new { id = comment.Id }),
                                          "self",
                                          "GET"));

            comment.Links.Add(
                new LinkDto(_urlHelper.Link("DeleteComment",
                                            new { id = comment.Id }),
                            "delete_comment",
                            "DELETE"));

            //comment.Links.Add(
            //    new LinkDto(_urlHelper.Link("UpdateComment",
            //    new { id = comment.Id }),
            //    "update_game",
            //    "PUT"));

            comment.Links.Add(
                new LinkDto(_urlHelper.Link("PartiallyUpdateComment",
                                            new { id = comment.Id }),
                            "partially_update_comment",
                            "PATCH"));

            return(comment);
        }
コード例 #17
0
        public void CheckCommentEmail()
        {
            CommentDto commentDto = JsonConvert.DeserializeObject <CommentDto>(commentResponse.GetCommentResponse(14));

            Assert.AreEqual("*****@*****.**", commentDto.email, "Email must be: [email protected]");
            Assert.AreNotEqual("Nathan@solon", commentDto.email, "Email must be incorrect: Nathan@solon");
        }
コード例 #18
0
 public IActionResult Post(
     [FromBody] CommentDto dto,
     [FromServices] ICreateCommentCommand command)
 {
     _executor.ExecuteCommand(command, dto);
     return(StatusCode(StatusCodes.Status201Created));
 }
コード例 #19
0
        public IHttpActionResult EditComment(CommentDto dto)
        {
            var currentUserId = User.Identity.GetUserId();
            var result        = _commentService.EditComment(dto, currentUserId);

            return(this.ReturnHttpResponse(result));
        }
コード例 #20
0
        public void Test()
        {
            CommentSearchDto commentSearchDto = new CommentSearchDto()
            {
                SubjectId = Guid.Parse("5dc6bb5f-9cfa-ff24-00a8-d50e576b275a")
            };

            long userId = 7;
            List <CommentDto> comments = _baseRepository
                                         .Select
                                         .Include(r => r.UserInfo)
                                         .Include(r => r.RespUserInfo)
                                         .IncludeMany(r => r.Childs.Take(2), t => t.Include(u => u.UserInfo))
                                         .IncludeMany(r => r.UserLikes)
                                         .WhereIf(commentSearchDto.SubjectId != null, r => r.SubjectId == commentSearchDto.SubjectId)
                                         .Where(r => r.RootCommentId == commentSearchDto.RootCommentId)
                                         .OrderByDescending(!commentSearchDto.RootCommentId.HasValue, r => r.CreateTime)
                                         .OrderBy(commentSearchDto.RootCommentId.HasValue, r => r.CreateTime)
                                         .ToPagerList(commentSearchDto, out long totalCount)
                                         .Select(r =>
            {
                CommentDto commentDto = Mapper.Map <CommentDto>(r);


                commentDto.TopComment = r.Childs.ToList().Select(u =>
                {
                    CommentDto childrenDto = Mapper.Map <CommentDto>(u);
                    return(childrenDto);
                }).ToList();
                commentDto.IsLiked = r.UserLikes.Where(u => u.CreateUserId == userId).IsNotEmpty();
                return(commentDto);
            }).ToList();
            //return new PagedResultDto<CommentDto>(comments, totalCount);
        }
コード例 #21
0
        public IActionResult Create([FromBody] CommentDto comment, [FromHeader] int UserID)
        {
            if (_user.GetUserById(UserID) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest));
            }

            var newComment = new Comment()
            {
                CreatedByUserId = UserID,
                Text            = comment.Text,
                PostId          = comment.PostId
            };

            _context.Comments.Add(newComment);
            var success = _context.SaveChanges();

            if (success < 1)
            {
                return(StatusCode(StatusCodes.Status400BadRequest));
            }

            this._loggerCommunication.logAction("Created a new comment");

            return(StatusCode(StatusCodes.Status201Created, new JsonResult(newComment)));
        }
コード例 #22
0
        public IActionResult Update(int id, [FromBody] CommentDto comment, [FromHeader] int UserID, [FromHeader] string UserRole)
        {
            var currentComment = _context.Comments.Find(id);

            if (currentComment == null)
            {
                return(StatusCode(StatusCodes.Status404NotFound));
            }

            if (currentComment.CreatedByUserId != UserID && UserRole != "Admin")
            {
                return(StatusCode(StatusCodes.Status403Forbidden));
            }

            currentComment.Text = comment.Text;

            _context.Comments.Update(currentComment);
            var success = _context.SaveChanges();

            if (success < 1)
            {
                return(StatusCode(StatusCodes.Status400BadRequest));
            }

            this._loggerCommunication.logAction("Updated a comment with id:" + id);

            return(StatusCode(StatusCodes.Status202Accepted, new JsonResult(currentComment)));
        }
コード例 #23
0
ファイル: CommentRepository.cs プロジェクト: DilyOkoye/Scapel
        public List <CommentDto> GetAllComment(CommentDto input)
        {
            var query = (from comment in _context.Comment.ToList()
                         join topic in _context.Topic.ToList()
                         on comment.TopicId equals topic.Id

                         select new CommentDto
            {
                TopicName = topic.Name,
                ContentType = comment.ContentType,
                Id = comment.Id,
                DateCreated = comment.DateCreated,
                Status = comment.Status,
                UserId = comment.UserId,
                Content = comment.Content
            }).ToList().Skip((input.PagedResultDto.Page - 1) * input.PagedResultDto.SkipCount).Take(input.PagedResultDto.MaxResultCount);

            // Map Records
            List <CommentDto> ratingDto = MappingProfile.MappingConfigurationSetups().Map <List <CommentDto> >(query);

            //Apply Sort
            ratingDto = Sort(input.PagedResultDto.Sort, input.PagedResultDto.SortOrder, ratingDto);

            // Apply search
            if (!string.IsNullOrEmpty(input.PagedResultDto.Search))
            {
                ratingDto = ratingDto.Where(p => p.Status != null && p.Status.ToLower().ToString().ToLower().Contains(input.PagedResultDto.Search.ToLower()) ||
                                            p.TopicName != null && p.TopicName.ToString().ToLower().Contains(input.PagedResultDto.Search.ToLower()) ||
                                            p.DateCreated != null && p.DateCreated.ToString().ToLower().Contains(input.PagedResultDto.Search.ToLower()) ||
                                            p.ContentType != null && p.ContentType.ToString().ToLower().ToString().Contains(input.PagedResultDto.Search.ToLower()) ||
                                            p.Content != null && p.Content.ToString().ToLower().ToString().Contains(input.PagedResultDto.Search.ToLower())
                                            ).ToList();
            }
            return(ratingDto);
        }
コード例 #24
0
        public async Task <IActionResult> GetNews(long id)
        {
            News news = await _dbContext.News.Include(u => u.Author).Include(p => p.Photo)
                        .FirstOrDefaultAsync(n => n.Id == id);

            if (news != null)
            {
                var newsToReturn = NewsForDetailsDto.Map(news);

                List <Comment> comments = await _dbContext.Comments.Include(a => a.Author)
                                          .Where(c => c.NewsId == id).ToListAsync();

                var commentsToReturn = CommentDto.Map(comments);
                newsToReturn.Comments = commentsToReturn;

                List <News> x = await _dbContext.News.Include(p => p.Photo)
                                .Where(s => s.Section == newsToReturn.Section && s.Id != id)
                                .OrderByDescending(z => z.AddedAt).ToListAsync();

                List <LatestNewsDto> otherInfotoReturn = LatestNewsDto.Map(x.Take(5).ToList());

                return(Ok(new DataForNewsDetailsComponentDto
                {
                    NewsForDetails = newsToReturn,
                    NewsForOtherInfos = otherInfotoReturn
                }));
            }
            else
            {
                return(NoContent());
            }
        }
コード例 #25
0
        private static IEnumerable <CommentDto> CreateCommentsDtoCollection()
        {
            var root = new CommentDto
            {
                Id   = "1",
                Name = "Andrew",
                Body = "Hi, how are you"
            };

            var subRoot = new CommentDto
            {
                Id       = "2",
                Name     = "Bob",
                Body     = "Fine, you?",
                ParentId = root.Id
            };

            var leaf = new CommentDto
            {
                Id       = "3",
                Name     = "John",
                Body     = "What`s up, guys",
                ParentId = subRoot.Id
            };

            return(new List <CommentDto>
            {
                root, subRoot, leaf
            });
        }
コード例 #26
0
ファイル: CommentRepository.cs プロジェクト: DilyOkoye/Scapel
        protected virtual async Task Create(CommentDto input)
        {
            Comment comment = MappingProfile.MappingConfigurationSetups().Map <Comment>(input);

            _context.Comment.Add(comment);
            await _context.SaveChangesAsync();
        }
コード例 #27
0
ファイル: PostStorage.cs プロジェクト: Dr1N/EbParser
        private async Task SaveChildCommentsAsync(IList <CommentDto> allComments,
                                                  CommentDto parent,
                                                  Comment parentModel,
                                                  Post post)
        {
            var children = allComments
                           .Where(c => c.ParrentId == parent.Id)
                           .ToList();

            if (children.Count == 0)
            {
                return;
            }

            foreach (var child in children)
            {
                var dbComment = new Comment()
                {
                    Author  = child.Author,
                    Publish = child.Publish,
                    Post    = post,
                    Content = child.Content,
                    Parent  = parentModel,
                    Updated = DateTime.Now,
                };
                _db.Comments.Add(dbComment);
                await SaveChildCommentsAsync(allComments, child, dbComment, post).ConfigureAwait(false);
            }
        }
コード例 #28
0
        public async Task AddComment(CommentDto comment)
        {
            try
            {
                var result = UnitOfWork.Comments.Create(Mapper.Map <Comment>(comment));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw;
            }

            var phone = await UnitOfWork.Phones.Get(comment.PhoneId).Include(p => p.Comments).FirstOrDefaultAsync();

            var average = phone.Comments.Select(c => c.Grade).Average();

            phone.Grade = Convert.ToInt32(average);
            UnitOfWork.Phones.Update(phone);

            try
            {
                await UnitOfWork.SaveAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw;
            }
        }
コード例 #29
0
        public void CommentDtoValidationTest()
        {
            var validator          = new DtoModelsValidator();
            var emptyFieldsComment = new CommentDto()
            {
                User = null,
                Text = null
            };
            var shortUsernameComment = new CommentDto()
            {
                User = "******",
                Text = "Text"
            };
            var validComment = new CommentDto()
            {
                User = "******",
                Text = "Text"
            };

            var nullCommentErrors          = validator.GetCommentDtoValidationErrors(null);
            var emptyFieldsCommentErrors   = validator.GetCommentDtoValidationErrors(emptyFieldsComment);
            var shortUsernameCommentErrors = validator.GetCommentDtoValidationErrors(shortUsernameComment);
            var validCommentErrors         = validator.GetCommentDtoValidationErrors(validComment);

            Assert.AreEqual(nullCommentErrors.Count, 3);
            Assert.AreEqual(emptyFieldsCommentErrors.Count, 2);
            Assert.AreEqual(shortUsernameCommentErrors.Count, 1);
            Assert.AreEqual(validCommentErrors.Count, 0);
        }
コード例 #30
0
        public async Task <CommentDto> Comment(CommentDto dto)
        {
            // Creamos un nuevo comentario y lo añadimos al contexto
            Comment comment = new Comment();

            comment      = _mapper.Map <Comment>(dto);
            comment.Date = DateTime.Now;
            _context.Comments.Add(comment);

            await _context.SaveChangesAsync();

            // Creamos un nuevo PostComment y lo añadimos al contexto
            PostComment postComment = new PostComment
            {
                PostId    = dto.PostId,
                CommentId = comment.Id
            };

            _context.PostsComments.Add(postComment);

            // Guardamos los cambios y devolvemos el dto de entrada
            await _context.SaveChangesAsync();

            return(comment.ToDto(postComment.PostId));
        }
コード例 #31
0
        internal static List<CommentDto> GetList(List<Comment> list, List<Comment> source)
        {
            var dtoList = new List<CommentDto>();

            foreach (var i in list)
            {
                var item = new CommentDto
                {
                    ID = i.CommentID,
                    Comment = i.Comment1,
                    Date = i.Date,
                    Parent = i.ReplyCommentID == null ? null : new CommentDto { ID = i.ReplyCommentID.Value },
                    Place = i.Place.ToEntity<PlaceDto>(),
                    User = i.User.ToEntity<UserDto>(),
                };

                item.Replys = CommentBusiness.GetList(source.Where(l => l.ReplyCommentID == i.CommentID).ToList(), source.Where(l => l.ReplyCommentID != i.CommentID).ToList());
                dtoList.Add(item);
            }

            return dtoList;
        }
コード例 #32
0
ファイル: CommentController.cs プロジェクト: Boshin/wojilu
        private List<CommentDto> getCommentDto( List<OpenComment> moreList )
        {
            List<CommentDto> list = new List<CommentDto>();
            foreach (OpenComment c in moreList) {

                Dictionary<String, String> userInfo = getUserInfo( c.Member, c.Author );

                CommentDto dto = new CommentDto();
                dto.Id = c.Id;
                dto.UserName = userInfo["userName"];
                dto.UserFace = userInfo["userFace"];
                dto.AuthorText = userInfo["authorText"];
                dto.Content = c.Content;
                dto.Created = c.Created.ToString( "g" );

                list.Add( dto );
            }

            return list;
        }
コード例 #33
0
ファイル: CommentAppService.cs プロジェクト: SNest/MvcTask
 public virtual void Create(CommentDto item)
 {
     this.unitOfWork.Entities<Comment, long>().Create(Mapper.Map<Comment>(item));
 }