public void Shouldly_ContestantPointsShouldBe1337()
            {
                var contestant = new Contestant {Points = 0};

                TestHelpers.Should.Error(
                    () => contestant.Points.ShouldBe(1337),
                    "contestant.Points should be 1337 but was 0");
            }
            public void NUnit_ContestantPointsShouldBe1337()
            {
                var contestant = new Contestant {Points = 0};

                var exception =
                    Should.Throw<Exception>(
                        () => Assert.That(contestant.Points, NUnit.Framework.Is.EqualTo(1337)));

                exception.Message.ShouldContainWithoutWhitespace("Expected: 1337 But was: 0");
            }
        public ContestantListAndCreate(Tournament tournament, EntityMode mode) : this()
        {
            Contestants = tournament.Contestants.ToList();
            var round1 = tournament.GetRoundNo(1);

            IsRegistrationClosed = tournament.Status != TournamentStatus.Prestart &&
                                   round1.Status != TournamentStatus.Running;
            IsDeletionClosed = tournament.Status != TournamentStatus.Prestart;
            TournamentId     = tournament.Id;
            Contestant       = new Contestant();
            if (mode == EntityMode.Create)
            {
                UpdateButtonText = Text.Create;
            }
            else
            {
                UpdateButtonText = Text.Update;
            }
        }
        private void CreateContestantAccount(Contestant contestant)
        {
            string lastSix  = contestant.ContestantId.Substring(contestant.ContestantId.Length - 6);
            string password = contestant.FirstName + lastSix + "!";
            var    user     = new ContestantAccount
            {
                UserName       = contestant.Email,
                Email          = contestant.Email,
                ContestantId   = contestant.ContestantId,
                EmailConfirmed = true
            };

            var result = userManager.CreateAsync(user, password).Result;

            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(user, "ContestantAccount").Wait();
            }
        }
        public void CreateContestantWithMultiplePerformers()
        {
            TimeSpan maxDuration = new TimeSpan(0, 5, 0);
            Contest  contest     = new Contest(name: "Dance", timeKeeperId: "123", maxDuration: maxDuration, status: "Pending");

            Division     division    = new Division("Alpha");
            PersonName   name        = new PersonName(firstName: "John", lastName: "Smith");
            Organization affiliation = new Organization("ABC");

            Division     division2    = new Division("Alpha");
            PersonName   name2        = new PersonName(firstName: "Bob", lastName: "Beach");
            Organization affiliation2 = new Organization("XYZ");

            Performance performance = new Performance(description: "Dancing an abc to xyz", duration: new TimeSpan(hours: 0, minutes: 2, seconds: 0));

            Contestant contestant = new Contestant(performance, ruleViolationPenalty: 0, tieBreakerPoints: 0);

            Assert.AreEqual(performance, contestant.Performance);
        }
        public static ContestantDto ConvertToDto(this Contestant contestant)
        {
            var performerService = new PerformerService(new PerformerRepo(),
                                                        new DivisionRepo(), new PersonNameRepo(), new OrganizationRepo(), new ContestantPerformerRepo());

            var performers = performerService.GetContestantPerformers(contestant.Id);

            var scoreCardService = new ScoreCardService(new ScoreCardRepo(), new ScorableCriterionRepo(), new ContestantRepo());

            var totalScore = scoreCardService.GetContestantTotalScore(contestant.Id, new TimeSpan(0, 5, 0));

            return(new ContestantDto()
            {
                Id = contestant.Id,
                Performance = ConvertToDto(contestant.Performance),
                Performers = performers.ConvertToDto(),
                TotalScore = totalScore
            });
        }
        public IActionResult Block(int id)
        {
            dynamic result = new ExpandoObject();

            Contestant c2 = _repo.BlockContestant(id);

            if (c2 == null)
            {
                result.status  = 0;
                result.message = "Verify your infromations";
            }
            else
            {
                result.status = 1;
                result.result = c2;
            }

            return(Ok(result));
        }
        public IActionResult Confirm(string code)
        {
            dynamic result = new ExpandoObject();

            Contestant c2 = _repo.ConfirmMail(code);

            if (c2 == null)
            {
                result.status  = 0;
                result.message = "Verify your infromations";
            }
            else
            {
                result.status = 1;
                result.result = c2;
            }

            return(Ok(result));
        }
