public ActionResult ReplyToAlertGET(string alertid) { //Check Alert is not null if (string.IsNullOrEmpty(alertid)) { TempData["ErrorMessage"] = "An error has occured"; return(RedirectToAction("Index")); } //Check Alert is an int if (!int.TryParse(alertid, out int AlertIdInt)) { TempData["ErrorMessage"] = "Error: Alert ID is incorrect"; return(RedirectToAction("Index")); } //Check Alert exists var Alert = _context.Alert.SingleOrDefault(n => n.Id == AlertIdInt); if (Alert == null) { TempData["ErrorMessage"] = "Error: The alert you are replying to doesn't exist"; return(RedirectToAction("Index")); } //Check if alert dismissed if (Alert.DismissedWhen != null) { TempData["ErrorMessage"] = "Error: The alert you are replying to has been dismissed"; return(RedirectToAction("Index")); } //If alert being replied to belongs to user and not group if (Alert.ToUserId != null && Alert.ToGroupId == null) { //Check Alert belongs to user if (Alert.ToUserId != User.Identity.GetUserId()) { TempData["ErrorMessage"] = "Error: This alert you attempted to reply to does not belong to you"; return(RedirectToAction("Index")); } //Populate data for view ReplyAlertViewModel model; using (ApplicationDbContext dbcontext = new ApplicationDbContext()) { Group ToGroup = dbcontext.Group.SingleOrDefault(n => n.Id == Alert.FromGroupId); ApplicationUser ToUser = dbcontext.Users.SingleOrDefault(n => n.Id.Equals(Alert.FromUserId)); model = new ReplyAlertViewModel() { ReplyingToMessage = Alert.Text, FromGroupName = null, FromUserName = User.Identity.GetUserName(), ReplyToGroupName = ToGroup?.Name, ReplyToUserName = ToUser?.UserName, Resource = null }; } //Return to view return(View("ReplyToAlert", model)); } //If alert being replied to belongs to group else { //Check logged in User is member of group var LoggedInUserId = User.Identity.GetUserId(); var GroupMember = _context.GroupMember.SingleOrDefault(n => (n.Group_Id == Alert.ToGroupId) && (n.User_Id.Equals(LoggedInUserId))); if (GroupMember == null) { TempData["ErrorMessage"] = "Error: You are not a member of the group to which this alert is associated to"; return(RedirectToAction("Index")); } //Populate data for view ReplyAlertViewModel model; using (ApplicationDbContext dbcontext = new ApplicationDbContext()) { Group ToGroup = dbcontext.Group.SingleOrDefault(n => n.Id == Alert.FromGroupId); ApplicationUser ToUser = dbcontext.Users.SingleOrDefault(n => n.Id.Equals(Alert.FromUserId)); Group FromGroup = dbcontext.Group.SingleOrDefault(n => n.Id == Alert.ToGroupId); model = new ReplyAlertViewModel() { ReplyingToMessage = Alert.Text, FromGroupName = FromGroup?.Name, FromUserName = User.Identity.GetUserName(), ReplyToGroupName = ToGroup?.Name, ReplyToUserName = ToUser?.UserName, Resource = FromGroup.Id.ToString() }; } //Return to view return(View("ReplyToAlert", model)); } }