public void Update(TopicNotification item)
 {
     // Check there's not an object with same identifier already in context
     if (_context.TopicNotification.Local.Select(x => x.Id == item.Id).Any())
     {
         throw new ApplicationException("Object already exists in context - you do not need to call Update. Save occurs on Commit");
     }
     _context.Entry(item).State = EntityState.Modified;
 }
        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)));
        }
 public void Delete(TopicNotification item)
 {
     _context.TopicNotification.Remove(item);
 }
Example #4
0
 /// <summary>
 /// Delete topic notification
 /// </summary>
 /// <param name="notification"></param>
 public void Delete(TopicNotification notification)
 {
     _topicNotificationRepository.Delete(notification);
 }
Example #5
0
 /// <summary>
 /// Add a new topic notification
 /// </summary>
 /// <param name="topicNotification"></param>
 public void Add(TopicNotification topicNotification)
 {
     _topicNotificationRepository.Add(topicNotification);
 }
Example #6
0
        public void Subscribe(SubscribeEmailViewModel subscription)
        {
            if (Request.IsAjaxRequest())
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        // Add logic to add subscr
                        var isCategory = subscription.SubscriptionType.Contains("category");
                        var id         = subscription.Id;

                        if (isCategory)
                        {
                            // get the category
                            var cat = _categoryService.Get(id);

                            if (cat != null)
                            {
                                // Create the notification
                                var categoryNotification = new CategoryNotification
                                {
                                    Category = cat,
                                    User     = LoggedOnUser
                                };
                                //save

                                _categoryNotificationService.Add(categoryNotification);
                            }
                        }
                        else
                        {
                            // get the category
                            var topic = _topicService.Get(id);

                            // check its not null
                            if (topic != null)
                            {
                                // Create the notification
                                var topicNotification = new TopicNotification
                                {
                                    Topic = topic,
                                    User  = LoggedOnUser
                                };
                                //save

                                _topicNotificationService.Add(topicNotification);
                            }
                        }

                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
            }
            else
            {
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }
        }
