示例#1
0
        public ActionResult ConfirmDelete(int?id)
        {
            if (!id.HasValue)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_test);
                return(this.RedirectToAction(x => x.Index()));
            }

            var test = this.testsData.GetById(id.Value);

            if (test == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_test);
                return(this.RedirectToAction(x => x.Index()));
            }

            if (!this.CheckIfUserHasProblemPermissions(test.ProblemId))
            {
                return(this.RedirectToContestsAdminPanelWithNoPrivilegesMessage());
            }

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                this.testRunsData.DeleteByTest(id.Value);

                this.testsData.Delete(test);

                this.submissionsBusiness.RecalculatePointsByProblem(test.ProblemId);

                scope.Complete();
            }

            this.TempData.AddInfoMessage(Resource.Test_deleted_successfully);
            return(this.RedirectToAction(c => c.Problem(test.ProblemId)));
        }
示例#2
0
        /// <summary>
        /// Redirects to Problem action after successful deletion of all tests
        /// </summary>
        /// <param name="id">Id for the problem which tests will be deleted</param>
        /// <returns>Redirects to /Administration/Tests/Problem/{id} after succesful deletion otherwise to /Administration/Test/ with proper error message</returns>
        public ActionResult ConfirmDeleteAll(int?id)
        {
            if (!id.HasValue || !this.problemsData.ExistsById(id.Value))
            {
                this.TempData.AddDangerMessage(Resource.Invalid_problem);
                return(this.RedirectToAction(c => c.Index()));
            }

            if (!this.CheckIfUserHasProblemPermissions(id.Value))
            {
                return(this.RedirectToContestsAdminPanelWithNoPrivilegesMessage());
            }

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                this.testRunsData.DeleteByProblem(id.Value);
                this.testsData.DeleteByProblem(id.Value);
                this.submissionsData.RemoveTestRunsCacheByProblem(id.Value);

                scope.Complete();
            }

            this.TempData.AddInfoMessage(Resource.Tests_deleted_successfully);
            return(this.RedirectToAction(c => c.Problem(id.Value)));
        }
示例#3
0
        public void DeleteById(int id)
        {
            var problem = this.problemsData
                          .GetByIdQuery(id)
                          .Select(p => new
            {
                p.ProblemGroupId,
                p.ProblemGroup.ContestId
            })
                          .FirstOrDefault();

            if (problem == null)
            {
                return;
            }

            using (var scope = TransactionsHelper.CreateTransactionScope(IsolationLevel.RepeatableRead))
            {
                this.testRunsData.DeleteByProblem(id);

                this.problemResourcesData.DeleteByProblem(id);

                this.submissionsData.DeleteByProblem(id);

                this.problems.Delete(id);
                this.problems.SaveChanges();

                if (!this.contestsData.IsOnlineById(problem.ContestId))
                {
                    this.problemGroupsBusiness.DeleteById(problem.ProblemGroupId);
                }

                scope.Complete();
            }
        }
示例#4
0
        public void NormalizePointsThatExceedAllowedLimitByContest(int contestId)
        {
            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                this.InternalNormalizeSubmissionPoints(contestId);
                this.InternalNormalizeParticipantScorePoints(contestId);

                scope.Complete();
            }
        }
        public ActionResult ConfirmDelete(int id)
        {
            var submission = this.Data.Submissions
                             .All()
                             .FirstOrDefault(s => s.Id == id);

            if (submission == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_submission_message);
                return(this.RedirectToAction(GlobalConstants.Index));
            }

            if (!submission.ProblemId.HasValue || !this.CheckIfUserHasProblemPermissions(submission.ProblemId.Value))
            {
                this.TempData[GlobalConstants.DangerMessage] = "Нямате привилегиите за това действие";
                return(this.RedirectToAction("Index", "Contests", new { area = "Administration" }));
            }

            if (!submission.ParticipantId.HasValue)
            {
                this.TempData[GlobalConstants.DangerMessage] = "Потребителя не съществува!";
                return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = "Administration" }));
            }

            var submissionProblemId     = submission.ProblemId.Value;
            var submissionParticipantId = submission.ParticipantId.Value;

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                this.testRunsData.DeleteBySubmission(id);

                this.Data.Submissions.Delete(id);
                this.submissionsForProcessingData.RemoveBySubmission(submission.Id);

                this.Data.SaveChanges();

                var isBestSubmission = this.IsBestSubmission(
                    submissionProblemId,
                    submissionParticipantId,
                    submission.Id);

                if (isBestSubmission)
                {
                    this.participantScoresBusiness.RecalculateForParticipantByProblem(
                        submission.ParticipantId.Value,
                        submission.ProblemId.Value);
                }

                this.Data.SaveChanges();

                scope.Complete();
            }

            return(this.RedirectToAction(GlobalConstants.Index));
        }
