Example #1
0
        public async Task Create_ValidModel_SuccessfullyAdded()
        {
            var post   = GetTestModel();
            var result = await _service.Create(post);

            _mockSet.Verify(m => m.Add(It.IsAny <Post>()), Times.Once());
            _mockContext.Verify(m => m.SaveChangesAsync(), Times.Once());
            Assert.AreEqual(post.Title, result.Title);
            Assert.AreEqual(post.Text, result.Text);
        }
        public ActionResult <Post> Create(Post post)
        {
            post.date = DateTime.Now.ToString("o", CultureInfo.InvariantCulture);
            _postService.Create(post);

            return(CreatedAtRoute("GetPost", new { id = post.id.ToString() }, post));
        }
Example #3
0
        public async Task <IActionResult> Create(CreateInputModel input)
        {
            Status result = await _postService.Create(input.Title, input.Description,
                                                      DateTime.UtcNow, input.AuthorId,
                                                      input.AuthorName);

            if (result == Status.Ok)
            {
                return(Ok(new Response
                {
                    Status = result,
                    Error = ""
                }));
            }
            else if (result == Status.InvalidData)
            {
                return(BadRequest(new Response
                {
                    Status = result,
                    Error = ""
                }));
            }
            else
            {
                return(StatusCode(500, (new Response
                {
                    Status = result,
                    Error = ""
                })));
            }
        }
 public async Task <IActionResult> CreatePost(CreatePostViewModel createPostViewModel)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images", createPostViewModel.FileUrl.FileName);
             using (var stream = new FileStream(path, FileMode.Create))
             {
                 await createPostViewModel.FileUrl.CopyToAsync(stream);
             }
             Post post = new Post()
             {
                 UserId       = HttpContext.Session.GetString("UserId"),
                 FileUrl      = "/Images/" + Path.GetFileName(path),
                 Description  = htmlEncoder.Encode(createPostViewModel.Description),
                 CreationDate = DateTime.Now
             };
             postService.Create(post);
         }
         return(RedirectToAction(nameof(Details), new { id = HttpContext.Session.GetString("UserId") }));
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.Message);
         return(View("Error", new ErrorViewModel()));
     }
 }
        public async Task ReturnNull_WhenCreatePostFailed()
        {
            // Arrange
            var post = new PostData.Builder()
            {
                Title          = "My title",
                Body           = "My body",
                UserIdentifier = 100,
            };

            var mockedPostEndpoint = new Mock <IPostEndpoint>();

            mockedPostEndpoint
            .Setup(endpoint => endpoint.Create(It.IsAny <CancellationToken>(), post))
            .ReturnsAsync(default(PostData));

            var sut = new PostService(mockedPostEndpoint.Object);

            // Act
            var result = await sut.Create(CancellationToken.None, post);

            // Assert
            result
            .Should().BeNull();
        }
Example #6
0
 public ActionResult CreateAction(Post model)
 {
     model.CreatedBy = Convert.ToInt64(Session["UserId"]);
     if (ModelState.IsValid)
     {
         try
         {
             var action = postService.Create(model);
             if (action)
             {
                 return(Redirect("/admin/post/index"));
             }
             else
             {
                 ModelState.AddModelError("", "Thêm thất bại");
             }
         }
         catch
         {
             ModelState.AddModelError("", "Thêm thất bại");
         }
     }
     else
     {
         ModelState.AddModelError("", "Thêm thất bại");
     }
     return(View("CreateHandle"));
 }
        // verileri kayit ederken db ayarlarinin ayni dbname icerisinde olduguna dikkat edin, eger db nameler farkliysa test verileri farkli veri tabanlarina kayit olur. tum test metotlarinda(Fact'lerde) ayri dbName'ler verilmesinin sebebi budur.
        public async Task <List <ApplicationResult <PostDto> > > CreatePost(List <CreatePostInput> fakePostList, string postDbName)
        {
            var options = new DbContextOptionsBuilder <ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options;
            MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new AutoMapperProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();
            ApplicationResult <CategoryDto> result = new ApplicationResult <CategoryDto>();

            using (var inMemoryContext = new ApplicationUserDbContext(options))
            {
                CategoryServiceShould categoryShould = new CategoryServiceShould();
                result = await categoryShould.CreateCategory(inMemoryContext, mapper);

                await categoryShould.AssertCreatedCategory(inMemoryContext, result);
            }

            List <ApplicationResult <PostDto> > createdPostResulList = new List <ApplicationResult <PostDto> >();

            using (var inMemoryContext = new ApplicationUserDbContext(options))
            {
                var service = new PostService(inMemoryContext, mapper);
                foreach (var item in fakePostList)
                {
                    item.CategoryId = result.Result.Id;
                    createdPostResulList.Add(await service.Create(item));
                }
            }
            return(createdPostResulList);
        }
