Esempio n. 1
0
        //[ProducesResponseType(typeof(TopicDto), StatusCodes.Status200OK)]
        public IActionResult AddTopic(TopicDto topicDto)
        {
            try
            {
                var topicDtos = _topicService.Add(topicDto);
                if (topicDtos)
                {
                    SuccessModel.SuccessCode    = "200";
                    SuccessModel.SuccessMessage = "Success";
                    return(Ok(SuccessModel));
                }
                else
                {
                    ErrorModel.ErrorCode    = "400";
                    ErrorModel.ErrorMessage = "Add Fail";
                    return(BadRequest(ErrorModel));
                }
            }
            catch (Exception ex)
            {
                ErrorModel.ErrorMessage = ex.Message;
                ErrorModel.ErrorCode    = "500";

                return(StatusCode(500, ErrorModel));
            }
        }
        public IHttpActionResult CreateTopic(CreateTopicDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (_topicService.FindByTitle(model.Title) != null)
            {
                return(BadRequest("Topic already exists"));
            }
            if (_userService.Get(model.ModeratingUserId) == null)
            {
                return(BadRequest("User not found."));
            }

            var topic = _topicService.Add(new Topic {
                Id               = Guid.NewGuid(),
                Title            = model.Title,
                Description      = model.Description,
                ModeratingUserId = model.ModeratingUserId,
                CreateDateTime   = DateTime.Now
            });

            return(Ok(Mapper.Map <BasicTopicDto>(topic)));
        }
Esempio n. 3
0
        public IHttpActionResult CreateWarTopic(string name, string warName, string warDetails)
        {
            var catId    = new Guid("B021A3BE-02C9-46B6-BCC8-A53900AB0A6A");
            var category = _categoryService.Get(catId);

            using (var unitOfWork = _unitOfWorkManager.NewUnitOfWork())
            {
                // Create the topic model
                var topic = new Topic
                {
                    Name     = warName,
                    Category = category,
                    User     = _membershipService.GetUser("Clyde en Marland")
                };

                // Create the topic
                topic = _topicService.Add(topic);

                // Save the changes
                unitOfWork.SaveChanges();

                // Now create and add the post to the topic
                var topicPost = _topicService.AddLastPost(topic, warDetails);
                // Save the changes
                unitOfWork.SaveChanges();
                unitOfWork.Commit();
            }
            return(Ok());
        }
        public ActionResult Create([FromBody] ExampleTopic model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.Status = TopicStatus.Draft;
                    model.Author = ExampleContext.Current.User;
                    var topicId = _topicService.Add(model);
                    if (topicId != null)
                    {
                        return(RedirectToAction("Edit", "Topic", new { id = topicId.Value }));
                    }

                    ModelState.AddModelError("SectionId", "SectionId is not valid");
                }
                catch (Exception exception)
                {
                    ExampleContext.Log.Error("TopicController.Create", exception);
                    ModelState.AddModelError(string.Empty, "Unexpected error. Try again.");
                }
            }

            return(View(model));
        }
Esempio n. 5
0
        public async Task <IActionResult> Create(NewTopicModel model)
        {
            if (ModelState.IsValid)
            {
                var userId = _userManager.GetUserId(User);
                var user   = await _userManager.FindByIdAsync(userId);

                var topic = new Topic
                {
                    Title = model.Title,
                    Forum = _forumService.GetById(model.ForumId)
                };
                var post = new Post
                {
                    Content = model.Content,
                    Created = DateTime.Now,
                    User    = user,
                    Topic   = topic,
                    IsHead  = true
                };

                await _topicService.Add(topic);

                await _postService.Add(post);

                return(RedirectToAction("Topics", "Forum", new { id = model.ForumId }));
            }
            return(View(model));
        }
Esempio n. 6
0
 public ActionResult Create(TopicViewModel topicViewModel)
 {
     if (ModelState.IsValid)
     {
         var topicModel = _mapper.Map <TopicModel>(topicViewModel);
         _topicService.Add(topicModel);
         return(RedirectToAction("Index"));
     }
     return(View());
 }
