public async Task <DbGrammarExercise> CreateGrammarExerciseAsync(DbGrammarExercise grammarExercise) { if (grammarExercise == null || grammarExercise.Id != 0) { return(null); } var test = await _context.Tests .Where(t => t.Id == grammarExercise.TestId) .SingleOrDefaultAsync(); test.NumberOfQuestions++; _context.GrammarExercises.Add(grammarExercise); await _context.SaveChangesAsync(); return(grammarExercise); }
public async Task <ApplicationUser> AddTestResultAsync(DbTestResult testResult, int userId, int testId) { var user = await _context.Users .Where(u => u.Id == userId) .SingleOrDefaultAsync(); var test = await _context.Tests .Include(t => t.Course) .ThenInclude(c => c.Editor) .Where(t => t.Id == testId) .SingleOrDefaultAsync(); var tryings = await _context.TestTryings .Include(tt => tt.BestResult) .Include(tt => tt.LastResult) .Where(tt => tt.TestId == testId && tt.UserId == userId) .SingleOrDefaultAsync(); var enrollment = await _context.Enrollments .Where(e => e.CourseId == test.CourseId && e.UserId == userId) .SingleOrDefaultAsync(); #region Tryings tryings.Attempts++; tryings.LastResult = testResult; if (tryings.BestResult.RightAnswers < testResult.RightAnswers) { enrollment.Points -= tryings.BestResult.Points; enrollment.Points += testResult.Points; tryings.BestResult = testResult; } if (!tryings.IsCorrect && testResult.RightAnswers >= test.NumberOfQuestions * 0.85) { tryings.IsCorrect = true; var testUsers = await _context.TestTryings .Where(tt => tt.UserId == userId && tt.Test.CourseId == test.CourseId) .ToListAsync(); bool newLevel = true; foreach (var testUser in testUsers) { if (!testUser.IsCorrect) { newLevel = false; } } if (newLevel) { enrollment.Level++; } } #endregion #region User points if (test.Course.EditorId != userId) { float actualPoints = testResult.RightAnswers / (float)test.NumberOfQuestions * (float)test.MaxPoints; int globalPoints = (int)Math.Ceiling(actualPoints / tryings.Attempts); user.Points += globalPoints; } #endregion await _context.SaveChangesAsync(); return(user); }