Esempio n. 1
0
 public bool IsValid(NewCommentViewModel comment)
 {
     return(!string.IsNullOrWhiteSpace(comment.SubwebbitId) &&
            !string.IsNullOrWhiteSpace(comment.ThreadId) &&
            !string.IsNullOrWhiteSpace(comment.Content) &&
            !string.IsNullOrWhiteSpace(comment.Author));
 }
Esempio n. 2
0
        public IActionResult Create(NewCommentViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Json(new { ok = false, reason = GenericMessages.FillOutForm }));
            }

            var userId       = this.usersService.GetIdFromUsername(model.Username);
            var creationInfo = this.mapper.Map <CreateCommentDto>(model);

            creationInfo.UserId = userId;

            var creationResult = this.commentsService.Create(creationInfo, out Comment comment);

            if (!creationResult)
            {
                return(this.Json(new { ok = false, reason = string.Format(GenericMessages.InvalidDataProvided) }));
            }

            var commentInfo = new {
                title   = comment.Title,
                body    = comment.Body,
                author  = comment.User.UserName,
                date    = comment.CreatedOn.ToShortDateString(),
                time    = comment.CreatedOn.ToShortTimeString(),
                isReply = model.Type?.ToLower() == "reply",
            };

            return(this.Json(new { ok = true, info = commentInfo }));
        }
Esempio n. 3
0
 private void EnsureCommentDetails(NewCommentViewModel comment)
 {
     if (!new CommentValidator().IsValid(comment))
     {
         throw new InvalidModelDetailsException();
     }
 }
Esempio n. 4
0
        public NewCommentViewController(Func <string, Task> saveAction)
        {
            ViewModel = new NewCommentViewModel(saveAction);

            Title = "New Comment";
            EdgesForExtendedLayout = UIRectEdge.None;

            var discardButton = new UIBarButtonItem {
                Image = Images.Buttons.Cancel
            };
            var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Save);

            NavigationItem.RightBarButtonItem = doneButton;
            NavigationItem.LeftBarButtonItem  = discardButton;

            _textView                  = new UITextView();
            _textView.Font             = UIFont.PreferredBody;
            _textView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;

            // Work around an Apple bug in the UITextView that crashes
            if (ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR)
            {
                _textView.AutocorrectionType = UITextAutocorrectionType.No;
            }

            OnActivation(d =>
            {
                discardButton
                .GetClickedObservable()
                .SelectUnit()
                .BindCommand(ViewModel.DiscardCommand)
                .AddTo(d);

                this.WhenAnyValue(x => x.ViewModel.DoneCommand.CanExecute)
                .Switch()
                .Subscribe(x => doneButton.Enabled = x)
                .AddTo(d);

                doneButton
                .GetClickedObservable()
                .Do(_ => _textView.ResignFirstResponder())
                .SelectUnit()
                .BindCommand(ViewModel.DoneCommand)
                .AddTo(d);

                _textView
                .GetChangedObservable()
                .Subscribe(x => ViewModel.Text = x)
                .AddTo(d);

                this.WhenAnyValue(x => x.ViewModel.Text)
                .Subscribe(x => _textView.Text = x)
                .AddTo(d);

                this.WhenAnyObservable(x => x.ViewModel.DismissCommand)
                .Select(_ => Unit.Default)
                .Subscribe(_dismissSubject)
                .AddTo(d);
            });
        }
Esempio n. 5
0
        public IHttpActionResult CreateComment(NewCommentViewModel comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var commentDto = _mapper.Map <NewCommentViewModel, NewCommentDTO>(comment);

            SetOrganizationAndUser(commentDto);
            var userHubDto = GetUserAndOrganizationHub();

            try
            {
                var commentCreatedDto = _commentService.CreateComment(commentDto);
                _asyncRunner.Run <NewCommentNotifier>(notif =>
                {
                    notif.Notify(commentCreatedDto, userHubDto);
                }, GetOrganizationName());

                return(Ok(new { commentCreatedDto.CommentId }));
            }
            catch (ValidationException e)
            {
                return(BadRequestWithError(e));
            }
        }
