コード例 #1
0
 public ActionResult Create(PostEditModelView postEditModel, int[] selectedTags)
 {
     if (selectedTags != null)
     {
         postEditModel.Post.Tags = Mapper.Map <IEnumerable <TagDTO>, List <TagModel> >(tagService.GetAll().Where(t => selectedTags.Contains(t.Id)).ToList());
         ModelState["Post.Tags"].Errors.Clear();
     }
     if (ModelState.IsValid)
     {
         try
         {
             var     postDto = Mapper.Map <PostModel, PostDTO>(postEditModel.Post);
             UserDTO userDto = userService.FindUserByLogin(User.Identity.Name);
             postDto.User = userDto;
             if (User.IsInRole(Role.Admin) || User.IsInRole(Role.Moderator))
             {
                 postDto.IsPublished = true;
             }
             else
             {
                 TempData["message"] = string.Format("Спасибо за публикацию! Ваш пост \"{0}\" был отправлен модератору.", postEditModel.Post.Title);
             }
             postService.AddPost(postDto);
             return(RedirectToAction("List"));
         }
         catch (ValidationException ex)
         {
             ModelState.AddModelError(ex.Property, ex.Message);
         }
     }
     postEditModel.Categories = GetCategories();
     postEditModel.Tags       = GetTags();
     return(View(postEditModel));
 }
コード例 #2
0
ファイル: RootController.cs プロジェクト: aleksans/TheBlog
        public ContentResult AddPost(Post post)
        {
            string json;

            ModelState.Clear();

            if (TryValidateModel(post))
            {
                _postService.AddPost(post);

                json = JsonConvert.SerializeObject(new
                {
                    id      = post.PostId,
                    success = true,
                    message = "Post added successfully"
                });
            }
            else
            {
                json = JsonConvert.SerializeObject(new
                {
                    id      = 0,
                    success = false,
                    message = "Failed to add the post"
                });
            }

            return(Content(json, "application/json"));
        }
コード例 #3
0
 public async Task <IActionResult> Create(PostViewModel post)
 {
     post.PostedTime = DateTime.Now.Date;
     post.AccountId  = (await _userManager.GetUserAsync(HttpContext.User)).Id;
     postService.AddPost(mapper.Map <PostDTO>(post));
     return(View("Details", post));
 }
コード例 #4
0
        public async Task <IActionResult> NewPost(NewPostViewModel model)
        {
            SetIsAuth();
            await postService.AddPost(Int32.Parse(Request.Cookies["user"]), model.Title, model.Preview, model.Text, model.Image);

            return(RedirectToAction("MyPage", "User"));
        }
コード例 #5
0
        public ActionResult Add(string postContent, string Id)
        {
            if (postContent is null)
            {
                throw new ArgumentNullException();
            }

            if (Id is null)
            {
                throw new ArgumentNullException();
            }

            if (ModelState.IsValid)
            {
                PostDTO postDTO = new PostDTO
                {
                    Content    = postContent,
                    PostDate   = DateTime.Now,
                    UserId     = GetUserId(),
                    UserPageId = Id
                };

                _postService.AddPost(postDTO);
            }

            return(RedirectToAction($"Index/{Id}", "Home"));
        }
コード例 #6
0
        public ActionResult NewPost(string blogId, string username, string password, IDictionary <string, object> post, bool publish)
        {
            if (string.IsNullOrEmpty(blogId))
            {
                throw new ArgumentException();
            }

            Blog blog = blogService.GetBlog(new BlogAddress(blogId));

            //TODO: (erikpo) Move into a model binder?
            PostInput postInput = new PostInput(blog.Name, post["title"] as string, post["description"] as string,
                                                post["mt_excerpt"] as string,
                                                (post["categories"] as object[]).OfType <string>() ??
                                                Enumerable.Empty <string>(),
                                                string.IsNullOrEmpty(post["mt_basename"] as string)
                                                    ? expressions.Slugify(post["title"] as string)
                                                    : post["mt_basename"] as string,
                                                publish ? DateTime.UtcNow : (DateTime?)null,
                                                blog.CommentingDisabled);

            ModelResult <Post> results = postService.AddPost(postInput, EntityState.Normal);

            if (results.IsValid)
            {
                return(new XmlRpcResult(results.Item.ID.ToString()));
            }

            return(new XmlRpcFaultResult(0, results.GetFirstException().Message));
        }
