示例#1
0
        [TransactionScopeAspect]//+++
        public IResult Update(PostUpdateDto post)
        {
            /*
             * var post2 = new Post
             * {
             *  Content = post.Content,
             *  Title = post.Title,
             *  Updated = DateTime.Now,
             *  Id = post.Id,
             *  UserId = post.UserId
             * };*/

            _postDal.Update2(post);
            if (post.CategoryId != null)
            {
                string[] category = post.CategoryId.Split("*");
                foreach (var item in category)
                {
                    if (item != "")
                    {
                        var postCategory = new PostCategoryCreateDto {
                            PostId = post.Id, CategoryId = item
                        };
                        _postCategoryService.Add(postCategory);
                    }
                }
            }


            //var postCategory2 = new PostCategory {PostId=post.Id,CategoryId=post.CategoryId, Id=post.PostCategoryId };
            // _postCategoryService.Update(postCategory2);
            return(new SuccessResult(Messages.PostUpdated));
        }
示例#2
0
        public void Update(int postId, PostUpdateDto postDto)
        {
            Post post = GetById(postId);

            post.content = postDto.content;
            post.editted = DateTime.Now;
            /* context.Posts.Update(post); */
            /* context.Posts.SaveChanges(); */
        }
示例#3
0
        public async Task <IResult> UpdateAsync(PostUpdateDto postUpdateDto, string modifiedByName)
        {
            var oldPost = await UnitOfWork.Posts.GetAsync(p => p.Id == postUpdateDto.Id);

            var post = Mapper.Map <PostUpdateDto, Post>(postUpdateDto, oldPost);

            post.ModifiedByName = modifiedByName;
            await UnitOfWork.Posts.UpdateAsync(post);

            await UnitOfWork.SaveAsync();

            return(new Result(ResultStatus.Success, Messages.Post.Update(post.Title)));
        }
示例#4
0
        public ActionResult <PostReadDto> UpdatePost(int id, PostUpdateDto _PostUpdateDto)
        {
            var postItem = _repository.GetPostById(id);

            if (postItem == null)
            {
                return(NotFound());
            }
            _mapper.Map(_PostUpdateDto, postItem);
            _repository.UpdatePost(postItem);
            _repository.SaveChanges();
            return(Ok(_mapper.Map <PostReadDto>(postItem)));
        }
示例#5
0
        public IActionResult UpdatePost(int PostId, [FromBody] PostUpdateDto PostDto)
        {
            if (PostDto == null || PostId != PostDto.Id)
            {
                return(BadRequest(ModelState));
            }
            var PostObj = _mapper.Map <Post>(PostDto);

            if (!_psRepo.UpdatePost(PostObj))
            {
                ModelState.AddModelError("", $"Something went wrong when updating the record {PostObj.Id}");
                return(StatusCode(500, ModelState));
            }
            return(NoContent());
        }
示例#6
0
        public ActionResult <PostOutDto> Update(string id, [FromBody] PostUpdateDto postInDto)
        {
            if (!ModelState.IsValid || postInDto == null)
            {
                return(BadRequest(new Message("Post not valid or null")));
            }

            //Check if there exist a post with {id}
            var post = _postRepository.GetById(id);

            if (post == null)
            {
                return(NotFound(new Message("No such post with this id: " + id)));
            }

            //Check if post is being updated by its owner
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, post.OwnerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            if (!string.IsNullOrWhiteSpace(postInDto.Title))
            {
                post.Title = postInDto.Title;
            }

            if (!string.IsNullOrWhiteSpace(postInDto.Content))
            {
                post.Content = postInDto.Content;
            }

            if (!string.IsNullOrWhiteSpace(postInDto.CategoryId))
            {
                post.Content = postInDto.CategoryId;
            }

            //Save changes
            if (!_postRepository.Update(post))
            {
                return(BadRequest(new Message("Error when updating post")));
            }

            var postOutDto = _mapper.Map <PostOutDto>(post);

            return(postOutDto);
        }
示例#7
0
        public async Task <ActionResult> UpdatePost(int id, PostUpdateDto post)
        {
            var postModelFromRepo = await _repository.GetPostByIdAsync(id);

            if (postModelFromRepo == null)
            {
                return(NotFound());
            }

            _mapper.Map(post, postModelFromRepo);

            _repository.UpdatePost(postModelFromRepo);
            await _repository.SaveChangesAsync();

            return(NoContent());
        }
        public async Task <PostWithDetailDto> UpdateAsync(Guid id, PostUpdateDto input)
        {
            var post = await _postRepository.GetAsync(id);

            post.SetTitle(input.Title);
            post.Content     = input.Content;
            post.Description = input.Description;

            var tagList = SplitTags(input.Tags);

            await RemoveOldTags(tagList, post);
            await AddNewTags(tagList, post);

            var newPost = await _postRepository.UpdateAsync(post);

            return(ObjectMapper.Map <Post, PostWithDetailDto>(newPost));
        }