示例#6
0
        private void HardDeleteByArchivedIds(ICollection <int> ids)
        {
            using (var scope = TransactionsHelper.CreateTransactionScope(IsolationLevel.ReadCommitted))
            {
                this.participantScoresData.RemoveSubmissionIdsBySubmissionIds(ids);
                this.submissions.HardDelete(s => ids.Contains(s.Id));

                this.archivedSubmissionsData.SetToHardDeletedFromMainDatabaseByIds(ids);

                scope.Complete();
            }
        }
        public ActionResult BulkDeleteSubmissions([DataSourceRequest] DataSourceRequest request)
        {
            request.PageSize = 0;

            var submissionsDataSourceResult = this.GetData().ToDataSourceResult(request);
            var submissions = submissionsDataSourceResult.Data;

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                foreach (GridModelType submission in submissions)
                {
                    this.Data.Submissions.Delete(submission.Id);
                    this.submissionsForProcessingData.RemoveBySubmission(submission.Id);
                }

                this.Data.SaveChanges();

                foreach (GridModelType submission in submissions)
                {
                    var dbSubmission = this.Data.Submissions.GetById(submission.Id);

                    if (!dbSubmission.ParticipantId.HasValue)
                    {
                        this.TempData[GlobalConstants.DangerMessage] = "Потребителя не съществува!";
                        return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = "Administration" }));
                    }

                    var submissionProblemId     = dbSubmission.ProblemId.Value;
                    var submissionParticipantId = dbSubmission.ParticipantId.Value;

                    var isBestSubmission = this.IsBestSubmission(
                        submissionProblemId,
                        submissionParticipantId,
                        dbSubmission.Id);

                    if (isBestSubmission)
                    {
                        this.participantScoresBusiness.RecalculateForParticipantByProblem(
                            dbSubmission.ParticipantId.Value,
                            dbSubmission.ProblemId.Value);
                    }
                }

                this.Data.SaveChanges();

                scope.Complete();
            }

            this.TempData[GlobalConstants.InfoMessage] = $"Успешно изтрихте {submissionsDataSourceResult.Total} решения.";
            return(this.RedirectToAction <SubmissionsController>(c => c.Index()));
        }
示例#8
0
        public void RetestById(int id)
        {
            var submissionIds = this.submissionsData.GetIdsByProblem(id).ToList();

            using (var scope = TransactionsHelper.CreateTransactionScope(IsolationLevel.RepeatableRead))
            {
                this.participantScoresData.DeleteAllByProblem(id);

                this.submissionsData.SetAllToUnprocessedByProblem(id);

                this.submissionsForProcessingData.AddOrUpdateBySubmissionIds(submissionIds);

                scope.Complete();
            }
        }
