public async Task <IActionResult> Create(CreatePostModel model) { if (ModelState.IsValid) { string uniquefilename = null; if (model.ImagePath != null && model.ImagePath.Length > 0) { uniquefilename = ProccedFileUpload(model); } Posted posted = new Posted(); posted.Point = model.Point; posted.SeasonId = model.SeasonId; posted.ImagePath = uniquefilename; posted.ApplicationUserId = model.ApplicationUserId; posted.CreatedAt = model.CreatedAt; _context.Add(posted); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ApplicationUserId"] = new SelectList(_context.Users, "Id", "Id", model.ApplicationUserId); ViewData["SeasonId"] = new SelectList(_context.Seasons, "Id", "Id", model.SeasonId); return(View(model)); }
public ActionResult CreatePost(CreatePostModel model) { if (!ModelState.IsValid) { ModelState.AddModelError("", "For some reason you can not create a post"); return(View(model)); } var firstOrDefault = _userRepo.Get.FirstOrDefault(u => u.Login == User.Identity.Name); if (firstOrDefault == null) { return(RedirectToAction("Error404", "Post")); } var post = new Post { Title = model.Title, Preview = model.Preview, Content = model.Content, UpdateTime = DateTime.Today, Tags = String.Concat('#', model.Tags), IdUser = firstOrDefault.Id }; _postRepo.Create(post); return(RedirectToAction("Index")); }
/// <inheritdoc /> Task <CreatePostModel> ITweetBokkApi.CreatePost(CreatePostModel model) { var arguments = new object[] { model }; var func = requestBuilder.BuildRestResultFuncForMethod("CreatePost", new Type[] { typeof(CreatePostModel) }); return((Task <CreatePostModel>)func(Client, arguments)); }
public async Task <IActionResult> CreatePost(CreatePostModel newPost) { newPost.userID = User.FindFirstValue(ClaimTypes.NameIdentifier); await _userPostsService.CreateNewPostAsync(_mapper.Map <CreatePostModelDTO>(newPost)); return(RedirectToAction("Index")); }
public void Invoke_GetBreedTypeIdByBreedTypeName_From_BreedTypeServices() { var createPostModel = new CreatePostModel() { Title = "1234567890", Description = "12345678901234567890", Status = true, LocationName = "TestLocation", AnimalTypeName = "TestAnimalTypeName", BreedTypeName = "TestBreed", AnimalName = "TestAnimalName", Birthday = DateTime.Now }; locationServicesMock .Setup(l => l.GetLocationIdByLocationName(It.IsAny <IAnimaniaConsoleContext>(), It.IsAny <string>())) .Returns(1); animalTypeServicesMock .Setup(a => a.GetAnimalTypeIdByAnimalTypeName(It.IsAny <IAnimaniaConsoleContext>(), It.IsAny <string>())) .Returns(1); breedTypeServicesMock .Setup(b => b.GetBreedTypeIdByBreedTypeName(It.IsAny <string>())) .Returns(1).Verifiable(); postService.CreatePost(createPostModel, 1); breedTypeServicesMock.Verify(x => x.GetBreedTypeIdByBreedTypeName(It.IsAny <string>()), Times.Once); }
public async Task CreateNewPostCheckIsTypeOfFile_Test() { var mock1 = new Mock <IRepository <Post> >(); var mock2 = new Mock <IHostingEnvironment>(); var fileMock = new Mock <IFormFile>(); var fileName = "i.txt"; fileMock.Setup(_ => _.FileName).Returns(fileName); CreatePostModel createPostModel = new CreatePostModel { Title = "Luxury interior in the design of apartments and houses", ShortDescription = "Designing premium interiors is a rejection of typical planning.", Image = fileMock.Object }; byte[] imageData = null; var postService = new PostService(mock1.Object, mock2.Object); Exception ex = await Assert.ThrowsAsync <Exception>(() => postService.CreatePost(createPostModel.Title, createPostModel.ShortDescription, createPostModel.Image.FileName, imageData)); Assert.Equal("Invalid file type.", ex.Message); }
public ActionResult Create(string postType) { IEnumerable <Textbook> textBookCollection = TextbookHandler.getAllTextbooks(); // test data //for(int i = 0; i < 100; i++) { // Textbook book = new Textbook( // i, // "Financial Accounting " + i, // "100000000000" + i, // "Author " + i, // 100 + i, // "AFM 10" + i, // null, // 10 + i, // 1, // 0, // DateTime.Now, // DateTime.Now // ); // textBookCollection.Add(book); //} // var viewModel = new CreatePostModel() { ActionBy = postType == "Buy" ? ActionBy.Buyer : ActionBy.Seller, BookCondition = BookCondition.Excellent, PostTypes = SelectListUtility.getPostTypes(), BookConditions = SelectListUtility.getBookConditions(), Textbooks = textBookCollection }; return(View("CreatePost", viewModel)); }
public void Create_Post_WhenArguments_AreValid() { var createPostModel = new CreatePostModel() { Title = "1234567890", Description = "12345678901234567890", Status = true, LocationName = "TestLocation", AnimalTypeName = "TestAnimalTypeName", BreedTypeName = "TestBreed", AnimalName = "TestAnimalName", Birthday = DateTime.Now }; locationServicesMock .Setup(l => l.GetLocationIdByLocationName(It.IsAny <IAnimaniaConsoleContext>(), It.IsAny <string>())) .Returns(1); animalTypeServicesMock .Setup(a => a.GetAnimalTypeIdByAnimalTypeName(It.IsAny <IAnimaniaConsoleContext>(), It.IsAny <string>())) .Returns(1); breedTypeServicesMock .Setup(b => b.GetBreedTypeIdByBreedTypeName(It.IsAny <string>())) .Returns(1); postService.CreatePost(createPostModel, 1); Assert.AreEqual(1, effortContext.Posts.Count()); }
public async Task CheckCreatePostNull_Test() { var fileMock = new Mock <IFormFile>(); var mock = new Mock <IPostService>(); var ms = new MemoryStream(); var writer = new StreamWriter(ms); var fileName = "i.jpg"; writer.Write(fileName); writer.Flush(); ms.Position = 0; fileMock.Setup(_ => _.OpenReadStream()).Returns(ms); fileMock.Setup(_ => _.Length).Returns(ms.Length); var createPostModel = new CreatePostModel { Title = "Luxury interior in the design of apartments and houses", ShortDescription = "Designing premium interiors is a rejection of typical planning.", Image = fileMock.Object }; Post post = null; byte[] imageData = new byte[255]; mock.Setup(repo => repo.CreatePost(createPostModel.Title, createPostModel.ShortDescription, createPostModel.Image.FileName, imageData)).Returns(async() => { return(post); }); var createNewPostController = new CreatePostController(mock.Object); Exception ex = await Assert.ThrowsAsync <Exception>(() => createNewPostController.CreatePost(createPostModel)); Assert.Equal("Post not created!", ex.Message); }
public IActionResult Index() { var indexModel = new CreatePostModel(); indexModel.UserPosts = _userPostsService.GetAllUserPosts(User.FindFirstValue(ClaimTypes.NameIdentifier)); return(View(indexModel)); }
public ActionResult Create() { var model = new CreatePostModel(); model.IsPublic = true; return(View(model)); }
public ActionResult CreatePost() { var universities = GetAllUniversities(); var model = new CreatePostModel(); model.Universities = GetSelectListItems(universities); return(View(model)); }
/// <summary> /// Method for the create post page. /// </summary> /// <returns>The Create Post View</returns> public ActionResult CreatePost() { CreatePostModel model = new CreatePostModel(); model.UserLoginName = claimsHelper.GetUserNameFromClaim((ClaimsIdentity)User.Identity); model.ExpirationDate = DateTime.Now; return(View(ViewNames.CreatePost, model)); }
/// <summary> /// Method for the edit post page. /// </summary> /// <param name="postId">the id of the post to edit.</param> /// <returns>The Create Post View</returns> public ActionResult EditPost(int postId) { CreatePostModel model = new CreatePostModel(); Post itemPost = new Post(); GetPostByPostIdQuery query = new GetPostByPostIdQuery(postId); itemPost = commandBus.ProcessQuery(query); model.PostId = itemPost.PostId; model.PostedBy = itemPost.PostedBy; model.PostPurpose = itemPost.PostPurpose; model.PostTitle = itemPost.PostTitle; model.PostDescription = itemPost.PostDescription; model.DatePosted = itemPost.DatePosted; model.PostStatus = itemPost.PostStatus; model.ExpirationDate = itemPost.ExpirationDate; model.CategoryId = itemPost.CategoryId; model.SubCategoryId = itemPost.SubCategoryId; model.Pictures = itemPost.Pictures; model.PostedByEmailAddress = itemPost.PostedByEmailAddress; model.TestPicturePaths = itemPost.TestPicturePaths; IEnumerable <SubCategoryEnum> subcategoryEnum = Enumeration.GetAll <SubCategoryEnum>().ToList(); List <SubCategoryEnum> subCategoriesList = new List <SubCategoryEnum>(); foreach (SubCategoryEnum subCat in Enumeration.GetAll <SubCategoryEnum>()) { if (subCat.ParentId == model.CategoryId) { subCategoriesList.Add(subCat); } } IEnumerable <SelectListItem> subcategoryList = subCategoriesList.Select(item => new SelectListItem() { Text = item.DisplayValue, Value = item.Id, }); model.SubcategoryList = subcategoryList; if (claimsHelper.GetUserNameFromClaim((ClaimsIdentity)User.Identity) == model.PostedBy) { SelectPicturesForPostQuery pictureQuery = new SelectPicturesForPostQuery(model.PostId); model.TestPicturePaths = commandBus.ProcessQuery(pictureQuery); model.Pictures = new List <string>(); foreach (Picture picture in model.TestPicturePaths) { model.Pictures.Add(GetBaseImage(picture.PictureImagePath)); } return(View(ViewNames.CreatePost, model)); } return(RedirectToAction("Index", "Post")); }
public void Should_Return_The_Right_Collection() { var ContextMock = new AnimaniaConsoleContext(Effort.DbConnectionFactory.CreateTransient()); var LocationMock = new Mock <ILocationServices>(); var AnimalTypeMock = new Mock <IAnimalTypeServices>(); var BreedTypeMock = new Mock <IBreedTypeServices>(); postServices = new PostServices(ContextMock, LocationMock.Object, AnimalTypeMock.Object, BreedTypeMock.Object); User user = new User() { Id = 1, UserName = "******", Password = "******", Email = "*****@*****.**" }; BreedType breed = new BreedType() { BreedTypeName = "TestBreed", AnimalTypeId = 1 }; AnimalType type = new AnimalType() { AnimalTypeName = "TestAnimalTypeName", }; Location location = new Location() { LocationName = "TestLocation", }; var animal = new Animal { AnimalName = "TestAnimalTypeName", Birthday = DateTime.Now, AnimalTypeId = 1, BreedTypeId = 1, LocationId = 1, UserId = 1 }; var post = new CreatePostModel() { Title = "1234567890", Description = "12345678901234567890", Status = true, Price = 12.0M, LocationName = location.LocationName, AnimalTypeName = "TestAnimalTypeName", BreedTypeName = "TestBreed", AnimalName = "TestAnimalName", Birthday = DateTime.Now }; Assert.IsInstanceOfType(postServices.GetAllMyPosts(1), typeof(IEnumerable <PostModel>)); }
public async Task <IActionResult> AddPost(CreatePostModel model) { var userId = _userManager.GetUserId(User); var user = await _userManager.FindByIdAsync(userId); var post = BuildPostEntity(model, user); _postService.Add(post).Wait(); // .Wait() blocks current thread until the Task is completed. return(RedirectToAction("Detail", "Student", new { id = post.Student.Id })); // need to new up the route-id object to avoid "Sequence contains no value" exception. }
public ActionResult Create(CreatePostModel post) { if (ModelState.IsValid) { PostDAO.CreatePost(UserDAO.GetUserId(User.Identity.Name), post.PostTitle, post.PostBody); return(RedirectToAction("Index")); } return(View(post)); }
public async Task <IActionResult> PostAsync([FromForm] CreatePostModel post) { var result = await _postService.CreatePostAsync(post); if (result.IsFailure) { return(BadRequest(result.Errors)); } return(Ok(result.Data)); }
public async Task <ActionResult> Create(CreatePostModel createPostModel) { if (ModelState.IsValid) { await createPostModel.AddPost(User.Identity.Name); return(RedirectToAction("Index")); } return(View(createPostModel)); }
//id parameter in Create(int id) will be the StudentId, this method directs to the create viewmodel to accept input. public IActionResult Create(int id) { var student = _studentService.GetById(id); var model = new CreatePostModel { StudentName = student.Name, StudentId = student.Id, AuthorName = User.Identity.Name }; return(View(model)); }
public ActionResult Create(CreatePostModel post, HttpPostedFileBase image = null) { if (ModelState.IsValid) { ContentRepository.addPost(post, image, User.Identity.Name); return(RedirectToAction("Index", "Home")); } else { return(View()); } }
public async Task <Post> CreatePostAsync(CreatePostModel model, FileDestinationMetadata metadata = null) { var entity = model.ToDest(); if (model.Image != null) { await SetPostImageUrlAsync(entity, model.Image, metadata); } PrepareCreate(entity); return(context.Post.Add(entity).Entity); }
public async Task <IActionResult> Create([FromBody] CreatePostModel post) { if (!ModelState.IsValid) { } var createdId = await _postService.CreateAsync(post); if (createdId.IsSucceed) { return(Ok(createdId.Data)); } return(BadRequest(createdId.FailureResult)); }
public ActionResult CreatePost(CreatePostModel model) { //var universities = GetAllUniversities(); // model.Universities = GetSelectListItems(universities); if (ModelState.IsValid) { DateTime date = DateTime.Now; Session["CreatePostModel"] = model; return(RedirectToAction("Post")); } return(View("Error")); }
// This private method 'reverses' the flow of data - that is, it passes the accepted input data from the ViewModel back to the Data Model to be INSERTed into the Db. private Post BuildPostEntity(CreatePostModel model, ApplicationUser user) { var student = _studentService.GetById(model.StudentId); return(new Post { Title = model.Title, Body = model.Body, Created = DateTime.Now, Instructor = user, Student = student }); }
public ActionResult EditPost(CreatePostModel model, int PostId) { Post post = EditPostToDatabase(model, PostId); post.tags = null; if (TagStringValidation(model.TagString)) { var tags = SeparateTags(model.TagString); PairPostWithNewTags(ref post, ref tags); } return(RedirectToAction("ViewPost", post.PostId)); }
public async Task <IActionResult> CreatePost([FromBody] CreatePostModel model) { try { var result = await _userBL.CreatePost(model.title, model.projectid, model.tags, model.description, model.code); return(Json(new { success = true })); } catch (Exception ex) { return(Json(new { success = false, message = ex.Message })); } }
public async Task <PostResponseModel> CreatePostAsync(CreatePostModel model) { var user = await userManager.FindByNameAsync(model.Name); await ctx.Entry(user) .Reference(r => r.Profile) .LoadAsync(); var post = new Post { Description = model.Description, Profile = ctx.Profiles.FirstOrDefault(p => p.User.UserName == model.Name), ProfileId = ctx.Profiles.FirstOrDefault(p => p.User.UserName == model.Name).Id, PostImages = new List <PostImage>(), PostSongs = new List <PostSong>(), PostVideos = new List <PostVideo>() }; if (model.PostImages != null) { foreach (var file in model.PostImages) { var image = await this.AddPostImage(file, post.Id); ctx.PostImages.Add(image); post.PostImages.Add(image); } } if (model.PostSongs != null) { foreach (var postSong in model.PostSongs) { var song = await this.AddPostSong(postSong, post.Id); ctx.PostSongs.Add(song); post.PostSongs.Add(song); } } if (model.PostVideos != null) { foreach (var video in model.PostVideos) { var postVideo = await this.AddPostVideos(video, post.Id); ctx.PostVideos.Add(postVideo); post.PostVideos.Add(postVideo); } } post.ProfileId = user.Profile.Id; post.Profile = user.Profile; post.DateOfCreation = DateTime.UtcNow; await postRepository.AddAsync(post, user); return(Ok(post)); }
public HttpResponseMessage CreateNewPost(CreatePostModel postModel, [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string sessionKey) { var createPostResponse = this.TryToExecuteOperation(() => { if (!usersRepository.All().Any(x => x.SessionKey == sessionKey)) { throw new InvalidOperationException("Not authorized user!"); } if (postModel == null) { throw new InvalidOperationException("The input model can not be null!"); } if (string.IsNullOrEmpty(postModel.Title) || string.IsNullOrEmpty(postModel.Text)) { throw new InvalidOperationException("The title and text in post can not be null or empty string!"); } var user = this.usersRepository.All().ToList() .FirstOrDefault(x => x.SessionKey == sessionKey); var post = DataMapper.CreatePostModelToPost(postModel); post.PostedBy = user; var dbTags = this.tagsRepository.All().ToList(); foreach (var tag in postModel.Tags) { var dbTag = dbTags.FirstOrDefault(x => x.Name == tag); if (dbTag != null) { post.Tags.Add(dbTag); } else { post.Tags.Add(new Tag() { Name = tag }); } } var dbPost = this.postsRepository.Add(post); var postResponseModel = DataMapper.PostToCreatePostResponseModel(dbPost); var response = this.Request.CreateResponse(HttpStatusCode.Created, postResponseModel); return(response); }); return(createPostResponse); }
public ActionResult Create([Bind(Exclude = "Photo, FileContent")] CreatePostModel model) { Post post = new Post(); var author = db.Users.Single(u => u.UserName == User.Identity.Name); post.Author = author; post.Content = model.Content; post.Title = model.Title; var tag = db.Tag.Single(t => t.Id == model.TagId); post.Tag = tag; var aCategory = db.Category.Single(c => c.CategoryName == tag.Category.CategoryName); post.Categories = aCategory; byte[] imageData = null; if (Request.Files.Count > 0) { HttpPostedFileBase poImgFile = Request.Files["Photo"]; using (var binary = new BinaryReader(poImgFile.InputStream)) { imageData = binary.ReadBytes(poImgFile.ContentLength); } } byte[] docData = null; var fileName = ""; if (Request.Files.Count > 0) { HttpPostedFileBase docFile = Request.Files["FileContent"]; using (var binary = new BinaryReader(docFile.InputStream)) { docData = binary.ReadBytes(docFile.ContentLength); fileName = docFile.FileName; } } post.FileName = fileName; post.FileContent = docData; post.Photo = imageData; db.Post.Add(post); db.SaveChanges(); return(RedirectToAction("Posts", new { category = post.Categories.CategoryName })); }