Example #7
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
            topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            topicViewModel.Categories = _categoryService.GetBaseSelectListCategories(AllowedCreateCategories());
            topicViewModel.IsTopicStarter = true;
            if (topicViewModel.PollAnswers == null)
            {
                topicViewModel.PollAnswers = new List<PollAnswer>();
            }
            /*---- End Re-populate ViewModel ----*/

            if (ModelState.IsValid)
            {
                // Check posting flood control
                // Flood control test
                if (!_topicService.PassedTopicFloodTest(topicViewModel.Name, LoggedOnReadOnlyUser))
                {
                    // Failed test so don't post topic
                    return View(topicViewModel);
                }

                // Check stop words
                var stopWords = _bannedWordService.GetAll(true);
                foreach (var stopWord in stopWords)
                {
                    if (topicViewModel.Content.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                        topicViewModel.Name.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    {
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message = LocalizationService.GetResourceString("StopWord.Error"),
                            MessageType = GenericMessages.danger
                        });

                        // Ahhh found a stop word. Abandon operation captain.
                        return View(topicViewModel);
                    }
                }

                // Quick check to see if user is locked out, when logged in
                if (LoggedOnReadOnlyUser.IsLockedOut || LoggedOnReadOnlyUser.DisablePosting == true || !LoggedOnReadOnlyUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess"));
                }

                var successfullyCreated = false;
                var cancelledByEvent = 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[SiteConstants.Instance.PermissionDenyAccess].IsTicked || permissions[SiteConstants.Instance.PermissionReadOnly].IsTicked || !permissions[SiteConstants.Instance.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
                        var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id);
                        topic = new Topic
                        {
                            Name = _bannedWordService.SanitiseBannedWords(topicViewModel.Name, bannedWords),
                            Category = category,
                            User = loggedOnUser
                        };

                        // Check Permissions for topic topions
                        if (permissions[SiteConstants.Instance.PermissionLockTopics].IsTicked)
                        {
                            topic.IsLocked = topicViewModel.IsLocked;
                        }
                        if (permissions[SiteConstants.Instance.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);

                            var e = new TopicMadeEventArgs { Topic = topic };
                            EventManager.Instance.FireBeforeTopicMade(this, e);
                            if (!e.Cancel)
                            {

                                // See if this is a poll and add it to the topic
                                if (topicViewModel.PollAnswers.Count(x => x != null) > 1)
                                {
                                    // Do they have permission to create a new poll
                                    if (permissions[SiteConstants.Instance.PermissionCreatePolls].IsTicked)
                                    {
                                        // Create a new Poll
                                        var newPoll = new Poll
                                        {
                                            User = loggedOnUser,
                                            ClosePollAfterDays = topicViewModel.PollCloseAfterDays
                                        };

                                        // 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)
                                        {
                                            if (pollAnswer.Answer != null)
                                            {
                                                // 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
                                        };
                                    }
                                }

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

                                // Update the users points score for posting
                                _membershipUserPointsService.Add(new MembershipUserPoints
                                {
                                    Points = SettingsService.GetSettings().PointsAddedPerPost,
                                    User = loggedOnUser,
                                    PointsFor = PointsFor.Post,
                                    PointsForId = topicPost.Id
                                });

                                // Now check its not spam
                                var akismetHelper = new AkismetHelper(SettingsService);
                                if (akismetHelper.IsSpam(topic))
                                {
                                    topic.Pending = true;
                                    moderate = true;
                                }

                                if (topicViewModel.Files != null)
                                {
                                    // Get the permissions for this category, and check they are allowed to update
                                    if (permissions[SiteConstants.Instance.PermissionAttachFiles].IsTicked &&
                                        LoggedOnReadOnlyUser.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 =
                                            HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath,
                                                LoggedOnReadOnlyUser.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);
                                }

                                // After tags sort the search field for the post
                                topicPost.SearchField = _postService.SortSearchField(topicPost.IsTopicStarter, topic,
                                    topic.Tags);

                                // 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);
                                }
                            }
                            else
                            {
                                cancelledByEvent = true;
                            }

                            try
                            {
                                unitOfWork.Commit();
                                if (!moderate)
                                {
                                    successfullyCreated = true;
                                }

                                // Only fire this if the create topic wasn't cancelled
                                if (!cancelledByEvent)
                                {
                                    EventManager.Instance.FireAfterTopicMade(this, new TopicMadeEventArgs { Topic = topic });
                                }
                            }
                            catch (Exception ex)
                            {
                                unitOfWork.Rollback();
                                LoggingService.Error(ex);
                                ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                            }

                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                        }
                    }
                }

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    if (successfullyCreated && !cancelledByEvent)
                    {
                        // Success so now send the emails
                        NotifyNewTopics(category, topic, unitOfWork);

                        // Redirect to the newly created topic
                        return Redirect($"{topic.NiceUrl}?postbadges=true");
                    }
                    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);
        }
        public void Subscribe(SubscribeEmailViewModel subscription)
        {
            if (Request.IsAjaxRequest())
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        // Add logic to add subscr
                        var isCategory = subscription.SubscriptionType.Contains("category");
                        var id         = subscription.Id;

                        if (isCategory)
                        {
                            // get the category
                            var cat = CategoryService.Get(Convert.ToInt32(id));

                            if (cat != null)
                            {
                                // Create the notification
                                var categoryNotification = new CategoryNotification
                                {
                                    Category   = cat,
                                    CategoryId = cat.Id,
                                    Member     = CurrentMember,
                                    MemberId   = CurrentMember.Id
                                };
                                //save

                                CategoryNotificationService.Add(categoryNotification);
                            }
                        }
                        else
                        {
                            // get the category
                            var topic = TopicService.Get(new Guid(id));

                            // check its not null
                            if (topic != null)
                            {
                                // Create the notification
                                var topicNotification = new TopicNotification
                                {
                                    Topic    = topic,
                                    Member   = CurrentMember,
                                    MemberId = CurrentMember.Id
                                };
                                TopicNotificationService.Add(topicNotification);
                            }
                        }

                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LogError(ex);
                        throw new Exception(Lang("Errors.GenericMessage"));
                    }
                }
            }
            else
            {
                throw new Exception(Lang("Errors.GenericMessage"));
            }
        }
Example #9
0
        /// <inheritdoc />
        public async Task <IPipelineProcess <Topic> > Process(IPipelineProcess <Topic> input, IMvcForumContext context)
        {
            _notificationService.RefreshContext(context);
            _activityService.RefreshContext(context);
            _localizationService.RefreshContext(context);

            try
            {
                // Get the Current user from ExtendedData
                var username     = input.ExtendedData[Constants.ExtendedDataKeys.Username] as string;
                var loggedOnUser = await context.MembershipUser.FirstOrDefaultAsync(x => x.UserName == username);

                // Are we in an edit mode
                var isEdit = input.ExtendedData[Constants.ExtendedDataKeys.IsEdit] as bool? == true;

                // If the topic has tags then process
                if (input.EntityToProcess.Tags != null && input.EntityToProcess.Tags.Any())
                {
                    // Don't throw if badge fails as it's logged
                    //await _badgeService.ProcessBadge(BadgeType.Tag, input.EntityToProcess.User);
                }

                if (isEdit == false)
                {
                    // Subscribe the user to the topic as they have checked the checkbox
                    if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Subscribe))
                    {
                        var subscribe = input.ExtendedData[Constants.ExtendedDataKeys.Subscribe] as bool?;
                        if (subscribe == true)
                        {
                            var alreadyHasNotification = await context.TopicNotification
                                                         .Include(x => x.Topic)
                                                         .Include(x => x.User)
                                                         .AnyAsync(x =>
                                                                   x.Topic.Id == input.EntityToProcess.Id && x.User.Id == loggedOnUser.Id);

                            if (alreadyHasNotification == false)
                            {
                                // Create the notification
                                var topicNotification = new TopicNotification
                                {
                                    Topic = input.EntityToProcess,
                                    User  = loggedOnUser
                                };

                                //save
                                _notificationService.Add(topicNotification);
                            }
                        }
                    }

                    // Should we add the topic created activity
                    if (input.EntityToProcess.Pending != true)
                    {
                        _activityService.TopicCreated(input.EntityToProcess);
                    }

                    // finally notify
                    _notificationService.Notify(input.EntityToProcess, loggedOnUser, NotificationType.Topic);
                }

                // Was the post successful
                await context.SaveChangesAsync();
            }
            catch (System.Exception ex)
            {
                input.AddError(ex.Message);
                _loggingService.Error(ex);
            }
            return(input);
        }