Exemple #9
0
        //[TestMethod]
        public void loopCompetition()
        {
            c.id     = -1;
            c.rounds = 3;
            var judgeCount = 5;

            for (int i = 0; i < 10; i++)
            {
                var contestant = new Contestant(i + 1, "Anton" + i, "", "Sweden", (i % 2) == 0, new DateTime(1980 + i, 01, 03));
                for (int j = 0; j < c.rounds; j++)
                {
                    var jump = new Jump(-1, 1 + j);
                    contestant.jumps.Add(jump);
                }
                c.contestants.Add(contestant);
            }

            c.saveToDatabase();
            //start av testet
            while (true)
            {
                if (c.currentContestantindex < c.contestants.Count)
                {
                    for (int i = 0; i < judgeCount; i++)
                    {
                        var score = new Score(i, i, 2 * i);
                        c.contestants[c.currentContestantindex].jumps[c.currentRound].scores.Add(score);
                    }
                    c.contestants[c.currentContestantindex].jumps[c.currentRound].calculateJumpScore();
                    c.contestants[c.currentContestantindex].calculateTotalScore();
                    c.currentContestantindex++;
                }
                else if (c.rounds < c.currentRound)
                {
                    c.currentContestantindex = 0;
                    c.currentRound++;
                }
                else
                {
                    break;
                }
            }
        }
