public ActionResult Create(TopicModel model)
        {
            if (model.UploadImage != null)
            {
                string filePath = System.IO.Path.GetFileName(model.UploadImage.FileName);

                model.UploadImage.SaveAs(Server.MapPath("~/Images/Topics/" + filePath));
                model.ImageName = filePath;
            }

            else
            {
                return(View(model));
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var modelBL = _mapper.Map <TopicBL>(model);

            _service.Create(modelBL);

            return(RedirectToAction("Index"));
        }
Esempio n. 2
0
        public ActionResult Create(TopicCreateModel model)
        {
            bool ok = true;

            if (ModelState.IsValid)
            {
                TopicCreateDTO topicDTO = Mapper.Map <TopicCreateModel, TopicCreateDTO>(model);

                ServiceMessage serviceMessage = service.Create(topicDTO);
                if (!serviceMessage.Succeeded)
                {
                    foreach (string error in serviceMessage.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                    ok = false;
                }
            }
            else
            {
                ok = false;
            }

            return(ok ? RedirectToAction("List") as ActionResult : View(model));
        }
Esempio n. 3
0
        public IActionResult Create([FromBody] CreateTopicModel model)
        {
            try
            {
                using (var wb = new WebClient())
                {
                    var data = new NameValueCollection();
                    data["secret"]   = _secretService.GetSecret("recaptcha-secret");
                    data["response"] = model.Token;

                    var response    = wb.UploadValues(_secretService.GetSecret("recaptcha-verify-url"), "POST", data);
                    var responseObj = JsonSerializer.Deserialize <RecaptchaResponseModel>(response);
                    if (responseObj.success)
                    {
                        var topic         = _topicService.Create(model, int.Parse(User.Identity.Name));
                        var topicResource = _mapper.Map <TopicResourceModel>(topic);
                        return(Ok(topicResource));
                    }
                    return(BadRequest(new { message = "Recaptcha verification failed" }));
                }
            }
            catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Esempio n. 4
0
        public IActionResult Create([FromBody] TopicDto topicDto)
        {
            // map dto to entity and set id
            Topic c = _mapper.Map <Topic>(topicDto);

            try
            {
                // save
                c = _topicService.Create(c);
                return(Ok(_mapper.Map <TopicDto>(c)));
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 5
0
        public void PagingWithAnnouncementsAndStickies()
        {
            ICategoryService categoryService = Initializer.CategoryService;
            IForumService    forumService    = Initializer.ForumService;
            ITopicService    topicService    = Initializer.TopicService;
            IUIService       uiService       = Initializer.UIService;

            Category category = categoryService.Create("category", 1, String.Empty);
            Forum    forum    = forumService.Create(category.Id, "forum", 1, String.Empty);

            Topic announcement1 = topicService.Create(forum.Id, "announcement", "bla", TopicType.Announcement);
            Topic announcement2 = topicService.Create(forum.Id, "announcement", "bla", TopicType.Announcement);
            Topic announcement3 = topicService.Create(forum.Id, "announcement", "bla", TopicType.Announcement);

            Topic sticky1 = topicService.Create(forum.Id, "sticky", "bla", TopicType.Sticky);
            Topic sticky2 = topicService.Create(forum.Id, "sticky", "bla", TopicType.Sticky);
            Topic sticky3 = topicService.Create(forum.Id, "sticky", "bla", TopicType.Sticky);

            Topic regular1 = topicService.Create(forum.Id, "regular", "bla");
            Topic regular2 = topicService.Create(forum.Id, "regular", "bla");

            IEnumerable <Topic> topics = uiService.FindTopicsByForum(forum.Id, 0, 5, true);

            topics.Count().Should().Be(6, "we should get the request +1 because more topics than will fit on one page");
            topics.First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(1).First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(2).First().Type.Should().Be(TopicType.Announcement);

            topics.Skip(3).First().Type.Should().Be(TopicType.Sticky);
            topics.Skip(4).First().Type.Should().Be(TopicType.Sticky);
            // We're not testing the last one, it should never be shown, it's just a "marker" to indicate that more exists (next page)

            topics = uiService.FindTopicsByForum(forum.Id, 1, 5, true);
            topics.Count().Should().Be(6, "we should get the 3 announcements and 1 sticky and 1 regular from the 2nd page (we have 8 in all, and 5 per page) and plus 1 to indicate \"more\" pages");
            topics.First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(1).First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(2).First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(3).First().Type.Should().Be(TopicType.Sticky);
            topics.Skip(4).First().Type.Should().Be(TopicType.Regular);

            topics = uiService.FindTopicsByForum(forum.Id, 2, 5, true);
            topics.Count().Should().Be(4, "we should get the 3 announcements and 1 regular from the 3nd page (we have 8 in all, and 5 per page)");
            topics.First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(1).First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(2).First().Type.Should().Be(TopicType.Announcement);
            topics.Skip(3).First().Type.Should().Be(TopicType.Regular);
        }
Esempio n. 6
0
        public ActionResult Create(TopicCreateViewModel topicCreateViewModel)
        {
            User currentUser = userService.GetByUsername(User.Identity.Name);

            Topic topic = new Topic(
                topicCreateViewModel.Name,
                topicCreateViewModel.Description,
                ParseLabels(topicCreateViewModel.Labels),
                currentUser
                );

            Topic created = topicService.Create(topic);

            return(RedirectToAction("Index"));
        }
Esempio n. 7
0
        public void TypeSortOrder()
        {
            ICategoryService categoryService = Initializer.CategoryService;
            IForumService    forumService    = Initializer.ForumService;
            ITopicService    topicService    = Initializer.TopicService;
            IUIService       uiService       = Initializer.UIService;

            Category category = categoryService.Create("category", 1, String.Empty);
            Forum    forum    = forumService.Create(category.Id, "forum", 1, String.Empty);

            String stickySubject       = "I'm sticky";
            Topic  sticky              = topicService.Create(forum.Id, stickySubject, "bla", TopicType.Sticky);
            String announcementSubject = "I'm announcement";
            Topic  announcement        = topicService.Create(forum.Id, announcementSubject, "bla", TopicType.Announcement);
            String regularSubject      = "I'm regular";
            Topic  regular             = topicService.Create(forum.Id, regularSubject, "bla");

            IEnumerable <Topic> topics = uiService.FindTopicsByForum(forum.Id, 0, 20);

            topics.Count().Should().Be(3, "3 topics were created");
            topics.First().Type.Should().Be(TopicType.Announcement, "Announcements should always be first");
            topics.Skip(1).First().Type.Should().Be(TopicType.Sticky, "Stickies should always be second");
            topics.Last().Type.Should().Be(TopicType.Regular, "Regulars should always be last");
        }
Esempio n. 8
0
        public void CreateNewTopicWithException()
        {
            ICategoryService categoryService = Initializer.CategoryService;
            IForumService    forumService    = Initializer.ForumService;
            ITopicService    topicService    = Initializer.TopicService;

            Category category = categoryService.Create("category", 1, String.Empty);
            Forum    forum    = forumService.Create(category.Id, "forum", 1, String.Empty);

            String subject = String.Empty;
            String text    = "The text";
            Action action  = () => topicService.Create(forum.Id, subject, text);

            action.ShouldThrow <ArgumentNullException>();
        }
Esempio n. 9
0
 public ActionResult Create(Topic topic, Guid categoryId, HttpPostedFileBase upload)
 {
     if (upload != null)
     {
         string UploadPath = "~/Images/";
         string fileName   = string.Concat(DateTime.Now.ToString().GetHashCode(), upload.FileName);
         var    imagePath  = Path.Combine(Server.MapPath(UploadPath), fileName);
         var    imageUrl   = Path.Combine(UploadPath, fileName);
         upload.SaveAs(imagePath);
         topic.Image = fileName;
     }
     topic.CreatedDate = DateTime.Now;
     topic.CategoryId  = categoryId;
     _topicService.Create(topic);
     return(RedirectToAction("Index"));
 }
Esempio n. 10
0
        public async Task <ActionResult> Create(AddTopicViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await topicService.Create(model.ForumId, model.Name, model.Text, User.Identity.Name);

                if (result.Succedeed)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError("", result.Message);
                }
            }

            return(View(model));
        }
Esempio n. 11
0
        /// <summary>
        /// Asks the service to create a new topic, using the supplied information.
        /// </summary>
        /// <param name="data">
        /// The supplied POST-data used to create a new topic.
        /// </param>
        /// <returns>
        /// HTTP Status Code 201 - Created + Unique link to newly created topic,
        ///     HTTP Status Code 400 - Bad Request if no ID was returned, or the supplied POST-data failed validation. Also contains information on failed validation cases.
        ///     HTTP Status Code 409 - Conflict if a topic with a provided unique value already exists,
        ///     HTTP Status Code 500 - Internal Server Error if the other codes don't apply. Contains exception on DEBUG.
        /// </returns>
        public IHttpActionResult Post(Topic data)
        {
            var result = _topicService.Create(data);

            switch (result.ActionStatus.Status)
            {
            case ActionStatusEnum.Success:
                return(CreateHttpActionResult("Topic", result.ActionStatus.Id));

            case ActionStatusEnum.ValidationError:
                return(ApiControllerExtension.BadRequest(this, result.BrokenValidationRules, data.GetType().Name));

            case ActionStatusEnum.Conflict:
                return(Conflict());
            }

            return(HandleErrorActionResult(result));
        }
Esempio n. 12
0
        public void CreateNewTopic()
        {
            ICategoryService categoryService = Initializer.CategoryService;
            IForumService    forumService    = Initializer.ForumService;
            ITopicService    topicService    = Initializer.TopicService;

            Category category = categoryService.Create("category", 1, String.Empty);
            Forum    forum    = forumService.Create(category.Id, "forum", 1, String.Empty);

            String subject = "The first subject";
            String text    = "The text";

            Topic topic = topicService.Create(forum.Id, subject, text);

            topic.Subject.Should().Be(subject);
            topic.Text.Should().Be(text);
            topic.Type.Should().Be(TopicType.Regular);
            topic.State.Should().Be(TopicState.None);
        }
Esempio n. 13
0
        public void PageCountTest()
        {
            ICategoryService categoryService = Initializer.CategoryService;
            IForumService    forumService    = Initializer.ForumService;
            ITopicService    topicService    = Initializer.TopicService;
            IUIService       uiService       = Initializer.UIService;

            Category category = categoryService.Create("category", 1, String.Empty);
            Forum    forum    = forumService.Create(category.Id, "forum", 1, String.Empty);

            Topic announcement1 = topicService.Create(forum.Id, "announcement", "bla", TopicType.Announcement);

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(1);
            Topic announcement2 = topicService.Create(forum.Id, "announcement", "bla", TopicType.Announcement);

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(1);
            Topic announcement3 = topicService.Create(forum.Id, "announcement", "bla", TopicType.Announcement);

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(1);

            Topic sticky1 = topicService.Create(forum.Id, "sticky", "bla", TopicType.Sticky);

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(1);
            Topic sticky2 = topicService.Create(forum.Id, "sticky", "bla", TopicType.Sticky);

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(1);
            Topic sticky3 = topicService.Create(forum.Id, "sticky", "bla", TopicType.Sticky);

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(2);

            Topic regular1 = topicService.Create(forum.Id, "regular", "bla");

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(2);
            Topic regular2 = topicService.Create(forum.Id, "regular", "bla");

            uiService.GetNumberOfForumPages(forum.Id, 5).Should().Be(3);
        }
Esempio n. 14
0
        public virtual async Task <ActionResult> Create(CreateEditTopicViewModel topicViewModel)
        {
            // Get the user and roles
            var loggedOnUser      = User.GetMembershipUser(MembershipService, false);
            var loggedOnUsersRole = loggedOnUser.GetRole(RoleService);

            // Get the category
            var category = _categoryService.Get(topicViewModel.Category);

            // First check this user is allowed to create topics in this category
            var permissions = RoleService.GetPermissions(category, loggedOnUsersRole);

            // Now we have the category and permissionSet - Populate the optional permissions
            // This is just in case the viewModel is return back to the view also sort the allowedCategories
            topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            topicViewModel.Categories          =
                _categoryService.GetBaseSelectListCategories(AllowedCreateCategories(loggedOnUsersRole));
            topicViewModel.IsTopicStarter = true;
            if (topicViewModel.PollAnswers == null)
            {
                topicViewModel.PollAnswers = new List <PollAnswer>();
            }

            if (ModelState.IsValid)
            {
                // See if the user has actually added some content to the topic
                if (string.IsNullOrWhiteSpace(topicViewModel.Content))
                {
                    ModelState.AddModelError(string.Empty,
                                             LocalizationService.GetResourceString("Errors.GenericMessage"));
                }
                else
                {
                    // Map the new topic (Pass null for new topic)
                    var topic = topicViewModel.ToTopic(category, loggedOnUser, null);

                    // Run the create pipeline
                    var createPipeLine = await _topicService.Create(topic, topicViewModel.Files, topicViewModel.Tags,
                                                                    topicViewModel.SubscribeToTopic, topicViewModel.Content, null);

                    if (createPipeLine.Successful == false)
                    {
                        // TODO - Not sure on this?
                        // Remove the topic if unsuccessful, as we may have saved some items.
                        await _topicService.Delete(createPipeLine.EntityToProcess);

                        // Tell the user the topic is awaiting moderation
                        ModelState.AddModelError(string.Empty, createPipeLine.ProcessLog.FirstOrDefault());
                        return(View(topicViewModel));
                    }

                    if (createPipeLine.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate))
                    {
                        var moderate = createPipeLine.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?;
                        if (moderate == true)
                        {
                            // Tell the user the topic is awaiting moderation
                            TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Moderate.AwaitingModeration"),
                                MessageType = GenericMessages.info
                            };

                            var settings = SettingsService.GetSettings();
                            var sb       = new StringBuilder();
                            sb.Append($"<p>{string.Concat("New Topic is pending approval.")}</p>");
                            var email = new Email
                            {
                                EmailTo = settings.AdminEmailAddress,
                                NameTo  = "Dear Admin",
                                Subject = string.Concat("New Topic is pending approval")
                            };
                            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                            _emailService.SendMail(email);
                            try
                            {
                                Context.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                Context.RollBack();
                                LoggingService.Error(ex);
                            }
                        }
                    }

                    // Redirect to the newly created topic
                    return(Redirect($"{topic.NiceUrl}?postbadges=true"));
                }
            }

            return(View(topicViewModel));
        }
Esempio n. 15
0
 public ActionResult <Topic> Post([FromBody] Topic topic)
 {
     return(_topService.Create(topic));
 }
Esempio n. 16
0
        /// <inheritdoc />
        public async Task <IPipelineProcess <Post> > Process(IPipelineProcess <Post> input, IMvcForumContext context)
        {
            _localizationService.RefreshContext(context);
            _topicService.RefreshContext(context);
            _postService.RefreshContext(context);
            try
            {
                // Do we have a topic title in the extended data
                var newTopicTitle = string.Empty;
                if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Name))
                {
                    newTopicTitle = input.ExtendedData[Constants.ExtendedDataKeys.Name] as string;
                }

                // Do we have a topic id in the extended data
                Guid?newTopicId = null;
                if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.TopicId))
                {
                    newTopicId = input.ExtendedData[Constants.ExtendedDataKeys.TopicId] as Guid?;
                }

                // Flag whether we should also move any reply to posts
                var moveReplayPosts = input.ExtendedData[Constants.ExtendedDataKeys.MovePosts] as bool?;

                // Hold the previous topic
                var previousTopic = input.EntityToProcess.Topic;

                // Hold the previous category
                var category = input.EntityToProcess.Topic.Category;

                // Hold the post creator
                var postCreator = input.EntityToProcess.User;

                // Hold the topic
                Topic topic;

                // If the dropdown has a value, then we choose that first
                if (newTopicId != null)
                {
                    // Get the selected topic
                    topic = _topicService.Get(newTopicId.Value);
                }
                else if (!string.IsNullOrWhiteSpace(newTopicTitle))
                {
                    // If we get here, we use the topic create pipeline!!
                    // Create the topic
                    topic = new Topic
                    {
                        Name     = newTopicTitle,
                        Category = category,
                        User     = postCreator
                    };

                    // Run the create pipeline
                    var createPipeLine = await _topicService.Create(topic, null, string.Empty, true, input.EntityToProcess.PostContent, null);

                    if (createPipeLine.Successful == false)
                    {
                        // Tell the user the topic is awaiting moderation
                        input.AddError(createPipeLine.ProcessLog.FirstOrDefault());
                        return(input);
                    }

                    // Set the post to be a topic starter
                    input.EntityToProcess.IsTopicStarter = true;

                    // Save the changes
                    await context.SaveChangesAsync();

                    // Set the topic
                    topic = createPipeLine.EntityToProcess;
                }
                else
                {
                    // No selected topic OR topic title, just redirect back to the topic
                    return(input);
                }

                // Now update the post to the new topic
                input.EntityToProcess.Topic = topic;

                // Also move any posts, which were in reply to this post
                if (moveReplayPosts == true)
                {
                    var relatedPosts = _postService.GetReplyToPosts(input.EntityToProcess.Id);
                    foreach (var relatedPost in relatedPosts)
                    {
                        relatedPost.Topic = topic;
                    }
                }

                var saveChanges = await context.SaveChangesAsync();

                if (saveChanges <= 0)
                {
                    // Nothing was saved so throw error message
                    input.AddError(_localizationService.GetResourceString("Errors.GenericMessage"));
                    return(input);
                }

                // Update Last post..  As we have done a save, we should get all posts including the added ones
                var lastPost = topic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();
                topic.LastPost = lastPost;

                // If any of the posts we are moving, were the last post - We need to update the old Topic
                var previousTopicLastPost =
                    previousTopic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();
                previousTopic.LastPost = previousTopicLastPost;

                // Do a final save
                saveChanges = await context.SaveChangesAsync();

                if (saveChanges <= 0)
                {
                    // Nothing was saved so throw error message
                    input.AddError(_localizationService.GetResourceString("Errors.GenericMessage"));
                    return(input);
                }
            }
            catch (Exception ex)
            {
                input.AddError(ex.Message);
                _loggingService.Error(ex);
            }
            return(input);
        }
Esempio n. 17
0
 public JsonResult Post([FromBody] Topic obj)
 {
     return(Json(_TopicService.Create(obj)));
 }