Exemple #1
0
 public void Check_CommentTitle_Valid(int textLength)
 {
     string text = GetStringWithDesiredLength(textLength);
     var validator = new CommentValidator();
     string[] errors;
     Assert.True(validator.Validate(Comment.Create(new CommentState { Text = text }), out errors));
 }
Exemple #2
0
        public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
        {
            ////app.UseCors("MyPolicy");

            // initialize endpoint
            var configurationManager  = new ConfigurationManager(this.config);
            var endpointInitializer   = new EndpointInitializer(configurationManager);
            var endpointConfiguration = new EndpointConfiguration(configurationManager.NsbEndpointName);

            endpointInitializer.Initialize(endpointConfiguration, true);
            applicationLifetime.ApplicationStopping.Register(this.OnShutdown);

            // start endpoint
            this.endpointInstance = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();

            // initialize validator
            var commentValidator = new CommentValidator();

            // initialize logger
            var legger = loggerFactory.AddLog4Net().CreateLogger("Web");

            app.UseOwin(x => x.UseNancy(opt => opt.Bootstrapper = new Bootstrapper(
                                            this.endpointInstance,
                                            commentValidator,
                                            legger)));
        }
Exemple #3
0
        public void TestGetAll()
        {
            var firstComment  = CommentBuilder.New().WithContent("FirstComment").Build();
            var secondComment = CommentBuilder.New().WithContent("SecondComment").Build();
            var thirdComment  = CommentBuilder.New().WithContent("ThirdComment").Build();

            var resultValidationFirst  = new CommentValidator().Validate(firstComment);
            var resultValidationSecond = new CommentValidator().Validate(secondComment);
            var resultValidationThird  = new CommentValidator().Validate(thirdComment);

            // Conhecimento MemoryCache
            CacheItemPolicy policy = new CacheItemPolicy();

            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(120);
            memoryCache.Add("firstComment", firstComment, policy);
            memoryCache.Add("secondComment", secondComment, policy);
            memoryCache.Add("thirdComment", thirdComment, policy);
            Assert.IsTrue(3 == memoryCache.GetCount());

            // Produção através dos métodos
            new CreateComment().CreateNewRegister(firstComment);
            new CreateComment().CreateNewRegister(secondComment);
            new CreateComment().CreateNewRegister(thirdComment);
            List <Comment> listComments = new GetComment().GetAllRegister();

            Assert.IsTrue(3 == listComments.Count);
        }