Exemple #10
0
        public void Expire()
        {
            if (SetUP)
            {
                if (TimeLeft.TotalMilliseconds < 5)
                {
                    List <Mobile> Const = Contestant.Return_Contestant_List(m_NewContestants);
                    if (Const.Count > 0)
                    {
                        int    r      = Utility.Random(Const.Count);
                        Mobile Winner = (Mobile)Const[r];
                        int    I      = 0;
                        while (Winner == null && I < Const.Count)
                        {
                            r      = Utility.Random(Const.Count);
                            Winner = (Mobile)Const[r];
                            I++;
                        }

                        if (Winner != null)
                        {
                            List <Mobile> Players = Bittiez.Tools.List_Connected_Players();
                            foreach (Mobile m in Players)
                            {
                                if (m.HasGump(typeof(RevGuide)))
                                {
                                    m.CloseGump(typeof(RevGuide));
                                }
                                m.SendMessage(38, "The Raffle for a " + Prize_Name + " has ended, the winner was " + Winner.RawName + "!");
                            }
                            Prize.Movable = true;
                            Winner.AddToBackpack(Prize);
                        }
                    }
                    reset();
                }
                else
                {
                    Bittiez.Tools.Start_Timer_Delayed_Call(TimeSpan.FromMinutes(5), Expire);
                }
            }
        }
        public async Task EnterCompetition_ContestantRelayedThrough()
        {
            // Arrange
            Contestant actualContestant   = null;
            var        request            = _fixture.Create <EnterCompetition>();
            var        expectedContestant = Contestant.Create(request.FirstName, request.LastName, request.Email, request.SerialNumber, request.ConfirmsCorrectAge, request.AcceptsTerms);
            var        repoMock           = new Mock <ICompetitionRepository>();

            repoMock.Setup(x => x.AddContestant(It.IsAny <Contestant>()))
            .Callback((Contestant contestant) => actualContestant = contestant).Returns(Task.CompletedTask);
            var handler = new EnterCompetitionHandler(repoMock.Object);

            // Act
            var response = await handler.Handle(request);

            // Assert
            actualContestant
            .Should().BeEquivalentTo(expectedContestant, options => options.Excluding(x => x.CreatedAt));
            actualContestant.CreatedAt.Should().BeCloseTo(expectedContestant.CreatedAt, 1.Seconds());
        }
        public void GenerateGeneralRankingWorksOnOneSeries()
        {
            Contestant     ion  = new Contestant("Ion", "Romania", 9.80);
            Contestant     john = new Contestant("John", "Sua", 9.825);
            Contestant     zoli = new Contestant("Zoli", "Ungaria", 9.91);
            ContestRanking ser1 = new ContestRanking();

            ser1.Contestants = new Contestant[] { ion, john, zoli };
            Contest contest = new Contest
            {
                Series = new ContestRanking[] { ser1 }
            };
            ContestRanking expectedGeneralRating = new ContestRanking();

            expectedGeneralRating.Contestants = new Contestant[] { ion, john, zoli };

            Program.GenerateGeneralRanking(ref contest);

            Assert.Equal <Contestant>(contest.GeneralRanking.Contestants, expectedGeneralRating.Contestants);
        }
        private Contestant CreateEntrant(DataEntities context, Order2021 order)
        {
            var contestant = new Contestant()
            {
                Firstname       = order.FirstName ?? "",
                Lastname        = order.LastName ?? "",
                Nationality     = order.LocalisedNationality,
                Title           = order.Title,
                Male            = (order.Title == "Mr"),
                DateofBirth     = SanitiseDateOfBirth(order.DateOfBirth),
                OnlineNicknames = order.OnlineNickname,
                DiscordNickname = order.DiscordNickname,
                email           = order.Email
            };

            context.Contestants.Add(contestant);

            context.SaveChanges();
            return(contestant);
        }
    internal void LineMouseUI(Contestant selected, Hex h)      //this should really have the relevant hexes passed to it rather than recalc them
    {
        ClearLineUI();

        List <Hex> hexesInLine;

        GridManager.Instance.DrawLineOnGrid(selected.CurrentHex, h.Occupant.CurrentHex, out hexesInLine);

        hexLine = new Dictionary <Hex, GameObject> ();

        foreach (Hex j in hexesInLine)
        {
            GameObject go = MonoBehaviour.Instantiate(UIHexBuilder.Instance.flatHexPrefab, selected.transform);
            go.transform.position = j.Position + new Vector3(0, 0.001f, 0);
            go.GetComponent <MeshRenderer>().material.color = new Color(2 / 3f, 0, 2 / 3f);

            go.name     = "TargetSelectorMode UI Hex";
            hexLine [j] = go;
        }
    }
Exemple #15
0
        public ActionResult Edit(Contestant a, int Id)
        {
            using (NabayubakDBEntities db = new NabayubakDBEntities())
            {
                var edit = db.Contestants.Where(x => x.Id == Id).FirstOrDefault();
                edit.Firstname   = a.Firstname;
                edit.Lastname    = a.Lastname;
                edit.DateOfBirth = a.DateOfBirth;
                edit.IsActive    = a.IsActive;
                edit.DistrictId  = a.DistrictId;
                edit.Gender      = a.Gender;
                db.SaveChanges();

                // for delete
                //var delete = db.Contestants.Where (x => x.Id == Id).FirstOrDefault();
                // db.Contestants.Remove(delete);
                // db.SaveChanges();
            }
            return(RedirectToAction("Index"));
        }
Exemple #16
0
    private IEnumerator RespondToQuestion()
    {
        Questions question = (Questions)(m_questionChoice1 * 4 * 4 + m_questionChoice2 * 4 + m_questionChoice3);

        m_contestorSpeechBubbleText[m_contestantIndex].text = m_chosenContestant.GetQuestionResponse(question);

        m_contestorSpeechBubbleAnimator[m_contestantIndex].SetBool("Shown", true);

        yield return(new WaitForSeconds(3.0f));

        m_contestorSpeechBubbleAnimator[m_contestantIndex].SetBool("Shown", false);

        yield return(new WaitForSeconds(0.2f));

        // Clear choices for next round
        m_chosenContestant = null;
        m_questionChoice1  = -1;
        m_questionChoice2  = -1;
        m_questionChoice3  = -1;
        yield return(null);
    }
