public Guid CreateFolder(FolderWriteViewModel folder) { var newFolder = new Folder { Name = folder.FolderName.Trim(), Description = folder.Description, AddedBy = folder.AddedBy, ParentFolder = folder.ParentFolder, CreatedAtUtc = DateTime.UtcNow, ParentGroup = folder.ParentGroup }; _context.Folder.Add(newFolder); _context.SaveChanges(); return(newFolder.Id); }
/// <inheritdoc /> public void DeleteSection(Guid id) { var section = _context.Section.Find(id); if (section != null) { _context.Section.Remove(section); _context.SaveChanges(); } }
public void Execute(IJobExecutionContext context) { try { // Process emails to send - Only send the amount per job from the siteconstants _emailService.ProcessMail(5); // Commit - Which deletes the jobs that have been sent _context.SaveChanges(); } catch (Exception ex) { _context.RollBack(); _loggingService.Error(ex); } }
public void ScrubUsers(MembershipUser user) { //// TODO - This REALLY needs to be refactored // PROFILE user.Website = string.Empty; user.Twitter = string.Empty; user.Facebook = string.Empty; user.Avatar = string.Empty; user.Signature = string.Empty; //// User Votes if (user.Votes != null) { var votesToDelete = new List <Vote>(); votesToDelete.AddRange(user.Votes); votesToDelete.AddRange(user.VotesGiven); foreach (var d in votesToDelete) { _voteService.Delete(d); } user.Votes.Clear(); user.VotesGiven.Clear(); _context.SaveChanges(); } // User badge time checks if (user.BadgeTypesTimeLastChecked != null) { var toDelete = new List <BadgeTypeTimeLastChecked>(); toDelete.AddRange(user.BadgeTypesTimeLastChecked); foreach (var obj in toDelete) { _badgeService.DeleteTimeLastChecked(obj); } user.BadgeTypesTimeLastChecked.Clear(); _context.SaveChanges(); } // User Badges if (user.Badges != null) { var toDelete = new List <Badge>(); toDelete.AddRange(user.Badges); foreach (var obj in toDelete) { _badgeService.Delete(obj); } user.Badges.Clear(); _context.SaveChanges(); } // User category notifications if (user.CategoryNotifications != null) { var toDelete = new List <CategoryNotification>(); toDelete.AddRange(user.CategoryNotifications); foreach (var obj in toDelete) { _categoryNotificationService.Delete(obj); } user.CategoryNotifications.Clear(); _context.SaveChanges(); } // User PM Received if (user.PrivateMessagesReceived != null) { var toDelete = new List <PrivateMessage>(); toDelete.AddRange(user.PrivateMessagesReceived); foreach (var obj in toDelete) { _privateMessageService.DeleteMessage(obj); } user.PrivateMessagesReceived.Clear(); _context.SaveChanges(); } // User PM Sent if (user.PrivateMessagesSent != null) { var toDelete = new List <PrivateMessage>(); toDelete.AddRange(user.PrivateMessagesSent); foreach (var obj in toDelete) { _privateMessageService.DeleteMessage(obj); } user.PrivateMessagesSent.Clear(); _context.SaveChanges(); } // User Favourites if (user.Favourites != null) { var toDelete = new List <Favourite>(); toDelete.AddRange(user.Favourites); foreach (var obj in toDelete) { _favouriteService.Delete(obj); } user.Favourites.Clear(); _context.SaveChanges(); } if (user.TopicNotifications != null) { var notificationsToDelete = new List <TopicNotification>(); notificationsToDelete.AddRange(user.TopicNotifications); foreach (var topicNotification in notificationsToDelete) { _topicNotificationService.Delete(topicNotification); } user.TopicNotifications.Clear(); } // Also clear their points var userPoints = user.Points; if (userPoints.Any()) { var pointsList = new List <MembershipUserPoints>(); pointsList.AddRange(userPoints); foreach (var point in pointsList) { point.User = null; _membershipUserPointsService.Delete(point); } user.Points.Clear(); } // Now clear all activities for this user var usersActivities = _activityService.GetDataFieldByGuid(user.Id); _activityService.Delete(usersActivities.ToList()); _context.SaveChanges(); // Also clear their poll votes var userPollVotes = user.PollVotes; if (userPollVotes.Any()) { var pollList = new List <PollVote>(); pollList.AddRange(userPollVotes); foreach (var vote in pollList) { vote.User = null; _pollVoteService.Delete(vote); } user.PollVotes.Clear(); _context.SaveChanges(); } //// ######### POSTS TOPICS ######## // Delete all topics first // This will get rid of everyone elses posts associated with this users topic too var topics = user.Topics; if (topics != null && topics.Any()) { var topicList = new List <Topic>(); topicList.AddRange(topics); foreach (var topic in topicList) { _topicService.Delete(topic); } user.Topics.Clear(); _context.SaveChanges(); } // Now sorts Last Posts on topics and delete all the users posts var posts = user.Posts; if (posts != null && posts.Any()) { var postIds = posts.Select(x => x.Id).ToList(); // Get all categories var allCategories = _categoryService.GetAll(); // Need to see if any of these are last posts on Topics // If so, need to swap out last post var lastPostTopics = _topicService.GetTopicsByLastPost(postIds, allCategories.ToList()); foreach (var topic in lastPostTopics.Where(x => x.User.Id != user.Id)) { var lastPost = topic.Posts.Where(x => !postIds.Contains(x.Id)).OrderByDescending(x => x.DateCreated).FirstOrDefault(); topic.LastPost = lastPost; } _context.SaveChanges(); // Delete all posts var postList = new List <Post>(); postList.AddRange(posts); foreach (var post in postList) { _postService.Delete(post, true); } user.UploadedFiles.Clear(); user.Posts.Clear(); _context.SaveChanges(); } }
/// <summary> /// Delete a post /// </summary> /// <param name="post"></param> /// <param name="ignoreLastPost"></param> /// <returns>Returns true if can delete</returns> public bool Delete(Post post, bool ignoreLastPost) { // Get the topic var topic = post.Topic; var votes = _voteService.GetVotesByPost(post.Id); #region Deleting Points // Remove the points the user got for this post _membershipUserPointsService.Delete(post.User, PointsFor.Post, post.Id); // Also get all the votes and delete anything to do with those foreach (var postVote in votes) { _membershipUserPointsService.Delete(PointsFor.Vote, postVote.Id); } // Also the mark as solution _membershipUserPointsService.Delete(PointsFor.Solution, post.Id); #endregion _context.SaveChanges(); #region Deleting Votes var votesToDelete = new List <Vote>(); votesToDelete.AddRange(votes); foreach (var vote in votesToDelete) { post.Votes.Remove(vote); _voteService.Delete(vote); } post.Votes.Clear(); #endregion #region Files // Clear files attached to post var filesToDelete = new List <UploadedFile>(); filesToDelete.AddRange(post.Files); foreach (var uploadedFile in filesToDelete) { // store the file path as we'll need it to delete on the file system var filePath = uploadedFile.FilePath; post.Files.Remove(uploadedFile); _uploadedFileService.Delete(uploadedFile); // And finally delete from the file system if (!string.IsNullOrWhiteSpace(filePath)) { File.Delete(HostingEnvironment.MapPath(filePath)); } } post.Files.Clear(); #endregion #region Favourites var postFavourites = new List <Favourite>(); postFavourites.AddRange(post.Favourites); foreach (var postFavourite in postFavourites) { post.Favourites.Remove(postFavourite); _favouriteService.Delete(postFavourite); } post.Favourites.Clear(); #endregion #region Post Edits var postEdits = new List <PostEdit>(); postEdits.AddRange(post.PostEdits); foreach (var postEdit in postEdits) { post.PostEdits.Remove(postEdit); _postEditService.Delete(postEdit); } post.PostEdits.Clear(); #endregion _context.SaveChanges(); // Before we delete the post, we need to check if this is the last post in the topic // and if so update the topic if (!ignoreLastPost) { var lastPost = topic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault(); if (lastPost != null && lastPost.Id == post.Id) { // Get the new last post and update the topic topic.LastPost = topic.Posts.Where(x => x.Id != post.Id).OrderByDescending(x => x.DateCreated).FirstOrDefault(); } if (topic.Solved && post.IsSolution) { topic.Solved = false; } // Save the topic _context.SaveChanges(); } // Remove from the topic topic.Posts.Remove(post); // now delete the post _context.Post.Remove(post); // Save changes _context.SaveChanges(); // Only the post was deleted, not the entire topic return(false); }
/// <inheritdoc /> public void Notify(Topic topic, MembershipUser loggedOnReadOnlyUser, NotificationType notificationType) { List <Guid> userIdsToNotify; var settings = _settingsService.GetSettings(); if (notificationType == NotificationType.Post) { userIdsToNotify = GetTopicNotificationsByTopic(topic).Select(x => x.User.Id).ToList(); } else { // Get all notifications for this category and for the tags on the topic userIdsToNotify = GetCategoryNotificationsByCategory(topic.Category).Select(x => x.User.Id).ToList(); // Merge and remove duplicate ids if (topic.Tags != null && topic.Tags.Any()) { var tagNotifications = GetTagNotificationsByTag(topic.Tags.ToList()).Select(x => x.User.Id) .ToList(); userIdsToNotify = userIdsToNotify.Union(tagNotifications).ToList(); } } if (userIdsToNotify.Any()) { // remove the current user from the notification, don't want to notify yourself that you // have just made a topic! userIdsToNotify.Remove(loggedOnReadOnlyUser.Id); if (userIdsToNotify.Count > 0) { try { // Now get all the users that need notifying var users = _context.MembershipUser .Where(x => userIdsToNotify.Contains(x.Id)) .AsNoTracking() .ToList(); // Create the email var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(_localizationService.GetResourceString(notificationType == NotificationType.Post ? "Post.Notification.NewPosts" : "Topic.Notification.NewTopics"), topic.Category.Name)); sb.Append($"<p>{topic.Name}</p>"); if (ForumConfiguration.Instance.IncludeFullPostInEmailNotifications) { sb.Append(topic.LastPost.PostContent.ConvertPostContent()); } sb.AppendFormat("<p><a href=\"{0}\">{0}</a></p>", string.Concat(StringUtils.ReturnCurrentDomain(), topic.Category.NiceUrl)); // create the emails and only send them to people who have not had notifications disabled var emails = users .Where(x => x.DisableEmailNotifications != true && !x.IsLockedOut && x.IsBanned != true).Select( user => new Email { Body = _emailService.EmailTemplate(user.UserName, sb.ToString()), EmailTo = user.Email, NameTo = user.UserName, Subject = string.Concat( _localizationService.GetResourceString(notificationType == NotificationType.Post ? "Post.Notification.Subject" : "Topic.Notification.Subject"), settings.ForumName) }).ToList(); // and now pass the emails in to be sent _emailService.SendMail(emails); _context.SaveChanges(); } catch (Exception ex) { _context.RollBack(); _loggingService.Error(ex); } } } }
/// <inheritdoc /> public void RefreshEditedPoll(Topic originalTopic, IList <PollAnswer> pollAnswers, int pollCloseAfterDays) { var panswers = pollAnswers.Where(x => !string.IsNullOrWhiteSpace(x?.Answer)).ToArray(); if (panswers.Any() && originalTopic.Poll != null) { // Now sort the poll answers, what to add and what to remove // Poll answers already in this poll. var newPollAnswerIds = panswers.Select(x => x.Id); // This post might not have a poll on it, if not they are creating a poll for the first time var originalPollAnswerIds = originalTopic.Poll.PollAnswers.Select(p => p.Id).ToList(); var pollAnswersToRemove = originalTopic.Poll.PollAnswers.Where(x => !newPollAnswerIds.Contains(x.Id)) .ToList(); // Set the amount of days to close the poll originalTopic.Poll.ClosePollAfterDays = pollCloseAfterDays; // Get existing answers var existingAnswers = panswers.Where(x => !string.IsNullOrWhiteSpace(x.Answer) && originalPollAnswerIds.Contains(x.Id)).ToList(); // Get new poll answers to add var newPollAnswers = panswers.Where(x => !string.IsNullOrWhiteSpace(x.Answer) && !originalPollAnswerIds.Contains(x.Id)).ToList(); // Loop through existing and update names if need be // If name changes remove the poll foreach (var existPollAnswer in existingAnswers) { // Get the existing answer from the current topic var pa = originalTopic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id); if (pa != null && pa.Answer != existPollAnswer.Answer) { var pollVotestToRemove = new List <PollVote>(); pollVotestToRemove.AddRange(pa.PollVotes); // Remove all the poll votes, as the answer has changed foreach (var answerPollVote in pollVotestToRemove) { pa.PollVotes.Remove(answerPollVote); Delete(answerPollVote); } pa.PollVotes.Clear(); _context.SaveChanges(); // If the answer has changed then update it pa.Answer = existPollAnswer.Answer; } } // Save existing _context.SaveChanges(); // Loop through and remove the old poll answers and delete foreach (var oldPollAnswer in pollAnswersToRemove) { // Clear poll votes if it's changed var pollVotestToRemove = new List <PollVote>(); pollVotestToRemove.AddRange(oldPollAnswer.PollVotes); foreach (var answerPollVote in pollVotestToRemove) { oldPollAnswer.PollVotes.Remove(answerPollVote); Delete(answerPollVote); } oldPollAnswer.PollVotes.Clear(); _context.SaveChanges(); // Remove from Poll originalTopic.Poll.PollAnswers.Remove(oldPollAnswer); // Delete Delete(oldPollAnswer); } // Save removed _context.SaveChanges(); // Poll answers to add foreach (var newPollAnswer in newPollAnswers) { if (newPollAnswer != null) { var npa = new PollAnswer { Poll = originalTopic.Poll, Answer = newPollAnswer.Answer }; Add(npa); originalTopic.Poll.PollAnswers.Add(npa); } } } else if (originalTopic.Poll != null) { // Now delete the poll Delete(originalTopic.Poll); // Remove from topic. originalTopic.Poll = null; } }
/// <summary> /// Delete a topic /// </summary> /// <param name="topic"></param> /// <param name="unitOfWork"></param> public void Delete(Topic topic) { // First thing - Set the last post as null and clear tags topic.LastPost = null; topic.Tags.Clear(); // Save here to clear the last post _context.SaveChanges(); // TODO - Need to refactor as some of the code below is duplicated in the post delete // Loop through all the posts and clear the associated entities // then delete the posts if (topic.Posts != null) { var postsToDelete = new List <Post>(); postsToDelete.AddRange(topic.Posts); foreach (var post in postsToDelete) { // Posts should only be deleted from this method as it clears // associated data _postService.Delete(post, true); } // Final clear topic.Posts.Clear(); } _context.SaveChanges(); // Remove all notifications on this topic too if (topic.TopicNotifications != null) { var notificationsToDelete = new List <TopicNotification>(); notificationsToDelete.AddRange(topic.TopicNotifications); foreach (var topicNotification in notificationsToDelete) { _topicNotificationService.Delete(topicNotification); } // Final Clear topic.TopicNotifications.Clear(); } // Remove all favourites on this topic too if (topic.Favourites != null) { var toDelete = new List <Favourite>(); toDelete.AddRange(topic.Favourites); foreach (var entity in toDelete) { _favouriteService.Delete(entity); } // Final Clear topic.Favourites.Clear(); } // Poll if (topic.Poll != null) { //Delete the poll answers var pollAnswers = topic.Poll.PollAnswers; if (pollAnswers.Any()) { var pollAnswersList = new List <PollAnswer>(); pollAnswersList.AddRange(pollAnswers); foreach (var answer in pollAnswersList) { answer.Poll = null; _pollAnswerService.Delete(answer); } } topic.Poll.PollAnswers.Clear(); topic.Poll.User = null; _pollService.Delete(topic.Poll); // Final Clear topic.Poll = null; } // Finally delete the topic _context.Topic.Remove(topic); }
public void SendMarkAsSolutionReminders() { try { var settings = _settingsService.GetSettings(false); var timeFrame = settings.MarkAsSolutionReminderTimeFrame ?? 0; if (timeFrame > 0 && settings.EnableMarkAsSolution) { var remindersToSend = _topicService.GetMarkAsSolutionReminderList(timeFrame); if (remindersToSend.Any()) { var amount = remindersToSend.Count; // Use settings days amount and also mark topics as reminded // Only send if markassolution is enabled and day is not 0 var emailListToSend = new List <Email>(); foreach (var markAsSolutionReminder in remindersToSend) { // Topic Link var topicLink = $"<a href=\"{settings.ForumUrl.TrimEnd('/')}{markAsSolutionReminder.Topic.NiceUrl}\">{markAsSolutionReminder.Topic.Name}</a>"; // Create the email var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format( _localizationService.GetResourceString("Tasks.MarkAsSolutionReminderJob.EmailBody"), topicLink, settings.ForumName, markAsSolutionReminder.PostCount)); // create the emails and only send them to people who have not had notifications disabled var user = markAsSolutionReminder.Topic.User; var email = new Email { Body = _emailService.EmailTemplate(user.UserName, sb.ToString(), settings), EmailTo = user.Email, NameTo = user.UserName, Subject = string.Format( _localizationService.GetResourceString( "Tasks.MarkAsSolutionReminderJob.Subject"), settings.ForumName) }; // Add to list emailListToSend.Add(email); // And now mark the topic as reminder sent markAsSolutionReminder.Topic.SolvedReminderSent = true; } // and now pass the emails in to be sent // We have to pass the current settings to SendMail when it's within a task _emailService.SendMail(emailListToSend, settings); _context.SaveChanges(); _loggingService.Error($"{amount} Mark as solution reminder emails sent"); } } } catch (Exception ex) { _context.RollBack(); _loggingService.Error(ex); } }
/// <summary> /// Delete a topic /// </summary> /// <param name="topic"></param> public void Delete(Topic topic) { // Remove all notifications on this topic too if (topic.TopicNotifications != null) { var notificationsToDelete = new List <TopicNotification>(); notificationsToDelete.AddRange(topic.TopicNotifications); foreach (var topicNotification in notificationsToDelete) { topic.TopicNotifications.Remove(topicNotification); _topicNotificationService.Delete(topicNotification); } // Final Clear topic.TopicNotifications.Clear(); } // Remove all favourites on this topic too if (topic.Favourites != null) { var toDelete = new List <Favourite>(); toDelete.AddRange(topic.Favourites); foreach (var entity in toDelete) { topic.Favourites.Remove(entity); _favouriteService.Delete(entity); } // Final Clear topic.Favourites.Clear(); } // Poll if (topic.Poll != null) { var pollToDelete = topic.Poll; // Final Clear topic.Poll = null; // Delete the poll _pollService.Delete(pollToDelete); } // First thing - Set the last post as null and clear tags topic.Tags.Clear(); // Save here to clear the last post _context.SaveChanges(); // Loop through all the posts and clear the associated entities // then delete the posts if (topic.Posts != null) { var postsToDelete = new List <Post>(); postsToDelete.AddRange(topic.Posts); foreach (var post in postsToDelete) { // Posts should only be deleted from this method as it clears // associated data _postService.Delete(post, true); } topic.Posts.Clear(); // Clear last post topic.LastPost = null; } // Finally delete the topic _context.Topic.Remove(topic); }