示例#9
0
        public (int updatedSubmissionsCount, int updatedParticipantScoresCount) NormalizeAllPointsThatExceedAllowedLimit()
        {
            int updatedSubmissionsCount,
                updatedParticipantScoresCount;

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                updatedSubmissionsCount       = this.InternalNormalizeSubmissionPoints();
                updatedParticipantScoresCount = this.InternalNormalizeParticipantScorePoints();

                scope.Complete();
            }

            return(updatedSubmissionsCount, updatedParticipantScoresCount);
        }
        public ActionResult Edit(int id, TestViewModel test)
        {
            if (test == null || !this.ModelState.IsValid)
            {
                ImportAllTypesInTest(test);
                return(this.View(test));
            }

            var existingTest = this.testsData.GetById(id);

            if (existingTest == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_test);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            if (!this.CheckIfUserHasProblemPermissions(existingTest.ProblemId))
            {
                this.RedirectToContestsAdminPanelWithNoPrivilegesMessage();
            }

            using (var scope = TransactionsHelper.CreateTransactionScope(IsolationLevel.RepeatableRead))
            {
                existingTest.InputData   = test.InputData;
                existingTest.OutputData  = test.OutputData;
                existingTest.OrderBy     = test.OrderBy;
                existingTest.IsTrialTest = test.Type == TestType.Trial;
                existingTest.IsOpenTest  = test.Type == TestType.Open;
                existingTest.HideInput   = test.HideInput;

                this.testsData.Update(existingTest);

                this.submissionsData.RemoveTestRunsCacheByProblem(existingTest.ProblemId);
                this.testRunsData.DeleteByProblem(existingTest.ProblemId);

                if (test.RetestProblem)
                {
                    this.problemsBusiness.RetestById(existingTest.ProblemId);
                }

                scope.Complete();
            }

            this.TempData.AddInfoMessage(Resource.Test_edited_successfully);
            return(this.RedirectToAction(c => c.Problem(existingTest.ProblemId)));
        }
        public ActionResult Create(ModelType model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                if (model.ProblemId.HasValue)
                {
                    var problem = this.Data.Problems.GetById(model.ProblemId.Value);
                    if (problem != null)
                    {
                        this.ValidateParticipant(model.ParticipantId, problem.ProblemGroup.ContestId);
                    }

                    var submissionType = this.GetSubmissionType(model.SubmissionTypeId.Value);
                    if (submissionType != null)
                    {
                        this.ValidateSubmissionContentLength(model, problem);
                        this.ValidateBinarySubmission(model, problem, submissionType);
                    }
                }

                if (this.ModelState.IsValid)
                {
                    var entity = model.GetEntityModel();
                    entity.Processed = false;

                    using (var scope = TransactionsHelper.CreateTransactionScope())
                    {
                        this.BaseCreate(entity);
                        this.submissionsForProcessingData.AddOrUpdateBySubmission(model.Id.Value);

                        scope.Complete();
                    }

                    this.TempData.AddInfoMessage(Resource.Successful_creation_message);
                    return(this.RedirectToAction(GlobalConstants.Index));
                }
            }

            this.ViewBag.SubmissionAction = "Create";
            return(this.View(model));
        }