示例#9
0
        public ActionResult UpdatePost(int id, PostUpdateDto updateDto)
        {
            var post = _repository.GetBlogPostById(id);

            if (post == null)
            {
                return(NotFound());
            }

            _mapper.Map(updateDto, post);

            _repository.UpdatePost(post);

            _repository.savechanges();

            return(NoContent());
        }
示例#10
0
        public ActionResult UpdatePost(int id, PostUpdateDto postUpdateDto)
        {
            var postModelFromRepo = _repository.GetPostById(id);

            if (postModelFromRepo == null)
            {
                return(NotFound());
            }

            _mapper.Map(postUpdateDto, postModelFromRepo);

            _repository.UpdatePost(postModelFromRepo);

            _repository.SaveChanges();

            return(NoContent());
        }
示例#11
0
        public ActionResult <PostDto> UpdatePost(PostUpdateDto post, [FromHeader] int accountId, [FromHeader] string key)
        {
            if (!authService.Authorize(key))
            {
                return(StatusCode(StatusCodes.Status401Unauthorized, "The user is not authorized!"));
            }
            if (userMockRepository.GetAccountByUserAccountID(post.UserId) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "User with that id does not exist!"));
            }
            if (contentRepository.GetContentById(post.ContentId) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Content with that id does not exist!"));
            }

            if (post.UserId != accountId)
            {
                return(StatusCode(StatusCodes.Status403Forbidden, "Not allowed, user does not have permission for that action!"));
            }


            try
            {
                var oldPost = postRepository.GetPostById(post.PostId);
                if (oldPost == null)
                {
                    return(NotFound());
                }
                Post postEntity = mapper.Map <Post>(post);
                postEntity.DateOfPublication = oldPost.DateOfPublication;
                postEntity.ExpiryDate        = oldPost.ExpiryDate;

                mapper.Map(postEntity, oldPost);

                postRepository.SaveChanges();
                fakeLoggerRepository.Log(LogLevel.Information, contextAccessor.HttpContext.TraceIdentifier, "", "Post updated", null);

                return(Ok(mapper.Map <PostDto>(oldPost)));
            }
            catch (Exception)
            {
                fakeLoggerRepository.Log(LogLevel.Error, contextAccessor.HttpContext.TraceIdentifier, "", "Error with updating post", null);
                return(StatusCode(StatusCodes.Status500InternalServerError, "Update error"));
            }
        }
        public Post Update(PostUpdateDto postUpdateDto)
        {
            if (IsPostExist(postUpdateDto.PostId))
            {
                var post = new Post()
                {
                    CategoryId  = postUpdateDto.CategoryId,
                    UserId      = postUpdateDto.UserId,
                    PostId      = postUpdateDto.PostId,
                    Content     = postUpdateDto.Content,
                    PublishDate = DateTime.Now,
                    Title       = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(postUpdateDto.Title)
                };

                return(_postDal.Update(post));
            }
            throw new Exception("Bu id ye ait Post bulunamamıştır. Lütfen id bilgilerini kontrol ediniz");
        }
示例#13
0
        public async Task <ActionResult <Post> > PutPost(int id, PostUpdateDto dto)
        {
            Post post = await _context.Posts.FindAsync(id);

            if (post == null)
            {
                return(NotFound());
            }

            _mapper.Map(dto, post);

            _context.Entry(post).State = EntityState.Modified;

            await _context.SaveChangesAsync();

            await BroadcastPostUpdated(id);

            return(Ok());
        }
示例#14
0
        [HttpPost("update")]//++++
        public async Task <IActionResult> Update([FromForm] PostUpdateDto post)
        {
            //eğer resim değiştirirse image ve imagename propları dolu olmak zorunda
            if (post.Image != null && post.ImageName != null)                       //resim değiştirmek isterse bu işlemler yapılacak.
            {
                var resimler = Path.Combine(_environment.WebRootPath, "postImage"); //dizin bilgisi
                System.IO.File.Delete(resimler + "\\" + post.ImageName);
                post.ImageName = $"{ Guid.NewGuid()}.jpg";
                using (var fileStream = new FileStream(Path.Combine(resimler, post.ImageName), FileMode.Create))
                { await post.Image.CopyToAsync(fileStream); }
            }

            var result = _postService.Update(post);

            if (result.Success)
            {
                return(Ok(result.Message));
            }
            return(BadRequest(result.Message));
        }
