public async void CreatePost_FailsOnSave_ReturnsException()
        {
            // Arrange
            int userId          = 2;
            var userFromRepo    = GetFakeUserList().SingleOrDefault(x => x.Id == userId);
            var postForCreation = new PostForCreationDto
            {
                NameOfDish  = "Katsu curry",
                Description = "chicken and rice",
                Ingredients = "chicken, rice",
                Method      = "fry chicken, boil rice",
                PrepTime    = "20 min",
                CookingTime = "20 min",
                Feeds       = "3",
                Cuisine     = "Japanese"
            };

            _repoMock.Setup(x => x.GetUser(userId)).ReturnsAsync(userFromRepo);
            _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(false);

            // Act
            Exception ex = await Assert.ThrowsAsync <Exception>(() => _postsController.CreatePost(userId, postForCreation));

            // Assert
            Assert.Equal("Creating the post failed on save", ex.Message);
        }
        public void CreatePost_UserAuthorized_ReturnsPost()
        {
            // Arrange
            int userId       = 2;
            var userFromRepo = GetFakeUserList().SingleOrDefault(x => x.Id == userId);

            var postForCreation = new PostForCreationDto
            {
                NameOfDish  = "Katsu curry",
                Description = "chicken and rice",
                Ingredients = "chicken, rice",
                Method      = "fry chicken, boil rice",
                PrepTime    = "20 min",
                CookingTime = "20 min",
                Feeds       = "3",
                Cuisine     = "Japanese",
                UserId      = userId
            };

            _repoMock.Setup(x => x.GetUser(userId)).ReturnsAsync(userFromRepo);
            _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true);

            //Act
            var result = _postsController.CreatePost(userId, postForCreation)
                         .Result;

            // Assert
            var okResult    = Assert.IsType <CreatedAtRouteResult>(result);
            var returnValue = Assert.IsType <PostsForDetailedDto>(okResult.Value);
        }
