public async Task <IActionResult> AddPostDescription(NewPostRequestDto newPost) { try { var userId = int.Parse(HttpContext.User.Identity.Name); var post = await _postService.AddNewPost(newPost, userId); await _notificationService.AddNewPostNotification(userId); var connections = await _connectionService.GetFriendsConnectionId(userId); var postJson = JsonConvert.SerializeObject(new { postContent = post.PostContent, postId = post.PostId, username = post.PostOwner.Username, postImage = post.PostImage, profilePicture = post.PostOwner.ProfilePicture }); await _hubContext.Clients.Clients(connections).SendAsync("NewPostNotification", postJson); return(Ok(true)); } catch (Exception ex) { return(BadRequest(ex)); } }
public ActionResult Index() { _userService.AddNewUser(new User() { Name = "Peter Rumbler", Password = "******", Email = "*****@*****.**" }); _userService.AddNewUser(new User() { Name = "Chisty Gullion", Password = "******", Email = "*****@*****.**" }); _userService.AddNewUser(new User() { Name = "David Wadleton", Password = "******", Email = "*****@*****.**" }); var poster = _userService.Get().Last(); _postService.AddNewPost(new Post { Content = "My first post", Title = "first post title" }, poster); _postService.Repost(_postService.Get().Last(), _userService.Get().Last()); //var recipient1 = _userService.Get().ElementAt(1); //var recipient2 = _userService.Get().ElementAt(2); //var recipients = new List<User> { recipient1, recipient2 }; //var m = new Message { Content = "some content", Subject = "ololo" }; //_messageService.AddNewMessage(m, sender, recipients); //var user = _userService.Get().First(); return(View()); }
public ActionResult New(EditPostViewModel postViewModelViewModel) { ActionResult result; var changedPost = ChangePost(postViewModelViewModel, post => postService.AddNewPost(post)); if (changedPost != null) { TempData[TempDataConstants.PostChanged] = "The post has been succesfully published"; result = RedirectToAction("Index", new { category = changedPost.Category.Name }); } else { postViewModelViewModel.Categories = GetCategories(); result = View(postViewModelViewModel); } return(result); }
public async Task <IActionResult> AddPost([FromBody] PostsVM post) { Posts newPost = new Posts(); newPost.Body = post.Body; newPost.Title = post.Title; newPost.Tags = post.Tags; newPost.CreatedAt = DateTime.Now; newPost.CreatedBy = Convert.ToInt32(HttpContext.Session.GetInt32("userid")); //using (var ms = new MemoryStream()) //{ // post.Thumbnail.CopyTo(ms); // var fileBytes = ms.ToArray(); // string s = Convert.ToBase64String(fileBytes); // newPost.Thumbnail = fileBytes; //} var result = await _postService.AddNewPost(newPost); return(Ok(1)); }
public ActionResult CreatePost(Post NewPost) { var LoggedInUser = GetLoggedInUser(); NewPost.UserId = LoggedInUser.Id; if (NewPost != null) { NewPost.DateCreated = Utils.FormattedDate(DateTime.Now); if (NewPost.Image != null) { var url = new ImageProcessor(_environment).UploadImage(NewPost.Image); if (url != null) { NewPost.PostImageUrl = url; } } var Response = _postService.AddNewPost(NewPost); if (Response >= 1) { return(Ok(new ResponseFormat { Success = true, Data = Response })); } return(BadRequest(new ResponseFormat { Error = true, ErrorMessage = "We could not process the request at this time" })); } return(BadRequest(new ResponseFormat { Error = true, ErrorMessage = "Post can not be null" })); }
public IActionResult Create(CreatePostDto newPost) { var post = _postService.AddNewPost(newPost); return(Created($"api/posts/{post.Id}", post)); }
public ActionResult CreatePost(CreateAjaxPostViewModel post) { PermissionSet permissions; Post newPost; Topic topic; using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id); // Check stop words var stopWords = _bannedWordService.GetAll(true); foreach (var stopWord in stopWords) { if (post.PostContent.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) { throw new Exception(LocalizationService.GetResourceString("StopWord.Error")); } } // Quick check to see if user is locked out, when logged in if (loggedOnUser.IsLockedOut || !loggedOnUser.IsApproved) { FormsAuthentication.SignOut(); throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess")); } topic = _topicService.Get(post.Topic); var postContent = _bannedWordService.SanitiseBannedWords(post.PostContent); var akismetHelper = new AkismetHelper(SettingsService); newPost = _postService.AddNewPost(postContent, topic, loggedOnUser, out permissions); if (akismetHelper.IsSpam(newPost)) { newPost.Pending = true; } try { unitOfWork.Commit(); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } } //Check for moderation if (newPost.Pending == true) { return(PartialView("_PostModeration")); } // All good send the notifications and send the post back using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Create the view model var viewModel = ViewModelMapping.CreatePostViewModel(newPost, new List <Vote>(), permissions, topic, LoggedOnReadOnlyUser, SettingsService.GetSettings(), new List <Favourite>()); // Success send any notifications NotifyNewTopics(topic, unitOfWork); // Return view return(PartialView("_Post", viewModel)); } }
public object CreateNewPost(int id, [FromBody] object requestBody) { var responseModel = new ResponseModel(); try { do { var userId = CoreHelper.GetUserId(HttpContext, ref responseModel); var body = requestBody != null ? JObject.Parse(requestBody.ToString() ?? "{}") : null; if (!CoreHelper.GetParameter(out var jsonContent, body, "Content", JTokenType.String, ref responseModel) || !CoreHelper.GetParameter(out var jsonImages, body, "Images", JTokenType.Array, ref responseModel, true) || !CoreHelper.GetParameter(out var jsonTourId, body, "TourId", JTokenType.Integer, ref responseModel, isNullable: true) || !CoreHelper.GetParameter(out var jsonRating, body, "Rating", JTokenType.Integer, ref responseModel, isNullable: true)) { break; } var isTourIdParsed = int.TryParse(jsonTourId?.ToString(), out var tourId); var isRatingParsed = int.TryParse(jsonRating?.ToString(), out var rating); var content = jsonContent?.ToString(); var images = jsonImages != null ? JsonConvert.DeserializeObject <string[]>(jsonImages.ToString()) : null; if (isTourIdParsed) { if (!isRatingParsed || rating < 1 || rating > 5) { throw new ExceptionWithMessage("Rating is invalid"); } } var post = new Post( content: content, tourId: isTourIdParsed ? tourId : (int?)null, images: images !, createAt: DateTime.Now, authorId: userId, rating: isRatingParsed ? rating : (int?)null ); if (!_postService.AddNewPost(post)) { responseModel.FromErrorCode(ErrorCode.Fail); break; } responseModel.FromErrorCode(ErrorCode.Success); responseModel.Data = new JArray() { JObject.FromObject(post) }; } while (false); } catch (Exception ex) { responseModel.FromException(ex); } return(responseModel.ToJson()); }
public object CreateTour(int id, [FromBody] object requestBody) { var responseModel = new ResponseModel(); try { do { var body = requestBody != null ? JObject.Parse(requestBody.ToString() ?? "{}") : null; if (!CoreHelper.GetParameter(out var jsonStartDate, body, "StartDay", JTokenType.Date, ref responseModel) || !CoreHelper.GetParameter(out var jsonEndDate, body, "EndDay", JTokenType.Date, ref responseModel) || !CoreHelper.GetParameter(out var jsonTotalDay, body, "TotalDay", JTokenType.Integer, ref responseModel) || !CoreHelper.GetParameter(out var jsonTotalNight, body, "TotalNight", JTokenType.Integer, ref responseModel) || !CoreHelper.GetParameter(out var jsonMaxMember, body, "MaxMember", JTokenType.Integer, ref responseModel) || !CoreHelper.GetParameter(out var jsonTimelines, body, "Timelines", JTokenType.Array, ref responseModel) || !CoreHelper.GetParameter(out var jsonName, body, "Name", JTokenType.String, ref responseModel) || !CoreHelper.GetParameter(out var jsonPrice, body, "Price", JTokenType.Float, ref responseModel) || !CoreHelper.GetParameter(out var jsonServices, body, "Services", JTokenType.Array, ref responseModel, isNullable: true)) { break; } if (_tourInfoService.TryGetTourInfoById(id, out var tourInfo) != ErrorCode.Success || tourInfo == null) { throw new ExceptionWithMessage("Tour info not found."); } // var timelines = jsonTimelines.ToObject<List<TimeLine>>(); var timelines = JsonConvert.DeserializeObject <List <TimeLine> >(jsonTimelines.ToString()); var name = jsonName?.ToString(); _ = DateTime.TryParse(jsonStartDate?.ToString(), out var startDate); _ = DateTime.TryParse(jsonEndDate?.ToString(), out var endDate); _ = int.TryParse(jsonMaxMember?.ToString(), out var maxMember); _ = int.TryParse(jsonTotalDay?.ToString(), out var totalDay); _ = int.TryParse(jsonTotalNight?.ToString(), out var totalNight); _ = float.TryParse(jsonPrice?.ToString(), out var price); var serviceIds = jsonServices != null ? JsonConvert.DeserializeObject <string[]>(jsonServices.ToString()) : null; // Get user id var userId = CoreHelper.GetUserId(HttpContext, ref responseModel); // Check user is exist if (!_userService.TryGetUsers(userId, out var _)) { responseModel.FromErrorCode(ErrorCode.UserNotFound); break; } var tour = new Tour( tourInfo: tourInfo, timelines: timelines, name: name, startDay: startDate, endDay: endDate, totalDay: totalDay, totalNight: totalNight, createById: userId, maxMember: maxMember, tourInfoId: id, services: serviceIds ?? new string[0], price: price ); // Add tour to tour info if (!_tourService.TryAddTour(tour, timelines)) { responseModel.FromErrorCode(ErrorCode.Fail); break; } var post = new Post( content: string.Empty, images: new string[0], authorId: userId, createAt: DateTime.Now, tourId: tour.Id, rating: null ); //Add post for tour if (!_postService.AddNewPost(post)) { responseModel.FromErrorCode(ErrorCode.Fail); break; } responseModel.FromErrorCode(ErrorCode.Success); responseModel.Data = new JArray { JObject.FromObject(tour) }; } while (false); } catch (Exception ex) { responseModel.FromException(ex); } return(responseModel.ToJson()); }
public ActionResult CreatePost(CreateAjaxPostViewModel post) { PermissionSet permissions; var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnUser = MembershipService.GetUser(loggedOnReadOnlyUser.Id); // Flood control if (!_postService.PassedPostFloodTest(loggedOnReadOnlyUser)) { throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } // Check stop words var stopWords = _bannedWordService.GetAll(true); foreach (var stopWord in stopWords) { if (post.PostContent.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) { throw new Exception(LocalizationService.GetResourceString("StopWord.Error")); } } // Quick check to see if user is locked out, when logged in if (loggedOnUser.IsLockedOut || !loggedOnUser.IsApproved) { FormsAuthentication.SignOut(); throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess")); } var topic = _topicService.Get(post.Topic); var postContent = _bannedWordService.SanitiseBannedWords(post.PostContent); var akismetHelper = new AkismetHelper(SettingsService); var newPost = _postService.AddNewPost(postContent, topic, loggedOnUser, out permissions); // Set the reply to newPost.InReplyTo = post.InReplyTo; if (akismetHelper.IsSpam(newPost)) { newPost.Pending = true; } if (!newPost.Pending.HasValue || !newPost.Pending.Value) { _activityService.PostCreated(newPost); } try { Context.SaveChanges(); } catch (Exception ex) { Context.RollBack(); LoggingService.Error(ex); throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } //Check for moderation if (newPost.Pending == true) { return(PartialView("_PostModeration")); } // All good send the notifications and send the post back // Create the view model var viewModel = ViewModelMapping.CreatePostViewModel(newPost, new List <Vote>(), permissions, topic, loggedOnReadOnlyUser, SettingsService.GetSettings(), new List <Favourite>()); // Success send any notifications NotifyNewTopics(topic, loggedOnReadOnlyUser); // Return view return(PartialView("_Post", viewModel)); }
public ActionResult CreatePost(CreateAjaxPostViewModel post) { PermissionSet permissions; Post newPost; Topic topic; using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Quick check to see if user is locked out, when logged in if (LoggedOnUser.IsLockedOut | !LoggedOnUser.IsApproved) { FormsAuthentication.SignOut(); throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess")); } topic = _topicService.Get(post.Topic); var postContent = _bannedWordService.SanitiseBannedWords(post.PostContent); var akismetHelper = new AkismetHelper(SettingsService); newPost = _postService.AddNewPost(postContent, topic, LoggedOnUser, out permissions); if (!akismetHelper.IsSpam(newPost)) { try { unitOfWork.Commit(); // Successful, add this post to the Lucene index if (_luceneService.CheckIndexExists()) { _luceneService.AddUpdate(_luceneService.MapToModel(newPost)); } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } } else { unitOfWork.Rollback(); throw new Exception(LocalizationService.GetResourceString("Errors.PossibleSpam")); } } //Check for moderation if (newPost.Pending == true) { return(PartialView("_PostModeration")); } else { // All good send the notifications and send the post back using (UnitOfWorkManager.NewUnitOfWork()) { // Create the view model var viewModel = new ViewPostViewModel { Permissions = permissions, Post = newPost, User = LoggedOnUser, ParentTopic = topic }; // Success send any notifications NotifyNewTopics(topic); return(PartialView("_Post", viewModel)); } } }