Esempio n. 7
0
        public IActionResult Add(Topic topic)
        {
            var result = _topicService.Add(topic);

            if (result.Success)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
Esempio n. 8
0
        public IActionResult AddTopic([FromBody] Topic param)
        {
            param.Id       = ObjectId.GenerateNewId().ToString();
            param.IsActive = true;
            var temp = _topicService.Add(param);

            if (temp != null)
            {
                return(Ok(param));
            }
            return(NoContent());
        }
Esempio n. 9
0
        public IActionResult Create([FromBody] TopicDTO topic)
        {
            if (ModelState.IsValid)
            {
                topic.CreateOn = DateTime.Now;
                topicService.Add(topic);

                return(Ok());
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Esempio n. 10
0
        public IHttpActionResult CreateTopic(int idUser, string name, string desc)
        {
            TopicDTO topic = new TopicDTO
            {
                Name        = name,
                Description = desc,
                Creator     = userService.GetById(idUser),
                OpenDate    = DateTime.Now,
                Messages    = new List <MessageDTO>(),
                Complaints  = new List <ComplaintDTO>(),
                Subscribers = new List <UserDTO>(),
                IsClosed    = false,
                IsDeleted   = false
            };

            topicService.Add(topic);
            return(Ok(topic));
        }
Esempio n. 11
0
 public Task <IResultModel> Add(TopicAddModel model)
 {
     return(_service.Add(model));
 }
Esempio n. 12
0
        public ActionResult MovePost(MovePostViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Firstly check if this is a post and they are allowed to move it
                var post = _postService.Get(viewModel.PostId);
                if (post == null)
                {
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
                }

                var permissions       = RoleService.GetPermissions(post.Topic.Category, UsersRole);
                var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

                // Does the user have permission to this posts category
                var cat = allowedCategories.FirstOrDefault(x => x.Id == post.Topic.Category.Id);
                if (cat == null)
                {
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
                }

                // Does this user have permission to move
                if (!permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                {
                    return(NoPermission(post.Topic));
                }

                var previousTopic = post.Topic;
                var category      = post.Topic.Category;
                var postCreator   = post.User;

                Topic topic;
                var   cancelledByEvent = false;
                // If the dropdown has a value, then we choose that first
                if (viewModel.TopicId != null)
                {
                    // Get the selected topic
                    topic = _topicService.Get((Guid)viewModel.TopicId);
                }
                else if (!string.IsNullOrEmpty(viewModel.TopicTitle))
                {
                    // 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();
                    }

                    // Create the topic
                    topic = new Topic
                    {
                        Name     = _bannedWordService.SanitiseBannedWords(viewModel.TopicTitle, bannedWords),
                        Category = category,
                        User     = postCreator
                    };

                    // Create the topic
                    topic = _topicService.Add(topic);

                    // Save the changes
                    unitOfWork.SaveChanges();

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

                    // Check the Events
                    var e = new TopicMadeEventArgs {
                        Topic = topic
                    };
                    EventManager.Instance.FireBeforeTopicMade(this, e);
                    if (e.Cancel)
                    {
                        cancelledByEvent = true;
                        ShowMessage(new GenericMessageViewModel
                        {
                            MessageType = GenericMessages.warning, Message = LocalizationService.GetResourceString("Errors.GenericMessage")
                        });
                    }
                }
                else
                {
                    // No selected topic OR topic title, just redirect back to the topic
                    return(Redirect(post.Topic.NiceUrl));
                }

                // If this create was cancelled by an event then don't continue
                if (!cancelledByEvent)
                {
                    // Now update the post to the new topic
                    post.Topic = topic;

                    // Also move any posts, which were in reply to this post
                    if (viewModel.MoveReplyToPosts)
                    {
                        var relatedPosts = _postService.GetReplyToPosts(viewModel.PostId);
                        foreach (var relatedPost in relatedPosts)
                        {
                            relatedPost.Topic = topic;
                        }
                    }

                    unitOfWork.SaveChanges();

                    // 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;

                    try
                    {
                        unitOfWork.Commit();

                        EventManager.Instance.FireAfterTopicMade(this, new TopicMadeEventArgs {
                            Topic = topic
                        });

                        // On Update redirect to the topic
                        return(RedirectToAction("Show", "Topic", new { slug = topic.Slug }));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message     = ex.Message,
                            MessageType = GenericMessages.danger
                        });
                    }
                }

                // Repopulate the topics
                var topics = _topicService.GetAllSelectList(allowedCategories, 30);
                topics.Insert(0, new SelectListItem
                {
                    Text  = LocalizationService.GetResourceString("Topic.Choose"),
                    Value = ""
                });

                viewModel.LatestTopics     = topics;
                viewModel.Post             = ViewModelMapping.CreatePostViewModel(post, post.Votes.ToList(), permissions, post.Topic, LoggedOnReadOnlyUser, SettingsService.GetSettings(), post.Favourites.ToList());
                viewModel.Post.MinimalPost = true;
                viewModel.PostId           = post.Id;

                return(View(viewModel));
            }
        }