Exemple #17
0
        public ActionResult Edit(int id = 0)
        {
            Contestant con = new Contestant();

            using (NabayubakDBEntities db = new NabayubakDBEntities())
            {
                con = db.Contestants.Find(id);
                int?districtId = con.DistrictId;

                ViewBag.Districtslist = db.Districts.ToList().Select(x => new SelectListItem {
                    Value = x.Id.ToString(), Text = x.Name, Selected = (x.Id == 1)
                });
                //ViewBag.Districtslist = db.Districts.ToList();
                if (con == null)
                {
                    return(HttpNotFound());
                }
                // return View(con);
            }
            return(View(con));
        }
Exemple #18
0
 public void InitializeTests()
 {
     _userId      = new UserIdentifier();
     _contestant1 = new Contestant {
         Id = Guid.NewGuid()
     };
     _contestant2 = new Contestant {
         Id = Guid.NewGuid()
     };
     _matchId = Guid.NewGuid();
     _stubContestantRepository = new Mock <IContestantRepository>();
     _stubContestantRepository.Setup(x => x.GetCount(WarId)).Returns(Task.FromResult(ContestantCount));
     _stubMatchRepository = new Mock <IMatchRepository>();
     _stubMatchRepository.Setup(x => x.Create(WarId,
                                              It.Is <MatchRequest>(m => m.Contestant1 == _contestant1.Id &&
                                                                   m.Contestant2 == _contestant2.Id &&
                                                                   m.UserIdentifier == _userId)))
     .Returns(Task.FromResult(_matchId));
     randomNumbers = new Queue <int>();
     _factory      = new RandomMatchStrategy(_stubMatchRepository.Object, _stubContestantRepository.Object, GenerateRandomNumber);
 }
Exemple #19
0
        public void CreateScoreCard()
        {
            ScoreRange        scoreRange        = new ScoreRange(0, 100);
            ScoreCriterion    scoreCriterion    = new ScoreCriterion("This is a description.", scoreRange);
            ScorableCriterion scorableCriterion = new ScorableCriterion(scoreCriterion);

            ScoreCriterion    scoreCriterion2    = new ScoreCriterion("This is another description.", scoreRange);
            ScorableCriterion scorableCriterion2 = new ScorableCriterion(scoreCriterion2);

            ICollection <ScorableCriterion> scorableCriteria = new List <ScorableCriterion>()
            {
                scorableCriterion, scorableCriterion2
            };

            Contest     contest     = new Contest("Talent Show", timeKeeperId: "123", maxDuration: new TimeSpan(0, 5, 0), status: "Pending");
            Performance performance = new Performance("Singing a song.", new TimeSpan(hours: 0, minutes: 4, seconds: 0));
            Contestant  contestant  = new Contestant(performance, ruleViolationPenalty: 0, tieBreakerPoints: 0);
            Judge       judge       = new Judge("abc");

            ScoreCard scoreCard = new ScoreCard(contestant, judge, scorableCriteria);

            double score1  = 50;
            double score2  = 75;
            double average = new List <double>()
            {
                score1, score2
            }.Average();

            scoreCard.ScorableCriteria.ElementAt(0).SetScoreAndComment(score1, "Not very good.");
            scoreCard.ScorableCriteria.ElementAt(1).SetScoreAndComment(score2, "Pretty good.");

            Assert.AreEqual(2, scoreCard.ScorableCriteria.Count);
            Assert.AreEqual(score1, scoreCard.ScorableCriteria.ElementAt(0).Score);
            Assert.AreEqual(scoreCriterion, scoreCard.ScorableCriteria.ElementAt(0).ScoreCriterion);
            Assert.AreEqual(score2, scoreCard.ScorableCriteria.ElementAt(1).Score);
            Assert.AreEqual(scoreCriterion2, scoreCard.ScorableCriteria.ElementAt(1).ScoreCriterion);
            Assert.AreEqual(average, scoreCard.AverageScore);
            Assert.AreEqual(contestant, scoreCard.Contestant);
            Assert.AreEqual(judge, scoreCard.Judge);
        }
        public Contestant RegisterUserForContest(int contest_id, int user_id, ContestRegistrationFormData data)
        {
            Contest contest = context.Contests.Include(x => x.Contestants).FirstOrDefault(x => x.Id == contest_id);

            var user = context.Users.Find(user_id);

            if (contest == null)
            {
                throw new ObjectNotFoundException("Contest with specified id not found");
            }

            if (user == null)
            {
                throw new ObjectNotFoundException("User with specified id not found");
            }

            // if user is already registered for this contest
            if (contest.Contestants.Count(x => x.User == user) > 0)
            {
                throw new InvalidOperationException("User is already registered for contest");
            }

            if (!contest.IsPublic && contest.Password != data.Password)
            {
                throw new InvalidOperationException("Wrong password for registation");
            }

            if (contest.StartDate < DateTime.Now)
            {
                throw new InvalidOperationException("Contest registration time has ended");
            }

            Trace.WriteLine(contest.Contestants.Count);
            var contestant = new Contestant(user);

            contest.Contestants.Add(contestant);
            context.SaveChanges();

            return(contestant);
        }
        public async Task <IActionResult> UpdateContestant(int id, [FromForm] Contestant contestant)
        {
            string photoName = "";

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // photo is uploaded
            if (contestant.Photo != null)
            {
                photoName           = _contestantProvider.UploadFile(contestant);
                contestant.PhotoUrl = photoName;
            }

            contestant.Id = id;
            _contestantContext.Update(contestant);
            await _contestantContext.SaveChangesAsync();

            return(Ok(new { status = true, message = "Contestent updated successfully" }));
        }