Exemple #4
0
        public ActionResult <Comment> Post(Guid autorId, string content, Guid publicationId)
        {
            var resultValidation = new UserExistValidator().Validate(autorId);

            if (!resultValidation.IsValid)
            {
                return(BadRequest(resultValidation.Errors));
            }

            var autor = userRepository.GetById(autorId);

            resultValidation = new PublicationExistValidator().Validate(publicationId);

            if (!resultValidation.IsValid)
            {
                return(BadRequest(resultValidation.Errors));
            }

            Comment comment = new Comment(autor, content, publicationId);

            resultValidation = new CommentValidator().Validate(comment);

            if (!resultValidation.IsValid)
            {
                return(BadRequest(resultValidation.Errors));
            }

            commentRepository.Create(comment);

            return(CreatedAtAction("Get", new { id = comment.Id }, comment));
        }
        public void DefaultValidation_CommentThatIsNull_ShouldThrowException()
        {
            ICommentValidator commentValidator = new CommentValidator();
            Action            action           = () => commentValidator.DefaultValidation(null as Comment);

            action.Should().Throw <NullReferenceException>().WithMessage("Comment can not be null");
        }
        public async Task <Guid> CreateCommentReplyAsync(Guid userId, string slug, Guid parentEntityId, Guid replyingToComment, Comment comment, CancellationToken cancellationToken)
        {
            if (Guid.Empty == userId)
            {
                throw new ArgumentOutOfRangeException(nameof(userId));
            }
            if (string.IsNullOrEmpty(slug))
            {
                throw new ArgumentOutOfRangeException(nameof(slug));
            }

            var now = _systemClock.UtcNow.UtcDateTime;

            var userCanPerformAction = await _permissionsService.UserCanPerformActionAsync(userId, slug, AddCommentRole, cancellationToken);

            if (!userCanPerformAction)
            {
                _logger.LogError($"Error: CreateCommentAsync - User:{0} does not have access to group:{1}", userId, slug);
                throw new SecurityException($"Error: User does not have access");
            }

            var threadId = await _commentCommand.GetThreadIdForComment(replyingToComment, cancellationToken);

            if (!threadId.HasValue)
            {
                _logger.LogError($"Error: CreateCommentReplyAsync - Cannot find the original comment when replying to comment:{0} in discussion: {1}", replyingToComment, parentEntityId);
                throw new SecurityException($"Error: User does not have access");
            }
            var entityId = Guid.NewGuid();

            var commentDto = new CommentDto()
            {
                EntityId      = entityId,
                Content       = comment.Content,
                CreatedAtUTC  = now,
                CreatedBy     = userId,
                ModifiedBy    = null,
                ModifiedAtUTC = null,
                FlaggedAsSpam = false,
                InReplyTo     = replyingToComment,
                ThreadId      = threadId,
                IsDeleted     = false,
                DiscussionId  = parentEntityId
            };

            var validator        = new CommentValidator();
            var validationResult = await validator.ValidateAsync(commentDto, cancellationToken);

            if (validationResult.Errors.Count > 0)
            {
                throw new ValidationException(validationResult);
            }

            var createdComment = await _commentCommand.CreateCommentAsync(commentDto, cancellationToken);

            _ = Task.Run(() => _commentNotificationService.SendNotificationToCommentCreatorAsync(userId, replyingToComment, cancellationToken), cancellationToken);

            return(createdComment);
        }
        public CommentValidatorTests()
        {
            _workItemRepository = Substitute.For <IWorkItemRepository>();

            _workItemRepository.GetById(1).Returns(new WorkItem());
            _workItemRepository.GetById(0).Returns <WorkItem>(value => null);

            _validator = new CommentValidator(_workItemRepository);
        }
        public void DefaultValidation_TopicThatIsNull_ShouldThrowException()
        {
            ICommentValidator commentValidator = new CommentValidator();
            Action            action           = () => commentValidator.DefaultValidation(new Comment()
            {
                DatePosted = DateTime.Now.AddDays(-5), MainBody = "yadayada", User = new User()
            });

            action.Should().Throw <NullReferenceException>().WithMessage("Comment must have a Topic");
        }
        public void DefaultValidation_DatePostedCanNotBeInFuture_ShouldThrowException()
        {
            ICommentValidator commentValidator = new CommentValidator();
            Action            action           = () => commentValidator.DefaultValidation(new Comment()
            {
                DatePosted = DateTime.Now.AddDays(5), MainBody = "yadayada", Topic = new Topic(), User = new User()
            });

            action.Should().Throw <ArgumentException>().WithMessage("DatePosted can not be in the future");
        }
        public void DefaultValidation_CommentCanNotBeEmptyOrNull_ShouldThrowException()
        {
            ICommentValidator commentValidator = new CommentValidator();
            Action            action           = () => commentValidator.DefaultValidation(new Comment()
            {
                DatePosted = DateTime.Now.AddDays(-5), Topic = new Topic(), User = new User()
            });

            action.Should().Throw <ArgumentException>().WithMessage("Comment must not be empty");
        }
Exemple #11
0
    public Comment(BlogEntry blogEntry, string name, string emailAddress, string commentText)
    {
        BlogEntry    = blogEntry;
        Name         = name;
        EmailAddress = emailAddress;
        CommentText  = commentText;
        DateWritten  = DateTime.Now;
        var commentValidator = new CommentValidator();

        commentValidator.ValidateAndThrow(this);
    }
Exemple #12
0
        public void CommentValidator_ThrowsInvalidValueLength()
        {
            CommentModel model = new CommentModel
            {
                PostId = new Guid("9834d7b9-618d-435b-b86e-d9e861111738"),
                Value  = "too small"
            };
            CommentValidator validator = new CommentValidator();

            validator.Validate(model);
        }
 public PostItemService(
     IPostItemRepository postItemRepository,
     ICommentRepository commentRepository,
     PostValidator postValidator,
     CommentValidator commentValidator)
 {
     this.postItemRepository = postItemRepository;
     this.commentRepository  = commentRepository;
     this.postValidator      = postValidator;
     this.commentValidator   = commentValidator;
 }
Exemple #14
0
        public void CommentValidator_ThrowsEmptyOrNullValue()
        {
            CommentModel model = new CommentModel
            {
                PostId = new Guid("9834d7b9-618d-435b-b86e-d9e861111738"),
                Value  = String.Empty
            };
            CommentValidator validator = new CommentValidator();

            validator.Validate(model);
        }