Esempio n. 13
0
        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")));
        }
Esempio n. 14
0
        public ActionResult Create(CreateEditTopicViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var cats = _categoryService.GetAllowedEditCategories(UsersRole);
                if (cats.Count > 0)
                {
                    if (ModelState.IsValid)
                    {
                        if (CheckCats(viewModel.Category, cats))
                        {
                            var topic = new Topic();
                            var post  = new Post();

                            topic.Name              = viewModel.Name;
                            topic.Category_Id       = viewModel.Category;
                            topic.IsLocked          = viewModel.IsLocked;
                            topic.IsSticky          = viewModel.IsSticky;
                            topic.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                            topic.Post_Id           = post.Id;

                            post.PostContent       = viewModel.Content;
                            post.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                            post.Topic_Id          = topic.Id;
                            post.IsTopicStarter    = true;

                            topic.ShotContent       = string.Concat(StringUtils.ReturnAmountWordsFromString(StringUtils.StripHtmlFromString(post.PostContent), 50), "....");
                            topic.isAutoShotContent = true;


                            // Sort image out first
                            if (viewModel.Files != null)
                            {
                                // Before we save anything, check the user already has an upload folder and if not create one
                                var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, topic.Id));
                                if (!Directory.Exists(uploadFolderPath))
                                {
                                    Directory.CreateDirectory(uploadFolderPath);
                                }

                                // Loop through each file and get the file info and save to the users folder and Db
                                var file = viewModel.Files[0];
                                if (file != null)
                                {
                                    // If successful then upload the file
                                    var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService, true);

                                    if (!uploadResult.UploadSuccessful)
                                    {
                                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                        {
                                            Message     = uploadResult.ErrorMessage,
                                            MessageType = GenericMessages.danger
                                        };
                                        return(View(viewModel));
                                    }

                                    // Save avatar to user
                                    topic.Image = uploadResult.UploadedFileName;
                                    //viewModel.Image = topic.Image;
                                }
                            }

                            try
                            {
                                _topicServic.Add(topic);
                                _postSevice.Add(post);


                                unitOfWork.Commit();

                                return(RedirectToAction("Edit", new { Id = topic.Id }));
                            }
                            catch (Exception ex)
                            {
                                LoggingService.Error(ex.Message);
                                unitOfWork.Rollback();
                            }
                        }
                        else
                        {
                            //viewModel.Category = null;
                            //No permission to create a Poll so show a message but create the topic
                            //TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                            //{
                            //    Message = LocalizationService.GetResourceString("Errors.NoPermissionCatergory"),
                            //    MessageType = GenericMessages.info
                            //};
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.CatergoryMessage"));
                        }
                    }
                    viewModel.Categories = _categoryService.GetBaseSelectListCategories(cats);
                    return(View(viewModel));
                }
                return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
            }
        }