Exemple #22
0
    public void SpawnContestant(ContestantData d, Hex startingHex)
    {
        //prefab is temp, will load prefab of correct type
        GameObject go = Instantiate(testContestant, startingHex.Position, testContestant.transform.rotation, transform);

        go.transform.GetChild(0).GetComponent <MeshRenderer> ().material.color = d.Team.Color;

        Contestant c = go.GetComponent <Contestant> ();

        //Here set contestant values in line with data
        c.CurrentHex = startingHex;
        c.Position   = startingHex.Position;
        c.Data       = d;
        d.Contestant = c;


        //UI
        StatUIManager.Instance.InitLabelUI(c);

        //Possible Actions
        if (d.CanShoot)
        {
            c.PossibleActions.Add(ContestantActionsFactory.CreateAction <DamagableObject> ("Shoot", ContestantActionsEnum.Shoot, 1f, c, 4, 3f, false));
        }

        Func <ICatcher, bool> throwReqs = (con) => {
            return(c.Ball != null && con.Ball == null);
        };

        c.PossibleActions.Add(ContestantActionsFactory.CreateAction <ICatcher> ("Throw", ContestantActionsEnum.Throw, 2f, c, (int)(d.Dexerity * 2), 3f, true, throwReqs));

        Func <Contestant, bool> checkForBall = (Contestant con) => {
            return(con.Ball != null);
        };

        c.PossibleActions.Add(ContestantActionsFactory.CreateAction <Contestant> ("Swipe", ContestantActionsEnum.Swipe, 0f, c, 1, 3f, false, checkForBall));

        ActionUIManager.Instance.CreateButtonPool(c);
    }
        private static Contestant LaunchEntelectHarnessManuallyAndGetTheWinner(
            string entelectHarnessFolderPath, Contestant player1, Contestant player2, int matchIndex)
        {
            string entelectLaunchPath = Path.Combine(entelectHarnessFolderPath, "launch.bat");

            Console.WriteLine("LAUNCHING {0}", entelectLaunchPath);
            Console.WriteLine("...");

            ProcessStartInfo startInfo = new ProcessStartInfo(entelectLaunchPath);

            startInfo.WorkingDirectory       = entelectHarnessFolderPath;
            startInfo.UseShellExecute        = true;
            startInfo.CreateNoWindow         = false;
            startInfo.RedirectStandardInput  = false;
            startInfo.RedirectStandardError  = false;
            startInfo.RedirectStandardOutput = false;
            Process process = Process.Start(startInfo);

            Thread.Sleep(15000);

            Process player1Process = LaunchPlayerProcess(player1);

            Thread.Sleep(2000);
            Process player2Process = LaunchPlayerProcess(player2);

            process.WaitForExit();

            EndPlayerProcess(player1Process);
            EndPlayerProcess(player2Process);

            // TODO: Load Json file with the game history

            // TODO: Save game outcome

            // TODO: Determine the winner

            // TODO: Return the winner, or null if a draw
            return(null);
        }
