public bool AddParticipantToDefaultTeam(string participantId) { using (var db = new ContestMeterDbContext()) { var user = db.Users.Find(participantId); if (user == null) { return(false); } var defaultTeam = db.Teams.FirstOrDefault(t => t.Name == "Одиночки"); if (defaultTeam == null) { return(false); } var teamParticipant = new TeamParticipant { Id = Guid.NewGuid(), TeamId = defaultTeam.Id, ParticipantId = user.Id }; db.Entry(teamParticipant).State = EntityState.Added; user.TeamId = defaultTeam.Id; defaultTeam.Participants.Add(user); db.Entry(user).State = EntityState.Modified; db.Entry(defaultTeam).State = EntityState.Modified; db.SaveChanges(); return(true); } }
public async System.Threading.Tasks.Task <ActionResult> Participate([Bind(Include = "ContestId, CurrentTaskId, CurrentTaskNumber, SelectedDevelopmentToolId")] ParticipantTaskPartialViewModel model, HttpPostedFileBase fileUpload) { var tasks = await _db.Tasks.Where(t => t.ContestId == model.ContestId).ToListAsync(); if (tasks == null || tasks.Count < 1) { TempData["Message"] = "Произошла ошибка: кол-во задач и компиляторов должно быть больше 0"; return(RedirectToAction("Contests")); //ViewBag.ErrorMessage = "Произошла ошибка: кол-во задач и компиляторов должно быть больше 0"; //return View("Error"); } var model2 = new ParticipantParticipateViewModel { ContestId = model.ContestId, CurrentTaskNumber = model.CurrentTaskNumber, Tasks = tasks }; if (ModelState.IsValid) { if (!string.IsNullOrEmpty(fileUpload?.FileName)) { var ext = Path.GetExtension(fileUpload.FileName); if (_allowedExtForSolutionFiles.Any(e => e == ext)) { byte[] solutionData; using (var binaryReader = new BinaryReader(fileUpload.InputStream)) { solutionData = binaryReader.ReadBytes(fileUpload.ContentLength); } var currentUserId = User.Identity.GetUserId(); var postedSolution = await _db.PostedSolutions.Where( s => s.TaskId == model.CurrentTaskId && s.UserId == currentUserId) .FirstOrDefaultAsync(); if (postedSolution != null) { postedSolution.Solution = solutionData; _db.Entry(postedSolution).State = EntityState.Modified; await _db.SaveChangesAsync(); } else { var postedSolutionId = Guid.NewGuid(); postedSolution = new PostedSolution { Id = postedSolutionId, UserId = User.Identity.GetUserId(), TaskId = model.CurrentTaskId, DevelopmentToolId = model.SelectedDevelopmentToolId, Solution = solutionData, IsChecked = false }; _db.PostedSolutions.Add(postedSolution); _db.SaveChanges(); } var task = postedSolution.Task; var contest = task.Contest; var devTool = _db.DevelopmentTools.Find(model.SelectedDevelopmentToolId); var user = _db.Users.Find(currentUserId); var postedSolutionsRootFolder = ConfigurationManager.AppSettings["PostedSolutionsRootFolder"]; var contestTypeName = contest.ContestsType.Name; var contestName = contest.Name; var userIp = user.Ip; var solutionsFolder = Path.Combine(postedSolutionsRootFolder, contestTypeName, contestName, userIp); if (!Directory.Exists(solutionsFolder)) { Directory.CreateDirectory(solutionsFolder); } var sourcePath = Path.Combine(solutionsFolder, task.ExecutableName) + ext; if (ByteArrayToFile(sourcePath, solutionData)) { try { var taskCheckSolution = new System.Threading.Tasks.Task <Solution>(() => { return(CheckPostedSolution(contest, user, task, devTool, solutionsFolder, LocalFolder, sourcePath)); }); _checkSolutionQueue.AddTask(taskCheckSolution); taskCheckSolution.Wait(); var solution = taskCheckSolution.Result; var userAttempt = new UserAttempt { Id = Guid.NewGuid(), ContestId = contest.Id, TaskId = task.Id, UserId = user.Id, CreatedDate = DateTime.Now, Solution = solutionData, SolutionExtension = ext, Score = solution.WeightedScore, DevelopmentToolId = devTool.Id, FailedRuns = solution.FailedRuns, FailedChecks = solution.FailedChecks }; _db.UserAttempts.Add(userAttempt); postedSolution.IsChecked = true; _db.Entry(postedSolution).State = EntityState.Modified; await _db.SaveChangesAsync(); TempData["Message"] = "Решение было отправлено и проверено. \nБаллов: " + solution.WeightedScore + "\nПроваленных запусков: " + solution.FailedRuns + "\nПроваленных тестов: " + solution.FailedChecks; //ToDo: вывести результат в другом виде? } catch (Exception ex) { var exeptionLog = new ExceptionsLog { Id = Guid.NewGuid(), ContestId = contest.Id, CreatedDate = DateTime.Now, UserId = user.Id, Text = ex.InnerException.Message }; _db.ExceptionsLogs.Add(exeptionLog); _db.SaveChanges(); TempData["Message"] = "При проверке решения возникло исключение: " + ex.InnerException.Message; //ToDo: вывести результат в другом виде? } if (Directory.Exists(postedSolutionsRootFolder)) { Directory.Delete(postedSolutionsRootFolder, true); } } else { TempData["Message"] = "Решение не было сохранено в локальном каталоге участника"; } } else { ModelState.AddModelError("", "Недопустимое расширения загружаемого файла решения"); return(View(model2)); } } else { ModelState.AddModelError("", "Не выбран загружаемый файл решения"); return(View(model2)); } //db.Tasks.Add(task); //await db.SaveChangesAsync(); return(RedirectToAction("Participate", new { id = model.ContestId, currentTaskNumber = model.CurrentTaskNumber })); } return(View(model2)); }
public async System.Threading.Tasks.Task <ActionResult> DeleteAccount(string id) { if (string.IsNullOrEmpty(id)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var user = db.Users.Find(id); if (user == null) { return(HttpNotFound()); } var administratorsRoleId = db.Roles.First(r => r.Name == "administrator").Id; var participantsRoleId = db.Roles.First(r => r.Name == "participant").Id; var teachersRoleId = db.Roles.First(r => r.Name == "teacher").Id; var userRoleId = user.Roles.First().RoleId; if (administratorsRoleId == userRoleId) { TempData["Message"] = "Администратор не может удалить свою учетную запись"; return(RedirectToAction("DeletedAccountsList")); //ViewBag.ErrorMessage = "Администратор не может удалить свою учетную запись"; //return View("Error"); } else if (participantsRoleId == userRoleId) { var userTeam = db.Teams.FirstOrDefault(t => t.Id == user.TeamId); if (userTeam != null) { userTeam.Participants.Remove(user); db.Entry(userTeam).State = EntityState.Modified; } var teamParticipants = db.TeamParticipants.FirstOrDefault(tp => tp.ParticipantId == user.Id && tp.TeamId == userTeam.Id); if (teamParticipants != null) { db.Entry(teamParticipants).State = EntityState.Deleted; } } else if (teachersRoleId == userRoleId) { var teacherContests = db.Contests.Where(c => c.TeacherId == user.Id); foreach (var teacherContest in teacherContests) { db.Entry(teacherContest).State = EntityState.Deleted; } db.SaveChanges(); } if (user.UserInfoId != null) { var userInfo = await db.UserInfos.FindAsync(user.UserInfoId); if (userInfo != null) { db.Entry(userInfo).State = EntityState.Deleted; await db.SaveChangesAsync(); } } var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db)); userManager.Delete(user); await db.SaveChangesAsync(); TempData["Message"] = "Пользователь " + user.UserName + " был удален."; return(RedirectToAction("DeletedAccountsList")); }