public ServiceModels.ServiceResponse Merge(int sourceId, int targetId) { var serviceResponse = new ServiceModels.ServiceResponse(); var sourceRecord = DbContext.Messages.FirstOrDefault(item => item.Id == sourceId); if (sourceRecord is null) { serviceResponse.Error("Source record not found"); } var targetRecord = DbContext.Messages.FirstOrDefault(item => item.Id == targetId); if (targetRecord is null) { serviceResponse.Error("Target record not found"); } if (!serviceResponse.Success) { return(serviceResponse); } if (sourceRecord.TimePosted > targetRecord.TimePosted) { Merge(sourceRecord, targetRecord); } else { Merge(targetRecord, sourceRecord); } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> ConfirmEmail(InputModels.ConfirmEmailInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var account = await UserManager.FindByIdAsync(input.UserId); if (account is null) { serviceResponse.Error($"Unable to load account '{input.UserId}'."); } if (serviceResponse.Success) { var identityResult = await UserManager.ConfirmEmailAsync(account, input.Code); if (!identityResult.Succeeded) { foreach (var error in identityResult.Errors) { Log.LogError($"Error confirming '{account.Email}'. Message: {error.Description}"); serviceResponse.Error(error.Description); } } else { Log.LogInformation($"User confirmed email '{account.Id}'."); } } await SignOut(); return(serviceResponse); }
public async Task <InputModels.ProcessedMessageInput> ProcessMessageInput(ServiceModels.ServiceResponse serviceResponse, string messageBody) { InputModels.ProcessedMessageInput processedMessage = null; try { processedMessage = PreProcessMessageInput(messageBody); PreProcessSmileys(processedMessage); ParseBBC(processedMessage); ProcessSmileys(processedMessage); await ProcessMessageBodyUrls(processedMessage); FindMentionedUsers(processedMessage); PostProcessMessageInput(processedMessage); } catch (ArgumentException e) { serviceResponse.Error(nameof(InputModels.MessageInput.Body), $"An error occurred while processing the message. {e.Message}"); } if (processedMessage is null) { serviceResponse.Error(nameof(InputModels.MessageInput.Body), $"An error occurred while processing the message."); return(processedMessage); } return(processedMessage); }
public async Task <ServiceModels.ServiceResponse> MergeBoard(InputModels.MergeInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var fromBoard = (await Records()).FirstOrDefault(b => b.Id == input.FromId); var toBoard = (await Records()).FirstOrDefault(b => b.Id == input.ToId); if (fromBoard is null) { serviceResponse.Error($"A record does not exist with ID '{input.FromId}'"); } if (toBoard is null) { serviceResponse.Error($"A record does not exist with ID '{input.ToId}'"); } if (!serviceResponse.Success) { return(serviceResponse); } var topicBoards = DbContext.TopicBoards.Where(m => m.BoardId == fromBoard.Id).ToList(); // Reassign messages to new board foreach (var topicBoard in topicBoards) { topicBoard.BoardId = toBoard.Id; DbContext.Update(topicBoard); } DbContext.SaveChanges(); var categoryId = fromBoard.CategoryId; // Delete the board DbContext.Boards.Remove(fromBoard); DbContext.SaveChanges(); // Remove the category if empty if (!DbContext.Boards.Any(b => b.CategoryId == categoryId)) { var categoryRecord = (await Categories()).FirstOrDefault(item => item.Id == categoryId); if (categoryRecord != null) { DbContext.Categories.Remove(categoryRecord); DbContext.SaveChanges(); } } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> UpdateAvatar(InputModels.UpdateAvatarInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var userRecord = await UserManager.FindByIdAsync(input.Id); if (userRecord is null) { var message = $"No user record found for '{input.Id}'."; serviceResponse.Error(message); Log.LogCritical(message); } CanEdit(input.Id); if (!serviceResponse.Success) { return(serviceResponse); } var allowedExtensions = new[] { ".gif", ".jpg", ".png", ".jpeg" }; var extension = Path.GetExtension(input.NewAvatar.FileName).ToLower(); if (!allowedExtensions.Contains(extension)) { serviceResponse.Error(nameof(input.NewAvatar), "Your avatar must end with .gif, .jpg, .jpeg, or .png"); } if (!serviceResponse.Success) { return(serviceResponse); } using (var inputStream = input.NewAvatar.OpenReadStream()) { inputStream.Position = 0; userRecord.AvatarPath = await ImageStore.Save(new ImageStoreSaveOptions { ContainerName = Constants.InternalKeys.AvatarContainer, FileName = $"avatar{userRecord.Id}.png", ContentType = "image/png", InputStream = inputStream, MaxDimension = 100, Overwrite = true }); } DbContext.Update(userRecord); DbContext.SaveChanges(); Log.LogInformation($"Avatar was modified by '{UserContext.ApplicationUser.DisplayName}' for account '{userRecord.DisplayName}'."); return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Create(InputModels.CreateSmileyInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var allowedExtensions = new[] { "gif", "png" }; var extension = Path.GetExtension(input.File.FileName).ToLower().Substring(1); if (Regex.IsMatch(input.File.FileName, @"[^a-zA-Z 0-9_\-\.]")) { serviceResponse.Error("File", "Your filename contains invalid characters."); } if (!allowedExtensions.Contains(extension)) { serviceResponse.Error("File", $"Your file must be: {string.Join(", ", allowedExtensions)}."); } if (DbContext.Smileys.Any(s => s.Code == input.Code)) { serviceResponse.Error(nameof(input.Code), "Another smiley exists with that code."); } if (!serviceResponse.Success) { return(serviceResponse); } var smileyRecord = new DataModels.Smiley { Code = input.Code, Thought = input.Thought, FileName = input.File.FileName }; DbContext.Smileys.Add(smileyRecord); using (var inputStream = input.File.OpenReadStream()) { smileyRecord.Path = await ImageStore.Save(new ImageStoreSaveOptions { ContainerName = Constants.InternalKeys.SmileyContainer, FileName = input.File.FileName, ContentType = input.File.ContentType, InputStream = inputStream, Overwrite = true }); } DbContext.SaveChanges(); serviceResponse.Message = $"Smiley '{smileyRecord.FileName}' was added with code '{smileyRecord.Code}'."; return(serviceResponse); }
public async Task<ServiceModels.ServiceResponse> EditMessage(InputModels.MessageInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); if (input.Id == 0) { throw new HttpBadRequestError(); } var record = DbContext.Messages.FirstOrDefault(m => m.Id == input.Id); if (record is null) { serviceResponse.Error(nameof(input.Id), $"No record found with the ID '{input.Id}'."); } var processedMessage = await ProcessMessageInput(serviceResponse, input.Body); if (serviceResponse.Success) { await UpdateMessageRecord(processedMessage, record); serviceResponse.RedirectPath = UrlHelper.DisplayMessage(record.Id); await ForumHub.Clients.All.SendAsync("updated-message", new HubModels.Message { TopicId = record.ParentId, MessageId = record.Id }); } return serviceResponse; }
public async Task <ServiceModels.ServiceResponse> MoveCategoryUp(int id) { var serviceResponse = new ServiceModels.ServiceResponse(); var targetCategory = (await Categories()).FirstOrDefault(b => b.Id == id); if (targetCategory is null) { serviceResponse.Error("No category found with that ID."); return(serviceResponse); } if (targetCategory.DisplayOrder > 1) { var displacedCategory = (await Categories()).First(b => b.DisplayOrder == targetCategory.DisplayOrder - 1); displacedCategory.DisplayOrder++; DbContext.Update(displacedCategory); targetCategory.DisplayOrder--; DbContext.Update(targetCategory); DbContext.SaveChanges(); } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> CreateReply(InputModels.MessageInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); if (input.Id == 0) { throw new HttpBadRequestError(); } var replyRecord = DbContext.Messages.FirstOrDefault(m => m.Id == input.Id); if (replyRecord is null) { serviceResponse.Error($"A record does not exist with ID '{input.Id}'"); } if (!serviceResponse.Success) { return(serviceResponse); } var processedMessage = await ProcessMessageInput(serviceResponse, input.Body); if (!serviceResponse.Success) { return(serviceResponse); } var record = CreateMessageRecord(processedMessage, replyRecord); serviceResponse.RedirectPath = UrlHelper.DirectMessage(record.Id); return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> EditMessage(InputModels.MessageInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); if (input.Id == 0) { throw new HttpBadRequestError(); } var record = DbContext.Messages.FirstOrDefault(m => m.Id == input.Id); if (record is null) { serviceResponse.Error(nameof(input.Id), $"No record found with the ID '{input.Id}'."); } var processedMessage = await ProcessMessageInput(serviceResponse, input.Body); if (serviceResponse.Success) { serviceResponse.RedirectPath = UrlHelper.DirectMessage(record.Id); UpdateMessageRecord(processedMessage, record); } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Create(InputModels.CreateRoleInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); if (input.Name != null) { input.Name = input.Name.Trim(); } if (string.IsNullOrEmpty(input.Name)) { serviceResponse.Error(nameof(InputModels.CreateRoleInput.Name), "Name is required"); } if (input.Description != null) { input.Description = input.Description.Trim(); } if (string.IsNullOrEmpty(input.Description)) { serviceResponse.Error(nameof(InputModels.CreateRoleInput.Description), "Description is required"); } if (!serviceResponse.Success) { return(serviceResponse); } if (await RoleManager.FindByNameAsync(input.Name) != null) { serviceResponse.Error(nameof(InputModels.CreateRoleInput.Name), "A role with this name already exists"); } if (!serviceResponse.Success) { return(serviceResponse); } await CreateRecord(input); serviceResponse.RedirectPath = UrlHelper.Action(nameof(Roles.Index), nameof(Roles)); return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Merge(int sourceId, int targetId) { var serviceResponse = new ServiceModels.ServiceResponse(); var sourceRecord = DbContext.Topics.FirstOrDefault(item => item.Id == sourceId); if (sourceRecord is null || sourceRecord.Deleted) { serviceResponse.Error("Source record not found"); } var targetRecord = DbContext.Topics.FirstOrDefault(item => item.Id == targetId); if (targetRecord is null || targetRecord.Deleted) { serviceResponse.Error("Target record not found"); } if (!serviceResponse.Success) { return(serviceResponse); } if (sourceRecord.FirstMessageTimePosted > targetRecord.FirstMessageTimePosted) { await Merge(sourceRecord, targetRecord); serviceResponse.RedirectPath = UrlHelper.Action(nameof(Topics.Latest), nameof(Topics), new { id = targetRecord.Id }); } else { await Merge(targetRecord, sourceRecord); serviceResponse.RedirectPath = UrlHelper.Action(nameof(Topics.Latest), nameof(Topics), new { id = sourceRecord.Id }); } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> MergeCategory(InputModels.MergeInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var fromCategory = (await Categories()).FirstOrDefault(b => b.Id == input.FromId); var toCategory = (await Categories()).FirstOrDefault(b => b.Id == input.ToId); if (fromCategory is null) { serviceResponse.Error($"A record does not exist with ID '{input.FromId}'"); } if (toCategory is null) { serviceResponse.Error($"A record does not exist with ID '{input.ToId}'"); } if (!serviceResponse.Success) { return(serviceResponse); } var displacedBoards = (await Records()).Where(b => b.CategoryId == fromCategory.Id).ToList(); foreach (var displacedBoard in displacedBoards) { displacedBoard.CategoryId = toCategory.Id; DbContext.Update(displacedBoard); } DbContext.SaveChanges(); DbContext.Categories.Remove(fromCategory); DbContext.SaveChanges(); return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> RemoveUser(string roleId, string userId) { var serviceResponse = new ServiceModels.ServiceResponse(); var roleRecord = await RoleManager.FindByIdAsync(roleId); if (roleRecord is null) { serviceResponse.Error($"A record does not exist with ID '{roleId}'"); } var userRecord = await UserManager.FindByIdAsync(userId); if (userRecord is null) { serviceResponse.Error($"A record does not exist with ID '{roleId}'"); } if (!serviceResponse.Success) { return(serviceResponse); } var result = await UserManager.RemoveFromRoleAsync(userRecord, roleRecord.Name); if (result.Succeeded) { if (userId == UserContext.ApplicationUser.Id) { await SignInManager.SignOutAsync(); } serviceResponse.RedirectPath = UrlHelper.Action(nameof(Roles.Edit), nameof(Roles), new { Id = roleId }); } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Create(int messageId) { var serviceResponse = new ServiceModels.ServiceResponse(); var message = DbContext.Messages.FirstOrDefault(r => r.Id == messageId); if (message is null) { serviceResponse.Error($@"No record was found with the id '{messageId}'."); } if ((await Records()).Any(r => r.MessageId == messageId)) { serviceResponse.Error($@"A message with the id '{messageId}' has already been submitted."); } if (serviceResponse.Success) { DbContext.Quotes.Add(new DataModels.Quote { MessageId = message.Id, PostedById = message.PostedById, TimePosted = message.TimePosted, SubmittedById = UserContext.ApplicationUser.Id, SubmittedTime = DateTime.Now, Approved = false, OriginalBody = message.OriginalBody, DisplayBody = message.DisplayBody }); DbContext.SaveChanges(); serviceResponse.Message = $"Quote added."; } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> MoveBoardUp(int id) { var serviceResponse = new ServiceModels.ServiceResponse(); var targetBoard = (await Records()).FirstOrDefault(b => b.Id == id); if (targetBoard is null) { serviceResponse.Error("No board found with that ID."); return(serviceResponse); } var categoryBoards = (await Records()).Where(b => b.CategoryId == targetBoard.CategoryId).OrderBy(b => b.DisplayOrder).ToList(); var currentIndex = 1; foreach (var board in categoryBoards) { board.DisplayOrder = currentIndex++; DbContext.Update(board); } DbContext.SaveChanges(); targetBoard = categoryBoards.First(b => b.Id == id); if (targetBoard.DisplayOrder > 1) { var displacedBoard = categoryBoards.FirstOrDefault(b => b.DisplayOrder == targetBoard.DisplayOrder - 1); if (displacedBoard != null) { displacedBoard.DisplayOrder++; DbContext.Update(displacedBoard); } targetBoard.DisplayOrder--; DbContext.Update(targetBoard); DbContext.SaveChanges(); } else { targetBoard.DisplayOrder = 2; } return(serviceResponse); }
public async Task<ServiceModels.ServiceResponse> CreateReply(InputModels.MessageInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); if (input.Id == 0) { throw new HttpBadRequestError(); } var replyRecord = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == input.Id); if (replyRecord is null) { serviceResponse.Error($"A record does not exist with ID '{input.Id}'"); } var now = DateTime.Now; var recentReply = (now - replyRecord.LastReplyPosted) < (now - now.AddSeconds(-30)); if (recentReply && replyRecord.ParentId == 0) { var targetId = replyRecord.LastReplyId > 0 ? replyRecord.LastReplyId : replyRecord.Id; var previousMessageRecord = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == targetId); if (previousMessageRecord?.PostedById == UserContext.ApplicationUser.Id) { await MergeReply(previousMessageRecord, input, serviceResponse); return serviceResponse; } } if (!serviceResponse.Success) { return serviceResponse; } var processedMessage = await ProcessMessageInput(serviceResponse, input.Body); if (serviceResponse.Success) { var record = CreateMessageRecord(processedMessage, replyRecord); serviceResponse.RedirectPath = UrlHelper.DisplayMessage(record.Id); await ForumHub.Clients.All.SendAsync("new-reply", new HubModels.Message { TopicId = record.ParentId, MessageId = record.Id }); } return serviceResponse; }
public async Task <ServiceModels.ServiceResponse> Register(InputModels.RegisterInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var birthday = new DateTime(input.BirthdayYear, input.BirthdayMonth, input.BirthdayDay); var user = new DataModels.ApplicationUser { DisplayName = input.DisplayName, Registered = DateTime.Now, LastOnline = DateTime.Now, UserName = input.Email, Email = input.Email, Birthday = birthday }; var identityResult = await UserManager.CreateAsync(user, input.Password); if (identityResult.Succeeded) { Log.LogInformation($"User created a new account with password '{input.Email}'."); var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = EmailConfirmationLink(user.Id, code); if (!EmailSender.Ready) { serviceResponse.RedirectPath = callbackUrl; return(serviceResponse); } await EmailSender.SendEmailConfirmationAsync(input.Email, callbackUrl); } else { foreach (var error in identityResult.Errors) { Log.LogError($"Error registering '{input.Email}'. Message: {error.Description}"); serviceResponse.Error(error.Description); } } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Edit(InputModels.QuotesInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); foreach (var quoteInput in input.Quotes) { var record = (await Records()).FirstOrDefault(r => r.Id == quoteInput.Id); if (record is null) { serviceResponse.Error($@"No record was found with the id '{quoteInput.Id}'."); } if (serviceResponse.Success) { if (quoteInput.Approved != record.Approved) { record.Approved = quoteInput.Approved; DbContext.Update(record); } if (quoteInput.OriginalBody != record.OriginalBody) { record.OriginalBody = quoteInput.OriginalBody; var processedMessageInput = await MessageRepository.ProcessMessageInput(serviceResponse, quoteInput.OriginalBody); record.DisplayBody = processedMessageInput.DisplayBody; DbContext.Update(record); } if (serviceResponse.Success) { DbContext.SaveChanges(); serviceResponse.Message = $"Changes saved."; } } } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Delete(int quoteId) { var serviceResponse = new ServiceModels.ServiceResponse(); var record = (await Records()).FirstOrDefault(r => r.Id == quoteId); if (record is null) { serviceResponse.Error($@"No record was found with the id '{quoteId}'."); } if (serviceResponse.Success) { DbContext.Quotes.Remove(record); await DbContext.SaveChangesAsync(); serviceResponse.Message = $"Quote deleted."; } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Delete(int id) { var serviceResponse = new ServiceModels.ServiceResponse(); var smileyRecord = await DbContext.Smileys.FindAsync(id); if (smileyRecord is null) { serviceResponse.Error($@"No smiley was found with the id '{id}'"); } if (!serviceResponse.Success) { return(serviceResponse); } var otherSmileys = DbContext.Smileys.Where(s => s.FileName == smileyRecord.FileName).ToList(); DbContext.Smileys.Remove(smileyRecord); var thoughts = DbContext.MessageThoughts.Where(t => t.SmileyId == id).ToList(); if (thoughts.Any()) { DbContext.MessageThoughts.RemoveRange(thoughts); } var container = CloudBlobClient.GetContainerReference("smileys"); if (!otherSmileys.Any() && await container.ExistsAsync()) { var blobReference = container.GetBlockBlobReference(smileyRecord.Path); await blobReference.DeleteIfExistsAsync(); } DbContext.SaveChanges(); serviceResponse.Message = $"The smiley was deleted."; return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Delete(int id) { var serviceResponse = new ServiceModels.ServiceResponse(); var smileyRecord = await DbContext.Smileys.FindAsync(id); if (smileyRecord is null) { serviceResponse.Error($@"No smiley was found with the id '{id}'"); } if (!serviceResponse.Success) { return(serviceResponse); } DbContext.Smileys.Remove(smileyRecord); var thoughts = DbContext.MessageThoughts.Where(t => t.SmileyId == id).ToList(); if (thoughts.Any()) { DbContext.MessageThoughts.RemoveRange(thoughts); } // Only delete the file if no other smileys are using the file. if (!DbContext.Smileys.Any(s => s.FileName == smileyRecord.FileName)) { await ImageStore.Delete(new ImageStoreDeleteOptions { ContainerName = Constants.InternalKeys.SmileyImageContainer, Path = smileyRecord.Path }); } DbContext.SaveChanges(); serviceResponse.Message = $"The smiley was deleted."; return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Login(InputModels.LoginInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var result = await SignInManager.PasswordSignInAsync(input.Email, input.Password, input.RememberMe, lockoutOnFailure : false); if (result.IsLockedOut) { Log.LogWarning($"User account locked out '{input.Email}'."); serviceResponse.RedirectPath = UrlHelper.Action(nameof(Account.Lockout), nameof(Account)); } else if (!result.Succeeded) { Log.LogWarning($"Invalid login attempt for account '{input.Email}'."); serviceResponse.Error("Invalid login attempt."); } else { Log.LogInformation($"User logged in '{input.Email}'."); } return(serviceResponse); }
public ServiceModels.ServiceResponse Update(InputModels.EditSmileysInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); foreach (var smileyInput in input.Smileys) { var smileyRecord = DbContext.Smileys.Find(smileyInput.Id); if (smileyRecord is null) { serviceResponse.Error($@"No smiley was found with the id '{smileyInput.Id}'"); break; } if (smileyRecord.Code != smileyInput.Code) { smileyRecord.Code = smileyInput.Code; DbContext.Update(smileyRecord); } if (smileyRecord.Thought != smileyInput.Thought) { smileyRecord.Thought = smileyInput.Thought; DbContext.Update(smileyRecord); } } if (!serviceResponse.Success) { return(serviceResponse); } DbContext.SaveChanges(); serviceResponse.Message = $"The smiley was updated."; return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> AddThought(InputModels.ThoughtInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var messageRecord = DbContext.Messages.Find(input.MessageId); if (messageRecord is null) { serviceResponse.Error($@"No message was found with the id '{input.MessageId}'"); } var smileyRecord = await DbContext.Smileys.FindAsync(input.SmileyId); if (messageRecord is null) { serviceResponse.Error($@"No smiley was found with the id '{input.SmileyId}'"); } if (!serviceResponse.Success) { return(serviceResponse); } var existingRecord = await DbContext.MessageThoughts .SingleOrDefaultAsync(mt => mt.MessageId == messageRecord.Id && mt.SmileyId == smileyRecord.Id && mt.UserId == UserContext.ApplicationUser.Id); if (existingRecord is null) { var messageThought = new DataModels.MessageThought { MessageId = messageRecord.Id, SmileyId = smileyRecord.Id, UserId = UserContext.ApplicationUser.Id }; DbContext.MessageThoughts.Add(messageThought); if (messageRecord.PostedById != UserContext.ApplicationUser.Id) { var notification = new DataModels.Notification { MessageId = messageRecord.Id, UserId = messageRecord.PostedById, TargetUserId = UserContext.ApplicationUser.Id, Time = DateTime.Now, Type = Enums.ENotificationType.Thought, Unread = true, }; DbContext.Notifications.Add(notification); } } else { DbContext.Remove(existingRecord); var notification = DbContext.Notifications.FirstOrDefault(item => item.MessageId == existingRecord.MessageId && item.TargetUserId == existingRecord.UserId && item.Type == Enums.ENotificationType.Thought); if (notification != null) { DbContext.Remove(notification); } } DbContext.SaveChanges(); serviceResponse.RedirectPath = UrlHelper.DirectMessage(input.MessageId); return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> DeleteMessage(int messageId) { var serviceResponse = new ServiceModels.ServiceResponse(); var record = DbContext.Messages.FirstOrDefault(m => m.Id == messageId); if (record is null) { serviceResponse.Error($@"No record was found with the id '{messageId}'"); } if (!serviceResponse.Success) { return(serviceResponse); } var parentId = record.ParentId; if (parentId != 0) { serviceResponse.RedirectPath = UrlHelper.DirectMessage(parentId); var directReplies = await DbContext.Messages.Where(m => m.ReplyId == messageId).ToListAsync(); foreach (var reply in directReplies) { reply.OriginalBody = $"[quote]{record.OriginalBody}\n" + $"Message deleted by {UserContext.ApplicationUser.DisplayName} on {DateTime.Now.ToString("MMMM dd, yyyy")}[/quote]" + reply.OriginalBody; reply.ReplyId = 0; DbContext.Update(reply); } DbContext.SaveChanges(); } else { serviceResponse.RedirectPath = UrlHelper.Action(nameof(Topics.Index), nameof(Topics)); } var topicReplies = await DbContext.Messages.Where(m => m.ParentId == messageId).ToListAsync(); foreach (var reply in topicReplies) { var replyThoughts = await DbContext.MessageThoughts.Where(mt => mt.MessageId == reply.Id).ToListAsync(); foreach (var replyThought in replyThoughts) { DbContext.MessageThoughts.Remove(replyThought); } DbContext.Messages.Remove(reply); } var messageBoards = await DbContext.MessageBoards.Where(m => m.MessageId == record.Id).ToListAsync(); foreach (var messageBoard in messageBoards) { DbContext.MessageBoards.Remove(messageBoard); } var messageThoughts = await DbContext.MessageThoughts.Where(mt => mt.MessageId == record.Id).ToListAsync(); foreach (var messageThought in messageThoughts) { DbContext.MessageThoughts.Remove(messageThought); } var notifications = DbContext.Notifications.Where(item => item.MessageId == record.Id).ToList(); foreach (var notification in notifications) { DbContext.Notifications.Remove(notification); } DbContext.Messages.Remove(record); DbContext.SaveChanges(); if (parentId > 0) { var parent = DbContext.Messages.FirstOrDefault(item => item.Id == parentId); if (parent != null) { RecountRepliesForTopic(parent); } } return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> UpdateBoard(InputModels.EditBoardInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var record = (await Records()).FirstOrDefault(b => b.Id == input.Id); if (record is null) { serviceResponse.Error($"A record does not exist with ID '{input.Id}'"); } DataModels.Category newCategoryRecord = null; if (!string.IsNullOrEmpty(input.NewCategory)) { input.NewCategory = input.NewCategory.Trim(); } if (!string.IsNullOrEmpty(input.NewCategory)) { newCategoryRecord = (await Categories()).FirstOrDefault(c => c.Name == input.NewCategory); if (newCategoryRecord is null) { var displayOrder = (await Categories()).DefaultIfEmpty().Max(c => c.DisplayOrder); newCategoryRecord = new DataModels.Category { Name = input.NewCategory, DisplayOrder = displayOrder + 1 }; DbContext.Categories.Add(newCategoryRecord); DbContext.SaveChanges(); } } else { try { var newCategoryId = Convert.ToInt32(input.Category); newCategoryRecord = (await Categories()).FirstOrDefault(c => c.Id == newCategoryId); if (newCategoryRecord is null) { serviceResponse.Error(nameof(input.Category), "No category was found with this ID."); } } catch (FormatException) { serviceResponse.Error(nameof(input.Category), "Invalid category ID"); } } if (!string.IsNullOrEmpty(input.Name)) { input.Name = input.Name.Trim(); } if (string.IsNullOrEmpty(input.Name)) { serviceResponse.Error(nameof(input.Name), "Name is a required field."); } if (!string.IsNullOrEmpty(input.Description)) { input.Description = input.Description.Trim(); } if (!serviceResponse.Success) { return(serviceResponse); } record.Name = input.Name; record.Description = input.Description; var oldCategoryId = -1; if (record.CategoryId != newCategoryRecord.Id) { var categoryBoards = (await Records()).Where(r => r.CategoryId == record.CategoryId).ToList(); if (categoryBoards.Count() <= 1) { oldCategoryId = record.CategoryId; } record.CategoryId = newCategoryRecord.Id; } var boardRoles = (from role in await RoleRepository.BoardRoles() where role.BoardId == record.Id select role).ToList(); foreach (var boardRole in boardRoles) { DbContext.BoardRoles.Remove(boardRole); } if (input.Roles != null) { var roleIds = (from role in await RoleRepository.SiteRoles() select role.Id).ToList(); foreach (var inputRole in input.Roles) { if (roleIds.Contains(inputRole)) { DbContext.BoardRoles.Add(new DataModels.BoardRole { BoardId = record.Id, RoleId = inputRole }); } else { serviceResponse.Error($"Role does not exist with id '{inputRole}'"); } } } if (!serviceResponse.Success) { return(serviceResponse); } DbContext.Update(record); DbContext.SaveChanges(); if (oldCategoryId >= 0) { var oldCategoryRecord = (await Categories()).FirstOrDefault(item => item.Id == oldCategoryId); if (oldCategoryRecord != null) { DbContext.Categories.Remove(oldCategoryRecord); DbContext.SaveChanges(); } } serviceResponse.RedirectPath = UrlHelper.Action(nameof(Controllers.Boards.Manage), nameof(Controllers.Boards), new { id = record.Id }); return(serviceResponse); }
public async Task<ServiceModels.ServiceResponse> AddThought(int messageId, int smileyId) { var serviceResponse = new ServiceModels.ServiceResponse(); var messageRecord = DbContext.Messages.Find(messageId); if (messageRecord is null) { serviceResponse.Error($@"No message was found with the id '{messageId}'"); } var smileyRecord = await DbContext.Smileys.FindAsync(smileyId); if (messageRecord is null) { serviceResponse.Error($@"No smiley was found with the id '{smileyId}'"); } if (!serviceResponse.Success) { return serviceResponse; } var existingRecord = await DbContext.MessageThoughts .FirstOrDefaultAsync(mt => mt.MessageId == messageRecord.Id && mt.SmileyId == smileyRecord.Id && mt.UserId == UserContext.ApplicationUser.Id); if (existingRecord is null) { var messageThought = new DataModels.MessageThought { MessageId = messageRecord.Id, SmileyId = smileyRecord.Id, UserId = UserContext.ApplicationUser.Id }; DbContext.MessageThoughts.Add(messageThought); if (messageRecord.PostedById != UserContext.ApplicationUser.Id) { var notification = new DataModels.Notification { MessageId = messageRecord.Id, UserId = messageRecord.PostedById, TargetUserId = UserContext.ApplicationUser.Id, Time = DateTime.Now, Type = ENotificationType.Thought, Unread = true, }; DbContext.Notifications.Add(notification); } } else { DbContext.Remove(existingRecord); var notification = DbContext.Notifications.FirstOrDefault(item => item.MessageId == existingRecord.MessageId && item.TargetUserId == existingRecord.UserId && item.Type == ENotificationType.Thought); if (notification != null) { DbContext.Remove(notification); } } DbContext.SaveChanges(); await ForumHub.Clients.All.SendAsync("updated-message", new HubModels.Message { TopicId = messageRecord.ParentId > 0 ? messageRecord.ParentId : messageRecord.Id, MessageId = messageRecord.Id }); serviceResponse.RedirectPath = UrlHelper.DisplayMessage(messageId); return serviceResponse; }
public async Task <ServiceModels.ServiceResponse> AddBoard(InputModels.CreateBoardInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); if ((await Records()).Any(b => b.Name == input.Name)) { serviceResponse.Error(nameof(input.Name), "A board with that name already exists"); } DataModels.Category categoryRecord = null; if (!string.IsNullOrEmpty(input.NewCategory)) { input.NewCategory = input.NewCategory.Trim(); } if (!string.IsNullOrEmpty(input.NewCategory)) { categoryRecord = (await Categories()).FirstOrDefault(c => c.Name == input.NewCategory); if (categoryRecord is null) { var displayOrder = (await Categories()).DefaultIfEmpty().Max(c => c.DisplayOrder); categoryRecord = new DataModels.Category { Name = input.NewCategory, DisplayOrder = displayOrder + 1 }; DbContext.Categories.Add(categoryRecord); } } else { try { var categoryId = Convert.ToInt32(input.Category); categoryRecord = (await Categories()).First(c => c.Id == categoryId); if (categoryRecord is null) { serviceResponse.Error(nameof(input.Category), "No category was found with this ID."); } } catch (FormatException) { serviceResponse.Error(nameof(input.Category), "Invalid category ID"); } } if (!string.IsNullOrEmpty(input.Name)) { input.Name = input.Name.Trim(); } if (string.IsNullOrEmpty(input.Name)) { serviceResponse.Error(nameof(input.Name), "Name is a required field."); } if (!string.IsNullOrEmpty(input.Description)) { input.Description = input.Description.Trim(); } var existingRecord = (await Records()).FirstOrDefault(b => b.Name == input.Name); if (existingRecord != null) { serviceResponse.Error(nameof(input.Name), "A board with that name already exists"); } if (!serviceResponse.Success) { return(serviceResponse); } DbContext.SaveChanges(); var record = new DataModels.Board { Name = input.Name, Description = input.Description, CategoryId = categoryRecord.Id }; DbContext.Boards.Add(record); DbContext.SaveChanges(); serviceResponse.RedirectPath = UrlHelper.Action(nameof(Controllers.Boards.Manage), nameof(Controllers.Boards), new { id = record.Id }); return(serviceResponse); }
public async Task <ServiceModels.ServiceResponse> Edit(InputModels.EditRoleInput input) { var serviceResponse = new ServiceModels.ServiceResponse(); var record = await RoleManager.FindByIdAsync(input.Id); if (record is null) { serviceResponse.Error(nameof(InputModels.EditRoleInput.Id), $"A record does not exist with ID '{input.Id}'"); } if (input.Name != null) { input.Name = input.Name.Trim(); } if (string.IsNullOrEmpty(input.Name)) { serviceResponse.Error(nameof(InputModels.EditRoleInput.Name), "Name is required"); } if (input.Description != null) { input.Description = input.Description.Trim(); } if (string.IsNullOrEmpty(input.Description)) { serviceResponse.Error(nameof(InputModels.EditRoleInput.Description), "Description is required"); } if (!serviceResponse.Success) { return(serviceResponse); } var existingRole = await RoleManager.FindByNameAsync(input.Name); if (existingRole != null && existingRole.Id != input.Id) { serviceResponse.Error(nameof(InputModels.EditRoleInput.Name), "A role with this name already exists"); } if (!serviceResponse.Success) { return(serviceResponse); } var modified = false; if (record.Name != input.Name) { record.Name = input.Name; modified = true; } if (record.Description != input.Description) { record.Description = input.Description; modified = true; } if (modified) { record.ModifiedById = UserContext.ApplicationUser.Id; record.ModifiedDate = DateTime.Now; await RoleManager.UpdateAsync(record); } serviceResponse.RedirectPath = UrlHelper.Action(nameof(Roles.Index), nameof(Roles)); return(serviceResponse); }