Exemple #24
0
        public void addScore_calculateScoreFor_11_Judges()
        {
            Contestant contestant1 = new Contestant(1, "Anton", "", "Sweden", true, new DateTime(1988, 01, 03));
            Jump       jump1       = new Jump(0, 3, true, "101A");
            Score      score1      = new Score(10, 1, 7.5);
            Score      score2      = new Score(10, 2, 7.5);
            Score      score3      = new Score(10, 3, 7.5);
            Score      score4      = new Score(10, 4, 7.5);
            Score      score5      = new Score(10, 5, 7.5);
            Score      score6      = new Score(10, 6, 7.5);
            Score      score7      = new Score(10, 7, 7.5);
            Score      score8      = new Score(10, 8, 7.5);
            Score      score9      = new Score(10, 9, 7.5);
            Score      score10     = new Score(10, 10, 7.5);
            Score      score11     = new Score(10, 11, 7.5);

            c.contestants.Add(contestant1);
            c.contestants[0].jumps.Add(jump1);

            c.contestants[0].jumps[0].scores.Add(score1);
            c.contestants[0].jumps[0].scores.Add(score2);
            c.contestants[0].jumps[0].scores.Add(score3);
            c.contestants[0].jumps[0].scores.Add(score4);
            c.contestants[0].jumps[0].scores.Add(score5);
            c.contestants[0].jumps[0].scores.Add(score6);
            c.contestants[0].jumps[0].scores.Add(score7);
            c.contestants[0].jumps[0].scores.Add(score8);
            c.contestants[0].jumps[0].scores.Add(score9);
            c.contestants[0].jumps[0].scores.Add(score10);
            c.contestants[0].jumps[0].scores.Add(score11);


            Assert.AreEqual(c.contestants[0].jumps.Count, 1);
            Assert.AreEqual(36, c.contestants[0].jumps[0].calculateJumpScore());

            c.contestants[0].calculateTotalScore();

            Assert.AreEqual(36, c.contestants[0].totalScore);
        }
        public void ContestantWithCorrectBoardPasses()
        {
            var lastGeneration = 100;
            var finalBoard     = new Coordinate[]
            {
                new Coordinate {
                    X = 1, Y = 1
                }
            };

            gameServiceMoq
            .Setup(gs => gs.GetNumGenerations())
            .Returns(lastGeneration);
            gameServiceMoq
            .Setup(gs => gs.CheckBoard(finalBoard))
            .Returns(true);
            gameServiceMoq
            .Setup(gs => gs.GetGameStatus())
            .Returns(new GameStatus(finalBoard));

            var wednesday = new Contestant(
                "wednesday",
                "wednesday's token",
                DateTime.Now,
                0
                );

            contestantService.AddContestant(wednesday);

            wednesday = wednesday
                        .UpdateGenerationsComputed(lastGeneration)
                        .UpdateFinalBoard(finalBoard);

            contestantService.UpdateContestant(wednesday);

            var newWednesday = contestantService.GetContestantByToken(wednesday.Token);

            newWednesday.CorrectFinalBoard.Should().BeTrue();
        }