Example #10
0
        public void Subscribe(SubscribeEmailViewModel subscription)
        {
            if(Request.IsAjaxRequest())
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        // Add logic to add subscr
                        var isCategory = subscription.SubscriptionType.Contains("category");
                        var isTag = subscription.SubscriptionType.Contains("tag");
                        var id = subscription.Id;
                        var dbUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id);

                        if (isCategory)
                        {
                            // get the category
                            var cat = _categoryService.Get(id);

                            if(cat != null)
                            {

                                // Create the notification
                                var categoryNotification = new CategoryNotification
                                {
                                    Category = cat,
                                    User = dbUser
                                };
                                //save

                                _categoryNotificationService.Add(categoryNotification);
                            }
                        }
                        else if (isTag)
                        {
                            // get the tag
                            var tag = _topicTagService.Get(id);

                            if (tag != null)
                            {

                                // Create the notification
                                var tagNotification = new TagNotification
                                {
                                    Tag = tag,
                                    User = dbUser
                                };
                                //save

                                _tagNotificationService.Add(tagNotification);
                            }
                        }
                        else
                        {
                            // get the category
                            var topic = _topicService.Get(id);

                            // check its not null
                            if (topic != null)
                            {

                                // Create the notification
                                var topicNotification = new TopicNotification
                                {
                                    Topic = topic,
                                    User = dbUser
                                };
                                //save

                                _topicNotificationService.Add(topicNotification);
                            }
                        }

                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
            }
            else
            {
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }
        }
Example #11
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")));
        }
        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)));
        }
 /// <summary>
 /// Add a new topic notification
 /// </summary>
 /// <param name="topicNotification"></param>
 public void Add(TopicNotification topicNotification)
 {
     ContextPerRequest.Db.TopicNotification.Add(topicNotification);
 }
 /// <summary>
 /// Delete topic notification
 /// </summary>
 /// <param name="notification"></param>
 public void Delete(TopicNotification notification)
 {
     ContextPerRequest.Db.TopicNotification.Remove(notification);
 }
 /// <summary>
 /// Delete topic notification
 /// </summary>
 /// <param name="notification"></param>
 public void Delete(TopicNotification notification)
 {
     _context.TopicNotification.Remove(notification);
 }
 /// <summary>
 /// Add a new topic notification
 /// </summary>
 /// <param name="topicNotification"></param>
 public TopicNotification Add(TopicNotification topicNotification)
 {
     return _context.TopicNotification.Add(topicNotification);
 }
 /// <summary>
 /// Add a new topic notification
 /// </summary>
 /// <param name="topicNotification"></param>
 public TopicNotification Add(TopicNotification topicNotification)
 {
     return(_context.TopicNotification.Add(topicNotification));
 }
 /// <summary>
 /// Delete topic notification
 /// </summary>
 /// <param name="notification"></param>
 public void Delete(TopicNotification notification)
 {
     _context.TopicNotification.Remove(notification);
 }
Example #19
0
        public virtual void Subscribe(EmailSubscriptionViewModel subscription)
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    // Add logic to add subscr
                    var isGroup = subscription.SubscriptionType.Contains("Group");
                    var isTag   = subscription.SubscriptionType.Contains("tag");
                    var id      = subscription.Id;
                    var dbUser  = MembershipService.GetUser(User.Identity.Name);

                    if (isGroup)
                    {
                        // get the Group
                        var cat = _groupService.Get(id);

                        if (cat != null)
                        {
                            // Create the notification
                            var GroupNotification = new GroupNotification
                            {
                                Group = cat,
                                User  = dbUser
                            };
                            //save

                            _notificationService.Add(GroupNotification);
                        }
                    }
                    else if (isTag)
                    {
                        // get the tag
                        var tag = _topicTagService.Get(id);

                        if (tag != null)
                        {
                            // Create the notification
                            var tagNotification = new TagNotification
                            {
                                Tag  = tag,
                                User = dbUser
                            };
                            //save

                            _notificationService.Add(tagNotification);
                        }
                    }
                    else
                    {
                        // get the Group
                        var topic = _topicService.Get(id);

                        // check its not null
                        if (topic != null)
                        {
                            // Create the notification
                            var topicNotification = new TopicNotification
                            {
                                Topic = topic,
                                User  = dbUser
                            };
                            //save

                            _notificationService.Add(topicNotification);
                        }
                    }

                    Context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Context.RollBack();
                    LoggingService.Error(ex);
                    throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                }
            }
            else
            {
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }
        }
Example #20
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));
        }