Example #8
0
 public ActionResult CreatePost(PostInfo post, int user)
 {
     post.AuthorId = studentService.GetById(user).Id;
     postService.Create(post);
     TempData["post"] = postService.GetAll().Last().Id;
     return(RedirectToAction("CreateTag", "Tag", new { user = post.AuthorId, post = TempData["post"] }));
 }
Example #9
0
        public void Articles_Service_Post_Create_Test()
        {
            Mock <IPostRepository> rep = new Mock <IPostRepository>();

            rep.Setup(a => a.GetNextId()).Returns(1);
            AuthorRefrence author = new AuthorRefrence(lastName: "test",
                                                       name: "test",
                                                       userName: "******"
                                                       );

            author.Id = 1;

            Category cat = new Category(name: "test", slug: "test", isParent: true, lineAge: "");

            cat.Id = 1;

            var model = new Post(title: "Test", sendDate: DateTime.Now,
                                 publishedDate: null, visitCount: 0, content: "test", description: "test", postImage: "test",
                                 slug: "test",
                                 authorId: 1, tagId: 1, categoryId: 1, author: author, category: cat)
            {
                Id = rep.Object.GetNextId()
            };

            rep.Setup(a => a.Create(model)).Returns(EntityAction.Added);



            IPostService service = new PostService(rep.Object);

            var result = service.Create(model);


            Assert.AreEqual(result, EntityAction.Added);
        }
Example #10
0
        public async void Post([FromBody] PostCreateViewModel model)
        {
            model.User = await _manager.GetUserAsync(User);

            //model.User = await _manager.FindByEmailAsync("*****@*****.**");
            _postService.Create(model);
        }
 public IActionResult Post([FromBody] PostSendViewModel post)
 {
     if (ModelState.IsValid)
     {
         _postService.Create(post);
         return(Ok(post));
     }
     return(BadRequest(ModelState));
 }
Example #12
0
        public async Task Create_UserNotAuthenticated_ReturnsNull()
        {
            A.CallTo(() => User.Exists()).Returns(false);
            A.CallTo(() => ForumService.Read(1)).Returns(new Forum());

            var post = await PostService.Create(1, new CreatePost());

            Assert.Null(post);
        }
 public ActionResult Create(Post post)
 {
     if (ModelState.IsValid)
     {
         postService.Create(post);
         return(Redirect("/Profile/Index"));
     }
     return(View(post));
 }
Example #14
0
        public ActionResult Create(int idTopic, post post)
        {
            post.user     = CurrentUser.get();
            post.topic    = t.FindById(idTopic);
            post.postDate = DateTime.Now;
            p.Create(post);
            p.Commit();

            return(RedirectToAction("Index", new { idTopic = post.idTopic }));
        }
Example #15
0
 public ActionResult Create(Post post)
 {
     if (ModelState.IsValid)
     {
         post.DateCreated = DateTime.Now;
         postService.Create(post);
         return(RedirectToAction(nameof(Index)));
     }
     return(View(post));
 }
