public async Task <IActionResult> EditItem(IFormCollection request) { try { if (string.IsNullOrEmpty(request.Str("navitem"))) { return(BadRequest(new ResponseHelper("Something went wrong, please try again later", "No nav-item data was sent"))); } NavItem updatedItem = JsonConvert.DeserializeObject <NavItem>(request.Str("navitem")); // If ID is zero, this is a new item, use the AddItem method if (updatedItem.Id == 0) { return(await AddItem(request)); } // Check whether an existing navitem has that id NavItem originalItem = await _Db.NavItems.AsNoTracking().FirstOrDefaultAsync((item) => item.Id == updatedItem.Id); if (originalItem == null) { return(NotFound(new ResponseHelper("Something went wrong, please try again later."))); } // Delete any old drop down links for the nav item List <NavItemPage> dropdowns = await _Db.NavItemPages.Where(n => n.NavItemId == updatedItem.Id).ToListAsync(); _Db.RemoveRange(dropdowns); await _Db.SaveChangesAsync(); // Mark item as updated _Db.Update(updatedItem); _Db.Entry(updatedItem).Property(i => i.OrderIndex).IsModified = false; _Db.Entry(updatedItem).Property(i => i.Section).IsModified = false; // Add new dropdowns, if any if (updatedItem.NavItemPages != null) { // Add order index to items before saving for (int i = 0; i < updatedItem.NavItemPages.Count; i++) { updatedItem.NavItemPages[i].OrderIndex = i; } _Db.AddRange(updatedItem.NavItemPages); } // Write changes to database await _Db.SaveChangesAsync(); return(Ok(updatedItem.Id)); } catch (Exception ex) { _Logger.LogError("Error updating navlink", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later.", ex.Message))); } }
public async Task <IActionResult> UpdateActivity(int activityId, [FromBody] ActivityArgs activityArgs) { // Check validation status - see ActivityArgs class for validation logic if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } // Check that QR code is not in use elsewhere if (!(await IsValidQrCode(activityArgs.QrCode, activityId))) { return(BadRequest(new ResponseHelper("QR code already in use."))); } // Use a transaction to avoid losing data if an exception is thrown using (var transaction = await _Db.Database.BeginTransactionAsync()) { // Retrieve existing activity - confirm its existence Activity oldActivity = await _Db.Activities.Include(a => a.ActivityImages).Where(a => a.Id == activityId).FirstOrDefaultAsync(); if (oldActivity == null) { return(NotFound(new ResponseHelper("Something went wrong. Please refresh the page and try again.", "Could not find activity in database"))); } oldActivity.TrackId = oldActivity.TrackId; oldActivity.Title = activityArgs.Title; oldActivity.Active = oldActivity.Active; oldActivity.ActivityType = activityArgs.ActivityType; oldActivity.FactFileId = activityArgs.FactFileId; oldActivity.Description = activityArgs.Description; oldActivity.Task = activityArgs.Task; oldActivity.ImageId = activityArgs.ImageId; oldActivity.CoordX = activityArgs.CoordX; oldActivity.CoordY = activityArgs.CoordY; oldActivity.QrCode = activityArgs.QrCode; // Save new activity to generate ID _Db.Update(oldActivity); await _Db.SaveChangesAsync(); // Remove old activity images _Db.RemoveRange(oldActivity.ActivityImages); // Add pivot table records for activity images _Db.AddRange(activityArgs.Images.Select(imageId => new ActivityImage { ImageId = imageId, ActivityId = oldActivity.Id })); // Save pivot table records await _Db.SaveChangesAsync(); // All database queries complete, commit the transaction transaction.Commit(); } return(Ok()); }
public async Task <IActionResult> DeleteCategory(int id) { try { FactFileCategory category = await _Db.FactFileCategories .Include(cat => cat.FactFileEntries) .ThenInclude(entry => entry.Activities) .Include(cat => cat.FactFileEntries) .ThenInclude(entry => entry.FactFileEntryImages) .Include(cat => cat.FactFileEntries) .ThenInclude(entry => entry.FactFileNuggets) .Where(cat => cat.Id == id) .FirstOrDefaultAsync(); if (category == null) { return(NotFound(new ResponseHelper("Something went wrong. If the problem persists, please contact the developers"))); } if (category.FactFileEntries.Any(entry => entry.Activities.Count > 0)) { StringBuilder message = new StringBuilder("Unable to delete the category as the following entries are linked to guided walk actvities:\n"); foreach (FactFileEntry entry in category.FactFileEntries) { if (entry.Activities.Count > 0) { message.AppendLine(entry.PrimaryName + ", "); } } return(BadRequest(new ResponseHelper(message.ToString()))); } // Delete all fact file entry images and nuggets first (can't use cascade delete due to EF Core) foreach (FactFileEntry entry in category.FactFileEntries) { _Db.RemoveRange(entry.FactFileEntryImages); _Db.RemoveRange(entry.FactFileNuggets); } _Db.Remove(category); await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error deleting category", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again in a few minutes.", ex.Message))); } }
public async Task <IActionResult> UpdateQuestion(int quizId, int questionId, [FromBody] QuestionArgs data) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } Quiz quiz = await _Db.Quizzes.FindAsync(quizId); QuizQuestion question = await _Db.QuizQuestions.Include(q => q.Answers).Where(q => q.Id == questionId).FirstOrDefaultAsync(); if (quiz == null || question == null) { return(NotFound(new ResponseHelper("Something went wrong. Please refresh your browser and try again.", "Unable to find question in database"))); } using (var transaction = await _Db.Database.BeginTransactionAsync()) { question.CorrectAnswerId = null; await _Db.SaveChangesAsync(); _Db.RemoveRange(question.Answers); await _Db.SaveChangesAsync(); question.ImageId = data.Image?.Id; question.Text = data.Text; question.TrueFalseAnswer = data.TrueFalseAnswer; question.AudioId = data.Audio?.Id; if (data.Answers != null) { foreach (AnswerArgs answerArgs in data.Answers) { QuizAnswer newAns = new QuizAnswer { QuizQuestionId = question.Id, Text = answerArgs.Text, ImageId = answerArgs.Image?.Id }; await _Db.AddAsync(newAns); await _Db.SaveChangesAsync(); if (data.Answers.IndexOf(answerArgs) == data.CorrectAnswerIndex) { question.CorrectAnswerId = newAns.Id; } } } quiz.UpdatedAt = DateTime.UtcNow; await _Db.SaveChangesAsync(); transaction.Commit(); } return(Ok()); }