public void ReadSubmissionResultsWhenParticipantHasSubmissionsShouldReturnNumberOfSubmissions()
        {
            var contest = this.CreateAndSaveContest("contest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);

            var problem = new Problem();
            contest.Problems.Add(problem);

            var submissionType = new SubmissionType();
            contest.SubmissionTypes.Add(submissionType);

            var participant = new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete);
            contest.Participants.Add(participant);

            for (int i = 0; i < 10; i++)
            {
                var submission = new Submission
                {
                    ContentAsString = "Test submission " + i,
                    SubmissionType = submissionType,
                    Problem = problem
                };

                participant.Submissions.Add(submission);
            }

            this.EmptyOjsData.SaveChanges();

            var result = this.CompeteController
                .ReadSubmissionResults(new DataSourceRequest(), problem.Id, this.IsCompete) as JsonResult;

            var responseData = result.Data as DataSourceResult;
            Assert.AreEqual(participant.Submissions.Count, responseData.Total);
        }
        public void DownloadResourceActionWhenCompetingResourceIsAvailableAndUserIsRegisteredForCompeteShouldReturnResource()
        {
            var contest = this.CreateAndSaveContest("testContest", this.ActiveContestWithPasswordOptions, this.InactiveContestOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File = new[]
                {
                    (byte)this.RandomGenerator.Next(0, byte.MaxValue),
                    (byte)this.RandomGenerator.Next(0, byte.MaxValue)
                },
                Name = "resourceName",
                FileExtension = "test"
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete));
            this.EmptyOjsData.SaveChanges();

            var result = this.CompeteController.DownloadResource(resource.Id, this.IsCompete) as FileContentResult;
            var expectedFileName = string.Format("{0}_{1}.{2}", problem.Name, resource.Name, resource.FileExtension);
            Assert.AreEqual(expectedFileName, result.FileDownloadName);
            Assert.IsTrue(resource.File.SequenceEqual(result.FileContents));
        }
        public void GetSubmissionContentWhenInvalidSubmissionIdShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("sample Name", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);
            var problem = new Problem();
            contest.Problems.Add(problem);

            var submissionType = new SubmissionType();
            contest.SubmissionTypes.Add(submissionType);

            var participant = new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete);
            contest.Participants.Add(participant);
            var submission = new Submission
            {
                ContentAsString = "test content"
            };

            participant.Submissions.Add(submission);
            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.GetSubmissionContent(-1);
                Assert.Fail("Expected an exception when an invalid submission id is provided.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.NotFound, ex.GetHttpCode());
            }
        }
        public void DownloadTaskLinkShouldNavigateProperly()
        {
            var contest = new Contest { Name = "1337", };
            var problem = new Problem { Contest = contest, Name = "1337", OldId = 1337 };
            var resource = new ProblemResource { Problem = problem, Type = ProblemResourceType.ProblemDescription };
            this.EmptyOjsData.Resources.Add(resource);
            this.EmptyOjsData.SaveChanges();

            this.VerifyUrlRedirection("~/Contest/DownloadTask/1337", string.Format("/Contests/Practice/DownloadResource/{0}", resource.Id));
        }
 public ContestProblemViewModel(Problem problem)
 {
     this.ProblemId = problem.Id;
     this.Name = problem.Name;
     this.ContestId = problem.ContestId;
     this.Resources = problem.Resources.AsQueryable()
                                         .OrderBy(x => x.OrderBy)
                                         .Where(x => !x.IsDeleted)
                                         .Select(ContestProblemResourceViewModel.FromResource);
     this.TimeLimit = problem.TimeLimit;
     this.MemoryLimit = problem.MemoryLimit;
 }
        public void ReadSubmissionResultsWhenParticipantHasNoSubmissionShouldReturnNoResults()
        {
            var contest = this.CreateAndSaveContest("contest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);
            var problem = new Problem();
            var submissionType = new SubmissionType();
            contest.Problems.Add(problem);
            contest.SubmissionTypes.Add(submissionType);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete));
            this.EmptyOjsData.SaveChanges();

            var result = this.CompeteController
                .ReadSubmissionResults(new DataSourceRequest(), problem.Id, this.IsCompete) as JsonResult;

            var responseData = result.Data as DataSourceResult;
            Assert.AreEqual(0, responseData.Total);
        }
 public ContestProblemViewModel(Problem problem)
 {
     this.ProblemId = problem.Id;
     this.Name = problem.Name;
     this.ContestId = problem.ContestId;
     this.ShowResults = problem.ShowResults;
     this.Resources = problem.Resources.AsQueryable()
                                         .OrderBy(x => x.OrderBy)
                                         .Where(x => !x.IsDeleted)
                                         .Select(ContestProblemResourceViewModel.FromResource);
     this.TimeLimit = problem.TimeLimit;
     this.MemoryLimit = problem.MemoryLimit;
     this.FileSizeLimit = problem.SourceCodeSizeLimit;
     this.CheckerName = problem.Checker.Name;
     this.CheckerDescription = problem.Checker.Description;
 }
        public static void AddTestsToProblem(Problem problem, TestsParseResult tests)
        {
            var lastTrialTest = problem.Tests.Where(x => x.IsTrialTest).OrderByDescending(x => x.OrderBy).FirstOrDefault();
            int zeroTestsOrder = 1;

            if (lastTrialTest != null)
            {
                zeroTestsOrder = lastTrialTest.OrderBy + 1;
            }

            for (int i = 0; i < tests.ZeroInputs.Count; i++)
            {
                problem.Tests.Add(new Test
                {
                    IsTrialTest = true,
                    OrderBy = zeroTestsOrder,
                    Problem = problem,
                    InputDataAsString = tests.ZeroInputs[i],
                    OutputDataAsString = tests.ZeroOutputs[i],
                });

                zeroTestsOrder++;
            }

            var lastTest = problem.Tests.Where(x => !x.IsTrialTest).OrderByDescending(x => x.OrderBy).FirstOrDefault();
            int count = 1;

            if (lastTest != null)
            {
                count = lastTest.OrderBy + 1;
            }

            for (int i = 0; i < tests.Inputs.Count; i++)
            {
                problem.Tests.Add(new Test
                {
                    IsTrialTest = false,
                    OrderBy = count,
                    Problem = problem,
                    InputDataAsString = tests.Inputs[i],
                    OutputDataAsString = tests.Outputs[i]
                });

                count++;
            }
        }
        public void ProblemActionWhenContestCanBeCompetedButUserIsNotRegisteredShouldRedirectToRegistration()
        {
            var contest = this.CreateAndSaveContest("testContest", this.ActiveContestWithPasswordAndQuestionsOptions, this.ActiveContestWithPasswordAndQuestionsOptions);
            var problem = new Problem
            {
                ContestId = contest.Id,
                Name = "Sample Problem"
            };

            contest.Problems.Add(problem);
            this.EmptyOjsData.SaveChanges();

            var result = this.CompeteController.Problem(problem.Id, this.IsCompete) as RedirectToRouteResult;

            Assert.IsNull(result.RouteValues["controller"]);
            Assert.AreEqual(contest.Id, result.RouteValues["id"]);
            Assert.AreEqual(this.IsCompete, result.RouteValues["official"]);
            Assert.AreEqual("Register", result.RouteValues["action"]);
        }
        public void SubmitActionWhenParticipantSendsAnotherSubmissionBeforeLimitHasPassedShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("test contest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);
            contest.LimitBetweenSubmissions = 100;

            var problem = new Problem
            {
                Name = "test problem"
            };

            var submissionType = new SubmissionType
            {
                Name = "test submission type"
            };

            contest.Problems.Add(problem);
            contest.SubmissionTypes.Add(submissionType);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete));
            this.EmptyOjsData.SaveChanges();

            var submission = new SubmissionModel
            {
                Content = "test content",
                ProblemId = problem.Id,
                SubmissionTypeId = submissionType.Id
            };

            var result = this.CompeteController.Submit(submission, this.IsCompete) as JsonResult;
            var receivedContestId = (int)result.Data;
            Assert.AreEqual(receivedContestId, contest.Id);

            try
            {
                var secondSubmissionResult = this.CompeteController.Submit(submission, this.IsCompete);
                Assert.Fail("Expected an exception when a participant sends too many submissions");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.ServiceUnavailable, ex.GetHttpCode());
            }
        }
        public void GetSubmissionContentWhenSubmissionNotMadeByTheParticipantShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("sample Name", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);
            var problem = new Problem();
            contest.Problems.Add(problem);

            var submissionType = new SubmissionType();
            contest.SubmissionTypes.Add(submissionType);

            var participant = new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete);

            var anotherUser = new UserProfile
            {
                UserName = "******",
                Email = "*****@*****.**"
            };

            this.EmptyOjsData.Users.Add(anotherUser);
            var anotherParticipant = new Participant(contest.Id, anotherUser.Id, this.IsCompete);

            contest.Participants.Add(participant);
            contest.Participants.Add(anotherParticipant);

            var submission = new Submission
            {
                ContentAsString = "test content"
            };

            anotherParticipant.Submissions.Add(submission);
            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.GetSubmissionContent(submission.Id);
                Assert.Fail("Expected an exception when trying to download a submission that was not made by the participant that requested it.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.GetHttpCode());
            }
        }
        public void ProblemActionWhenContestCanBeCompetedUserIsRegisteredAndProblemHasMaterialsShouldReturnPartialView()
        {
            var contest = this.CreateAndSaveContest("testContest", this.ActiveContestNoPasswordOptions, this.InactiveContestOptions);
            var problem = new Problem()
            {
                ContestId = contest.Id,
                Name = "Sample Problem",
                Resources = new HashSet<ProblemResource>
                {
                    new ProblemResource
                    {
                        File = new byte[10],
                        FileExtension = "txt"
                    },
                    new ProblemResource
                    {
                        File = new byte[100],
                        FileExtension = "docx"
                    },
                    new ProblemResource
                    {
                        Link = "http://www.testlink.com"
                    }
                },
                Checker = new Checker { Name = "Checker" }
            };

            contest.Problems.Add(problem);
            this.EmptyOjsData.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete));
            this.EmptyOjsData.SaveChanges();

            var result = this.CompeteController.Problem(problem.Id, this.IsCompete) as PartialViewResult;
            var model = result.Model as ContestProblemViewModel;

            Assert.AreEqual("Compete", result.ViewBag.CompeteType);
            Assert.IsNotNull(model);
            Assert.AreEqual(problem.Name, model.Name);
            Assert.AreEqual(problem.Id, model.ProblemId);
            Assert.AreEqual(problem.Resources.Count, model.Resources.Count());
        }
        public void ReadSubmissionResultsWhenUserNotRegisteredForContestShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("contest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);

            var problem = new Problem();
            contest.Problems.Add(problem);

            var submissionType = new SubmissionType();
            contest.SubmissionTypes.Add(submissionType);

            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.ReadSubmissionResults(new DataSourceRequest(), problem.Id, this.IsCompete);
                Assert.Fail("Expected an exception when user is not registered for exam, but tries to access his results");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Unauthorized, ex.GetHttpCode());
            }
        }
        public void SubmitActionWhenParticipantSendsAnotherSubmissionAndThereIsNoLimitShouldReturnJson()
        {
            var contest = this.CreateAndSaveContest("test contest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);

            // no limit between submissions
            contest.LimitBetweenSubmissions = 0;

            var problem = new Problem
            {
                Name = "test problem"
            };

            var submissionType = new SubmissionType
            {
                Name = "test submission type"
            };

            contest.Problems.Add(problem);
            contest.SubmissionTypes.Add(submissionType);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete));
            this.EmptyOjsData.SaveChanges();

            var submission = new SubmissionModel
            {
                Content = "test content",
                ProblemId = problem.Id,
                SubmissionTypeId = submissionType.Id
            };

            var result = this.CompeteController.Submit(submission, this.IsCompete) as JsonResult;
            var receivedContestId = (int)result.Data;
            Assert.AreEqual(receivedContestId, contest.Id);

            var secondSubmissionResult = this.CompeteController.Submit(submission, this.IsCompete) as JsonResult;
            var secondSubmissionResultContestId = (int)secondSubmissionResult.Data;

            Assert.AreEqual(receivedContestId, secondSubmissionResultContestId);
        }
        public void DownloadResourceActionWhenCompeteAndUserNotRegisteredForCompeteShouldRegirectToRegistrationPage()
        {
            var contest = this.CreateAndSaveContest("testContest", this.InactiveContestOptions, this.ActiveContestWithPasswordOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File = new byte[1],
                FileExtension = "test"
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            this.EmptyOjsData.SaveChanges();

            var result = this.CompeteController.DownloadResource(resource.Id, this.IsPractice) as RedirectToRouteResult;

            Assert.AreEqual("Register", result.RouteValues["action"]);
            Assert.AreEqual(contest.Id, result.RouteValues["id"]);
            Assert.AreEqual(this.IsPractice, result.RouteValues["official"]);
        }
        public void ProblemActionWhenContestCannotBePracticedShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("testContest", this.InactiveContestOptions, this.InactiveContestOptions);
            var problem = new Problem
            {
                ContestId = contest.Id,
                Name = "Sample Problem"
            };

            contest.Problems.Add(problem);
            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.Problem(problem.Id, this.IsPractice);
                Assert.Fail("No exception was thrown when a contest cannot be competed, but a contest roblem is requested.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.GetHttpCode());
            }
        }
        private void AddTestsToProblem(Problem problem, HttpPostedFileBase testArchive)
        {
            var extension = testArchive.FileName.Substring(testArchive.FileName.Length - 4, 4);

            if (extension != ".zip")
            {
                throw new ArgumentException("Тестовете трябва да бъдат в .ZIP файл");
            }

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

                var parsedTests = new TestsParseResult();

                parsedTests = ZippedTestsManipulator.Parse(memory);

                if (parsedTests.ZeroInputs.Count != parsedTests.ZeroOutputs.Count || parsedTests.Inputs.Count != parsedTests.Outputs.Count)
                {
                    throw new ArgumentException("Невалидни тестове");
                }

                ZippedTestsManipulator.AddTestsToProblem(problem, parsedTests);
            }
        }
        private void AddResourcesToProblem(Problem problem, IEnumerable<ProblemResourceViewModel> resources)
        {
            var orderCount = 0;

            foreach (var resource in resources)
            {
                if (!string.IsNullOrEmpty(resource.Name) && resource.Type == ProblemResourceType.Video && resource.Link != null)
                {
                    problem.Resources.Add(new ProblemResource
                    {
                        Name = resource.Name,
                        Type = resource.Type,
                        OrderBy = orderCount,
                        Link = resource.Link,
                    });

                    orderCount++;
                    continue;
                }
                else if (!string.IsNullOrEmpty(resource.Name) && resource.Type != ProblemResourceType.Video && resource.File != null)
                {
                    problem.Resources.Add(new ProblemResource
                    {
                        Name = resource.Name,
                        Type = resource.Type,
                        OrderBy = orderCount,
                        File = resource.File.InputStream.ToByteArray(),
                        FileExtension = resource.FileExtension
                    });

                    orderCount++;
                    continue;
                }
            }
        }
        public ActionResult Create(int id, HttpPostedFileBase testArchive, DetailedProblemViewModel problem)
        {
            if (problem.Resources != null && problem.Resources.Count() > 0)
            {
                var validResources = problem.Resources
                .All(res => !string.IsNullOrEmpty(res.Name) &&
                    ((res.Type == ProblemResourceType.AuthorsSolution && res.File != null && res.File.ContentLength > 0) ||
                    (res.Type == ProblemResourceType.ProblemDescription && res.File != null && res.File.ContentLength > 0) ||
                    (res.Type == ProblemResourceType.Video && !string.IsNullOrEmpty(res.Link))));

                if (!validResources)
                {
                    ModelState.AddModelError("Resources", "Ресурсите трябва да бъдат попълнени изцяло!");
                }
            }

            if (problem != null && ModelState.IsValid)
            {
                var newProblem = new Problem
                {
                    Name = problem.Name,
                    ContestId = id,
                    MaximumPoints = problem.MaximumPoints,
                    MemoryLimit = problem.MemoryLimit,
                    TimeLimit = problem.TimeLimit,
                    SourceCodeSizeLimit = problem.SourceCodeSizeLimit,
                    OrderBy = problem.OrderBy,
                    Checker = this.Data.Checkers.All().Where(x => x.Name == problem.Checker).FirstOrDefault()
                };

                if (problem.Resources != null && problem.Resources.Count() > 0)
                {
                    this.AddResourcesToProblem(newProblem, problem.Resources);
                }

                if (testArchive != null && testArchive.ContentLength != 0)
                {
                    try
                    {
                        this.AddTestsToProblem(newProblem, testArchive);
                    }
                    catch (Exception ex)
                    {
                        TempData.Add("DangerMessage", ex.Message);
                        problem.AvailableCheckers = this.Data.Checkers.All().Select(checker => new SelectListItem { Text = checker.Name, Value = checker.Name });
                        return this.View(problem);
                    }
                }

                this.Data.Problems.Add(newProblem);
                this.Data.SaveChanges();

                TempData.Add("InfoMessage", "Задачата беше добавена успешно");
                return this.RedirectToAction("Contest", new { id = id });
            }

            problem.AvailableCheckers = this.Data.Checkers.All().Select(checker => new SelectListItem { Text = checker.Name, Value = checker.Name });

            return this.View(problem);
        }
        public TestsControllerBaseTestsClass()
        {
            var firstCategory = new ContestCategory()
            {
                Id = 1,
                Name = "Category"
            };

            var secondCategory = new ContestCategory()
            {
                Id = 2,
                Name = "Another category"
            };

            var thirdCategory = new ContestCategory()
            {
                Id = 3,
                Name = "And another category"
            };

            var contest = new Contest
            {
                Id = 1,
                Name = "Contest",
                CategoryId = 1,
                Category = firstCategory
            };

            var otherContest = new Contest
            {
                Id = 2,
                Name = "Other contest",
                CategoryId = 1,
                Category = firstCategory
            };

            firstCategory.Contests.Add(contest);
            firstCategory.Contests.Add(otherContest);

            var selectedProblem = new Problem
            {
                Id = 1,
                Name = "Problem",
                Contest = contest,
                ContestId = 1,
            };

            var otherProblem = new Problem
            {
                Id = 2,
                Name = "Other problem",
                Contest = contest,
                ContestId = 1,
            };

            var problemWithOnlyTrialTests = new Problem
            {
                Id = 3,
                Name = "OnlyTrialTests",
                Contest = contest,
                ContestId = 1,
            };

            var problemWithOnlyNormalTests = new Problem
            {
                Id = 4,
                Name = "OnlyNormalTests",
                Contest = contest,
                ContestId = 1,
            };

            var testRun = new TestRun()
            {
                Id = 1,
                TestId = 1,
                ResultType = TestRunResultType.CorrectAnswer,
                MemoryUsed = 100,
                TimeUsed = 100,
                SubmissionId = 1,
                ExecutionComment = "Comment execution",
                CheckerComment = "Comment checker",
                Submission = new Submission
                {
                    Id = 1,
                    CreatedOn = DateTime.Now,
                },
            };

            var test = new Test
            {
                Id = 1,
                InputDataAsString = "Sample test input",
                OutputDataAsString = "Sample test output",
                IsTrialTest = false,
                TestRuns = new HashSet<TestRun>()
                {
                    testRun,
                },
                Problem = selectedProblem,
                ProblemId = 1,
                OrderBy = 5,
            };

            testRun.Test = test;

            selectedProblem.Tests.Add(test);

            selectedProblem.Tests.Add(new Test
            {
                InputDataAsString = "Trial input test 1",
                OutputDataAsString = "Trial output test 1",
                IsTrialTest = true,
                Problem = selectedProblem,
                ProblemId = 1,
            });

            selectedProblem.Tests.Add(new Test
            {
                InputDataAsString = "Trial input test 2",
                OutputDataAsString = "Trial output test 2",
                IsTrialTest = true,
                Problem = selectedProblem,
                ProblemId = 1,
            });

            problemWithOnlyTrialTests.Tests.Add(new Test
            {
                InputDataAsString = "Zero test 1\nZero test 1 second line",
                OutputDataAsString = "Zero test 1\nZero test 1 second lint output",
                IsTrialTest = true,
                Problem = selectedProblem,
                ProblemId = 1,
            });

            for (int i = 0; i < 10; i++)
            {
                selectedProblem.Tests.Add(new Test
                {
                    InputDataAsString = i.ToString(),
                    OutputDataAsString = (i + 1).ToString(),
                    IsTrialTest = false,
                    Problem = selectedProblem,
                    ProblemId = 1,
                });
            }

            otherProblem.Tests.Add(new Test
            {
                InputDataAsString = "Trial input test 1 other",
                OutputDataAsString = "Trial output test 1 other",
                IsTrialTest = true,
                Problem = selectedProblem,
                ProblemId = 1,
            });

            otherProblem.Tests.Add(new Test
            {
                InputDataAsString = "Trial input test 2 other",
                OutputDataAsString = "Trial output test 2 other",
                IsTrialTest = true,
                Problem = selectedProblem,
                ProblemId = 1,
            });

            for (int i = 0; i < 10; i++)
            {
                otherProblem.Tests.Add(new Test
                {
                    InputDataAsString = i.ToString() + "other",
                    OutputDataAsString = (i + 1).ToString() + "other",
                    IsTrialTest = false,
                    Problem = selectedProblem,
                    ProblemId = 1,
                });
            }

            for (int i = 0; i < 10; i++)
            {
                problemWithOnlyNormalTests.Tests.Add(new Test
                {
                    InputDataAsString = "Only normal tests " + i.ToString(),
                    OutputDataAsString = "Only normal tests output" + i.ToString(),
                    IsTrialTest = false,
                    Problem = selectedProblem,
                    ProblemId = 1,
                });
            }

            contest.Problems.Add(selectedProblem);
            contest.Problems.Add(otherProblem);
            contest.Problems.Add(problemWithOnlyTrialTests);
            contest.Problems.Add(problemWithOnlyNormalTests);

            this.TestViewModel = new TestViewModel
            {
                Id = 1,
                InputFull = "Input test",
                OutputFull = "Output test",
                IsTrialTest = false,
                OrderBy = 1,
                ProblemId = 1,
            };

            //// TODO: get these mocks in base class for reuse

            var listsOfTests = new List<Test>(selectedProblem.Tests);

            this.data = new Mock<IOjsData>();
            this.Problems = new Mock<IDeletableEntityRepository<Problem>>();
            this.Tests = new Mock<ITestRepository>();
            this.TestsRuns = new Mock<ITestRunsRepository>();
            this.Categories = new Mock<IDeletableEntityRepository<ContestCategory>>();
            this.Contests = new Mock<IContestsRepository>();
            this.Submissions = new Mock<ISubmissionsRepository>();

            this.Problems.Setup(x => x.All()).Returns((new List<Problem>() { selectedProblem, otherProblem, problemWithOnlyTrialTests, problemWithOnlyNormalTests }).AsQueryable());

            this.Tests.Setup(x => x.All()).Returns(listsOfTests.AsQueryable());
            this.Tests.Setup(x => x.Add(It.IsAny<Test>())).Callback((Test t) => { listsOfTests.Add(t); });
            this.Tests.Setup(x => x.Delete(It.IsAny<int>())).Callback((int id) =>
            {
                foreach (var currentTest in listsOfTests)
                {
                    if (currentTest.Id == id)
                    {
                        listsOfTests.Remove(currentTest);
                        break;
                    }
                }
            });

            this.TestsRuns.Setup(x => x.All()).Returns(new List<TestRun>() { testRun }.AsQueryable());
            this.Categories.Setup(x => x.All()).Returns(new List<ContestCategory>() { firstCategory, secondCategory, thirdCategory }.AsQueryable());
            this.Contests.Setup(x => x.All()).Returns(new List<Contest>() { contest, otherContest }.AsQueryable());

            this.data.SetupGet(x => x.Problems).Returns(this.Problems.Object);
            this.data.SetupGet(x => x.Tests).Returns(this.Tests.Object);
            this.data.SetupGet(x => x.TestRuns).Returns(this.TestsRuns.Object);
            this.data.SetupGet(x => x.ContestCategories).Returns(this.Categories.Object);
            this.data.SetupGet(x => x.Contests).Returns(this.Contests.Object);
            this.data.SetupGet(x => x.Submissions).Returns(this.Submissions.Object);

            this.TestsController = new TestsController(this.data.Object);

            this.ControllerContext = new ControllerContext(this.MockHttpContestBase(), new RouteData(), this.TestsController);
        }
        public void Copy(OjsDbContext context, TelerikContestSystemEntities oldDb)
        {
            context.Configuration.AutoDetectChangesEnabled = false;
            foreach (var task in oldDb.Tasks.OrderBy(x => x.Id).Include(x => x.Contest1).ToList())
            {
                var contest = context.Contests.FirstOrDefault(x => x.OldId == task.Contest);
                var problem = new Problem
                                  {
                                      OldId = task.Id,
                                      Contest = contest,
                                      Name = task.Name,
                                      MaximumPoints = (short)task.MaxPoints,
                                      TimeLimit = task.TimeLimit,
                                      MemoryLimit = (int)task.MemoryLimit * 2, // Multiplying memory limit by 2 because the previous worker didn't respect the memory limit
                                      OrderBy = 0,
                                      ShowResults = task.Contest1.ShowResults,
                                      CreatedOn = task.AddedOn,
                                      PreserveCreatedOn = true,
                                  };

                if (task.DescriptionLink != null || (task.Description != null && task.Description.Length != 0))
                {
                    var resource = new ProblemResource
                                              {
                                                  CreatedOn = task.AddedOn,
                                                  PreserveCreatedOn = true,
                                                  Name = string.Format("Условие на задачата"),
                                                  Type = ProblemResourceType.ProblemDescription,
                                              };

                    if (task.DescriptionLink != null)
                    {
                        if (task.Id == 368)
                        {
                            task.DescriptionLink =
                                "http://downloads.academy.telerik.com/svn/oop/Lectures/9.%20Exam%20Preparation/DocumentSystem-Skeleton.rar";
                        }

                        if (task.Id == 369)
                        {
                            task.DescriptionLink =
                                "http://downloads.academy.telerik.com/svn/oop/Lectures/9.%20Exam%20Preparation/AcademyGeometry-Skeleton.zip";
                        }

                        var web = new WebClient();
                        var data = web.DownloadData(task.DescriptionLink);
                        resource.File = data;
                        resource.FileExtension = task.DescriptionLink.GetFileExtension();
                    }
                    else
                    {
                        resource.File = task.Description;
                        resource.FileExtension = task.DescriptionFormat;
                    }

                    problem.Resources.Add(resource);
                }

                switch (task.Checker1.Name)
                {
                    case "Exact":
                        problem.Checker = context.Checkers.FirstOrDefault(x => x.Name == "Exact");
                        break;
                    case "Trim":
                        problem.Checker = context.Checkers.FirstOrDefault(x => x.Name == "Trim");
                        break;
                    case "Sort":
                        problem.Checker = context.Checkers.FirstOrDefault(x => x.Name == "Sort lines");
                        break;
                    default:
                        problem.Checker = null;
                        break;
                }

                context.Problems.Add(problem);
            }

            context.SaveChanges();
            context.Configuration.AutoDetectChangesEnabled = true;
        }
        public void SubmitActionWhenParticipantSendsEmptySubmissionContestShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("test contest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);

            // no limit between submissions
            contest.LimitBetweenSubmissions = 0;

            var problem = new Problem
            {
                Name = "test problem"
            };

            var submissionType = new SubmissionType
            {
                Name = "test submission type"
            };

            contest.Problems.Add(problem);
            contest.SubmissionTypes.Add(submissionType);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete));
            this.EmptyOjsData.SaveChanges();

            var submission = new SubmissionModel
            {
                Content = string.Empty,
                ProblemId = problem.Id,
                SubmissionTypeId = submissionType.Id
            };

            this.TryValidateModel(submission, this.CompeteController);

            try
            {
                var result = this.CompeteController.Submit(submission, this.IsCompete);
                Assert.Fail("Expected an exception when sending a submission with no content");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.BadRequest, ex.GetHttpCode());
            }
        }
        public void DownloadResourceActionWhenPracticingWhenNoFileExtensionAndUserIsRegisteredForContestShouldThrowAnException()
        {
            var contest = this.CreateAndSaveContest("testContest", this.InactiveContestOptions, this.ActiveContestWithPasswordOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File = new[]
                {
                    (byte)this.RandomGenerator.Next(0, byte.MaxValue),
                    (byte)this.RandomGenerator.Next(0, byte.MaxValue)
                }
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsPractice));
            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.DownloadResource(resource.Id, this.IsPractice) as FileContentResult;
                Assert.Fail("Expected an exception when trying to download a resource without a file extension.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.GetHttpCode());
            }
        }
        private void AddTestsToProblem(Problem problem, HttpPostedFileBase testArchive)
        {
            var extension = testArchive.FileName.Substring(testArchive.FileName.Length - 4, 4);

            if (extension != GlobalConstants.ZipExtention)
            {
                throw new ArgumentException(GlobalResource.Must_be_zip_file);
            }

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

                var parsedTests = ZippedTestsManipulator.Parse(memory);

                if (parsedTests.ZeroInputs.Count != parsedTests.ZeroOutputs.Count || parsedTests.Inputs.Count != parsedTests.Outputs.Count)
                {
                    throw new ArgumentException(GlobalResource.Invalid_tests);
                }

                ZippedTestsManipulator.AddTestsToProblem(problem, parsedTests);
            }
        }
        public ActionResult Create(int id, HttpPostedFileBase testArchive, DetailedProblemViewModel problem)
        {
            if (problem.Resources != null && problem.Resources.Any())
            {
                var validResources = problem.Resources
                .All(res => !string.IsNullOrEmpty(res.Name) &&
                    ((res.Type == ProblemResourceType.AuthorsSolution && res.File != null && res.File.ContentLength > 0) ||
                    (res.Type == ProblemResourceType.ProblemDescription && res.File != null && res.File.ContentLength > 0) ||
                    (res.Type == ProblemResourceType.Video && !string.IsNullOrEmpty(res.Link))));

                if (!validResources)
                {
                    this.ModelState.AddModelError("Resources", GlobalResource.Resources_not_complete);
                }
            }

            if (this.ModelState.IsValid)
            {
                var newProblem = new Problem
                {
                    Name = problem.Name,
                    ContestId = id,
                    MaximumPoints = problem.MaximumPoints,
                    MemoryLimit = problem.MemoryLimit,
                    TimeLimit = problem.TimeLimit,
                    SourceCodeSizeLimit = problem.SourceCodeSizeLimit,
                    ShowResults = problem.ShowResults,
                    ShowDetailedFeedback = problem.ShowDetailedFeedback,
                    OrderBy = problem.OrderBy,
                    Checker = this.Data.Checkers.All().FirstOrDefault(x => x.Name == problem.Checker)
                };

                if (problem.Resources != null && problem.Resources.Any())
                {
                    this.AddResourcesToProblem(newProblem, problem.Resources);
                }

                if (testArchive != null && testArchive.ContentLength != 0)
                {
                    try
                    {
                        this.AddTestsToProblem(newProblem, testArchive);
                    }
                    catch (Exception ex)
                    {
                        // TempData is not working with return this.View
                        var systemMessages = new SystemMessageCollection
                                {
                                    new SystemMessage
                                    {
                                        Content = ex.Message,
                                        Type = SystemMessageType.Error,
                                        Importance = 0
                                    }
                                };
                        this.ViewBag.SystemMessages = systemMessages;
                        problem.AvailableCheckers = this.Data.Checkers.All().Select(checker => new SelectListItem { Text = checker.Name, Value = checker.Name });
                        return this.View(problem);
                    }
                }

                this.Data.Problems.Add(newProblem);
                this.Data.SaveChanges();

                this.TempData.AddInfoMessage(GlobalResource.Problem_added);
                return this.RedirectToAction("Contest", new { id });
            }

            problem.AvailableCheckers = this.Data.Checkers.All().Select(checker => new SelectListItem { Text = checker.Name, Value = checker.Name });

            return this.View(problem);
        }
        private void ValidateBinarySubmission(ModelType model, Problem problem, SubmissionType submissionType)
        {
            if (submissionType.AllowBinaryFilesUpload && !string.IsNullOrEmpty(model.ContentAsString))
            {
                this.ModelState.AddModelError("SubmissionTypeId", "Невалиден тип на решението!");
            }

            if (submissionType.AllowedFileExtensions != null)
            {
                if (!submissionType.AllowedFileExtensionsList.Contains(model.FileExtension))
                {
                    this.ModelState.AddModelError("Content", "Невалидно разширение на файл!");
                }
            }
        }
        private void RetestSubmissions(Problem problem)
        {
            var submissionIds = problem.Submissions.Select(s => new { Id = s.Id }).ToList();
            foreach (var submissionId in submissionIds)
            {
                var currentSubmission = this.Data.Submissions.GetById(submissionId.Id);
                currentSubmission.Processed = false;
                currentSubmission.Processing = false;
            }

            this.Data.SaveChanges();
        }
        public void DownloadResourceActionWhenPracticingButPracticeNotAllowedShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("testContest", this.InactiveContestOptions, this.InactiveContestOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File = new byte[1],
                FileExtension = "test"
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.DownloadResource(resource.Id, this.IsPractice) as RedirectToRouteResult;
                Assert.Fail("Expected an exception when a user is trying to download a resource for a contest that cannot be practiced.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.GetHttpCode());
            }
        }
        public void SubmitActionWhenUserIsNotRegisteredToParticipateShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("someContest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var submissionType = new SubmissionType
            {
                Name = "test submission type"
            };

            contest.Problems.Add(problem);
            contest.SubmissionTypes.Add(submissionType);
            this.EmptyOjsData.SaveChanges();

            var submission = new SubmissionModel
            {
                Content = "test submission",
                ProblemId = problem.Id,
                SubmissionTypeId = submissionType.Id
            };

            try
            {
                var result = this.CompeteController.Submit(submission, this.IsCompete);
                Assert.Fail("An exception was expected when a user is trying to submit for a contest that he isn't registered for.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Unauthorized, ex.GetHttpCode());
            }
        }
 private void ValidateSubmissionContentLength(ModelType model, Problem problem)
 {
     if (model.Content.Length > problem.SourceCodeSizeLimit)
     {
         this.ModelState.AddModelError("Content", "Решението надвишава лимита за големина!");
     }
 }