Example #16
0
        public async Task <IActionResult> CreateOrUpdate(PostInputModel model, int?id)
        {
            if (!ModelState.IsValid)
            {
                return(View("Edit", model));
            }

            Post post;
            var  tagList = await _tagService.List();

            if (id == null)
            {
                // Create
                post          = _mapper.Map <Post>(model);
                post.AuthorId = _userManager.GetUserId(User);
                post.TagPosts = model.GetTagPosts(tagList);
                if (string.IsNullOrWhiteSpace(post.Excerpt))
                {
                    var lineBreak = post.Content.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                    if (lineBreak < 0)
                    {
                        lineBreak = post.Content.Length;
                    }
                    var length = Math.Min(lineBreak, 500);
                    var sub    = post.Content.Substring(0, length);
                    post.Excerpt = Regex.Replace(sub, "<[^>]*(>|$)", "");
                }

                await _postService.Create(post);
            }
            else
            {
                // Update
                post = await _postService.GetById(id.Value);

                if (post.IsDraft)
                {
                    post.CreatedTime  = DateTime.UtcNow;
                    post.ModifiedTime = null;
                }
                else
                {
                    post.ModifiedTime = DateTime.UtcNow;
                }

                _mapper.Map(model, post);
                post.TagPosts = model.GetTagPosts(tagList);

                await _postService.Update(post);
            }

            return(RedirectToAction(nameof(Article), new { post.Slug }));
        }
        public ActionResult <Post> Create(Post post, string userId)
        {
            var user = _userService.GetForUser(userId);

            user.Posts.Add(post.PostId);

            _userService.Update(user.Id, user);

            _postService.Create(post);

            return(post);
        }
Example #18
0
        //[ValidateAntiForgeryToken]
        public ActionResult <Post> Create(Post post)
        {
            //post.Created = post.LastUpdated = DateTime.Now;
            //post.UserId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
            //post.UserName = User.Identity.Name;

            if (ModelState.IsValid)
            {
                _postSvc.Create(post);
            }
            return(Ok(post));
        }
Example #19
0
        public async Task CreatePost()
        {
            var options = new DbContextOptionsBuilder <ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: "Test_PostCreate").Options;
            MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new AutoMapperProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();
            ApplicationResult <CategoryDto> resultCreateCategory = new ApplicationResult <CategoryDto>();

            // create category
            using (var inMemoryContext = new ApplicationUserDbContext(options))
            {
                CategoryServiceShould categoryShould = new CategoryServiceShould();
                resultCreateCategory = await categoryShould.CreateCategory(inMemoryContext, mapper);
            }
            // check create category
            ApplicationResult <PostDto> resultPost = new ApplicationResult <PostDto>();

            using (var inMemoryContext = new ApplicationUserDbContext(options))
            {
                CategoryServiceShould categoryShould = new CategoryServiceShould();
                await categoryShould.AssertCreatedCategory(inMemoryContext, resultCreateCategory);

                // create post
                var             service  = new PostService(inMemoryContext, mapper);
                CreatePostInput fakePost = new CreatePostInput
                {
                    CategoryId  = resultCreateCategory.Result.Id,
                    Content     = "Lorem Ipsum Dolor Sit Amet",
                    Title       = "Lorem Ipsum Dolor",
                    UrlName     = "lorem-ipsum-dolor",
                    CreatedBy   = "Tester1",
                    CreatedById = Guid.NewGuid().ToString()
                };
                resultPost = await service.Create(fakePost);
            }
            // check post create service
            using (var inMemoryContext = new ApplicationUserDbContext(options))
            {
                Assert.True(resultPost.Succeeded);
                Assert.NotNull(resultPost.Result);
                Assert.Equal(1, await inMemoryContext.Posts.CountAsync());
                var item = await inMemoryContext.Posts.FirstAsync();

                Assert.Equal("Tester1", item.CreatedBy);
                Assert.Equal("Lorem Ipsum Dolor", item.Title);
                Assert.Equal("lorem-ipsum-dolor", item.UrlName);
                Assert.Equal("Lorem Ipsum Dolor Sit Amet", item.Content);
                Assert.Equal(resultCreateCategory.Result.Id, item.CategoryId);
            }
        }
Example #20
0
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var post = _mapper.Map <CodePassio_Core.Entities.Post>(Post);

            _postService.Create(post);

            return(RedirectToPage("./Index"));
        }
Example #21
0
        public async Task <ActionResult <ResultOutDto <Post> > > PostPost([FromBody] PostCreateInDto createOptions)
        {
            try
            {
                var post = await _postService.Create(createOptions);

                return(Ok(ResultOutDtoBuilder.Success(post)));
            }
            catch (NotExistedException e)
            {
                return(NotFound(ResultOutDtoBuilder.Fail <Post>(e, "Not exist")));
            }
        }