示例#12
0
        public ActionResult Import(string problemId, HttpPostedFileBase file, bool retestTask, bool deleteOldFiles)
        {
            if (!int.TryParse(problemId, out var id))
            {
                this.TempData.AddDangerMessage(Resource.Invalid_problem);
                return(this.RedirectToAction(c => c.Index()));
            }

            var problem = this.problemsData.GetById(id);

            if (problem == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_problem);
                return(this.RedirectToAction(c => c.Index()));
            }

            if (!this.CheckIfUserHasProblemPermissions(id))
            {
                this.TempData.AddDangerMessage(GeneralResource.No_privileges_message);
                return(this.Json("No premissions"));
            }

            if (file == null || file.ContentLength == 0)
            {
                this.TempData.AddDangerMessage(Resource.No_empty_file);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            var extension = Path.GetExtension(file.FileName);

            if (extension != ".zip")
            {
                this.TempData.AddDangerMessage(Resource.Must_be_zip);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            TestsParseResult parsedTests;

            using (var memory = new MemoryStream())
            {
                file.InputStream.CopyTo(memory);
                memory.Position = 0;

                try
                {
                    parsedTests = ZippedTestsParser.Parse(memory);
                }
                catch
                {
                    this.TempData.AddDangerMessage(Resource.Zip_damaged);
                    return(this.RedirectToAction(c => c.Problem(id)));
                }
            }

            if (!ZippedTestsParser.AreTestsParsedCorrectly(parsedTests))
            {
                this.TempData.AddDangerMessage(Resource.Invalid_tests);
                return(this.RedirectToAction(c => c.Problem(id)));
            }

            int addedTestsCount;

            using (var scope = TransactionsHelper.CreateTransactionScope(IsolationLevel.RepeatableRead))
            {
                this.submissionsData.RemoveTestRunsCacheByProblem(problem.Id);

                if (deleteOldFiles)
                {
                    this.testRunsData.DeleteByProblem(problem.Id);
                    this.testsData.DeleteByProblem(problem.Id);
                }

                addedTestsCount = ZippedTestsParser.AddTestsToProblem(problem, parsedTests);

                this.problemsData.Update(problem);

                if (retestTask)
                {
                    this.problemsBusiness.RetestById(problem.Id);
                }

                scope.Complete();
            }

            this.TempData.AddInfoMessage(string.Format(Resource.Tests_added_to_problem, addedTestsCount));
            return(this.RedirectToAction(c => c.Problem(id)));
        }
示例#13
0
        public async Task <ActionResult> EqualizeUserIdFromSulsAndJudgeByUserName(string userName)
        {
            var userInfoResponse = await this.httpRequester.GetAsync <ExternalUserInfoModel>(
                new { userName },
                string.Format(UrlConstants.GetUserInfoByUsernameApiFormat, Settings.SulsPlatformBaseUrl),
                Settings.ApiKey);

            if (!userInfoResponse.IsSuccess || userInfoResponse.Data == null)
            {
                return(this.Content($"Cannot get user info from SoftUni Platform for user \"{userName}\""));
            }

            var correctUserId = userInfoResponse.Data.Id;

            var user = this.Data.Users.GetByUsername(userName);

            if (user == null)
            {
                return(this.Content($"Cannot find user with UserName: \"{userName}\" in the database"));
            }

            if (user.Id == correctUserId)
            {
                return(this.Content($"User \"{userName}\" has the same Id as in SoftUni Platform"));
            }

            var tempUserIdToStoreParticipants = this.Data.Users.GetByUsername("gogo4ds")?.Id;

            if (string.IsNullOrEmpty(tempUserIdToStoreParticipants))
            {
                return(this.Content("Invalid temp UserId to store participants"));
            }

            var participantsForUser = this.participantsData.GetAllByUser(user.Id);

            var participantIdsForUser = participantsForUser.Select(x => x.Id).ToList();

            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                this.participantsData.Update(
                    participantsForUser,
                    _ => new Participant
                {
                    UserId = tempUserIdToStoreParticipants,
                });

                this.Data.Users.Update(
                    u => u.UserName == userName,
                    _ => new UserProfile
                {
                    Id = correctUserId,
                });

                if (participantIdsForUser.Any())
                {
                    participantsForUser = this.participantsData
                                          .GetAll()
                                          .Where(p => participantIdsForUser.Contains(p.Id));

                    this.participantsData.Update(
                        participantsForUser,
                        _ => new Participant
                    {
                        UserId = correctUserId,
                    });
                }

                scope.Complete();
            }

            return(this.Content(
                       $@"Done. Changed Id of User ""{userName}"" to match the Id from Suls that is ""{correctUserId}"" 
                and modified his {participantIdsForUser.Count} Participants to point to the new Id"));
        }
        public ActionResult Retest(int id)
        {
            var submission = this.Data.Submissions.GetById(id);

            if (!this.ModelState.IsValid)
            {
                var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
                foreach (var modelStateError in modelStateErrors)
                {
                    this.TempData.AddDangerMessage(modelStateError.ErrorMessage);
                }

                return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = string.Empty }));
            }

            if (submission == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_submission_message);
                return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = string.Empty }));
            }

            var problemIdIsValid   = submission.ProblemId.HasValue;
            var userOwnsSubmission = this.CheckIfUserOwnsSubmission(id);

            if (!problemIdIsValid ||
                (!this.CheckIfUserHasProblemPermissions(submission.ProblemId.Value) &&
                 !userOwnsSubmission))
            {
                return(this.RedirectToContestsAdminPanelWithNoPrivilegesMessage());
            }

            if (this.CheckIfUserHasProblemPermissions(submission.ProblemId.Value) ||
                (string.IsNullOrEmpty(submission.TestRunsCache) &&
                 userOwnsSubmission &&
                 submission.Processed))
            {
                if (!submission.ParticipantId.HasValue)
                {
                    this.TempData[GlobalConstants.DangerMessage] = "Потребителя не съществува!";
                    return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = "Administration" }));
                }

                if (this.IsSubmissionProcessing(submission))
                {
                    this.TempData[GlobalConstants.DangerMessage] = Resource.Submission_is_processing;
                    return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = "Administration" }));
                }

                var submissionProblemId     = submission.ProblemId.Value;
                var submissionParticipantId = submission.ParticipantId.Value;

                using (var scope = TransactionsHelper.CreateTransactionScope())
                {
                    submission.Processed = false;

                    this.submissionsForProcessingData.AddOrUpdateBySubmission(submission.Id);

                    var submissionIsBestSubmission = this.IsBestSubmission(
                        submissionProblemId,
                        submissionParticipantId,
                        submission.Id);

                    if (submissionIsBestSubmission)
                    {
                        this.participantScoresBusiness.RecalculateForParticipantByProblem(
                            submissionParticipantId,
                            submissionProblemId);
                    }

                    this.Data.SaveChanges();

                    scope.Complete();
                }

                this.TempData.AddInfoMessage(Resource.Retest_successful);
                return(this.RedirectToAction("View", "Submissions", new { area = "Contests", id }));
            }

            this.TempData[GlobalConstants.DangerMessage] = "Решението не може да бъде ретествано в момента";
            return(this.RedirectToAction(nameof(ContestsController.Index), "Contests", new { area = string.Empty }));
        }
        public ActionResult Update(ModelType model)
        {
            if (model.Id.HasValue)
            {
                if (!model.ProblemId.HasValue || !this.CheckIfUserHasProblemPermissions(model.ProblemId.Value))
                {
                    this.TempData[GlobalConstants.DangerMessage] = "Нямате привилегиите за това действие";
                    return(this.RedirectToAction("Index", "Contests", new { area = "Administration" }));
                }

                var submission = this.Data.Submissions.GetById(model.Id.Value);
                if (model.SubmissionTypeId.HasValue)
                {
                    var submissionType = this.Data.SubmissionTypes.GetById(model.SubmissionTypeId.Value);
                    if (submissionType.AllowBinaryFilesUpload && model.FileSubmission == null)
                    {
                        model.Content       = submission.Content;
                        model.FileExtension = submission.FileExtension;
                        if (this.ModelState.ContainsKey("Content"))
                        {
                            this.ModelState["Content"].Errors.Clear();
                        }
                    }
                }

                if (this.ModelState.IsValid)
                {
                    var problem = this.Data.Problems.GetById(model.ProblemId.Value);
                    if (problem != null)
                    {
                        this.ValidateParticipant(model.ParticipantId, problem.ProblemGroup.ContestId);
                    }

                    var submissionType = this.GetSubmissionType(model.SubmissionTypeId.Value);
                    if (submissionType != null)
                    {
                        this.ValidateSubmissionContentLength(model, problem);
                        this.ValidateBinarySubmission(model, problem, submissionType);
                    }

                    if (this.ModelState.IsValid)
                    {
                        if (this.IsSubmissionProcessing(submission))
                        {
                            this.TempData[GlobalConstants.DangerMessage] = Resource.Submission_is_processing;
                            return(this.RedirectToAction(nameof(this.Update), "Submissions", new { area = "Administration" }));
                        }

                        var submissionProblemId     = model.ProblemId.Value;
                        var submissionParticipantId = model.ParticipantId.Value;

                        using (var scope = TransactionsHelper.CreateTransactionScope())
                        {
                            submission.Processed = false;

                            this.submissionsForProcessingData.AddOrUpdateBySubmission(submission.Id);

                            var submissionIsBestSubmission = this.IsBestSubmission(
                                submissionProblemId,
                                submissionParticipantId,
                                submission.Id);

                            if (submissionIsBestSubmission)
                            {
                                this.participantScoresBusiness.RecalculateForParticipantByProblem(
                                    submissionParticipantId,
                                    submissionProblemId);
                            }

                            this.Data.SaveChanges();

                            this.UpdateAuditInfoValues(model, submission);
                            this.BaseUpdate(model.GetEntityModel(submission));

                            scope.Complete();
                        }

                        this.TempData.AddInfoMessage(Resource.Successful_edit_message);
                        return(this.RedirectToAction(GlobalConstants.Index));
                    }
                }
            }

            this.ViewBag.SubmissionAction = "Update";
            return(this.View(model));
        }
