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 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 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 ParticipantViewModel(Participant participant, bool official)
 {
     this.Contest = ContestViewModel.FromContest.Compile()(participant.Contest);
     this.LastSubmissionTime = participant.Submissions.Any() ? (DateTime?)participant.Submissions.Max(x => x.CreatedOn) : null;
     this.ContestIsCompete = official;
 }
        public ActionResult Register(bool official, ContestRegistrationModel registrationData)
        {
            // check if the user has already registered for participation and redirect him to the correct action
            var participantFound = this.Data.Participants.Any(registrationData.ContestId, this.UserProfile.Id, official);

            if (participantFound)
            {
                return this.RedirectToAction("Index", new { id = registrationData.ContestId, official });
            }

            var contest = this.Data.Contests.GetById(registrationData.ContestId);
            ValidateContest(contest, official);

            if (official && contest.HasContestPassword && (contest.ContestPassword != registrationData.Password))
            {
                this.ModelState.AddModelError("Password", Resource.Views.CompeteRegister.Incorrect_password);
            }

            if (!official && contest.HasPracticePassword && (contest.PracticePassword != registrationData.Password))
            {
                this.ModelState.AddModelError("Password", Resource.Views.CompeteRegister.Incorrect_password);
            }

            var questionsToAnswerCount = official ?
                contest.Questions.Where(x => x.AskOfficialParticipants).Count() :
                contest.Questions.Where(x => x.AskPracticeParticipants).Count();

            if (questionsToAnswerCount != registrationData.Questions.Count())
            {
                this.ModelState.AddModelError("Questions", Resource.Views.CompeteRegister.Not_all_questions_answered);
            }

            if (!ModelState.IsValid)
            {
                return this.View(new ContestRegistrationViewModel(contest, registrationData, official));
            }

            var participant = new Participant(registrationData.ContestId, this.UserProfile.Id, official);
            this.Data.Participants.Add(participant);
            foreach (var question in registrationData.Questions)
            {
                participant.Answers.Add(new ParticipantAnswer
                                                {
                                                    ContestQuestionId = question.QuestionId,
                                                    Answer = question.Answer
                                                });
            }

            this.Data.SaveChanges();

            return this.RedirectToAction("Index", new { id = registrationData.ContestId, official });
        }
        public ActionResult Register(int id, bool official)
        {
            var participantFound = this.Data.Participants.Any(id, this.UserProfile.Id, official);
            if (participantFound)
            {
                // Participant exists. Redirect to index page.
                return this.RedirectToAction("Index", new { id, official });
            }

            var contest = this.Data.Contests.All().Include(x => x.Questions).FirstOrDefault(x => x.Id == id);

            ValidateContest(contest, official);

            if (contest.ShouldShowRegistrationForm(official))
            {
                var contestRegistrationModel = new ContestRegistrationViewModel(contest, official);
                return this.View(contestRegistrationModel);
            }

            var participant = new Participant(id, this.UserProfile.Id, official);
            this.Data.Participants.Add(participant);
            this.Data.SaveChanges();

            return this.RedirectToAction("Index", new { id, official });
        }
        public ActionResult Register(bool official, ContestRegistrationModel registrationData)
        {
            // check if the user has already registered for participation and redirect him to the correct action
            var participantFound = this.Data.Participants.Any(registrationData.ContestId, this.UserProfile.Id, official);

            if (participantFound)
            {
                return this.RedirectToAction(GlobalConstants.Index, new { id = registrationData.ContestId, official });
            }

            var contest = this.Data.Contests.GetById(registrationData.ContestId);
            ValidateContest(contest, official);

            if (official && contest.HasContestPassword)
            {
                if (string.IsNullOrEmpty(registrationData.Password))
                {
                    this.ModelState.AddModelError("Password", Resource.Views.CompeteRegister.Empty_Password);
                }
                else if (contest.ContestPassword != registrationData.Password)
                {
                    this.ModelState.AddModelError("Password", Resource.Views.CompeteRegister.Incorrect_password);
                }
            }

            if (!official && contest.HasPracticePassword)
            {
                if (string.IsNullOrEmpty(registrationData.Password))
                {
                    this.ModelState.AddModelError("Password", Resource.Views.CompeteRegister.Empty_Password);
                }
                else if (contest.PracticePassword != registrationData.Password)
                {
                    this.ModelState.AddModelError("Password", Resource.Views.CompeteRegister.Incorrect_password);
                }
            }

            var questionsToAnswerCount = official ?
                contest.Questions.Count(x => x.AskOfficialParticipants) :
                contest.Questions.Count(x => x.AskPracticeParticipants);

            if (questionsToAnswerCount != registrationData.Questions.Count())
            {
                this.ModelState.AddModelError("Questions", Resource.Views.CompeteRegister.Not_all_questions_answered);
            }

            var contestQuestions = contest.Questions.ToList();

            var participant = new Participant(registrationData.ContestId, this.UserProfile.Id, official);
            this.Data.Participants.Add(participant);
            var counter = 0;
            foreach (var question in registrationData.Questions)
            {
                var contestQuestion = contestQuestions.FirstOrDefault(x => x.Id == question.QuestionId);

                var regularExpression = contestQuestion.RegularExpressionValidation;
                bool correctlyAnswered = false;

                if (!string.IsNullOrEmpty(regularExpression))
                {
                    correctlyAnswered = Regex.IsMatch(question.Answer, regularExpression);
                }

                if (contestQuestion.Type == ContestQuestionType.DropDown)
                {
                    int contestAnswerId;
                    if (int.TryParse(question.Answer, out contestAnswerId) && contestQuestion.Answers.Any(x => x.Id == contestAnswerId))
                    {
                        correctlyAnswered = true;
                    }

                    if (!correctlyAnswered)
                    {
                        this.ModelState.AddModelError(string.Format("Questions[{0}].Answer", counter), "Invalid selection");
                    }
                }

                participant.Answers.Add(new ParticipantAnswer
                                                {
                                                    ContestQuestionId = question.QuestionId,
                                                    Answer = question.Answer
                                                });

                counter++;
            }

            if (!this.ModelState.IsValid)
            {
                return this.View(new ContestRegistrationViewModel(contest, registrationData, official));
            }

            this.Data.SaveChanges();

            return this.RedirectToAction(GlobalConstants.Index, new { id = registrationData.ContestId, official });
        }
        public ActionResult Register(int id, bool official, ContestRegistrationModel registrationData)
        {
            // check if the user has already registered for participation and redirect him to the correct
            // action
            var participantFound = this.Data.Participants.Any(id, this.UserProfile.Id, official);

            if (participantFound)
            {
                return this.RedirectToAction("Index", new { id, official });
            }

            var contest = this.Data.Contests.GetById(id);

            ValidateContest(contest, official);

            // check if the contest is official, has a password and if the user entered the correct password
            if (official && contest.HasContestPassword && !contest.ContestPassword.Equals(registrationData.Password))
            {
                this.ModelState.AddModelError("Password", "Incorrect password!");
            }

            // check if the contest is practice, has a password and if the user entered the correct password
            if (!official && contest.HasPracticePassword && !contest.PracticePassword.Equals(registrationData.Password))
            {
                this.ModelState.AddModelError("Password", "Incorrect password!");
            }

            var questionsToAnswerCount = official ?
                contest.Questions.Where(x => x.AskOfficialParticipants).Count() :
                contest.Questions.Where(x => x.AskPracticeParticipants).Count();

            if (questionsToAnswerCount != registrationData.Questions.Count())
            {
                // TODO: add an appropriate model error
                this.ModelState.AddModelError(string.Empty, string.Empty);
            }

            registrationData.Questions.Each((x, i) =>
            {
                if (string.IsNullOrEmpty(x.Answer))
                {
                    this.ModelState.AddModelError(string.Format("Questions[{0}].Answer", i), "Answer is required");
                }
            });

            if (!ModelState.IsValid)
            {
                return this.View(new ContestRegistrationViewModel(contest, registrationData, official));
            }

            registrationData.Questions.Each(q =>
            {
                var contestQuestion = contest.Questions.FirstOrDefault(x => x.Id == q.QuestionId);

                contestQuestion.Answers.Add(new ContestQuestionAnswer
                {
                    QuestionId = q.QuestionId,
                    Text = q.Answer
                });
            });

            var participant = new Participant(id, this.UserProfile.Id, official);
            this.Data.Participants.Add(participant);
            this.Data.SaveChanges();

            return this.RedirectToAction("Index", new { id, official });
        }
        public void Copy(OjsDbContext context, TelerikContestSystemEntities oldDb)
        {
            context.Configuration.AutoDetectChangesEnabled = false;
            context.Configuration.ValidateOnSaveEnabled = false;
            var participants = oldDb.Participants.Select(x =>
                new
                    {
                        x.Id,
                        x.Contest,
                        OldUserId = x.User1.Id,
                        x.RegisteredOn,
                        x.IsOfficial,
                        x.Answer,
                    }).ToList();

            var contests = context.Contests.Select(x => new { x.OldId, x.Id, Question = x.Questions.FirstOrDefault() }).ToDictionary(x => x.OldId);
            var users = context.Users.Select(x => new { x.OldId, x.Id }).ToDictionary(x => x.OldId);

            foreach (var oldParticipant in participants)
            {
                if (!contests.ContainsKey(oldParticipant.Contest))
                {
                    continue;
                }

                var contest = contests[oldParticipant.Contest];

                if (!users.ContainsKey(oldParticipant.OldUserId))
                {
                    // User is no longer active
                    continue;
                }

                var participant = new Participant
                                      {
                                          OldId = oldParticipant.Id,
                                          PreserveCreatedOn = true,
                                          CreatedOn = oldParticipant.RegisteredOn,
                                          IsOfficial = oldParticipant.IsOfficial,
                                          ContestId = contest.Id,
                                          UserId = users[oldParticipant.OldUserId].Id,
                                      };

                if (contest.Question != null)
                {
                    var answer = new ParticipantAnswer
                            {
                                ContestQuestionId = contest.Question.Id,
                                Answer = oldParticipant.Answer,
                                Participant = participant,
                            };

                    context.ParticipantAnswers.Add(answer);
                }

                context.Participants.Add(participant);
            }

            context.SaveChanges();
            context.Configuration.AutoDetectChangesEnabled = true;
            context.Configuration.ValidateOnSaveEnabled = true;
        }