コード例 #7
0
        public virtual IActionResult Post([FromBody] PostModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new Post
                    {
                        Title           = model.Title,
                        Body            = model.Body,
                        BodyOverview    = model.BodyOverview,
                        MetaTitle       = model.MetaTitle,
                        MetaDescription = model.MetaDescription,
                        MetaKeywords    = model.MetaKeywords,
                        Tags            = model.Tags,
                        AllowComments   = model.AllowComments,
                        StartDateUtc    = model.StartDateUtc,
                        EndDateUtc      = model.EndDateUtc
                    };
                    _postService.AddPost(entity);

                    return(Ok());
                }

                return(new BadRequestResult());
            }
            catch (Exception ex)
            {
                base.LogError <PostsController>(ex);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
コード例 #8
0
        public string NewPost(string blogId, string username, string password, Post post, bool publish)
        {
            Oxite.Model.User user = getUser(username, password);

            Oxite.Model.Area area = areaService.GetArea(new Guid(blogId));

            Oxite.Model.Post newPost = new Oxite.Model.Post
            {
                Title     = post.title,
                Body      = post.description,
                Created   = post.dateCreated == default(DateTime) ? DateTime.Now : post.dateCreated,
                Slug      = string.IsNullOrEmpty(post.mt_basename) ? expressions.Slugify(post.title) : post.mt_basename,
                BodyShort = post.mt_excerpt,
                Creator   = user,
                State     = Oxite.Model.EntityState.Normal
            };

            if (publish)
            {
                newPost.Published = DateTime.Now;
            }

            if (post.categories != null)
            {
                newPost.Tags = new List <Oxite.Model.Tag>(post.categories.Select(s => new Oxite.Model.Tag()
                {
                    Name = s
                }));
            }

            postService.AddPost(area, newPost);

            Oxite.Model.Post createdPost = postService.GetPost(area, newPost.Slug);
            return(createdPost.ID.ToString());
        }
コード例 #9
0
ファイル: PostController.cs プロジェクト: Maxai2/HabrAspNet
        public IActionResult AddPost([FromBody] UserViewModel model)
        {
            if (model.PostName == null || model.PostText == null)
            {
                return(View(model));
            }

            int length        = model.PostText.Length;
            int previewLength = length;

            if (length > 50)
            {
                previewLength = length / 2;
            }

            string preview = model.PostText.Substring(0, previewLength) + "...";

            var post = new Post()
            {
                PostDate    = DateTime.Now,
                PostName    = model.PostName,
                PostPreview = preview,
                PostText    = model.PostText,
                User        = userService.GetUsers().Find(u => u.Id == Int32.Parse(Request.Cookies["id"]))
            };

            postService.AddPost(post);

            return(PartialView("_PostsPartial", post));
        }
コード例 #10
0
        public async Task <IActionResult> AddPost([FromBody] PostEditRequest request)
        {
            var appUser = (AppUser)HttpContext.Items["User"];
            var result  = await _service.AddPost(appUser, request);

            return(Ok(result));
        }
コード例 #11
0
        public ActionResult Add(PostViewModel post, int studentId)
        {
            Post postMap = Mapper.Map <PostViewModel, Post>(post);

            postService.AddPost(postMap, studentId);
            return(RedirectToAction("Posts", "Post", new { studentId = studentId }));
        }
コード例 #12
0
        public IActionResult Create(HomeViewModel vm)
        {
            var userProfileId = int.Parse(HttpContext.Session.GetString("sessionUser"));
            var post          = new Post(vm.PostFormViewModel.Content, userProfileId);

            _postService.AddPost(post);
            return(RedirectToAction("Index"));
        }
コード例 #13
0
 public ActionResult AddPost(Post post)
 {
     if (ModelState.IsValid && Request.IsAuthenticated)
     {
         postService.AddPost(post);
     }
     return(RedirectToAction("Index", "Home"));
 }
コード例 #14
0
        public void GetPosts(PostViewModel postViewModel)
        {
            var id   = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var post = mapper.Map <Post>(postViewModel);

            postService.AddPost(post, id);
            Response.Redirect(Request.Path);
        }
コード例 #15
0
        public IActionResult Add(PostViewModel viewModel)
        {
            if (_postService.AddPost(viewModel.Post))
            {
                return(RedirectToAction("Index"));
            }

            return(View(viewModel));
        }
コード例 #16
0
        public async Task <ActionResult <PostDTO> > Post(PostDTO post)
        {
            if (ModelState.IsValid)
            {
                postService.AddPost(post);
            }

            return(Ok());
        }
コード例 #17
0
ファイル: PostsController.cs プロジェクト: tRamq/InfoHub
        public ActionResult AddPost([FromBody] PostDto post)
        {
            var userId = (int)HttpContext.Items["UserId"];

            post.UserId = userId;

            var addedPost = _postService.AddPost(post);

            return(new OkObjectResult(addedPost));
        }
コード例 #18
0
ファイル: PostController.cs プロジェクト: cempaydas/Petscope
        public IActionResult AddPost(Post post)
        {
            if (post == null)
            {
                return(BadRequest());
            }
            var re = _IPostService.AddPost(post);

            return(Ok(re));
        }
コード例 #19
0
        public int Add(PostDTO post)
        {
            ApplicationUser applicationUser = RequestContext.GetLoggedInUser();

            post.UserID  = applicationUser.UserID;
            post.Contact = applicationUser.Mobile;
            int postId = _postService.AddPost(post);

            return(postId);
        }
コード例 #20
0
        public IActionResult AddPost(PostViewModel model)
        {
            Post post = _mapper.Map <Post>(model);

            post.Theme = _themeService.GetThemeById(model.ThemeId);
            post.user  = GetAuthorizeUser().Result;
            _postService.AddPost(post);

            return(RedirectToAction(nameof(Index)));
        }
コード例 #21
0
        public async Task <IActionResult> AddPost(PostDto postDto)
        {
            var post = _mapper.Map <Post>(postDto);
            await _postService.AddPost(post);

            postDto = _mapper.Map <PostDto>(post);
            var response = new ApiResponse <PostDto>(postDto);

            return(Ok(response));
        }
コード例 #22
0
        public async Task <IActionResult> Post(Posts post)
        {
            var result = await _service.AddPost(post);

            if (result != null)
            {
                return(Ok(result));
            }
            return(StatusCode(StatusCodes.Status204NoContent));
        }
コード例 #23
0
        public ActionResult Create(AddPostViewModel post)
        {
            if (ModelState.IsValid)
            {
                postService.AddPost(Mapper.Map <Post>(post), post.UploadedImage);

                return(this.RedirectToAction(c => c.Index()));
            }

            return(View(Views.Create, post));
        }
コード例 #24
0
        public async Task <CustomApiResponse> Post([FromBody] PostsDto entity)
        {
            //var inputEntity = _mapper.Map<Posts>(entity);
            //if (await _postService.IsExisted(entity.Name))
            //{
            //	return new CustomApiResponse("PostName đã tồn tại", true);
            //}
            var result = await _postService.AddPost(entity);

            return(new CustomApiResponse(result));
        }
コード例 #25
0
        public async Task <IActionResult> Add(NewPostModel newPostModel)
        {
            var result = await postService.AddPost(newPostModel, User);

            await profileService.AddBookmark(
                User.GetUserId(),
                result.PostId,
                newPostModel.EnableNotifications);

            return(Ok(result.PostId)); // todo?: return Created()
        }
コード例 #26
0
 public IActionResult AddPost([FromBody] Post post)
 {
     try
     {
         _postService.AddPost(post);
         return(Ok("Post added!"));
     }
     catch (Exception e)
     {
         return(BadRequest("Oops, something went wrong!" + e.Message));
     }
 }
コード例 #27
0
        public IActionResult CreatePost(CreatePostViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var postDTO = _mapper.Map <CreatePostViewModel, CreatePostDTO>(model);

            postDTO.AuthorId = HttpContext.User.GetUserId();
            _postService.AddPost(postDTO);
            return(Ok());
        }
コード例 #28
0
 public IActionResult Create([Bind("PostTitle,PostText")] Post post)
 {
     if (!string.IsNullOrEmpty(post.PostText) && !string.IsNullOrEmpty(post.PostTitle))
     {
         post.Status       = PostStatus.Created;
         post.AuthorEmail  = User.Identity.Name;
         post.AuthorName   = User.Identity.Name;
         post.CreationDate = DateTime.Now;
         _postService.AddPost(post);
         return(RedirectToAction(nameof(Index)));
     }
     return(View(post));
 }
コード例 #29
0
        public async Task <ActionResult> AddPost([FromBody] PostInsertDto post)
        {
            try
            {
                var postAdded = await _postsService.AddPost(post, ClaimResolver.getUserIdFromToken(User));

                return(Ok(postAdded));
            }
            catch (Exception Ex)
            {
                return(BadRequest("The post cannot be added due to bad connection with the database" + Ex.Message));
            }
        }
コード例 #30
0
        public void When_a_user_attempts_to_post_a_valid_post_it_should_be_added()
        {
            //Arrange
            Post p = pb.getValidPost();

            Mock.Arrange(() => _pr.Save(Arg.IsAny <Post>())).OccursOnce();
            //Act
            ps.AddPost(p);
            //Assert
            Mock.Assert(_pr);
        }