Exemple #15
0
        public void TestValidationCommentWithInvalidTopic()
        {
            var okUser = UserBuilder.New().Build();

            new UserRepository().Create(okUser);

            var badComment1 = CommentBuilder.New().WithContent("  ").Build();

            var resultValidation2 = new CommentValidator().Validate(badComment1);

            Assert.False(resultValidation2.IsValid);
        }
Exemple #16
0
        public void TestValidationCommentWithValidResult()
        {
            var okUser = UserBuilder.New().Build();

            new UserRepository().Create(okUser);

            var okComment = CommentBuilder.New().Build();

            var resultValidation1 = new CommentValidator().Validate(okComment);

            Assert.True(resultValidation1.IsValid);
        }
Exemple #17
0
        public void TestValidationCommentWithInvalidPublicationId()
        {
            var okUser = UserBuilder.New().Build();

            new UserRepository().Create(okUser);

            var badComment1 = CommentBuilder.New().WithPublicationId(Guid.Parse("00000000-0000-0000-0000-000000000000")).Build();

            var resultValidation2 = new CommentValidator().Validate(badComment1);

            Assert.False(resultValidation2.IsValid);
        }
 public Comment EditCommentVotes(string command, int commentId)
 {
     try
     {
         var comment = _context.Comments.SingleOrDefault(com => com.Id == commentId);
         comment = CommentValidator.ValidateCommand(comment, command);
         _context.Comments.Update(comment);
         _context.SaveChanges();
         return(comment);
     }
     catch (Exception)
     {
         throw;
     }
 }
 public static void Initialize(TestContext testContext)
 {
     ApplicationUserValidator = new ApplicationUserValidator();
     FollowerValidator        = new FollowerValidator();
     CredentialValidator      = new CredentialValidator();
     CredentialTypeValidator  = new CredentialTypeValidator();
     RoleValidator            = new RoleValidator();
     UserRoleValidator        = new UserRoleValidator();
     RolePermissionValidator  = new RolePermissionValidator();
     PermissionValidator      = new PermissionValidator();
     MemeValidator            = new MemeValidator();
     CommentValidator         = new CommentValidator();
     Hasher        = new Pbkdf2Hasher();
     SaltGenerator = new RandomSaltGenerator();
 }
Exemple #20
0
        public ActionResult <Comment> Put(Guid id, string content)
        {
            var resultValidation = new CommentExistValidator().Validate(id);

            if (!resultValidation.IsValid)
            {
                return(BadRequest(resultValidation.Errors));
            }

            Comment oldComment = commentRepository.GetById(id);
            Comment newComment = new Comment(id, oldComment.Autor, content, oldComment.PublicationId);

            resultValidation = new CommentValidator().Validate(newComment);

            if (!resultValidation.IsValid)
            {
                return(BadRequest(resultValidation.Errors));
            }

            return(Ok(commentRepository.Update(newComment)));
        }
Exemple #21
0
        public void TestGetById()
        {
            var comment = CommentBuilder.New().WithId(new Guid()).Build();

            var resultValidation = new CommentValidator().Validate(comment);

            // Conhecimento MemoryCache
            CacheItemPolicy policy = new CacheItemPolicy();

            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60);
            memoryCache.Add("commentGetId", comment, policy);
            Comment commentGet = (Comment)memoryCache["commentGetId"];

            Assert.IsTrue(commentGet.Id == Guid.Parse("00000000-0000-0000-0000-000000000000"));

            // Produção através dos métodos
            new CreateComment().CreateNewRegister(comment);
            var idGet = new GetComment().GetRegisterById(comment.Id);

            Assert.IsNotNull(idGet);
        }