Example #3
0
        public async Task <IActionResult> CreatePost(int profileId, PostForCreationDto PostForCreation)
        {
            if (profileId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            PostForCreation.ProfileId = profileId;

            var profile = await _repo.getProfile(profileId);

            if (profile == null)
            {
                return(BadRequest("Could Not Find Profile"));
            }

            var post = _mapper.Map <Posts>(PostForCreation);

            _repo.Add(post);

            if (await _repo.SaveAll())
            {
                var postToReturn = _mapper.Map <PostToReturnDto>(post);
                return(Ok(postToReturn));
            }

            return(BadRequest("Failed to upload Post"));
        }
Example #4
0
        public ActionResult <PostDto> CreatePostForAuthor(Guid authorId, PostForCreationDto post)
        {
            if (!_discussionWebRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var postModel = _mapper.Map <Data.Models.Post>(post);

            return(AddPostToRepository(ref authorId, ref postModel));
        }
        public async Task <IActionResult> CreatePost([FromBody] PostForCreationDto post)
        {
            var postEntity = _mapper.Map <Post>(post);
            var userFromDb = await _userManager.GetUserAsync(this.User);

            postEntity.CreatedById = userFromDb.Id;
            _repository.Post.CreatePost(postEntity);
            await _repository.SaveAsync();

            var postToReturn = _mapper.Map <PostDto>(postEntity);

            return(Ok(postToReturn));
        }
Example #6
0
        public async Task <IActionResult> CreatePost([FromForm] PostForCreationDto newPostDto)
        {
            if (newPostDto.Files != null && !Services.ImageService.ValidateImages(newPostDto.Files))
            {
                return(Conflict(new { error = "invalid file format" }));
            }
            Post post = new Post {
                Text      = newPostDto.Text,
                Title     = newPostDto.Title,
                CreatedAt = DateTime.UtcNow
            };
            var addedPostId = await _rep.AddPostAsync(post, newPostDto.Tags, newPostDto.Username, newPostDto.Files);

            return(Ok(addedPostId));
        }
        public async Task <IActionResult> CreatePost(int userId, PostForCreationDto postForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            postForCreationDto.UserId = userId;
            var post = _mapper.Map <Post>(postForCreationDto);

            _repo.Add(post);
            if (await _repo.SaveAll())
            {
                var postToReturn = _mapper.Map <PostToReturnDto>(post);
                return(CreatedAtRoute("GetPost", new { id = post.Id }, postToReturn));
            }
            throw new Exception("Field To Create Post");
        }
Example #8
0
        public async Task <IActionResult> CreatePost(PostForCreationDto postForCreationDto)
        {
            var post = _mapper.Map <Post>(postForCreationDto);


            _repo.Add(post);

            if (await _repo.SaveAll())
            {
                var postToReturn = _mapper.Map <PostToReturnDto>(post);


                return(CreatedAtRoute("GetPost", new { id = post.Id }, postToReturn));
            }

            return(BadRequest("Failed to save post"));
        }
Example #9
0
        public IActionResult Post([FromBody] PostForCreationDto newPost)
        {
            if (newPost.Content.Contains("bugger"))
            {
                return(BadRequest(new ErrorDto {
                    Reason = "Unacceptable language"
                }));
            }

            var post = new PostDto
            {
                Id       = 3,
                Content  = newPost.Content,
                PostedAt = DateTime.UtcNow
            };

            return(CreatedAtRoute("GetPost", new { id = post.Id }, post));
        }
Example #10
0
        public async Task <IActionResult> AddPost([FromForm] PostForCreationDto postForCreationDto)
        {
            var userId = int.Parse(this.User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (userId != postForCreationDto.UserId)
            {
                return(Unauthorized());
            }

            var file = postForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream)
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            var post = new Post()
            {
                UserId         = postForCreationDto.UserId,
                DateOfCreation = DateTime.Now,
                Text           = postForCreationDto.Text,
                Photo          = uploadResult.Url.ToString()
            };

            _repo.Add(post);

            if (await _repo.SaveAll())
            {
                return(Ok());
            }

            return(BadRequest("Could not add post"));
        }
        public void CreatePost_UnauthorizedUserClaims_ReturnsUnauthorized()
        {
            // Arrange
            int userId          = 1;
            var postForCreation = new PostForCreationDto
            {
                NameOfDish  = "Katsu curry",
                Description = "chicken and rice",
                Ingredients = "chicken, rice",
                Method      = "fry chicken, boil rice",
                PrepTime    = "20 min",
                CookingTime = "20 min",
                Feeds       = "3",
                Cuisine     = "Japanese"
            };

            // Act
            var result = _postsController.CreatePost(userId, postForCreation)
                         .Result;

            // Assert
            Assert.IsType <UnauthorizedResult>(result);
        }
        public async Task <IActionResult> CreatePost(int userId, PostForCreationDto postForCreationDto)
        {
            // Validate id of logged in user == userId
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _recipeRepo.GetUser(userId);

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

            post.Author = userFromRepo.UserName;

            userFromRepo.Posts.Add(post);

            if (await _recipeRepo.SaveAll())
            {
                var postToReturn = _mapper.Map <PostsForDetailedDto>(post);
                return(CreatedAtRoute("GetPost", new { userId = userId, id = post.PostId }, postToReturn));
            }

            throw new Exception("Creating the post failed on save");
        }
Example #13
0
        public async Task <IActionResult> CreatePost([FromBody] PostForCreationDto post)
        {
            if (post == null)
            {
                _logger.LogError("PostForCreationDto object sent from client is null.");
                return(BadRequest("PostForCreationDto object is null"));
            }

            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid model state for the PostForCreationDto object");
                return(UnprocessableEntity(ModelState));
            }

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

            _context.Posts.CreatePost(postEntity);
            await _context.SaveAsync();

            var postToReturn = _mapper.Map <PostDto>(postEntity);

            return(CreatedAtRoute("PostById", new { id = postToReturn.Id },
                                  postToReturn));
        }
Example #14
0
        public async Task <IActionResult> CreatePost([FromForm] PostForCreationDto postForCreationDto)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var userFromRepo = await _repo.GetUser(userId);

            var postToCreate = new Post();

            postToCreate.Title       = postForCreationDto.Title;
            postToCreate.Description = postForCreationDto.Description;
            postToCreate.Category    = postForCreationDto.Category;
            postToCreate.Links       = postForCreationDto.Links;
            postToCreate.Created     = postForCreationDto.Created;
            postToCreate.Updated     = postForCreationDto.Updated;
            // var postToCreate = _mapper.Map<Post>(postForCreationDto);

            userFromRepo.Posts.Add(postToCreate);
            // _repo.Add<Post>(postToCreate);
            await _repo.SaveAll();

            var postFromRepo = await _repo.GetPost(postToCreate.Id);

            var tags = postForCreationDto.Tags.Split(",");

            for (int i = 0; i < tags.Length; i++)
            {
                var tag = await _repo.GetTag(tags[i]);

                if (tag == null)
                {
                    tag = new Tag {
                        Value = tags[i]
                    };

                    _repo.Add(tag);
                    await _repo.SaveAll();

                    // tag = await _repo.GetTag(tags[i]);
                }

                var postTag = new PostTag {
                    PostId = postFromRepo.Id,
                    TagId  = tag.Id
                };

                postFromRepo.Tags.Add(postTag);
            }

            var files = new IFormFile[] {
                postForCreationDto.Image1,
                postForCreationDto.Image2,
                postForCreationDto.Image3,
                postForCreationDto.Image4,
                postForCreationDto.Image5
            };

            for (int i = 0; i < files.Length; i++)
            {
                var file = files[i];
                if (file == null || file.Length <= 0)
                {
                    continue;
                }
                var uploadResult = new ImageUploadResult();

                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }

                var postImage = new PostImage();
                postImage.DateAdded = DateTime.Now;
                postImage.Url       = uploadResult.Uri.ToString();
                postImage.PublicId  = uploadResult.PublicId;

                // _repo.Add<PostImage>(postImageToCreate);
                if (i == postForCreationDto.MainImage)
                {
                    postImage.IsMain = true;
                }
                postFromRepo.PostImages.Add(postImage);
            }


            // if(userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            //     return Unauthorized();

            // var userFromRepo = await _repo.GetUser(userId);

            // var file = postForCreationDto.Image1;

            // var uploadResult = new ImageUploadResult();

            // if(file.Length > 0){
            //     using (var stream = file.OpenReadStream())
            //     {
            //         var uploadParams = new ImageUploadParams()
            //         {
            //             File = new FileDescription(file.Name, stream),
            //             Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
            //         };

            //         uploadResult = _cloudinary.Upload(uploadParams);
            //     }
            // }

            // postForCreationDto.Url = uploadResult.Uri.ToString();
            // postForCreationDto.PublicId = uploadResult.PublicId;

            // var postImage = _mapper.Map<PostImage>(postImageForCreationDto);

            // if (!userFromRepo.Photos.Any(u=>u.IsMain))
            //     photo.IsMain = true;
            // postImage.PostId = 0;

            // userFromRepo.Photos.Add(photo);
            // _repo.Add<PostImage>(postImage);

            if (await _repo.SaveAll())
            {
                var postToReturn = _mapper.Map <PostForDetailsDto>(postToCreate);
                return(CreatedAtRoute("GetPost", new { controller = "Posts", id = postToCreate.Id }, postToReturn));
            }

            return(BadRequest("Failed to create post."));
        }