示例#16
0
        public void RecalculatePointsByProblem(int problemId)
        {
            using (var scope = TransactionsHelper.CreateTransactionScope())
            {
                var problemSubmissions = this.submissionsData
                                         .GetAllByProblem(problemId)
                                         .Include(s => s.TestRuns)
                                         .Include(s => s.TestRuns.Select(tr => tr.Test))
                                         .ToList();

                var submissionResults = problemSubmissions
                                        .Select(s => new
                {
                    s.Id,
                    s.ParticipantId,
                    CorrectTestRuns = s.TestRuns.Count(t =>
                                                       t.ResultType == TestRunResultType.CorrectAnswer &&
                                                       !t.Test.IsTrialTest),
                    AllTestRuns = s.TestRuns.Count(t => !t.Test.IsTrialTest),
                    MaxPoints   = s.Problem.MaximumPoints
                })
                                        .ToList();

                var problemSubmissionsById = problemSubmissions.ToDictionary(s => s.Id);
                var topResults             = new Dictionary <int, ParticipantScoreModel>();

                foreach (var submissionResult in submissionResults)
                {
                    var submission = problemSubmissionsById[submissionResult.Id];
                    var points     = 0;
                    if (submissionResult.AllTestRuns != 0)
                    {
                        points = (submissionResult.CorrectTestRuns * submissionResult.MaxPoints) /
                                 submissionResult.AllTestRuns;
                    }

                    submission.Points = points;
                    submission.CacheTestRuns();

                    if (!submissionResult.ParticipantId.HasValue)
                    {
                        continue;
                    }

                    var participantId = submissionResult.ParticipantId.Value;

                    if (!topResults.ContainsKey(participantId) || topResults[participantId].Points < points)
                    {
                        topResults[participantId] = new ParticipantScoreModel
                        {
                            Points       = points,
                            SubmissionId = submission.Id
                        };
                    }
                    else if (topResults[participantId].Points == points)
                    {
                        if (topResults[participantId].SubmissionId < submission.Id)
                        {
                            topResults[participantId].SubmissionId = submission.Id;
                        }
                    }
                }

                this.submissions.SaveChanges();

                var participants = topResults.Keys.ToList();

                var existingScores = this.participantScoresData
                                     .GetAllByProblem(problemId)
                                     .Where(p => participants.Contains(p.ParticipantId))
                                     .ToList();

                foreach (var existingScore in existingScores)
                {
                    var topScore = topResults[existingScore.ParticipantId];

                    existingScore.Points       = topScore.Points;
                    existingScore.SubmissionId = topScore.SubmissionId;
                }

                this.submissions.SaveChanges();

                scope.Complete();
            }
        }