Esempio n. 6
0
        public async Task <IHttpActionResult> CreateComment(NewCommentViewModel comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var commentDto = _mapper.Map <NewCommentViewModel, NewCommentDTO>(comment);

            SetOrganizationAndUser(commentDto);

            try
            {
                var commentCreatedDto = _commentService.CreateComment(commentDto);

                var membersToNotify = _wallService.GetWallMembersIds(commentCreatedDto.WallId, commentDto);
                NotificationHub.SendWallNotification(commentCreatedDto.WallId, membersToNotify, commentCreatedDto.WallType, GetUserAndOrganizationHub());

                var commentsAuthorsToNotify = _commentService.GetCommentsAuthorsToNotify(
                    commentDto.PostId,
                    new List <string>()
                {
                    commentCreatedDto.CommentCreator
                });

                if (commentCreatedDto.PostCreator != commentCreatedDto.CommentCreator && _commentService.IsPostAuthorAppNotificationsEnabled(commentCreatedDto.PostCreator))
                {
                    var notificationAuthorDto = await _notificationService.CreateForComment(GetUserAndOrganization(), commentCreatedDto, NotificationType.WallComment, new List <string> {
                        commentCreatedDto.PostCreator
                    });

                    if (notificationAuthorDto != null)
                    {
                        NotificationHub.SendNotificationToParticularUsers(_mapper.Map <NotificationViewModel>(notificationAuthorDto), GetUserAndOrganizationHub(), new List <string>()
                        {
                            commentCreatedDto.PostCreator
                        });
                    }

                    commentsAuthorsToNotify.Remove(commentCreatedDto.PostCreator);
                }

                if (commentsAuthorsToNotify.Count > 0)
                {
                    var notificationDto = await _notificationService.CreateForComment(GetUserAndOrganization(), commentCreatedDto, NotificationType.FollowingComment, commentsAuthorsToNotify);

                    if (notificationDto != null)
                    {
                        NotificationHub.SendNotificationToParticularUsers(_mapper.Map <NotificationViewModel>(notificationDto), GetUserAndOrganizationHub(), commentsAuthorsToNotify);
                    }
                }

                return(Ok(new { commentCreatedDto.CommentId }));
            }
            catch (ValidationException e)
            {
                return(BadRequestWithError(e));
            }
        }
Esempio n. 7
0
        public IViewComponentResult Invoke(Guid topicId)
        {
            var model = new NewCommentViewModel {
                PostId = topicId
            };

            return(View(model));
        }
Esempio n. 8
0
        public async Task <IActionResult> NewComment(NewCommentViewModel model)
        {
            model.UserId = await _currentUserService.GetUserId();

            var result = await _commentService.AddComment(model);

            return(RedirectToAction(nameof(Index), new { id = model.PostId }));
        }
Esempio n. 9
0
        public ActionResult Comment(NewCommentViewModel model)
        {
            var userId = this.authenticationProvider.CurrentUserId;

            this.commentService.AddCommentToLog(model.Content, model.LogId, userId);

            return(this.RedirectToAction("Details", "Logs", new { id = model.LogId, page = -1 }));
        }
Esempio n. 10
0
        public async Task <IActionResult> AddComment(NewCommentViewModel newComment)
        {
            var loggedUser = await _userManager.GetUserAsync(User);

            newComment.UserId = loggedUser.Id;

            _commentService.AddComment(newComment);

            return(RedirectToAction("Index", "Post"));
        }