Example #22
0
        public ActionResult Create(PostViewModel model)
        {
            var service = new PostService();
            var result  = service.Create(model.Title, model.Content, model.BlogID);

            if (result == Logic.Enums.EPostCreationResult.NameAlreadyTaken)
            {
                CreateErrorMessage(l10n.Translation.NameNotUnique);
                return(View(model));
            }
            Db.Save();
            return(RedirectToAction("Index", "Blog", new { id = model.BlogID }));
        }
Example #23
0
        public ActionResult Create(Post post)
        {
            try
            {
                // TODO: Add insert logic here

                postService.Create(post);
                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
Example #24
0
        public async Task TryToCreatePostWhenUnauthorizedAndCheckIfThrowsCorrectException()
        {
            PostService service = await Helpers.GetService(false);

            AsyncTestDelegate testedDelegate = async() => await service.Create(new CreatePostDto
            {
                Title   = "Title of post no.2",
                Content = "Content of post no.2 #tag4 #tag5 \n #tag6"
            });

            var httpResponseException = Assert.ThrowsAsync <HttpErrorException>(testedDelegate);

            Assert.AreEqual(HttpStatusCode.Unauthorized, httpResponseException.HttpStatusCode);
            Assert.AreEqual("You cannot create post if you are not logged in", httpResponseException.Message);
        }
Example #25
0
        public async Task TryToCreatePostWithTitleTooLongAndCheckIfThrowsCorrectException()
        {
            PostService service = await Helpers.GetService(true);

            AsyncTestDelegate testedDelegate = async() => await service.Create(new CreatePostDto
            {
                Title   = new string('a', Consts.PostTitleLength + 1),
                Content = "Content of post no.2 #tag4 #tag5 \n #tag6"
            });

            var httpResponseException = Assert.ThrowsAsync <HttpErrorException>(testedDelegate);

            Assert.AreEqual(HttpStatusCode.BadRequest, httpResponseException.HttpStatusCode);
            Assert.AreEqual("Title is too long", httpResponseException.Message);
        }
Example #26
0
        public ActionResult Create(Post post)
        {
            if (ModelState.IsValid)
            {
                post.Url = BlogHelper.GenerateSlug(post.Title);
                //post.Author = post.Author; //User.Identity.Name;
                post.Date = DateTime.Now;

                postService.Create(post);

                return(RedirectToAction("Index"));
            }

            return(View());
        }
Example #27
0
        public void CreatePost(User author, string postType, string content, bool isPublic, List <Circle> circles)
        {
            var newPost = new Post
            {
                PostAuthor   = author.Id,
                PostType     = postType,
                PostContent  = content,
                CreationTime = DateTime.Now,
                IsPublic     = isPublic,
                Circles      = circles,
                Comments     = new List <Comment>()
            };

            _postService.Create(newPost);
        }
Example #28
0
        public async Task MustCallServiceOnCreate()
        {
            var request = new PostCreateViewModel()
            {
                Title = "Teste", Text = "<p>Teste</p>"
            };

            _mockRepository.Setup(x => x.Save(It.IsAny <Post>())).Returns(Task.FromResult(1));
            _mockRepository.Setup(x => x.GetPermalinks(It.IsAny <string>())).Returns(1);

            await _service.Create(request);

            _mockRepository.Verify(x => x.Save(It.IsAny <Post>()), Times.Once);
            _mockRepository.Verify(x => x.GetPermalinks(It.IsAny <string>()), Times.Once);
            _mockRepository.VerifyNoOtherCalls();
        }
        public IActionResult Create([FromBody] PostDTO postDTO)
        {
            var post = new Post()
            {
                Id        = postDTO.Id,
                Text      = postDTO.Text,
                ImageUrl  = postDTO.ImageUrl,
                CreatedAt = postDTO.CreatedAt,
                UpdatedAt = postDTO.CreatedAt,
                UserId    = GetUserIdFromToken()
            };

            _logger.LogInformation($"Creating Post {post}");
            post = _postService.Create(post);
            return(Ok(post));
        }
Example #30
0
        //[Route("")]
        public IHttpActionResult Create([FromBody] PostModel postModel)
        {
            if (postModel == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var id = _post.Create(postModel);

            return(CreatedAtRoute("GetSinglePost", new { id = id }, postModel));
        }