Esempio n. 15
0
        public ActionResult Create(CreateEditTopicViewModel topicViewModel)
        {
            // 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, UsersRole);

            // 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
            var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

            topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            topicViewModel.Categories          = GetBaseSelectListCategories(allowedCategories);
            topicViewModel.IsTopicStarter      = true;
            if (topicViewModel.PollAnswers == null)
            {
                topicViewModel.PollAnswers = new List <PollAnswer>();
            }
            /*---- End Re-populate ViewModel ----*/

            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;
                var moderate            = false;
                var topic = new Topic();

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    // Check this users role has permission to create a post
                    if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked || !permissions[AppConstants.PermissionCreateTopics].IsTicked)
                    {
                        // Add a model error that the user has no permissions
                        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();
                        }

                        // Create the topic model
                        topic = new Topic
                        {
                            Name     = _bannedWordService.SanitiseBannedWords(topicViewModel.Name, bannedWords),
                            Category = category,
                            User     = LoggedOnUser
                        };

                        // Check Permissions for topic topions
                        if (permissions[AppConstants.PermissionLockTopics].IsTicked)
                        {
                            topic.IsLocked = topicViewModel.IsLocked;
                        }
                        if (permissions[AppConstants.PermissionCreateStickyTopics].IsTicked)
                        {
                            topic.IsSticky = topicViewModel.IsSticky;
                        }

                        // 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.Count > 0)
                            {
                                // Do they have permission to create a new poll
                                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
                            });

                            // Check for moderation
                            if (category.ModerateTopics == true)
                            {
                                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
                            var topicPost = _topicService.AddLastPost(topic, topicViewModel.Content);

                            // Now check its not spam
                            var akismetHelper = new AkismetHelper(SettingsService);
                            if (!akismetHelper.IsSpam(topic))
                            {
                                if (topicViewModel.Files != null)
                                {
                                    // Get the permissions for this category, and check they are allowed to update
                                    if (permissions[AppConstants.PermissionAttachFiles].IsTicked && LoggedOnUser.DisableFileUploads != true)
                                    {
                                        // woot! User has permission and all seems ok
                                        // Before we save anything, check the user already has an upload folder and if not create one
                                        var uploadFolderPath = Server.MapPath(string.Concat(SiteConstants.UploadFolderPath, LoggedOnUser.Id));
                                        if (!Directory.Exists(uploadFolderPath))
                                        {
                                            Directory.CreateDirectory(uploadFolderPath);
                                        }

                                        // Loop through each file and get the file info and save to the users folder and Db
                                        foreach (var file in topicViewModel.Files)
                                        {
                                            if (file != null)
                                            {
                                                // If successful then upload the file
                                                var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService);
                                                if (!uploadResult.UploadSuccessful)
                                                {
                                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                                    {
                                                        Message     = uploadResult.ErrorMessage,
                                                        MessageType = GenericMessages.danger
                                                    };
                                                    unitOfWork.Rollback();
                                                    return(View(topicViewModel));
                                                }

                                                // Add the filename to the database
                                                var uploadedFile = new UploadedFile
                                                {
                                                    Filename       = uploadResult.UploadedFileName,
                                                    Post           = topicPost,
                                                    MembershipUser = LoggedOnUser
                                                };
                                                _uploadedFileService.Add(uploadedFile);
                                            }
                                        }
                                    }
                                }

                                // 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();
                                    if (!moderate)
                                    {
                                        successfullyCreated = true;
                                    }
                                }
                                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)));
                    }
                    if (moderate)
                    {
                        // Moderation needed
                        // Tell the user the topic is awaiting moderation
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Moderate.AwaitingModeration"),
                            MessageType = GenericMessages.info
                        };

                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(View(topicViewModel));
        }
Esempio n. 16
0
        public ActionResult Create(CreateEditTopicViewModel viewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var cats = _categoryService.GetAllowedEditCategories(UsersRole);
                if (cats.Count > 0)
                {
                    if (ModelState.IsValid)
                    {
                        if (CheckCats(viewModel.Category, cats))
                        {
                            var topic = new Topic();
                            var post  = new Post();

                            topic.Name              = viewModel.Name;
                            topic.Category_Id       = viewModel.Category;
                            topic.IsLocked          = viewModel.IsLocked;
                            topic.IsSticky          = viewModel.IsSticky;
                            topic.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                            topic.Id = post.Id;

                            post.PostContent       = viewModel.Content;
                            post.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                            post.Topic_Id          = topic.Id;
                            post.IsTopicStarter    = true;



                            try
                            {
                                _topicServic.Add(topic);
                                _postSevice.Add(post);



                                unitOfWork.Commit();
                            }
                            catch (Exception ex)
                            {
                                LoggingService.Error(ex.Message);
                                unitOfWork.Rollback();
                            }
                        }
                        else
                        {
                            //viewModel.Category = null;
                            //No permission to create a Poll so show a message but create the topic
                            //TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                            //{
                            //    Message = LocalizationService.GetResourceString("Errors.NoPermissionCatergory"),
                            //    MessageType = GenericMessages.info
                            //};
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.CatergoryMessage"));
                        }
                    }
                    viewModel.Categories = _categoryService.GetBaseSelectListCategories(cats);
                    return(View(viewModel));
                }
                return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
            }
        }