示例#15
0
 public async Task <ActionResult> Update([FromForm] PostUpdateDto PostUpdateDto)
 {
     return(await HandleExceptions(async() =>
     {
         var role = User.Claims.FirstOrDefault(x => x.Type.Equals(ClaimsIdentity.DefaultRoleClaimType))?.Value;
         var userId = User.Claims.FirstOrDefault(x => x.Type.Equals(ClaimsIdentity.DefaultNameClaimType))?.Value;
         var authorId = await _postManager.GetPostAuthorIdAsync(PostUpdateDto.Id);
         if (role != "Admin" && Int32.Parse(userId) != authorId)
         {
             return Forbid("Access denied");
         }
         if (ModelState.IsValid)
         {
             var hostRoot = _hostServices.GetHostPath();
             await _postManager.UpdatePostAsync(PostUpdateDto, hostRoot);
             return Ok();
         }
         return BadRequest("Model state is not valid");
     }));
 }
示例#16
0
        public void Update2(PostUpdateDto postUpdateDto)
        {
            using (var context = new BlogDbContext())
            {
                var entity = context.Posts.SingleOrDefault(w => w.Id == postUpdateDto.Id);

                if (postUpdateDto.Title != null)
                {
                    entity.Title = postUpdateDto.Title;
                }

                if (postUpdateDto.Content != null)
                {
                    entity.Content = postUpdateDto.Content;
                }

                if (postUpdateDto.ImageName != null)
                {
                    entity.ImageName = postUpdateDto.ImageName;
                }

                if (postUpdateDto.Title != null)
                {
                    entity.Title = postUpdateDto.Title;
                }

                if (postUpdateDto.isActive != null)
                {
                    entity.IsActive = postUpdateDto.isActive;
                }

                if (postUpdateDto.isDeleted != null)
                {
                    entity.IsDeleted = postUpdateDto.isDeleted;
                }

                entity.Updated = DateTime.Now;
                context.SaveChanges();
            }
        }
示例#17
0
        public async Task <IActionResult> UpdatePost([FromRoute] Guid id,
                                                     [FromBody] PostUpdateDto postToUpdate)
        {
            //model state validation is not required due to the [ApiController] attribute automatically returning UnprocessableEntity (see startup.cs)
            //when model binding fails

            var postFromRepo = await _postRepository.GetPostAsync(id);

            if (postFromRepo == null)
            {
                return(NotFound());
            }

            //fetch the user id from the JWT via HttpContext. Then get the user from the repository. This is to ensure that an authorized user
            //is calling the API with a valid user id
            var user = await _userRepository.GetUserAsync(User.GetUserId());

            //check if the user is an administrator or owner of the object
            var isAdmin            = User?.IsAdministrator() ?? false;
            var userIsAdminOrOwner = isAdmin ? isAdmin : (user?.Id != postFromRepo.UserId ? false : true);

            if (!userIsAdminOrOwner)
            {
                //returning status code instead of Forbid() as forbid only works with authentication handlers
                return(StatusCode(403, new { Error = "You cannot modify other users submissions unless you are an administrator." }));
            }

            _mapper.Map(postToUpdate, postFromRepo);  //map fields from PostUpdateDto to Post that was fetched from repository
            _postRepository.UpdatePost(postFromRepo); //Call to empty method. This is just for information and is not required

            if (!await _postRepository.SaveChangesAsync())
            {
                throw new Exception($"Error updating Post {postFromRepo.Id} to the database");
            }

            return(NoContent());
        }
示例#18
0
        public async Task <IActionResult> EditPost(int id, PostUpdateDto postUpdateDto)
        {
            try
            {
                var postToUpdate = await _postService.GetPostById(id);

                if (postToUpdate == null)
                {
                    throw new ArgumentNullException("Invalid request");
                }
                else
                {
                    _mapper.Map(postUpdateDto, postToUpdate);
                    await _postService.UpdatePostInDatabase(postToUpdate);

                    return(NoContent());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
示例#19
0
 public Task <PostDto> UpdateAsync(PostUpdateDto updateDto)
 {
     throw new NotImplementedException();
 }
 public Task <PostWithDetailDto> UpdateAsync(Guid id, PostUpdateDto input)
 {
     return(_postAppService.UpdateAsync(id, input));
 }
 public void UpdatePost(PostUpdateDto postUpdateDto)
 {
     _postService.Update(postUpdateDto);
 }