public async Task <bool> UpdateTopic(string CID, string MID, string TID, CreateTopicViewModel model) { var course = await GetCourse(CID); var module = course.Modules.SingleOrDefault(x => x.Id == MID); var topic = module.Topics.SingleOrDefault(x => x.Id == TID); var utopic = new Topic { Id = topic.Id, Discription = model.Discription, Name = model.Name, Position = model.Position, Path = topic.Path, Type = model.Type }; var result1 = module.Topics.Remove(topic); if (result1) { course.Modules.Remove(module); module.Topics.Add(utopic); course.Modules.Add(module); var updated = await _course.ReplaceOneAsync(x => x.Id == CID, course); return(updated.IsAcknowledged); } return(false); }
public ActionResult Create(CreateTopicViewModel model, String returnUrl) { if (ModelState.IsValid) { Topic newTopic = new Topic() { Title = model.Title, Text = model.Text, AddedDate = DateTime.Now, Like = 0, UserAddedID = GetUserId(), CategoryID = categoryRepository.CategoryRepository .Where(e => e.Name.Equals("UserBlog")) .Select(e => e.CategoryID) .FirstOrDefault() }; topicRepository.Insert(newTopic); return(Redirect(returnUrl ?? Url.Action("Index", "UserBlog", new { userID = GetUserId() }))); } else { return(View()); } }
public async Task <IActionResult> Create(CreateTopicViewModel model) { if (ModelState.IsValid) { User user = await _userManager.FindByNameAsync(User.Identity.Name); if (user is null) { throw new InvalidOperationException("There is no current user."); } if (String.IsNullOrWhiteSpace(model.Name) || String.IsNullOrWhiteSpace(model.Description)) { ModelState.AddModelError(String.Empty, "Both title and text must be provided."); } else { var topic = new Topic() { User = user, Name = model.Name, Description = model.Description, CreationTime = DateTime.Now, LastChangeTime = DateTime.Now, Messages = null }; await _context.TopicModels.AddAsync(topic); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } } return(View(model)); }
public async Task <IActionResult> Create(CreateTopicViewModel model) { if (ModelState.IsValid && model.Questions.Count != 0) { Topic topic = new Topic { Id = Guid.NewGuid().ToString(), Name = model.Name, }; await _db.Topics.AddAsync(topic); foreach (var item in model.Questions) { Question question = new Question() { Id = Guid.NewGuid().ToString(), QuestionString = item.QuestionString, AnswerString = item.AnswerString, Topic = topic, TopicId = topic.Id }; await _db.Questions.AddAsync(question); } await _db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(model)); }
public ActionResult Create(CreateTopicViewModel topicVM) { if (ModelState.IsValid && Session["UserLoggedInId"] != null) { var userBO = new UserBO(); var author = userBO.Get((Guid)Session["UserLoggedInId"]).Result; var newTopic = new Topic { Id = Guid.NewGuid(), UserId = author.Id, Title = topicVM.Title, Description = topicVM.Description, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, IsDeleted = false }; var result = topicBO.Create(newTopic); if (result.HasSucceeded) { return(RedirectToAction("Index")); } return(HttpNotFound()); } //ViewBag.UserId = new SelectList(db.Users, "Id", "Name", topic.UserId); return(View(topicVM)); }
public async Task <IActionResult> Create(CreateTopicViewModel viewmodel) { ModelState.Remove("Topic.UserId"); ModelState.Remove("Topic.User"); if (ModelState.IsValid) { viewmodel.Topic.TotalViews = 0; viewmodel.Topic.UserId = (await GetCurrentUserAsync()).Id; _context.Add(viewmodel.Topic); await _context.SaveChangesAsync(); if (viewmodel.Topic.HouseExclusive == true) { return(RedirectToAction("ViewCommonRoom", "Home", new { category = "All" })); } else { return(RedirectToAction("ViewGreatHall", "Home", new { category = "All" })); } } return(View(viewmodel)); }
public async Task <IActionResult> CreateTopic(CreateTopicViewModel vm) { User user = await _userManager.GetUserAsync(HttpContext.User); Topic topic = new Topic() { Title = vm.Title, Description = vm.Description, Forum = await _forumRepository.GetById(vm.Forum.Id), Posts = new List <Post> { new Post { Contents = vm.Contents, User = user, Created = DateTime.Now, Updated = DateTime.Now } }, User = user, Created = DateTime.Now, Updated = DateTime.Now }; int topic_id = await _topicRepository.Create(topic); await _userRepository.CountPost(user.Id); return(RedirectToAction("Topic", new { id = topic_id })); }
// GET: Topics/Create public async Task <IActionResult> Create(bool?House) { ApplicationUser user = await GetCurrentUserAsync(); House house = await _context.House.FirstOrDefaultAsync(h => h.HouseId == user.HouseId); user.House = house; CreateTopicViewModel viewmodel = new CreateTopicViewModel(); List <TopicCategory> categories = await _context.TopicCategory.ToListAsync(); List <SelectListItem> categoryOptions = categories.Select(c => { return(new SelectListItem { Text = c.Label, Value = c.TopicCategoryId.ToString() }); }).ToList(); if (House != false) { Topic topic = new Topic(); topic.HouseExclusive = true; viewmodel.Topic = topic; } viewmodel.CategoryOptions = categoryOptions; viewmodel.User = user; return(View(viewmodel)); }
public ActionResult CreateTopic(int teamId) { this.ValidateIfCurrentUserIsMemberOfTeam(teamId); CreateTopicViewModel createTopicViewModel = this.service.GetCreateTopicViewModel(teamId); createTopicViewModel.AuthorName = User.Identity.Name; return(this.View(createTopicViewModel)); }
public ActionResult Create(CreateTopicViewModel createTopicView) { var createTopicDto = Mapper.Map <CreateTopicDto>(createTopicView); _topicService.CreateTopic(createTopicDto); return(RedirectToAction("Item", "Section", new { Id = createTopicView.SectionId })); }
public ActionResult Create(int id) { var newTopic = new CreateTopicViewModel(); newTopic.Forum = db.Fora.Find(id); return(View(newTopic)); }
public ActionResult Create() { CreateTopicViewModel model = new CreateTopicViewModel() { Topic = new Topic(), MasterPage = UpdateMasterPageData() }; return(View("~/Views/Admin/CreateTopic.cshtml", model)); }
public CreateTopicViewModel GetCreateTopicViewModel(int teamId) { var teamModel = this.GetTeamById(teamId); var createTopicViewModel = new CreateTopicViewModel() { TeamViewModel = teamModel, TeamId = teamId }; return(createTopicViewModel); }
public ActionResult Create(CreateTopicViewModel model) { if (model.Title != string.Empty && model.Text != string.Empty && model.Text.Length > 100) { // Add logged user id do new Topic. topics.Insert(new Domain.Entity.Topic() { Title = model.Title, Text = model.Text, AddedDate = DateTime.Now, UserAddedID = User.Identity.GetUserId(), Like = 0, CategoryID = category.CategoryRepository.Where(e => e.Name.Equals("HomePage")).FirstOrDefault().CategoryID }); return(RedirectToAction("Index")); } return(View()); }
public ActionResult Create() { using (UnitOfWorkManager.NewUnitOfWork()) { var allowedCategories = _categoryService.GetAllowedCategories(UsersRole).ToList(); if (allowedCategories.Any() && LoggedOnUser.DisablePosting != true) { var viewModel = new CreateTopicViewModel { Categories = allowedCategories, LoggedOnUser = LoggedOnUser }; return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } }
public ActionResult Create(CreateTopicViewModel newTopic) { newTopic.Topic.LastPostDate = DateTime.Now; newTopic.Topic.PostCount = 1; newTopic.Topic.ViewsCount = 0; newTopic.Topic.UserID = User.Identity.GetUserId(); if (User.Identity.IsAuthenticated) { var user = db.Users.Find(User.Identity.GetUserId()); newTopic.Topic.UserID = user.Id; db.Users.Find(User.Identity.GetUserId()).PostsCount++; if (!user.OwnRank) { db.Users.Find(User.Identity.GetUserId()).Rank = UserManagement.GetRank(user.PostsCount); } } else { newTopic.Topic.UserID = null; } newTopic.Topic.ForumID = newTopic.Forum.ID; db.Topics.Add(newTopic.Topic); db.SaveChanges(); newTopic.Post.Date = DateTime.Now; newTopic.Post.TopicID = db.Topics.ToList().Last().ID; if (User.Identity.IsAuthenticated) { newTopic.Post.UserID = User.Identity.GetUserId(); } else { newTopic.Post.UserID = null; } newTopic.Post.Content = Html.EditMarkers(newTopic.Post.Content); db.Posts.Add(newTopic.Post); db.Fora.Find(newTopic.Topic.ForumID).TopicCount++; db.Fora.Find(newTopic.Topic.ForumID).PostCount++; db.SaveChanges(); return(RedirectToAction("Details", "Topic", new { id = newTopic.Topic.ID })); }
public async Task <IActionResult> Index([FromBody] CreateTopicViewModel vm) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.Select(v => v.Errors))); } var categoryExist = await _categoriesRepository.Contains(vm.CategoryId); if (categoryExist) { var topic = _mapper.Map <Topic>(vm); await _topicsRepository.AddAsync(topic); return(Ok()); } return(BadRequest()); }
public async Task <bool> CreateTopic(string CID, string MID, CreateTopicViewModel model) { var course = await GetCourse(CID); var module = await GetModuleById(CID, MID); var topic = new Topic { Id = Guid.NewGuid().ToString(), Discription = model.Discription, Name = model.Name, Position = model.Position, Path = null, Type = model.Type }; course.Modules.SingleOrDefault(x => x.Id == MID).Topics.Add(topic); var result = await _course.ReplaceOneAsync(x => x.Id == CID, course); return(result.IsAcknowledged); }
public async Task <IActionResult> Create(CreateTopicViewModel model) { if (!this.ModelState.IsValid) { return(this.View(model)); } var userId = this.userManager.GetUserId(this.User); try { await this.topicService.CreateAsync(userId, model.Title, model.Content); } catch (Exception ex) { this.ModelState.AddModelError(string.Empty, ex.Message); return(this.View(model)); } return(this.View("CreateSuccessful")); }
public ActionResult GetContext(string urlSite) { if (urlSite == null) { CreateTopicViewModel model = new CreateTopicViewModel() { Topic = new Topic(), MasterPage = UpdateMasterPageData() }; return(View("~/Views/Admin/CreateTopic.cshtml", model)); } CreateTopicViewModel modelDone = new CreateTopicViewModel() { Topic = new Topic() { ContextTopic = topicService.GetContextFromOtherSite(urlSite) }, MasterPage = UpdateMasterPageData() }; return(View("~/Views/Admin/CreateTopic.cshtml", modelDone)); }
public async Task <IActionResult> Post([FromForm] CreateTopicViewModel topicViewModel) { if (!ModelState.IsValid) { return(BadRequest()); } var topicDto = _mapper.Map <CreateTopicViewModel, TopicDto>(topicViewModel); byte[] fileBytes; using (var stream = new MemoryStream()) { await topicViewModel.Image.CopyToAsync(stream); fileBytes = stream.ToArray(); } await _topicService.CreateTopicWithImage(topicDto, topicViewModel.Image.FileName, _hostingEnvironment.WebRootPath, fileBytes); return(Ok()); }
public ActionResult CreateTopic(CreateTopicViewModel model) { if (ModelState.IsValid) { Topic topic = new Topic { Author = User.Identity.Name, Name = model.Name }; topic.Comments.Add(new Comment { Author = User.Identity.Name, Content = model.Content }); db.Topics.Add(topic); db.SaveChanges(); return(RedirectToAction("Index")); } return(View()); }
public async Task <IActionResult> CreateTopic(int id) { CreateTopicViewModel vm = new CreateTopicViewModel() { Forum = await _forumRepository.GetById(id) }; // Manually set breadcrumb nodes var childNode1 = new MvcBreadcrumbNode("Forum", "Home", vm.Forum.Title) { RouteValues = new { id = vm.Forum.Id } }; var childNode2 = new MvcBreadcrumbNode("CreateTopic", "Home", "Creating topic") { RouteValues = new { id = vm.Forum.Id }, OverwriteTitleOnExactMatch = true, Parent = childNode1 }; ViewData["BreadcrumbNode"] = childNode2; return(View(vm)); }
public ActionResult Create(CreateTopicViewModel topicViewModel) { if (ModelState.IsValid) { // Quick check to see if user is locked out, when logged in if (LoggedOnUser.IsLockedOut || LoggedOnUser.DisablePosting == true || !LoggedOnUser.IsApproved) { FormsAuthentication.SignOut(); return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess"))); } var successfullyCreated = false; Category category; var topic = new Topic(); using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Not using automapper for this one only, as a topic is a post and topic in one category = _categoryService.Get(topicViewModel.Category); // First check this user is allowed to create topics in this category var permissions = RoleService.GetPermissions(category, UsersRole); // Check this users role has permission to create a post if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked) { // Throw exception so Ajax caller picks it up ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.NoPermission")); } else { // We get the banned words here and pass them in, so its just one call // instead of calling it several times and each call getting all the words back var bannedWordsList = _bannedWordService.GetAll(); List <string> bannedWords = null; if (bannedWordsList.Any()) { bannedWords = bannedWordsList.Select(x => x.Word).ToList(); } topic = new Topic { Name = _bannedWordService.SanitiseBannedWords(topicViewModel.Name, bannedWords), Category = category, User = LoggedOnUser }; // See if the user has actually added some content to the topic if (!string.IsNullOrEmpty(topicViewModel.Content)) { // Check for any banned words topicViewModel.Content = _bannedWordService.SanitiseBannedWords(topicViewModel.Content, bannedWords); // See if this is a poll and add it to the topic if (topicViewModel.PollAnswers != null && topicViewModel.PollAnswers.Count > 0) { if (permissions[AppConstants.PermissionCreatePolls].IsTicked) { // Create a new Poll var newPoll = new Poll { User = LoggedOnUser }; // Create the poll _pollService.Add(newPoll); // Save the poll in the context so we can add answers unitOfWork.SaveChanges(); // Now sort the answers var newPollAnswers = new List <PollAnswer>(); foreach (var pollAnswer in topicViewModel.PollAnswers) { // Attach newly created poll to each answer pollAnswer.Poll = newPoll; _pollAnswerService.Add(pollAnswer); newPollAnswers.Add(pollAnswer); } // Attach answers to poll newPoll.PollAnswers = newPollAnswers; // Save the new answers in the context unitOfWork.SaveChanges(); // Add the poll to the topic topic.Poll = newPoll; } else { //No permission to create a Poll so show a message but create the topic TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Errors.NoPermissionPolls"), MessageType = GenericMessages.info }; } } // Update the users points score for posting _membershipUserPointsService.Add(new MembershipUserPoints { Points = SettingsService.GetSettings().PointsAddedPerPost, User = LoggedOnUser }); // Create the topic topic = _topicService.Add(topic); // Save the changes unitOfWork.SaveChanges(); // Now create and add the post to the topic _topicService.AddLastPost(topic, topicViewModel.Content); // Now check its not spam var akismetHelper = new AkismetHelper(SettingsService); if (!akismetHelper.IsSpam(topic)) { // Add the tags if any too if (!string.IsNullOrEmpty(topicViewModel.Tags)) { // Sanitise the tags topicViewModel.Tags = _bannedWordService.SanitiseBannedWords(topicViewModel.Tags, bannedWords); // Now add the tags _topicTagService.Add(topicViewModel.Tags.ToLower(), topic); } // Subscribe the user to the topic as they have checked the checkbox if (topicViewModel.SubscribeToTopic) { // Create the notification var topicNotification = new TopicNotification { Topic = topic, User = LoggedOnUser }; //save _topicNotificationService.Add(topicNotification); } try { unitOfWork.Commit(); successfullyCreated = true; // Successful, add this post to the Lucene index if (_luceneService.CheckIndexExists()) { _luceneService.AddUpdate(_luceneService.MapToModel(topic)); } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } } else { unitOfWork.Rollback(); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.PossibleSpam")); } } else { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } } } using (UnitOfWorkManager.NewUnitOfWork()) { if (successfullyCreated) { // Success so now send the emails NotifyNewTopics(category); // Redirect to the newly created topic return(Redirect(string.Format("{0}?postbadges=true", topic.NiceUrl))); } var allowedCategories = _categoryService.GetAllowedCategories(UsersRole).ToList(); if (allowedCategories.Any()) { topicViewModel.Categories = allowedCategories; } } return(View(topicViewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); }
public ActionResult Create(CreateTopicViewModel topicViewModel) { if (ModelState.IsValid) { // Quick check to see if user is locked out, when logged in if (CurrentMember.IsLockedOut || CurrentMember.DisablePosting == true || !CurrentMember.IsApproved) { MemberService.LogOff(); return(ErrorToHomePage(Lang("Errors.NoPermission"))); } var successfullyCreated = false; var moderate = false; Category category; var topic = new Topic(); using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Before we do anything DB wise, check it contains no bad links if (BannedLinkService.ContainsBannedLink(topicViewModel.TopicContent)) { ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.BannedLink"), MessageType = GenericMessages.Danger }); return(Redirect(Urls.GenerateUrl(Urls.UrlType.TopicCreate))); } // Not using automapper for this one only, as a topic is a post and topic in one category = CategoryService.Get(topicViewModel.Category); // First check this user is allowed to create topics in this category var permissions = PermissionService.GetPermissions(category, _membersGroup, MemberService, CategoryPermissionService); // Check this users role has permission to create a post if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked) { // Throw exception so Ajax caller picks it up ModelState.AddModelError(string.Empty, Lang("Errors.NoPermission")); } else { // We get the banned words here and pass them in, so its just one call // instead of calling it several times and each call getting all the words back topic = new Topic { Name = BannedWordService.SanitiseBannedWords(topicViewModel.TopicName, Dialogue.Settings().BannedWords), Category = category, CategoryId = category.Id, Member = CurrentMember, MemberId = CurrentMember.Id }; // See if the user has actually added some content to the topic if (!string.IsNullOrEmpty(topicViewModel.TopicContent)) { // Check for any banned words topicViewModel.TopicContent = BannedWordService.SanitiseBannedWords(topicViewModel.TopicContent, Dialogue.Settings().BannedWords); // See if this is a poll and add it to the topic if (topicViewModel.PollAnswers != null && topicViewModel.PollAnswers.Any(x => !string.IsNullOrEmpty(x.Answer))) { // Do they have permission to create a new poll if (permissions[AppConstants.PermissionCreatePolls].IsTicked) { // Create a new Poll var newPoll = new Poll { Member = CurrentMember, MemberId = CurrentMember.Id }; // Create the poll PollService.Add(newPoll); // Save the poll in the context so we can add answers unitOfWork.SaveChanges(); // Now sort the answers var newPollAnswers = new List <PollAnswer>(); foreach (var pollAnswer in topicViewModel.PollAnswers) { // Attach newly created poll to each answer pollAnswer.Poll = newPoll; PollService.Add(pollAnswer); newPollAnswers.Add(pollAnswer); } // Attach answers to poll newPoll.PollAnswers = newPollAnswers; // Save the new answers in the context unitOfWork.SaveChanges(); // Add the poll to the topic topic.Poll = newPoll; } else { //No permission to create a Poll so show a message but create the topic ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.NoPermissionPolls"), MessageType = GenericMessages.Info }); } } // Check for moderation if (category.ModerateAllTopicsInThisCategory) { topic.Pending = true; moderate = true; } // Create the topic topic = TopicService.Add(topic); // Save the changes unitOfWork.SaveChanges(); // Now create and add the post to the topic TopicService.AddLastPost(topic, topicViewModel.TopicContent, PostService); // Update the users points score for posting MemberPointsService.Add(new MemberPoints { Points = Settings.PointsAddedPerNewPost, Member = CurrentMember, MemberId = CurrentMember.Id, RelatedPostId = topic.LastPost.Id }); // Now check its not spam var akismetHelper = new AkismetHelper(); if (akismetHelper.IsSpam(topic)) { // Could be spam, mark as pending topic.Pending = true; } // Subscribe the user to the topic as they have checked the checkbox if (topicViewModel.SubscribeToTopic) { // Create the notification var topicNotification = new TopicNotification { Topic = topic, Member = CurrentMember, MemberId = CurrentMember.Id }; //save TopicNotificationService.Add(topicNotification); } try { unitOfWork.Commit(); if (!moderate) { successfullyCreated = true; } // Update the users post count MemberService.AddPostCount(CurrentMember); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); ModelState.AddModelError(string.Empty, Lang("Errors.GenericMessage")); } } else { ModelState.AddModelError(string.Empty, Lang("Errors.GenericMessage")); } } } using (UnitOfWorkManager.NewUnitOfWork()) { if (successfullyCreated) { // Success so now send the emails NotifyNewTopics(category); // Redirect to the newly created topic return(Redirect($"{topic.Url}?postbadges=true")); } if (moderate) { // Moderation needed // Tell the user the topic is awaiting moderation return(MessageToHomePage(Lang("Moderate.AwaitingModeration"))); } } } ShowMessage(); return(Redirect(Urls.GenerateUrl(Urls.UrlType.TopicCreate))); }
public async Task <IActionResult> CreateTopic(CreateTopicViewModel model) { // Формируем модель подраздела Subsection subsection = await _websiteDB.Subsections.Include(s => s.Section).FirstOrDefaultAsync(s => s.Id == model.SubsectionId); ViewBag.SubsectionId = subsection.Id; ViewBag.SubsectionName = subsection.SubsectionName; // Проверяем, чтобы пользователь был авторизован if (User.Identity.IsAuthenticated) { // Проверка валидации модели if (ModelState.IsValid) { // Проверяем, чтобы такой существовал if (subsection != null) { // Формируем омдель авторизованного пользователя с его ролью User user = await _websiteDB.Users.Include(u => u.Role).FirstOrDefaultAsync(u => u.Name == User.Identity.Name); // Проверяем, чтобы уровень доступа пользователя был не ниже уровня раздела if (user != null && subsection.Section.SectionAccessLevel <= user.Role.AccessLevel) { // Создаем модель топика Topic topic = new Topic() { Id = Guid.NewGuid(), Subsection = subsection, TopicName = model.TopicName, TopicDate = DateTime.Now, Announcement = model.Announcement, User = user, Views = 0 }; // И модель первого в нём сообщения, которое и будет сообщением только что созданной темы Reply reply = new Reply() { Id = Guid.NewGuid(), ReplyBody = model.TopicBody, ReplyDate = DateTime.Now, User = user, Topic = topic }; // Добавляем всё в базу и сохраняем await _websiteDB.Topics.AddAsync(topic); await _websiteDB.Replies.AddAsync(reply); await _websiteDB.SaveChangesAsync(); // Редирект в только что созданную тему return(RedirectToAction("ViewTopic", "Forum", new { topicId = topic.Id })); } } // Ошибка 404, если подраздел не найден return(Redirect("/Main/PageNotFound")); } // Это должен быть возврат модели с ошибками. Пока не закончено!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return(View(model)); } // Если пользователь не авторизован, перенаправляем его на страницу авторизации return(RedirectToAction("Login", "Account")); }
public async Task <IActionResult> CreateTopic(CreateTopicViewModel viewModel) { var createdTopicEntry = await _topicService.CreateTopic(viewModel.Title, viewModel.Message); return(RedirectToActionPermanent("Index", new { topicId = createdTopicEntry.Entity.Id })); }
public async Task <IActionResult> UpdateTopic([FromRoute] string CID, [FromRoute] string MID, [FromRoute] string TID, [FromBody] CreateTopicViewModel model) { var result = await _MongocourseService.UpdateTopic(CID, MID, TID, model); if (result) { return(Ok(new { status = 1, Message = "Updated Successfully" })); } return(BadRequest(new { status = 0, Message = "Update Failed " })); }
// POST api/<controller> public void Post(CreateTopicViewModel createTopicView) { var createTopicDto = Mapper.Map <CreateTopicDto>(createTopicView); _topicService.CreateTopic(createTopicDto); }
public ActionResult Create(CreateTopicViewModel topicViewModel) { if (ModelState.IsValid) { // Quick check to see if user is locked out, when logged in if (CurrentMember.IsLockedOut || CurrentMember.DisablePosting == true || !CurrentMember.IsApproved) { ServiceFactory.MemberService.LogOff(); return(ErrorToHomePage("No Permission")); } var successfullyCreated = false; var moderate = false; Category category; var topic = new Topic(); using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Before we do anything DB wise, check it contains no bad links if (ServiceFactory.BannedLinkService.ContainsBannedLink(topicViewModel.TopicContent)) { ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.BannedLink"), MessageType = GenericMessages.Danger }); return(Redirect(Urls.GenerateUrl(Urls.UrlType.TopicCreate))); } // Not using automapper for this one only, as a topic is a post and topic in one category = ServiceFactory.CategoryService.Get(topicViewModel.Category); // First check this user is allowed to create topics in this category var permissions = ServiceFactory.PermissionService.GetPermissions(category, _membersGroups); // Check this users role has permission to create a post if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked) { // Throw exception so Ajax caller picks it up ModelState.AddModelError(string.Empty, "No Permission"); } else { // We get the banned words here and pass them in, so its just one call // instead of calling it several times and each call getting all the words back topic = new Topic { Name = ServiceFactory.BannedWordService.SanitiseBannedWords(topicViewModel.TopicName, Dialogue.Settings().BannedWords), Category = category, CategoryId = category.Id, Member = CurrentMember, MemberId = CurrentMember.Id }; // See if the user has actually added some content to the topic if (!string.IsNullOrEmpty(topicViewModel.TopicContent)) { // Check for any banned words topicViewModel.TopicContent = ServiceFactory.BannedWordService.SanitiseBannedWords(topicViewModel.TopicContent, Dialogue.Settings().BannedWords); // See if this is a poll and add it to the topic if (topicViewModel.PollAnswers != null && topicViewModel.PollAnswers.Count > 0) { // Do they have permission to create a new poll if (permissions[AppConstants.PermissionCreatePolls].IsTicked) { // Create a new Poll var newPoll = new Poll { Member = CurrentMember, MemberId = CurrentMember.Id }; // Create the poll ServiceFactory.PollService.Add(newPoll); // Save the poll in the context so we can add answers unitOfWork.SaveChanges(); // Now sort the answers var newPollAnswers = new List <PollAnswer>(); foreach (var pollAnswer in topicViewModel.PollAnswers) { // Attach newly created poll to each answer pollAnswer.Poll = newPoll; ServiceFactory.PollService.Add(pollAnswer); newPollAnswers.Add(pollAnswer); } // Attach answers to poll newPoll.PollAnswers = newPollAnswers; // Save the new answers in the context unitOfWork.SaveChanges(); // Add the poll to the topic topic.Poll = newPoll; } else { //No permission to create a Poll so show a message but create the topic ShowMessage(new GenericMessageViewModel { Message = Lang("No PermissionPolls"), MessageType = GenericMessages.Info }); } } //get user post count > 5 var currentMemberPostCount = ServiceFactory.PostService.GetByMember(CurrentMember.Id).Count(); if (CurrentMember.Badges == null) { CurrentMember.Badges = ServiceFactory.BadgeService.GetallMembersBadges(CurrentMember.Id); } var hasBadge = CurrentMember.Badges != null && CurrentMember.Badges.Any(x => x.Name == "UserFivePost"); // Check for moderation if (category.ModerateAllTopicsInThisCategory || (currentMemberPostCount < 5 && !hasBadge)) { NotifyCategoryAdmin(topic); topic.Pending = true; moderate = true; } // Create the topic topic = ServiceFactory.TopicService.Add(topic); // Save the changes unitOfWork.SaveChanges(); // Now create and add the post to the topic ServiceFactory.TopicService.AddLastPost(topic, topicViewModel.TopicContent); // Update the users points score for posting ServiceFactory.MemberPointsService.Add(new MemberPoints { Points = Settings.PointsAddedPerNewPost, Member = CurrentMember, MemberId = CurrentMember.Id, RelatedPostId = topic.LastPost.Id }); // Now check its not spam var akismetHelper = new AkismetHelper(); if (akismetHelper.IsSpam(topic)) { // Could be spam, mark as pending topic.Pending = true; } // Subscribe the user to the topic as they have checked the checkbox if (topicViewModel.SubscribeToTopic) { // Create the notification var topicNotification = new TopicNotification { Topic = topic, Member = CurrentMember, MemberId = CurrentMember.Id }; //save ServiceFactory.TopicNotificationService.Add(topicNotification); } try { unitOfWork.Commit(); if (!moderate) { successfullyCreated = true; } // Update the users post count ServiceFactory.MemberService.AddPostCount(CurrentMember); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); ModelState.AddModelError(string.Empty, "Something went wrong. Please try again"); } } else { ModelState.AddModelError(string.Empty, "Please enter some content"); } } } using (UnitOfWorkManager.NewUnitOfWork()) { if (successfullyCreated) { //TODO: programtically add topic guid to page forum tab properties if (topicViewModel.PageId > 0) { var nodeId = topicViewModel.PageId; var node = ApplicationContext.Services.ContentService.GetPublishedVersion(nodeId); if (node != null) { var topicPickerValue = node.GetValue("topicPicker"); if (topicPickerValue != null) { var documentTopics = Newtonsoft.Json.JsonConvert.DeserializeObject <string[]>(topicPickerValue.ToString()).ToList(); documentTopics.Add(topic.Id.ToString()); string[] newTopics = documentTopics.Select(x => x).ToArray(); string topicsJson = Newtonsoft.Json.JsonConvert.SerializeObject(newTopics); node.SetValue("topicPicker", topicsJson); ApplicationContext.Services.ContentService.Save(node); ApplicationContext.Services.ContentService.Publish(node); } } } // Success so now send the emails NotifyNewTopics(category); // Redirect to the newly created topic return(Redirect(string.Format("{0}?postbadges=true", topic.Url))); } if (moderate) { // Moderation needed // Tell the user the topic is awaiting moderation ShowMessage(new GenericMessageViewModel { Message = Lang("Awaiting Moderation"), MessageType = GenericMessages.Warning }); return(Redirect(category.Url)); //return MessageToHomePage("Awaiting Moderation"); } } } ShowModelErrors(); return(Redirect(Urls.GenerateUrl(Urls.UrlType.TopicCreate))); }