Esempio n. 1
0
        public async Task <IActionResult> Update(Guid id, UpdatePostInput model)
        {
            if (ModelState.IsValid)
            {
                if (id != model.Id)
                {
                    ModelState.AddModelError(string.Empty, "Forma müdahele etme!");
                }
                else
                {
                    model.ModifiedById = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                    model.ModifiedBy   = User.FindFirst(ClaimTypes.Name).Value;

                    var updatePost = await _postService.Update(model);

                    if (updatePost.Succeeded)
                    {
                        return(RedirectToAction("Details", new { id = model.Id }));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Bir hata olustu:\n" + updatePost.ErrorMessage);
                    }
                }
            }
            var categoryList = await _categoryService.GetAll();

            ViewBag.CategoryDDL = categoryList.Result.Select(c => new SelectListItem
            {
                Selected = false,
                Value    = c.Id.ToString(),
                Text     = c.Name
            }).ToList();
            return(View(model));
        }
        public async Task <ApplicationResult <PostDto> > Update(UpdatePostInput input)
        {
            try
            {
                var getExistPost = await _context.Posts.FindAsync(input.Id);

                // hata var mi kontrol ediyoruz varsa demekki boyle bir post yok
                if (getExistPost == null)
                {
                    return(new ApplicationResult <PostDto>
                    {
                        Result = new PostDto(),
                        Succeeded = false,
                        ErrorMessage = "Böyle bir Post bulunamadı"
                    });
                }
                // useri al
                // var user = await _userManager.FindByIdAsync(input.CreatedById);
                // getExistPost.ModifiedBy = user.UserName;
                _mapper.Map(input, getExistPost);
                _context.Update(getExistPost);
                await _context.SaveChangesAsync();

                return(await Get(getExistPost.Id));
            }
            catch (Exception ex)
            {
                return(new ApplicationResult <PostDto>
                {
                    Result = new PostDto(),
                    Succeeded = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Esempio n. 3
0
        public async Task <UpdatePostPayload> UpdatePostAsync(UpdatePostInput input,
                                                              [ScopedService] ApiContext context,
                                                              [Service] ITopicEventSender eventSender)
        {
            Post post = await context.Posts.Include(p => p.Tags)
                        .SingleOrDefaultAsync(p => p.Id == input.Id)
                        .ConfigureAwait(false);

            if (post == null)
            {
                return(new UpdatePostPayload(new ApiError("POST_NOT_FOUND", "Post not found.")));
            }

            Post postWithTitle = await context.Posts.FirstOrDefaultAsync(p => p.Title == input.Title)
                                 .ConfigureAwait(false);

            if (postWithTitle != null && postWithTitle.Id != post.Id)
            {
                return(new UpdatePostPayload(new ApiError("POST_WITH_TITLE_EXISTS", "A post with that title already exists.")));
            }

            await ApplyUpdatedValuesToPost(post, input, context).ConfigureAwait(false);

            await context.SaveChangesAsync()
            .ConfigureAwait(false);

            await eventSender.SendAsync(nameof(PostSubscriptions.OnPostUpdatedAsync), post.Id)
            .ConfigureAwait(false);

            return(new UpdatePostPayload(post));
        }
        public async Task UpdatePost()
        {
            string postDbName  = "postDbUpdatePost";
            var    optionsPost = new DbContextOptionsBuilder <ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options;
            MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new AutoMapperProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();
            List <CreatePostInput> fakePostList = new List <CreatePostInput>
            {
                new CreatePostInput
                {
                    Content     = "Lorem Ipsum Dolor Sit Amet",
                    Title       = "Lorem Ipsum Dolor",
                    UrlName     = "lorem-ipsum-dolor",
                    CreatedBy   = "Tester1",
                    CreatedById = Guid.NewGuid().ToString()
                }
            };
            ApplicationResult <PostDto>         resultUpdatePost = new ApplicationResult <PostDto>();
            List <ApplicationResult <PostDto> > resultList       = await CreatePost(fakePostList, postDbName);

            using (var inMemoryContext = new ApplicationUserDbContext(optionsPost))
            {
                await AssertCreatedPostAsync(inMemoryContext, resultList, fakePostList);

                var item = await inMemoryContext.Posts.FirstOrDefaultAsync();

                PostService     service    = new PostService(inMemoryContext, mapper);
                UpdatePostInput fakeUpdate = new UpdatePostInput
                {
                    Id           = item.Id,
                    CreatedById  = item.CreatedById,
                    ModifiedById = Guid.NewGuid().ToString(),
                    ModifiedBy   = "Tester1 Updated",
                    Content      = "Lorem Ipsum Dolor Sit Amet Updated",
                    Title        = "Lorem Ipsum Dolor Updated",
                    UrlName      = "lorem-ipsum-dolor-updated"
                };
                resultUpdatePost = await service.Update(fakeUpdate);
            }

            using (var inMemoryContext = new ApplicationUserDbContext(optionsPost))
            {
                Assert.Equal(1, await inMemoryContext.Posts.CountAsync());
                Assert.True(resultUpdatePost.Succeeded);
                Assert.NotNull(resultUpdatePost.Result);
                var item = await inMemoryContext.Posts.FirstAsync();

                Assert.Equal("Tester1", item.CreatedBy);
                Assert.Equal("Tester1 Updated", item.ModifiedBy);
                Assert.Equal("Lorem Ipsum Dolor Sit Amet Updated", item.Content);
                Assert.Equal("Lorem Ipsum Dolor Updated", item.Title);
                Assert.Equal("lorem-ipsum-dolor-updated", item.UrlName);
                Assert.Equal(resultUpdatePost.Result.ModifiedById, item.ModifiedById);
            }
        }
Esempio n. 5
0
        public async Task Update(UpdatePostInput input)
        {
            // Determine user is the author of the post or not
            (var res, var post) = await IsOwner(AbpSession.UserId, input.Id);

            if (!res)
            {
                return;
            }

            ObjectMapper.Map(input, post);
            await _postManager.UpdateAsync(post);
        }
        public async Task Update(UpdatePostInput input)
        {
            var entity = await _manager.GetById(input.Id);

            if (entity == null)
            {
                throw new UserFriendlyException($"Post {input.Id} not found");
            }

            if (entity.UserId != AbpSession.UserId)
            {
                throw new UserFriendlyException("Access denied");
            }

            entity.Update(input.Name, input.Content);

            await _manager.Update(entity);
        }
Esempio n. 7
0
        /// <summary>
        /// Applies the updated values to post.
        /// </summary>
        /// <param name="post">The post.</param>
        /// <param name="input">The input.</param>
        /// <param name="context">The context.</param>
        private static async Task ApplyUpdatedValuesToPost(Post post, UpdatePostInput input, ApiContext context)
        {
            post.Title    = input.Title;
            post.Content  = input.Content;
            post.Modified = DateTimeOffset.UtcNow;

            List <int> updatedTagIds = input.Tags.ConvertAll(t => t.Id);

            post.Tags.RemoveAll(t => !updatedTagIds.Contains(t.Id));

            List <int> currentTagIds = post.Tags.ConvertAll(t => t.Id);

            List <Tag> tagsToAdd = await context.Tags.AsNoTracking()
                                   .Where(t => updatedTagIds.Contains(t.Id) && !currentTagIds.Contains(t.Id))
                                   .ToListAsync()
                                   .ConfigureAwait(false);

            post.Tags.AddRange(tagsToAdd);
        }
Esempio n. 8
0
        public async Task <BlogResponse> UpdatePostAsync(string id, UpdatePostInput input)
        {
            var response = new BlogResponse();

            var post = await _posts.FindAsync(id.ToObjectId());

            if (post is null)
            {
                response.IsFailed($"The post id not exists.");
                return(response);
            }

            var tags = await _tags.GetListAsync();

            var newTags = input.Tags.Where(item => !tags.Any(x => x.Name == item)).Select(x => new Tag
            {
                Name  = x,
                Alias = x.ToLower()
            });

            if (newTags.Any())
            {
                await _tags.InsertManyAsync(newTags);
            }

            post.Title    = input.Title;
            post.Author   = input.Author;
            post.Url      = input.Url.GeneratePostUrl(input.CreatedAt.ToDateTime());
            post.Markdown = input.Markdown;
            post.Category = await _categories.GetAsync(input.CategoryId.ToObjectId());

            post.Tags = await _tags.GetListAsync(input.Tags);

            post.CreatedAt = input.CreatedAt.ToDateTime();
            await _posts.UpdateAsync(post);

            return(response);
        }
Esempio n. 9
0
        public async Task <IActionResult> Update(Guid id)
        {
            var post = await _postService.Get(id);

            var categoryList = await _categoryService.GetAll();

            ViewBag.CategoryDDL = categoryList.Result.Select(c => new SelectListItem
            {
                Selected = false,
                Value    = c.Id.ToString(),
                Text     = c.Name
            }).ToList();
            UpdatePostInput model = new UpdatePostInput
            {
                Id          = post.Result.Id,
                CategoryId  = post.Result.CategoryId,
                Content     = post.Result.Content,
                Title       = post.Result.Title,
                UrlName     = post.Result.UrlName,
                CreatedById = post.Result.CreatedById
            };

            return(View(model));
        }
Esempio n. 10
0
 public ActionResult Update(UpdatePostInput input)
 {
     this.Service.Update(input);
     return(this.UpdateSuccessMsg());
 }
Esempio n. 11
0
        public async Task <ActionResult <ApplicationResult <PostDto> > > Put(Guid id, [FromBody] UpdatePostInput input)
        {
            if (ModelState.IsValid)
            {
                var getService = await _postService.Get(id);

                input.CreatedById = getService.Result.CreatedById;
                input.CreatedBy   = getService.Result.CreatedBy;

                input.Id           = getService.Result.Id;
                input.ModifiedById = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                input.ModifiedBy   = User.FindFirst(ClaimTypes.Name).Value;

                var updateService = await _postService.Update(input);

                if (updateService.Succeeded)
                {
                    return(Ok(updateService));
                }
                ModelState.AddModelError("Error", updateService.ErrorMessage);
            }
            return(BadRequest(new ApplicationResult <PostDto>
            {
                Result = new PostDto(),
                Succeeded = false,
                ErrorMessage = string.Join(", ", ModelState.Values)
            }));
        }