Exemple #26
0
        public ActionResult MemDetails(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            //var electionName = db.Contestants.Include("election").Where(x => x.contestant_id == id);

            var electionName = (from s in db.Contestants.Include("election")
                                where s.contestant_id == id
                                select s.election.pollName).FirstOrDefault();

            ViewBag.ename = electionName;

            Contestant con = db.Contestants.Find(id);

            if (con == null)
            {
                return(HttpNotFound());
            }
            return(View(con));
        }
        public IEnumerable <Contestant> getRacesByTeam(string team)
        {
            log.InfoFormat("Getting contestants with {0}", team);
            IDbConnection     con         = DbUtils.getConnection(props);
            List <Contestant> contestants = new List <Contestant>();

            using (var comm = con.CreateCommand())
            {
                comm.CommandText = "select contestantID, name, team, engineCap " +
                                   "from Contestants WHERE team=@t";
                IDbDataParameter paramTeam = comm.CreateParameter();
                paramTeam.ParameterName = "@t";
                paramTeam.Value         = team;
                comm.Parameters.Add(paramTeam);

                using (var dataR = comm.ExecuteReader())
                {
                    while (dataR.Read())
                    {
                        int    idC  = dataR.GetInt32(0);
                        string name = dataR.GetString(1);
                        //string team = dataR.GetString(2);
                        int engC = dataR.GetInt32(3);

                        Contestant contestant = new Contestant(idC, name, team, engC);
                        contestants.Add(contestant);
                    }
                }
            }

            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }


            return(contestants);
        }
Exemple #28
0
        public ActionResult EditContestants(Contestant model)
        {
            if (Request.Files[0].ContentLength == 0 || Request.Files[0].FileName == "")
            {
                TempData["MessageType"] = "danger";
                TempData["Message"]     = "Please input your personal image!!";
                return(View(model));
            }
            if (Request.Files[0].ContentLength >= 20000000)
            {
                TempData["MessageType"] = "danger";
                TempData["Message"]     = "File too large!!";
                return(View(model));
            }
            if (Request.Files[0].ContentType.Substring(0, 5) != "image")
            {
                TempData["MessageType"] = "danger";
                TempData["Message"]     = "Invalid file type!!";
                return(View(model));
            }
            var c = db.Contestants.Find(model.Id);

            c.manifesto  = model.manifesto;
            c.PositionId = model.PositionId;
            var g = Request.Files[0];

            c.CampaignPictureName     = g.FileName;
            c.CampaignPictureFileType = g.ContentType;

            using (var reader = new BinaryReader(g.InputStream))
            {
                c.CampaignPictureContent = reader.ReadBytes(g.ContentLength);
            }
            db.SaveChanges();
            TempData["MessageType"] = "success";
            TempData["Message"]     = "Your Registration was successful!!";
            return(RedirectToAction("EditContestants", new { Id = model.Id }));
        }