Exemple #22
0
        public IActionResult CreateComment(string content, Guid postId, Guid userId)
        {
            var post = getByIdPostUseCase.GetById(postId);
            var user = getByIdUserUseCase.GetById(userId);

            if (post == null && user == null)
            {
                return(BadRequest());
            }
            var comment = new Domain.Entities.Comment(content, post, user);

            var validationResult = new CommentValidator().Validate(comment);

            if (!validationResult.IsValid)
            {
                return(BadRequest(validationResult.Errors));
            }

            addCommentUseCase.Add(comment);
            return(new OkObjectResult(comment));
        }
        private Comment CreateComment(Document inDocument)
        {
            using var documentContext = this.ApiServiceContext.CreateApiDocumentContext(inDocument);
            var inComment = documentContext.GetResource <Comment>();

            var apiCommentResource = inDocument.GetResource();

            if (apiCommentResource?.Relationships != null)
            {
                // Author foreign key (optional)
                if (apiCommentResource.Relationships.TryGetRelationship("author", out var apiCommentAuthorRelationship))
                {
                    if (apiCommentAuthorRelationship.IsToOneRelationship())
                    {
                        var apiCommentAuthorToOneRelationship = (ToOneRelationship)apiCommentAuthorRelationship;
                        var apiCommentAuthorId = Convert.ToInt64(apiCommentAuthorToOneRelationship.Data.Id);
                        inComment.AuthorId = apiCommentAuthorId;
                    }
                }

                // Article foreign key (required)
                if (apiCommentResource.Relationships.TryGetRelationship("article", out var apiCommentArticleRelationship))
                {
                    if (apiCommentArticleRelationship.IsToOneRelationship())
                    {
                        var apiCommentArticleToOneRelationship = (ToOneRelationship)apiCommentArticleRelationship;
                        var apiCommentArticleId = Convert.ToInt64(apiCommentArticleToOneRelationship.Data.Id);
                        inComment.ArticleId = apiCommentArticleId;
                    }
                }
            }

            var validator = new CommentValidator();

            validator.ValidateAndThrow(inComment);

            var outComment = this.BloggingRepository.CreateComment(inComment);

            return(outComment);
        }
Exemple #24
0
 public CommentShould()
 {
     this.configuration = new CommentValidator();
 }
        public async Task UpdateCommentAsync(Guid userId, string slug, Guid parentEntityId, Guid commentId, Comment comment, byte[] rowVersion, CancellationToken cancellationToken)
        {
            if (Guid.Empty == userId)
            {
                throw new ArgumentOutOfRangeException(nameof(userId));
            }
            if (string.IsNullOrEmpty(slug))
            {
                throw new ArgumentOutOfRangeException(nameof(slug));
            }
            if (Guid.Empty == parentEntityId)
            {
                throw new ArgumentOutOfRangeException(nameof(parentEntityId));
            }
            if (Guid.Empty == commentId)
            {
                throw new ArgumentOutOfRangeException(nameof(commentId));
            }

            var now = _systemClock.UtcNow.UtcDateTime;

            var userCanAddComment = await _permissionsService.UserCanPerformActionAsync(userId, slug, AddCommentRole, cancellationToken);

            if (!userCanAddComment)
            {
                _logger.LogError($"Forbidden: UpdateCommentAsync - User:{0} does not have access to group:{1}", userId, slug);
                throw new ForbiddenException($"Forbidden: User does not have access to this group");
            }

            var userCanEditComment = await _permissionsService.UserCanPerformActionAsync(userId, slug, EditCommentRole, cancellationToken);

            var databaseCommentDto = await _commentCommand.GetCommentAsync(commentId, cancellationToken);

            if (databaseCommentDto.CreatedById != userId && !userCanEditComment)
            {
                _logger.LogError($"Forbidden: UpdateCommentAsync - User:{0} does not have permission to edit comment:{1}", userId, commentId);
                throw new ForbiddenException("Forbidden: User does not have permission to edit this comment");
            }

            if (!databaseCommentDto.RowVersion.SequenceEqual(rowVersion))
            {
                _logger.LogError($"Precondition Failed: UpdateCommentAsync - Comment:{0} has changed prior to submission ", commentId);
                throw new PreconditionFailedExeption("Precondition Failed: Comment has changed prior to submission");
            }

            var commentDto = new CommentDto()
            {
                EntityId      = databaseCommentDto.Id,
                Content       = comment.Content,
                ModifiedBy    = userId,
                ModifiedAtUTC = now,
            };

            var validator        = new CommentValidator();
            var validationResult = await validator.ValidateAsync(commentDto, cancellationToken);

            if (validationResult.Errors.Count > 0)
            {
                throw new ValidationException(validationResult);
            }

            await _commentCommand.UpdateCommentAsync(commentDto, rowVersion, cancellationToken);
        }
Exemple #26
0
        /// <summary>
        /// Method to validate model
        /// </summary>
        /// <returns>Returns the result of validation</returns>
        protected override FluentValidation.Results.ValidationResult Validate()
        {
            var validator = new CommentValidator();

            return(validator.Validate(this));
        }