public async Task <IActionResult> Edit(string id, PostInputModel postInput) { var existsPost = this.postsService .Exists(x => x.Id == id); if (!existsPost) { return(this.NotFound()); } if (!this.ModelState.IsValid) { var post = new PostEditModel() { Id = id, PostInput = postInput, }; this.SetSelectListItems(post); return(this.View(post)); } var image = await this.cloudinaryService.SaveImageAsync(postInput.FormFile); await this.postsService.EditAsync(id, postInput, image); this.TempData[GlobalConstants.MessageKey] = $"Successfully edited post!"; return(this.RedirectToAction("Details", "Posts", new { area = "Forum", id })); }
public async Task <IActionResult> Create(PostInputModel postInput) { var existsCategory = this.categoriesService .Exists(x => x.Id == postInput.CategoryId); if (!existsCategory) { return(this.NotFound()); } if (!this.ModelState.IsValid) { return(this.View(postInput)); } var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var image = await this.cloudinaryService.SaveImageAsync(postInput.FormFile); await this.postsService.AddAsync(postInput, image, userId); this.TempData[GlobalConstants.MessageKey] = "Successfully created post!"; return(this.RedirectToAction("Details", "Categories", new { id = postInput.CategoryId })); }
public async Task CreatePostFailDueToInvalidTitle(string email, string password, int categoryId, string title, string body) { var token = await this.Login(email, password); this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); var post = new PostInputModel { CategoryId = categoryId, Title = title, Body = body }; var json = new StringContent( JsonConvert.SerializeObject(post), Encoding.UTF8, "application/json"); var response = await this.client.PostAsync(PostCreateEndpoint, json); var content = JsonConvert.DeserializeObject <ReturnMessage>(await response.Content.ReadAsStringAsync()); Assert.Equal(StatusCodes.Status400BadRequest, content.Status); Assert.Equal($"Post with title '{title}' already exists", content.Message); }
public async Task CreatePostSuccessfully(string email, string password, int categoryId, string title, string body) { var token = await this.Login(email, password); this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); var post = new PostInputModel { CategoryId = categoryId, Title = title, Body = body }; var json = new StringContent( JsonConvert.SerializeObject(post), Encoding.UTF8, "application/json"); var response = await this.client.PostAsync(PostCreateEndpoint, json); response.EnsureSuccessStatusCode(); var content = JsonConvert.DeserializeObject <CreateEditReturnMessage <PostViewModel> >(await response.Content.ReadAsStringAsync()); Assert.Equal(StatusCodes.Status200OK, content.Status); Assert.Equal("Post created successfully", content.Message); Assert.Equal(title, content.Data.Title); Assert.Equal(body, content.Data.Body); Assert.Equal(email.Split("@")[0], content.Data.Author); }
public async Task <IActionResult> AddPost([FromBody] PostInputModel inputModel) { try { var category = context.PostCategories.SingleOrDefault(c => c.CategoryID == inputModel.CategoryID); if (category == null) { return(BadRequest("Invalid category Id")); } context.Posts.Add(new Post { Title = inputModel.Title, Content = inputModel.Content, CategoryID = inputModel.CategoryID, PostedDate = DateTime.UtcNow, LastUpdatedDate = DateTime.UtcNow, UserID = HttpContext.Session.GetInt32("USER_LOGIN_KEY").Value }); await context.SaveChangesAsync(); return(Ok()); } catch (DbUpdateException e) { return(StatusCode(StatusCodes.Status500InternalServerError)); } }
public void AddPost_returns_one_when_correct() { var user = new ForumUser { Id = Guid.NewGuid().ToString(), UserName = TestsConstants.TestUsername3 }; this.dbService.DbContext.Users.Add(user); this.dbService.DbContext.SaveChanges(); var forum = new SubForum { Id = Guid.NewGuid().ToString(), Posts = new List <Models.Post>() }; this.dbService.DbContext.Forums.Add(forum); this.dbService.DbContext.SaveChanges(); var model = new PostInputModel { ForumId = forum.Id, Description = TestsConstants.ValidPostDescription, ForumName = forum.Name, Name = TestsConstants.ValidPostName }; var expectedResult = 1; var actualResult = this.postService.AddPost(model, user, forum.Id).GetAwaiter().GetResult(); Assert.Equal(expectedResult, actualResult); }
public async Task <PostViewModel> Post([FromBody] PostInputModel model) { var post = new Models.Post { Content = model.Description, Title = model.Title, OwnerId = CurrentUserId, OwnerName = User.Identity.Name }; await _postRepo.AddAsync(post); var response = new PostViewModel() { Id = post.Id, Title = post.Title, Description = post.Content, OwnerName = post.OwnerName, CreatedDate = post.Created }; await _postMessageHubContext.Clients.All.InvokeAsync("AddPostSuccess", response); return(response); }
public ActionResult Create(PostInputModel input) { if (input != null && this.ModelState.IsValid) { var userId = this.User.Identity.GetUserId(); var post = new Post { Title = input.Title, Content = input.Content, AuthorId = userId, CategoryId = input.CategoryId }; this.Data.Posts.Add(post); this.Data.SaveChanges(); post.LastActivity = post.CreatedOn; this.Data.Posts.Update(post); this.Data.SaveChanges(); return(this.RedirectToAction("Details", "Posts", new { area = string.Empty, id = post.Id })); } return(this.View(input)); }
public async Task <PostViewModel> Create(PostInputModel model, string email) { if (this.IsValidPostTitle(model.Title)) { throw new ArgumentException($"Post with title '{model.Title}' already exists"); } if (this.IsValidCategory(model.CategoryId)) { throw new ArgumentException("The category provided for the creation of this post is not valid!"); } var user = this.userRepository.Query().FirstOrDefault(u => u.Email == email); var post = this.Mapper.Map <Post>(model); post.CreationDate = DateTime.UtcNow; post.Author = user; await this.postRepository.AddAsync(post); await this.postRepository.SaveChangesAsync(); post = this.postRepository.Query().Include(p => p.Category).FirstOrDefault(p => p.Id == post.Id); return(this.Mapper.Map <Post, PostViewModel>(post)); }
public ActionResult Create([DataSourceRequest] DataSourceRequest request, PostInputModel model) { var postId = 0; if (this.ModelState.IsValid && model != null) { var postToAdd = new Post { Title = model.Title, Content = this._sanitizer.Sanitize(model.Content), }; if (this.User.Identity.IsAuthenticated) { postToAdd.AuthorId = this.User.Identity.GetUserId(); } this._posts.Add(postToAdd); this._posts.SaveChanges(); postId = postToAdd.Id; } var postToDisplay = this._posts.All().Project().To <PostsViewModel>().First(x => x.Id == postId); return(Json(new[] { postToDisplay }.ToDataSourceResult(request, this.ModelState))); }
public IActionResult Edit(PostInputModel model) { if (this.ModelState.IsValid) { this.postService.EditPost(model); } return(this.Redirect("/Post/Index")); }
public async Task <IActionResult> Create(PostInputModel model, string returnUrl, int groupId) { var user = await this.userManager.GetUserAsync(this.User); await this.postsService.CreateAsync(model, user.Id, groupId); return(this.Redirect(returnUrl)); }
public ActionResult Tweet(int?id) { var postInputModel = new PostInputModel { QuestionID = id }; return(this.View(postInputModel)); }
public IActionResult New() { var model = new PostInputModel { IsDraft = true }; return(View("Edit", model)); }
[HttpPost] //Detail of function is in API controller public IActionResult AddPost(PostInputModel model) { if (HttpContext.Session.GetInt32("USER_LOGIN_KEY") == null) { return(RedirectToAction("Login", "Account")); } return(RedirectToAction("Index")); }
public async Task <Post> Post(PostInputModel model) { var post = new Post(model.Body, model.Excerpt, model.Title); await _context.Posts.AddAsync(post); await _context.SaveChangesAsync(); return(post); }
public async Task <IActionResult> Create(PostInputModel model) { if (this.ModelState.IsValid) { var user = await this.userManager.GetUserAsync(HttpContext.User); this.postService.Create(model, user.Id); } return(this.Redirect("/Post/Index")); }
public PostInputModel GetPostInputForm(Category category) { PostInputModel model = new PostInputModel() { CategoryId = category.Id, Category = category }; return(model); }
public Post EditPost(PostInputModel model) { Post post = this.dbContext.Posts.FirstOrDefault(x => x.Id == model.Id); post.Title = model.Title; post.Description = model.Description; this.dbContext.SaveChanges(); return(post); }
public async Task UserLoggedInBannedTryingToCreateAPost(string email, string password, string bannedUserEmail, string bannedUserPassword, string bannedUserUsername, int categoryId, string title, string body) { await this.Register(bannedUserEmail, bannedUserPassword, bannedUserUsername); var bannedUserToken = await this.Login(bannedUserEmail, bannedUserPassword); var token = await this.Login(email, password); this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); var response = await this.client.GetAsync(AdminGetAll); var content = JsonConvert.DeserializeObject <ICollection <UserViewModel> >(await response.Content.ReadAsStringAsync()); var secondUser = content.First(uvm => uvm.Email == bannedUserEmail); response.EnsureSuccessStatusCode(); Assert.Equal(email, content.First().Email); Assert.Equal(bannedUserEmail, secondUser.Email); var json = new StringContent( JsonConvert.SerializeObject("{}"), Encoding.UTF8, "application/json"); response = await this.client.PostAsync(AdminBanEndpoint + secondUser.Id, json); var secondResponseContent = JsonConvert.DeserializeObject <CreateEditReturnMessage <UserViewModel> >(await response.Content.ReadAsStringAsync()); Assert.Equal($"User banned successfully", secondResponseContent.Message); Assert.Equal(StatusCodes.Status200OK, secondResponseContent.Status); var post = new PostInputModel { CategoryId = categoryId, Title = title, Body = body }; json = new StringContent( JsonConvert.SerializeObject(post), Encoding.UTF8, "application/json"); this.client.DefaultRequestHeaders.Remove("Authorization"); this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + bannedUserToken); var responseBannedCreatePost = await this.client.PostAsync(PostCreateEndpoint, json); var responseContent = JsonConvert.DeserializeObject <ReturnMessage>(await responseBannedCreatePost.Content.ReadAsStringAsync()); Assert.Equal(StatusCodes.Status401Unauthorized, responseContent.Status); Assert.Equal(UnauthorizedMiddlewareError, responseContent.Message); }
public async Task CreateAsync(PostInputModel model, GamingForumUser poster) { Post post = this.mapper.Map <PostInputModel, Post>(model); post.Poster = poster; post.PostedOn = DateTime.UtcNow; await this.context.Posts.AddAsync(post); await this.context.SaveChangesAsync(); }
public IActionResult Create() { var categories = this.categoriesService.GetAll <PostCategoriesViewModel>(); var viewModel = new PostInputModel { Categories = categories, }; return(this.View(viewModel)); }
public ActionResult Create(PostInputModel post, IFormFile foto) { //var uri = ArmazenamentoDeFotos.ArmazenarFotoDoPost(foto); //post.UrlIagem = uri.ToString(); post.Proprietario = User.Identity.Name; RedeSocialApi.Post("post", post); return(RedirectToAction(nameof(Index))); }
public IActionResult Edit(string id) { var post = this.postService.GetPostById(id); PostInputModel postInputModel = new PostInputModel() { Id = id, Title = post.Title, Description = post.Description }; return(this.View(postInputModel)); }
public string Create([Bind(Include = "Title,Content")] PostInputModel postToCreate) { /* * Exemplo de modelo de input model * Nessa abordagem, foi criada uma classe especificamente para receber o input do usuário no cadastro. Poderia utilizar * a entidade Post já existente, mas foi criada uma nova para deixar explícito que essa é uma classe de input model */ string title = postToCreate.Title; string content = postToCreate.Content; return("OK"); }
public void TestCreatePostShouldNotAddWithInvalidUser() { PostInputModel model = new PostInputModel() { Title = "Some text", Description = "Some description" }; Post result = this.postService.Create(model, "112"); Assert.Null(result); }
public void TestCreatePostShouldWorkWithInvalidData() { PostInputModel model = new PostInputModel() { Title = "", Description = "" }; Post result = this.postService.Create(model, "12"); Assert.Null(result); }
public Task <ActionResult <PostViewModel> > PostAsync([FromBody] PostInputModel inputModel) => ExecuteAsync <PostViewModel>(async() => { var post = new Post(GetUserId(), inputModel.Message, inputModel.ImageUrl, inputModel.Latitude, inputModel.Longitude); if (await _postsRepository.AddAsync(post) != 1) { return(BadRequest()); } return(Ok((PostViewModel)post)); });
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 void TestGetPostByIdShouldWorkWithInvalidId() { PostInputModel model = new PostInputModel() { Title = "Some more text", Description = "Some more description" }; Post post = this.postService.Create(model, "112"); Post result = this.postService.GetPostById("dsffvdv542"); Assert.Null(result); }
public ActionResult Add(PostInputModel post) { if (!this.ModelState.IsValid) { return this.View(post); } var currentUserId = this.User.Identity.GetUserId(); var newPost = this.postsService.Add(post.Title, post.Content, post.EventTime, post.RegionId, post.PostCategoryId, post.PetId, currentUserId, post.UploadedFiles); if (newPost == null) { this.ModelState.AddModelError(string.Empty, "Възникна грешка."); return this.View(post); } return this.RedirectToAction(nameof(this.Details), new { id = newPost.Id }); }