Exemple #29
0
    static void Main()
    {
        const int MIN_CONTESTANTS = 0;
        const int MAX_CONTESTANTS = 30;
        int       num;
        int       revenue = 0;
        //HINT: set QUIT variable to character datatype equal to 'Z' here for user input
        const char QUIT = 'Z';
        //HINT: set space here as default value for the option variable value
        char option = ' ';

        Contestant[] contestants = new Contestant[MAX_CONTESTANTS];
        num = getContestantNumber(MIN_CONTESTANTS, MAX_CONTESTANTS);

        revenue = getContestantData(num, contestants, revenue);
        WriteLine("\n\nRevenue expected this year is {0}", revenue.ToString("C"));

        //HINT: check user input for stopping before calling getLists method with while loop here
        while (option != QUIT)
        {
            option = getLists(num, contestants);
        }
    }
        public void UpdateContestant(Contestant contestant)
        {
            if (contestant is null)
            {
                throw new ArgumentNullException(nameof(contestant));
            }
            if (GameService.GetGameStatus().IsStarted == false)
            {
                return;
            }

            var existingContestantRecord = GetContestantByToken(contestant.Token);

            if (existingContestantRecord.CorrectFinalBoard != null)
            {
                return;
            }

            contestant = updateContestantIfFinished(contestant);

            contestants.AddOrUpdate(contestant.Token, contestant, (token, existing) => contestant);
            // Console.WriteLine("Contestants: " + JsonSerializer.Serialize(GetContestants()));
        }
        public void VerifyGradesArePersisted()
        {
            var gameService       = new GameService();
            var contestantService = new InMemoryContestantService(gameService, timeServiceMoq.Object);
            var startingBoard     = new Coordinate[]
            {
                new Coordinate {
                    X = 1, Y = 1
                }
            };
            var endingBoard = new Coordinate[]
            {
                new Coordinate {
                    X = 1, Y = 1
                }
            };

            gameService.StartGame(startingBoard, 100, endingBoard);
            var jonathan = new Contestant(
                "jonathan",
                "token",
                DateTime.Now,
                0
                );

            contestantService.AddContestant(jonathan);

            jonathan = jonathan
                       .UpdateGenerationsComputed(100)
                       .UpdateFinalBoard(endingBoard);

            contestantService.UpdateContestant(jonathan);

            var newJonathan = contestantService.GetContestantByToken(jonathan.Token);

            newJonathan.CorrectFinalBoard.Should().BeTrue();
        }
        public void save(Contestant entity)
        {
            var con = DbUtils.getConnection(props);

            using (var comm = con.CreateCommand())
            {
                log.InfoFormat("Saving entity with id {0}", entity.id);
                comm.CommandText = "INSERT INTO Contestants(name,team,engineCap) VALUES (@name, @team, @engCap);";


                var paramName = comm.CreateParameter();
                paramName.ParameterName = "@name";
                paramName.Value         = entity.Name;
                comm.Parameters.Add(paramName);

                var paramTeam = comm.CreateParameter();
                paramTeam.ParameterName = "@team";
                paramTeam.Value         = entity.Team;
                comm.Parameters.Add(paramTeam);

                var paramEng = comm.CreateParameter();
                paramEng.ParameterName = "@engCap";
                paramEng.Value         = entity.EngineCap;
                comm.Parameters.Add(paramEng);

                var result = comm.ExecuteNonQuery();
                con.Close();
                if (result == 0)
                {
                    throw new Exception("No contestant added!");
                }
            }
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
        }
	private IEnumerator RespondToQuestion()
	{
		Questions question = (Questions)(m_questionChoice1 * 4 * 4 + m_questionChoice2 * 4 + m_questionChoice3);
		m_contestorSpeechBubbleText[m_contestantIndex].text = m_chosenContestant.GetQuestionResponse(question);
		
		m_contestorSpeechBubbleAnimator[m_contestantIndex].SetBool("Shown",true);
		
		yield return new WaitForSeconds(3.0f);
		
		m_contestorSpeechBubbleAnimator[m_contestantIndex].SetBool("Shown",false);
		
		yield return new WaitForSeconds(0.2f);

		// Clear choices for next round
		m_chosenContestant = null;
		m_questionChoice1 = -1;
		m_questionChoice2 = -1;
		m_questionChoice3 = -1;
		yield return null;
	}
	private IEnumerator ChooseContestantForQuestion()
	{
		// Text fades in
		yield return StartCoroutine(FadeText(m_chooseContestantText,0.5f,true));
		
		m_chosenContestant = null;
		while (m_chosenContestant == null) // Updated by button press
			yield return null;

		// Text fades out
		yield return StartCoroutine(FadeText(m_chooseContestantText,0.5f,false));
	}
	public void ChooseContestant(Contestant _contestant)
	{
		m_chosenContestant = _contestant;
		for (int i = 0; i < m_contestants.Length; ++i)
		{
			if (m_contestants[i] == _contestant)
				m_contestantIndex = i;
		}
	}
        public void AnotherExample()
        {
            var player = new Contestant();

            player.Score.ShouldBe(42);
        }
            public void Shouldly_ContestantPointsShouldBe1337_HappyPath()
            {
                var contestant = new Contestant {Points = 0};

                contestant.Points.ShouldBe(0);
            }