Esempio n. 11
0
        public IActionResult Add(int Id, NewCommentViewModel comment)
        {
            if (!ModelState.IsValid)
            {
                return(View(comment));
            }

            _commentservices.Add(Id, comment.Title, comment.Content, comment.Author);

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 12
0
        public ActionResult CreateNew(NewCommentViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                model.UserId   = User.Identity.GetUserId();
                model.UserName = User.Identity.Name;
            }

            _commentsService.AddComment(model);

            return(Json(new { }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 13
0
        public async Task <IActionResult> CreateComment([FromRoute] int postId,
                                                        [FromBody] NewCommentViewModel newComment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var newCommentResponse = await _commentService.CreateComment(postId, newComment);

            return(Ok(newCommentResponse));
        }
Esempio n. 14
0
        public void AddNewComment(NewCommentViewModel vm)
        {
            var comment = new Comment()
            {
                UserId    = vm.UserId,
                AlbumId   = vm.AlbumId,
                Content   = vm.Content,
                DateAdded = DateTime.Now
            };

            _db.Comments.Add(comment);

            _db.SaveChanges();
        }
Esempio n. 15
0
        public async Task <bool> AddComment(NewCommentViewModel model)
        {
            var comment = new Comment
            {
                CreatedOn = DateTime.Now,
                Content   = model.Content,
                PostId    = model.PostId,
                UserId    = model.UserId
            };

            await _context.Comments.AddAsync(comment);

            return(await _context.SaveChangesAsync() > 0);
        }
Esempio n. 16
0
        public async Task <NewCommentResponseViewModel> CreateComment(int postId, NewCommentViewModel comment)
        {
            var newComment = _mapper.Map <Comment>(comment);
            var post       = await _postRepository.Get(postId);

            newComment.Post   = post;
            newComment.PostId = post.Id;
            var addedComment = await _commentRepository.Add(newComment);

            var response = new NewCommentResponseViewModel()
            {
                Id = addedComment.Id
            };

            return(response);
        }
Esempio n. 17
0
        public void TestComment_ShouldCallAuthenticationProviderCurrentUserId()
        {
            // Arrange
            var model = new NewCommentViewModel();

            var mockedService = new Mock <ICommentService>();
            var mockedAuthenticationProvider = new Mock <IAuthenticationProvider>();

            var controller = new CommentController(mockedService.Object, mockedAuthenticationProvider.Object);

            // Act
            controller.Comment(model);

            // Assert
            mockedAuthenticationProvider.Verify(p => p.CurrentUserId, Times.Once);
        }
Esempio n. 18
0
        public async Task Post(NewCommentViewModel comment)
        {
            EnsureCommentDetails(comment);
            var updateInfo = new UpdatingOperation(comment.SubwebbitId, comment.ThreadId);

            if (!string.IsNullOrWhiteSpace(comment.ParentCommentId))
            {
                updateInfo.AddNestedCommentFilter(ObjectId.Parse(comment.ParentCommentId));
            }

            var newComment = new Comment(comment.Author, comment.Content);

            await Collection.UpdateOneAsync(updateInfo.Filter,
                                            UpdateBuilder.AddToSet(updateInfo.ModelHierarchy + "." + nameof(Thread.Comments).ToLower(), newComment),
                                            updateInfo.Options);
        }
Esempio n. 19
0
        public void TestComment_ShouldRedirectCorrectly(int logId)
        {
            // Arrange
            var model = new NewCommentViewModel {
                LogId = logId
            };

            var mockedService = new Mock <ICommentService>();
            var mockedAuthenticationProvider = new Mock <IAuthenticationProvider>();

            var controller = new CommentController(mockedService.Object, mockedAuthenticationProvider.Object);

            // Act, Assert
            controller
            .WithCallTo(c => c.Comment(model))
            .ShouldRedirectTo((LogsController c) => c.Details(logId, It.IsAny <int>(), It.IsAny <int>()));
        }
Esempio n. 20
0
        public void TestComment_ModelStateIsNotValid_ShouldNotCallAuthenticationProviderCurrentUserId()
        {
            // Arrange
            var model = new NewCommentViewModel();

            var mockedService = new Mock <ICommentService>();
            var mockedAuthenticationProvider = new Mock <IAuthenticationProvider>();

            var controller = new CommentController(mockedService.Object, mockedAuthenticationProvider.Object);

            controller.ModelState.AddModelError("", "");

            // Act
            controller.Comment(model);

            // Assert
            mockedAuthenticationProvider.Verify(p => p.CurrentUserId, Times.Never);
        }
Esempio n. 21
0
        public async Task <IActionResult> Post([FromBody] NewCommentViewModel model)
        {
            if (ModelState.IsValid)
            {
                Comment newComment = new Comment();
                if (User.Identity.IsAuthenticated)
                {
                    newComment = new Comment
                    {
                        Approved  = false,
                        PostedOn  = DateTime.Now,
                        Text      = model.Content,
                        PostId    = model.PostId,
                        ReplyOnId = model.ReplyOnId,
                        UserId    = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value
                    };
                }
                else
                {
                    if (model.Name == null)
                    {
                        return(BadRequest());
                    }
                    newComment = new Comment
                    {
                        Approved  = false,
                        PostedOn  = DateTime.Now,
                        Text      = model.Content,
                        PostId    = model.PostId,
                        ReplyOnId = model.ReplyOnId,
                        UserName  = model.Name
                    };
                }
                this.unitOfWork.CommentsRepository.Add(newComment);
                await this.unitOfWork.Save();

                return(CreatedAtAction("Post", new { id = newComment.CommentId }));
            }
            else
            {
                return(BadRequest());
            }
        }
Esempio n. 22
0
        public async Task <IActionResult> Post(NewCommentViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(HttpContext.User);

                var result = new Comment
                {
                    CommentText = model.WrittenText,
                    CommentDate = DateTime.Now,
                    PostId      = model.PostId,
                    FullName    = $"{user.Name} {user.Surname}"
                };

                _context.Add(result);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Post"));
            }
            return(View());
        }
        public int AddComment(NewCommentViewModel commentModel)
        {
            using (DataContext db = new DataContext())
            {
                try
                {
                    CommentViewModel model = (CommentViewModel)commentModel;

                    model.DateCreated = DateTime.Now;

                    Comment comment = Mapper.Map <Comment>(model);
                    db.Comments.Add(comment);
                    db.SaveChanges();
                    return(comment.Id);
                }
                catch (Exception ex)
                {
                    return(0);
                }
            }
        }
Esempio n. 24
0
        public void TestComment_ShouldCallEntryServiceAddEntryToLogCorrectly(int logId, string content, string userId)
        {
            // Arrange
            var model = new NewCommentViewModel
            {
                LogId   = logId,
                Content = content
            };

            var mockedService = new Mock <ICommentService>();
            var mockedAuthenticationProvider = new Mock <IAuthenticationProvider>();

            mockedAuthenticationProvider.Setup(p => p.CurrentUserId).Returns(userId);

            var controller = new CommentController(mockedService.Object, mockedAuthenticationProvider.Object);

            // Act
            controller.Comment(model);

            // Assert
            mockedService.Verify(s => s.AddCommentToLog(content, logId, userId), Times.Once);
        }
Esempio n. 25
0
        public HttpResponseMessage AddPhotoComment(NewCommentViewModel viewModel)
        {
            var photoCommentModel = new PhotoCommentModel(
                User.Id,
                viewModel.PhotoId,
                viewModel.CommentText,
                viewModel.Reply);

            try
            {
                _photoCommentService.AddPhotoComment(User.Id, photoCommentModel);
            }
            catch (NoEnoughPrivilegesException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }

            return(Request.CreateResponse(HttpStatusCode.Created));
        }
Esempio n. 26
0
        public async Task <IHttpActionResult> CreateComment(NewCommentViewModel comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userAndOrg = GetUserAndOrganization();

            var wallPost = await _wallService.GetWallPostAsync(userAndOrg, comment.PostId);

            if (!await _permissionService.UserHasPermissionAsync(userAndOrg, BasicPermissions.Comment) && wallPost.WallType != WallType.Events)
            {
                return(Forbidden());
            }

            var commentDto = _mapper.Map <NewCommentViewModel, NewCommentDto>(comment);

            SetOrganizationAndUser(commentDto);
            var userHubDto = GetUserAndOrganizationHub();

            try
            {
                var commentCreatedDto = await _commentService.CreateCommentAsync(commentDto);

                _asyncRunner.Run <NewCommentNotifier>(async notifier =>
                {
                    await notifier.NotifyAsync(commentCreatedDto, userHubDto);
                }, GetOrganizationName());

                return(Ok(new { commentCreatedDto.CommentId }));
            }
            catch (ValidationException e)
            {
                return(BadRequestWithError(e));
            }
        }
Esempio n. 27
0
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> NewComment([FromBody] NewCommentViewModel newCommentViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var comment = new Comment()
            {
                ServiceId       = newCommentViewModel.ServiceId,
                NodePubKey      = newCommentViewModel.NodePubKey,
                DateCreated     = DateTime.Now,
                DateModified    = DateTime.Now,
                UserId          = GetUserId(),
                Username        = User.Identity.Name,
                Body            = newCommentViewModel.CommentBody,
                ParentCommentId = newCommentViewModel.ParentCommentId
            };

            var authorizationResult = await authorizationService.AuthorizeAsync(User, comment, "CanCrudOwnComment");

            if (authorizationResult.Succeeded)
            {
                _repository.AddNewComment(comment);
                _unitOfWork.Complete();
                return(Ok(CreateCommentViewModel(comment)));
            }
            else if (User.Identity.IsAuthenticated)
            {
                return(new ForbidResult());
            }
            else
            {
                return(new ChallengeResult());
            }
        }
        public List <NewCommentViewModel> GetNewCommentList(List <int> projectIds, string mention, int userId)
        {
            List <NewCommentViewModel> commentViewModel = new List <NewCommentViewModel>();

            foreach (int projectId in projectIds)
            {
                var query = context.Comments.Include(x => x.Project).Include(x => x.User).Where(x => x.ProjectId == projectId && x.UserId != userId && x.State == 1 && x.Seen == 0 && x.Mension == mention).ToList();

                foreach (var data in query)
                {
                    NewCommentViewModel model = new NewCommentViewModel();

                    model.TaskId      = data.Id;
                    model.ProjectId   = data.ProjectId;
                    model.TaskId      = data.TaskId;
                    model.ProjectName = data.Project.Name;
                    model.ByUserName  = data.User.Name;

                    commentViewModel.Add(model);
                }
            }

            return(commentViewModel);
        }
Esempio n. 29
0
        public async Task <IHttpActionResult> Post(NewCommentViewModel comment)
        {
            await Logic.Post(comment);

            return(Ok());
        }
 public NewCommentPage(int id)
 {
     InitializeComponent();
     _id            = id;
     BindingContext = model = new NewCommentViewModel(_id);
 }