protected void btnAttend_Click(object sender, EventArgs e) { if (!Permission.Check("contest.attend", false)) return; int contestID = (int)ViewState["contestID"]; using (MooDB db = new MooDB()) { contest = (from c in db.Contests where c.ID == contestID select c).Single<Contest>(); if (DateTimeOffset.Now > contest.EndTime) { return; } User currentUser = ((SiteUser)User.Identity).GetDBUser(db); if (contest.User.Contains(currentUser)) { return; } contest.User.Add(currentUser); db.SaveChanges(); Logger.Info(db, "报名比赛#" + contest.ID); } Response.Redirect("~/Contest/?id=" + contestID, true); }
protected void Page_Load(object sender, EventArgs e) { if (!Permission.Check("contest.read", true)) return; if (!Page.IsPostBack) { using (MooDB db = new MooDB()) { if (Request["id"] != null) { int contestID = int.Parse(Request["id"]); contest = (from c in db.Contests where c.ID == contestID select c).SingleOrDefault<Contest>(); } if (contest == null) { PageUtil.Redirect(Resources.Moo.FoundNothing, "~/"); return; } ViewState["contestID"] = contest.ID; Page.DataBind(); } } }
public ActionResult Contest(string key) { contest = new Contest(); contest.GetContestByKey(key); ContestVideos convids = new ContestVideos(); convids.GetContestVideosForContest(contest.ContestID); ViewBag.ContestName = contest.Name; SongRecords sngrcs = new SongRecords(); SongRecord sngrcd = null; BootBaronLib.AppSpec.DasKlub.BOL.Video vidCon = null; foreach (BootBaronLib.AppSpec.DasKlub.BOL.VideoContest.ContestVideo vi in convids) { vidCon = new BootBaronLib.AppSpec.DasKlub.BOL.Video(vi.VideoID); sngrcd = new SongRecord(vidCon); sngrcs.Add(sngrcd); } sngrcs.Sort(delegate(BootBaronLib.AppSpec.DasKlub.BOL.ArtistContent.SongRecord p1, BootBaronLib.AppSpec.DasKlub.BOL.ArtistContent.SongRecord p2) { return p2.VideoID.CompareTo(p1.VideoID); }); return View(sngrcs); }
public ActionResult Contest(string key) { _contest = new Contest(); _contest.GetContestByKey(key); var convids = new ContestVideos(); convids.GetContestVideosForContest(_contest.ContestID); ViewBag.ContestName = _contest.Name; var sngrcs = new SongRecords(); sngrcs.AddRange(convids.Select(vi => new Video(vi.VideoID)).Select(vidCon => new SongRecord(vidCon))); sngrcs.Sort((p1, p2) => p2.VideoID.CompareTo(p1.VideoID)); return View(sngrcs); }
protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e) { using (MooDB db = new MooDB()) { int contestID = (int)ViewState["contestID"]; contest = (from c in db.Contests where c.ID == contestID select c).Single<Contest>(); grid.PageIndex = e.NewPageIndex; BindGridView(); grid.DataBind(); } }
public bool loadWorkBook(Workbook wb) { if (wb != null) { this.WorkBooks.Add(wb); Contest c = new Contest(); c.Name = wb.Name; c.Contestants = getParticipants(wb); return true; } return false; }
public override void DetermineWinners(Contest contest) { var winningPhotos = contest.Photos .Where(p => p.IsDeleted == false && p.Votes.Count > 0) .OrderByDescending(p => p.Votes.Count) .ThenBy(p => p.CreatedOn) .Take(this.WinnersCount) .ToList(); ICollection<User> winners = winningPhotos.Select(p => p.Owner).ToList(); contest.Winners = winners; contest.WinningPhotosId = winningPhotos.Select(p => p.Id).ToList(); contest.IsFinalized = true; contest.IsActive = false; contest.FinishedOn = DateTime.Now; contest.WallpaperUrl = winningPhotos.First().Url; }
public IActionResult Contest(Contest contest) { contest.Fighters = _fighters; string startValidation = _validation.StartValidation(contest.Fighters, contest.CheckBoxFighters); if (!string.IsNullOrEmpty(startValidation)) { contest.ErrorMessage = startValidation; } else { Result winners = _rules.Contest(contest.Fighters, contest.CheckBoxFighters); return(View("Contest", winners)); } return(View("Index", contest)); }
// GET: Contests/Edit/5 public async Task <ActionResult> Edit(int?id) { if (Session["isAdmin"] == null) { return(RedirectToAction("Login", "Home")); } if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Contest contest = await db.Contest.FindAsync(id); if (contest == null) { return(HttpNotFound()); } return(View(contest)); }
public async Task <ContestResponseModel> SaveContest(ContestUpdateModel contestResponse) { var user = await _userContext.GetUser() ?? throw new Exception("User not found"); int institutionId = contestResponse.InstitutionId == 0 && user.InstitutionId.HasValue ? user.InstitutionId.Value : contestResponse.InstitutionId; Contest contestEntity = _mapper.Map <Contest>(contestResponse); contestEntity.InstitutionId = institutionId; await _repository.Save(contestEntity); await _contestCategoryMappingsRepository.SaveCategoryMappings(contestEntity.Id, contestResponse.ContestCategories); await _contestRingsRepository.SaveCategoryRings(contestEntity.Id, contestResponse.Rings); return(_mapper.Map <ContestResponseModel>(contestEntity)); }
public DataTable[] Build(int contestID) { contest = Contest.GetContest(contestID); data = new Dictionary <string, UserData>(); SubmissionsFilter f = new SubmissionsFilter(contestID); foreach (Submission s in Submission.GetSubmissions(f)) { if (Problem.GetProblem(s.ProblemID).ContestID == contestID) { ProcessSubmission(s); } } DataTable[] dts = new DataTable[] { FormatMonitor(contest), FormatStatistics(contest) }; dts[0].TableName = "Монитор"; dts[1].TableName = "Статистика"; return(dts); }
public ContestViewDto(Contest contest, IList <ProblemInfoDto> problems) : base(contest) { Id = contest.Id; Title = contest.Title; Description = contest.Description; IsPublic = contest.IsPublic; Mode = contest.Mode; BeginTime = contest.BeginTime; EndTime = contest.EndTime; HasScoreBonus = contest.HasScoreBonus; ScoreBonusTime = contest.ScoreBonusTime; ScoreBonusPercentage = contest.ScoreBonusPercentage; HasScoreDecay = contest.HasScoreDecay; IsScoreDecayLinear = contest.IsScoreDecayLinear; ScoreDecayTime = contest.ScoreDecayTime; ScoreDecayPercentage = contest.ScoreDecayPercentage; Problems = problems; }
public List <SoloEvent> GetSoloEventSchedule(Contest contest) { // Ensure that the data is in a valid state to begin scheduling this.Validate(contest); // For scheduling purposes, we only care about solo events that have competitors associated with them List <SoloEvent> soloEvents = contest.SoloEvents.Where(x => x.SoloEventCompetitors.Any()).ToList(); contest.ScheduledSoloEvents = soloEvents; // Assign the judges to events this.AssignJudgesToEvents(contest); // Set the Start times of all solo events this.SetStartTimes(contest); return(soloEvents); }
public ActionResult <Contest> AddOrUpdateContest(Contest contest) { Contest obj; if (contest.IdContest != 0) { obj = contestService.Update(contest); if (obj == null) { return(NoContent( )); } } else { obj = contestService.Add(contest); } return(Ok(obj)); }
// Helper method that returns a Competitor instance with a populated List of SoloEventCompetitor instances matching with the given Contest protected static Competitor GetFakeCompetitor(int competitorId, Contest contest, Grade grade, Instrument instrument, params Idiom[] idioms) { var competitor = new Competitor { CompetitorId = competitorId }; foreach (Idiom idiom in idioms) { SoloEvent targetSoloEvent = contest.SoloEvents.Single(x => x.Grade == grade && x.Idiom == idiom && x.Instrument == instrument); var soloEventCompetitor = new SoloEventCompetitor { CompetitorId = competitorId, SoloEventId = targetSoloEvent.SoloEventId, SoloEvent = targetSoloEvent }; competitor.RegisteredSoloEvents.Add(soloEventCompetitor); targetSoloEvent.SoloEventCompetitors.Add(soloEventCompetitor); } return(competitor); }
public void GetMatchingJudge_NoMatchingJudge_Throws() { // Test: GetMatchingJudge called for a BassDrum SoloEvent, but no judge exists with BassDrum expertise - should throw an error Contest contest = this.Contest; contest.ContestJudges.Add(new ContestJudge { // This judge has no instruments matching with the solo event Judge = new Judge { Instruments = new List <Instrument> { Instrument.BassDrum } }, Contest = contest }); Assert.Throws <InvalidOperationException>(() => this.service.GetMatchingJudge(contest, contest.SoloEvents.First())); }
public void ValidateContestWhenContestCanBeCompetedButTryingToPracticeItShouldThrowAnException() { var contest = new Contest { IsVisible = true, StartTime = new DateTime(1990, 1, 1) }; try { CompeteController.ValidateContest(contest, false); Assert.Fail("Expected an exception when contest is null"); } catch (HttpException ex) { Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.GetHttpCode()); } }
public void CheckPermission(IPhotoContestData data, User user, Contest contest) { if (!contest.IsOpenForSubmissions) { throw new BadRequestException("The registration for this contest is closed."); } if (!contest.InvitedUsers.Contains(user)) { throw new BadRequestException("The user is not selected to participate."); } var invitation = user.PendingInvitations.FirstOrDefault(i => i.ContestId == contest.Id); invitation.Status = InvitationStatus.Accepted; data.SaveChanges(); }
private void SaveMisc3(PKM pk) { pk.PID = Util.GetHexValue(TB_PID.Text); pk.Nature = WinFormsUtil.GetIndex(CB_Nature); pk.Gender = PKX.GetGenderFromString(Label_Gender.Text); if (pk is IContestStats s) { Contest.CopyContestStatsTo(s); } pk.FatefulEncounter = CHK_Fateful.Checked; pk.Ball = WinFormsUtil.GetIndex(CB_Ball); pk.Version = WinFormsUtil.GetIndex(CB_GameOrigin); pk.Language = WinFormsUtil.GetIndex(CB_Language); pk.Met_Level = Util.ToInt32(TB_MetLevel.Text); pk.Met_Location = WinFormsUtil.GetIndex(CB_MetLocation); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { RequirementsProcessor rp = new RequirementsProcessor(GetType()); rp.ProcessRequirements(); if (rp.ProblemIDDefined) { selprob.ProblemID = rp.ProblemID; Problem p = Problem.GetProblem(rp.ProblemID); Contest t = Contest.GetContest(p.ContestID); if (!Page.User.IsInRole("Administrator") && t.Time == ContestTime.Forthcoming) { throw new NeJudgeInvalidParametersException("problemID"); } //"Соревнование, задачу с которого вы хотите просмотреть, ещё не началось. Попробуйте позже." problemView.ProblemID = p.ID; #region Возня со ссылками InitLinks(rp.ProblemID); if (Page.User.IsInRole("Administrator")) { editHL.Visible = true; HideLinks(); } else { if (Page.User.IsInRole("Anonymous") || t.Time == ContestTime.Past) { HideLinks(); } } #endregion } else { problemTable.Visible = false; } } }
public vContest(Contest Contest) { DB DbContext = new DB(); ID = Contest.ID; Format = Contest.Format.ToString(); Join = (from s in DbContext.Statuses where s.ContestID == Contest.ID select s.UserID).Distinct().ToList().Count; Title = HttpUtility.HtmlEncode(Contest.Title); Begin = Contest.Begin.ToString("yyyy-MM-dd HH:mm"); Official = Contest.Official; Duration = Helpers.Time.ToTimeLength(Contest.Begin, Contest.End); if (DateTime.Now < Contest.Begin) { StatusAsInt = 0; } else if (DateTime.Now < Contest.End) { StatusAsInt = 1; } else { StatusAsInt = 2; } switch (Contest.JoinMethod) { case ContestJoinMethod.Appoint: Private = "指定人员"; break; case ContestJoinMethod.Group: Private = Contest.Group.Title + "团队"; break; case ContestJoinMethod.Password: Private = "密码"; break; default: Private = ""; break; } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ContestIDValidator cv = new ContestIDValidator(); cv.Process(); if (cv.ParameterDefined) { if (Contest.GetContest(cv.ValidatedValue).Time == ContestTime.Forthcoming && !Page.User.IsInRole("Administrator")) { throw new NeJudgeInvalidParametersException("contestID"); } //Hide("Ёто соревнование начнетс¤ через " + HtmlFunctions.BeautifyTimeSpan(db.GetContest(tid).Beginning - DateTime.Now, false) + ". —ейчас задачи посмотреть нельз¤."); #region —сылочки (Visible в зависимости от роли) statHL.NavigateUrl = UrlRenderer.RenderStatusUrl(cv.ValidatedValue); quesHL.NavigateUrl = UrlRenderer.RenderQuestionsUrl(cv.ValidatedValue); monHL.NavigateUrl = UrlRenderer.RenderMonitorUrl(cv.ValidatedValue); editHL.NavigateUrl = UrlRenderer.RenderEditContestUrl(cv.ValidatedValue); printHL.NavigateUrl = UrlRenderer.RenderPrintContestUrl(cv.ValidatedValue); if (Page.User.IsInRole("Anonymous")) { statHL.Visible = false; quesHL.Visible = false; } if (Page.User.IsInRole("Administrator")) { editHL.Visible = true; } #endregion } else { monHL.Visible = false; statHL.Visible = false; quesHL.Visible = false; printHL.Visible = false; } } }
/// <summary> /// Called when [navigated to asynchronous]. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="mode">The mode.</param> /// <param name="state">The state.</param> /// <returns></returns> public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state) { if (state.Any()) { // restore state state.Clear(); } else { // There should be a registration ID that is passed to this page // Otherwise, we need to throw an exception // If a contest was passed to this model, load it up for registration var passedRegistration = parameter as PilotRegistrationListViewItemViewModel; if (passedRegistration == null) { base.Throw(new Exception($"This page, {nameof(EditPilotRegistrationPageViewModel)} requires a registration view model parameter.")); } this.Airframe = passedRegistration.Airframes.FirstOrDefault(); this.AmaNumber = passedRegistration.AmaNumber; this.FirstName = passedRegistration.FirstName; this.LastName = passedRegistration.LastName; this.IsPaid = passedRegistration.IsPaid; this.AirframesSignedOff = passedRegistration.AirframesSignedOff; this.pilotId = passedRegistration.PilotId; this.registrationId = passedRegistration.RegistrationId; this.isNewPilot = passedRegistration.IsNewPilot; var contestResult = await this.contestQueryInteractor.Value.GetAllContestsAsync(); if (contestResult.IsFaulted) { base.Alert($"{nameof(EditPilotRegistrationPageViewModel)}:{nameof(OnNavigatedToAsync)} - Could not get contests."); } this.contest = contestResult.Value.Where(c => c.Id == passedRegistration.ContestId).SingleOrDefault(); if (contest == null) { base.Alert($"{nameof(EditPilotRegistrationPageViewModel)}:{nameof(OnNavigatedToAsync)} - Could not find the contest for this registration."); } } }
public Task <IdentityResult> SetStateForContestAsync(int contestId, string contestState) { return(Task <IdentityResult> .Factory.StartNew(() => { using (PortalContext context = _getContext()) { int stateobjId = context.Set <ContestState>().Single(x => x.ContestStateName.Equals(contestState)).ContestStateId; Contest contest = context.Contests.Find(contestId); if (contest == null) { return IdentityResult.Failed(new[] { "Контест отсутствует в БД" }); } contest.IdContestState = stateobjId; context.SaveChanges(); return IdentityResult.Success; } })); }
protected List <ContestJudge> GetContestJudges(Contest contest, Instrument instrument, params Idiom[] idioms) { var result = new List <ContestJudge>(); int judgeId = 0; foreach (Idiom idiom in idioms) { var judge = new Judge(); judge.JudgeId = judgeId++; judge.Instruments.Add(instrument); judge.Idioms.Add(idiom); result.Add(new ContestJudge { JudgeId = judge.JudgeId, Judge = judge, Contest = contest }); } return(result); }
/// <summary> /// Validates the contest. /// </summary> /// <param name="contestToCreate">The contest to create.</param> /// <returns></returns> private bool ValidateContest(Contest contestToCreate) { Validate.IsNotNull(contestToCreate, nameof(contestToCreate)); if (string.IsNullOrEmpty(contestToCreate.Name)) { return(false); } if (contestToCreate.NumberOfFlyoffRounds < 0) { return(false); } if (contestToCreate.NumberOfPilots < 0) { return(false); } if (contestToCreate.Rounds == null || contestToCreate.Rounds?.Count < 0) { return(false); } if (contestToCreate.StartDate > contestToCreate.EndDate) { return(false); } if (contestToCreate.Type == ContestType.Unknown) { return(false); } if (contestToCreate.PilotRoster == null || contestToCreate.PilotRoster.Count < 0) { return(false); } return(true); }
/// <summary> /// Called when [navigated to asynchronous]. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="mode">The mode.</param> /// <param name="state">The state.</param> /// <returns></returns> public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state) { if (state.Any()) { // restore state var previousState = state[nameof(ContestInfoViewModel)] as ContestInfoViewModel; // Set any previous contest in progress (if a contest was sent in as a parameter // before the app was suspended for instance) contest = previousState.contest; if (previousState != null) { this.NumberOfPilotsPerRoundData = previousState.NumberOfPilotsPerRoundData; this.AllowDrop = previousState.AllowDrop; this.ContestName = previousState.ContestName; this.EndDate = previousState.EndDate; this.ContestId = previousState.contestId; this.SelectedNumberOfFlyoffRounds = previousState.SelectedNumberOfFlyoffRounds; this.SelectedNumberOfPilotsPerGroup = previousState.SelectedNumberOfPilotsPerGroup; this.StartDate = previousState.StartDate; this.ContestRegistrationFee = previousState.ContestRegistrationFee; } state.Clear(); } else { // If a contest was passed to this model, load it up for editing if (parameter is Contest passedContest) { this.contest = passedContest; LoadUI(); } else { this.contest = new Contest(); this.ContestId = string.Empty; this.SelectedNumberOfPilotsPerGroup = 7; this.SelectedNumberOfFlyoffRounds = 0; } } await Task.CompletedTask; }
public bool UpdateContest(Contest contest) { try { if (contest.Participantes == null) { contest.Participantes.Add("unlam_01"); } string documentName = "Contests/" + contest.Id; client.Update(documentName, contest); return(true); } catch (Exception e) { return(false); } }
private void finishButton_Click(object sender, EventArgs e) { if (Page.IsValid) { if (tid == -1) { Contest t = new Contest(DateTime.Parse(beginningTextBox.Text), DateTime.Parse(endingTextBox.Text), nameTextbox.Text.Trim()); tid = InsertContest(t); addButton.Visible = true; finishButton.Text = "«акончить"; } else { Contest t = new Contest(DateTime.Parse(beginningTextBox.Text), DateTime.Parse(endingTextBox.Text), nameTextbox.Text.Trim()); UpdateContest(t); Response.Redirect("~/contest.aspx?tid=" + tid); } } }
public async Task ContestStorageCmdInteractor_DeleteContestAsync_BadContestObjectParameter() { var contest = new Contest { Name = string.Empty, NumberOfFlyoffRounds = 0, Rounds = new Dictionary <int, Round>(), StartDate = DateTimeOffset.Now, EndDate = DateTimeOffset.Now.AddDays(1), Type = ContestType.F3K, Id = "234wsdfs" }; mockContestRepository.Setup(c => c.DeleteAsync(It.IsAny <string>())).Returns <bool>(x => Task.FromResult(new Result <bool>(false))); var contestCmdInteractor = new ContestStorageCmdInteractor(mockContestRepository.Object, mockLogger.Object); var result = await contestCmdInteractor.DeleteContestAsync(contest); // Name is empty Assert.IsTrue(result.IsFaulted); // Contest Flyoff Rounds is out of range contest.Name = "foo"; contest.NumberOfFlyoffRounds = -1; result = await contestCmdInteractor.DeleteContestAsync(contest); Assert.IsTrue(result.IsFaulted); // Contest Rounds is out of range contest.NumberOfFlyoffRounds = 0; contest.Rounds = null; result = await contestCmdInteractor.DeleteContestAsync(contest); // Contest Rounds is out of range Assert.IsTrue(result.IsFaulted); contest.Id = string.Empty; contest.Rounds = new Dictionary <int, Round>(); result = await contestCmdInteractor.DeleteContestAsync(contest); // Contest ID is invalid Assert.IsTrue(result.IsFaulted); }
protected void btnSubmit_Click(object sender, EventArgs e) { if (!Page.IsValid) return; if (!Permission.Check("contest.create", false)) return; int contestID; using (MooDB db = new MooDB()) { Contest contest = new Contest() { Title = txtTitle.Text, Description = txtDescription.Text, Status = "Before", StartTime = timeStart.Value, EndTime = timeEnd.Value, AllowTestingOnStart = chkAllowTestingOnStart.Checked, HideTestCaseOnStart = chkHideTestCaseOnStart.Checked, LockProblemOnStart = chkLockProblemOnStart.Checked, LockTestCaseOnStart = chkLockTestCaseOnStart.Checked, LockSolutionOnStart = chkLockSolutionOnStart.Checked, LockPostOnStart = chkLockPostOnStart.Checked, LockRecordOnStart=chkLockRecordOnStart.Checked, HideProblemOnStart=chkHideProblemOnStart.Checked, AllowTestingOnEnd=chkAllowTestingOnEnd.Checked, HideTestCaseOnEnd=chkHideTestCaseOnEnd.Checked, LockProblemOnEnd=chkLockProblemOnEnd.Checked, LockTestCaseOnEnd=chkLockTestCaseOnEnd.Checked, LockSolutionOnEnd=chkLockSolutionOnEnd.Checked, LockPostOnEnd=chkLockPostOnEnd.Checked, LockRecordOnEnd=chkLockRecordOnEnd.Checked , HideProblemOnEnd=chkHideProblemOnEnd.Checked }; db.Contests.AddObject(contest); db.SaveChanges(); contestID = contest.ID; Logger.Info(db, "创建比赛#" + contestID); } PageUtil.Redirect("创建成功", "~/Contest/?id=" + contestID); }
static void Main(string[] args) { // Singing contest with 20 participants. var singing_contest = new Contest(20); // Gather 1000 random votes for (int i = 0; i < 1000; i++) { singing_contest.VoteRandom(); } // Tally up the votes for (int i = 0; i < singing_contest.Participants; i++) { Console.WriteLine($"Participant# : {i+1}, Votes = {singing_contest.Votes[i]}"); } Console.WriteLine($"Total Votes = {singing_contest.TotalVotes}"); Console.WriteLine("Press [Enter] to exit."); Console.ReadLine(); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); LoadJudgesProgressRing.IsActive = true; LoadJudgesTextBlock.Visibility = Visibility.Visible; LoadProjectsProgressRing.IsActive = true; LoadProjectsTextBlock.Visibility = Visibility.Visible; LoadCriteriasProgressRing.IsActive = true; LoadCriteriasTextBlock.Visibility = Visibility.Visible; ContestToLoad = (ContestDetails)e.Parameter; if (ContestToLoad != null) { EditingContest = true; await LoadContestDetailsAsync(); } else { ContestToEdit = new Contest(-1, ContestToLoad, new ObservableCollection <Project>(), new ObservableCollection <JudgeMember>(), new ObservableCollection <Criteria>()); ContestToEdit.ContestDetails = new ContestDetails(); } LoadJudgesProgressRing.IsActive = false; LoadJudgesTextBlock.Visibility = Visibility.Collapsed; LoadProjectsProgressRing.IsActive = false; LoadProjectsTextBlock.Visibility = Visibility.Collapsed; LoadCriteriasProgressRing.IsActive = false; LoadCriteriasTextBlock.Visibility = Visibility.Collapsed; Judges = ContestToEdit.JudgeMembers; Projects = ContestToEdit.Projects; Criterias = ContestToEdit.Criterias; JudgesListView.ItemsSource = Judges; ProjectsListView.ItemsSource = Projects; CriteriaListView.ItemsSource = Criterias; }
public IActionResult planContest([FromBody] Contest contest) { var claimsIdentity = this.User.Identity as ClaimsIdentity; try { userService.IsUserAnOrganizator(claimsIdentity); var response = contestService.planContest(contest); if (response == null) { throw new AppException("Błąd planowania konkursu"); } return(Ok(response)); } catch (Exception e) { return(BadRequest(new { message = e.Message })); } }
public static bool ShouldShowRegistrationForm(this Contest contest, bool isOfficialParticipant) { // Show registration form if contest password is required var showRegistrationForm = (isOfficialParticipant && contest.HasContestPassword) || (!isOfficialParticipant && contest.HasPracticePassword); // Show registration form if contest is official and questions should be asked if (isOfficialParticipant && contest.Questions.Any(x => x.AskOfficialParticipants)) { showRegistrationForm = true; } // Show registration form if contest is not official and questions should be asked if (!isOfficialParticipant && contest.Questions.Any(x => x.AskPracticeParticipants)) { showRegistrationForm = true; } return(showRegistrationForm); }
public IActionResult ReadOneContest([FromBody] ApiModel body) { int?contestID = JsonConvert .DeserializeObject <int>(body.Content); if (contestID == null) { return(Json(new { success = false })); } Contest retrievedContest = dbContext.Contests .SingleOrDefault(c => c.ContestID == contestID); var res = new { success = true, retrievedContest }; return(Json(res)); }
static void Main(string[] args) { try { Console.WriteLine("Enter Number of Candidates"); int n = Int32.Parse(Console.ReadLine()); Console.WriteLine("Enter number of voters"); int m = Int32.Parse(Console.ReadLine()); IList <IList <int> > ballots = new List <IList <int> >(); for (int i = 0; i < m; i++) { Console.WriteLine("Enter ballots for voter number {0} seperated by ','", i + 1); string[] input = Console.ReadLine().Replace(" ", string.Empty).Split(','); List <int> ballot = input.Select(int.Parse).ToList(); ballots.Add(ballot); } List <int> candidates = new List <int>(); for (int i = 0; i < n; i++) { candidates.Add(i + 1); } // Initialize a new contest Contest contest = new Contest(candidates, ballots); contest.RunContest(); // Report the winner(s) Console.WriteLine("The winners for the contest are : "); foreach (int entry in contest.Winners) { Console.WriteLine(entry); } Console.WriteLine(); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } }
private bool AcceptSubmit(Examination oldExam, Examination newExam, Contest contest) { var totalTimes = oldExam.TimeUsing; if (oldExam.StartAgain == null) { totalTimes += ((DateTime.Now - oldExam.CreatedDate.Value).TotalSeconds) / 60.0; } else { totalTimes += ((DateTime.Now - oldExam.StartAgain.Value).TotalSeconds) / 60.0; } if (oldExam.Status == 1) { return(false); } return(true); }
protected void Page_Load(object sender, EventArgs e) { if (!Permission.Check("contest.result.read", true)) return; if (!Page.IsPostBack) { using (MooDB db = new MooDB()) { if (Request["id"] != null) { int id = int.Parse(Request["id"]); contest = (from c in db.Contests where c.ID == id select c).SingleOrDefault<Contest>(); } if (contest == null) { PageUtil.Redirect(Resources.Moo.FoundNothing, "~/"); return; } averageScore = (from u in contest.User let maxScores = from p in contest.Problem let records = from r in u.Record where r.CreateTime > contest.StartTime && r.CreateTime < contest.EndTime && r.Problem.ID == p.ID && r.JudgeInfo != null && r.JudgeInfo.Score >= 0 select r.JudgeInfo.Score let maxScore = records.DefaultIfEmpty(0).Max(s => s) select maxScore let score = maxScores.Sum(maxScore => maxScore) select score).DefaultIfEmpty(0).Average(s => (double)s); AddColumns(); BindGridView(); ViewState["contestID"] = contest.ID; Page.DataBind(); } } }
public ActionResult Add(ContestViewModel model) { var loggedUserId = User.Identity.GetUserId(); var user = this.Data.Users.All().FirstOrDefault(u => u.Id == loggedUserId); if (user != null) { if (model == null) { return View(model); } if (!ModelState.IsValid) { return View(model); } var newContest = new Contest() { Title = model.Title, Description = model.Description, CreatorId = loggedUserId, CreatedOn = DateTime.Now, ClosesOn = model.ClosesOn, NumberOfAllowedParticipants = model.NumberOfAllowedParticipants, ParticipationStrategy = model.ParticipationStrategy, DeadlineStrategy = model.DeadlineStrategy, RewardStrategy = model.RewardStrategy, VotingStrategy = model.VotingStrategy }; user.CreatedContests.Add(newContest); this.Data.SaveChanges(); this.TempData["SuccessMessage"] = "Contest successfully created!"; return RedirectToAction("MyContests", "Home"); } return View(); }
protected void btnAdd_Click(object sender, EventArgs e) { if (!Page.IsValid) return; if (!Permission.Check("contest.modify", false)) return; int contestID = (int)ViewState["contestID"]; int problemID = int.Parse(txtProblemID.Text); using (MooDB db = new MooDB()) { Problem problem = (from p in db.Problems where p.ID == problemID select p).Single<Problem>(); contest = (from c in db.Contests where c.ID == contestID select c).Single<Contest>(); contest.Problem.Add(problem); db.SaveChanges(); Logger.Info(db, string.Format("向比赛#{0}加入题目#{1}", contest.ID, problem.ID)); } Response.Redirect("~/Contest/?id=" + contestID); }
public ActionResult AddContest(ContestViewModel contest) { var loggedUserId = User.Identity.GetUserId(); var user = this.Data.Users.All().FirstOrDefault(u => u.Id == loggedUserId); if (user != null) { if (!ModelState.IsValid) { return View(contest); } if (contest == null) { return View(contest); } var newContest = new Contest() { Title = contest.Title, Description = contest.Description, CreatorId = loggedUserId, CreatenOn = DateTime.Now, ClosesOn = contest.ClosesOn, NumberOfAllowedParticipants = contest.NumberOfAllowedParticipants, ParticipationStrategy = contest.ParticipationStrategy, DeadlineStrategy = contest.DeadlineStrategy, RewardStrategy = contest.RewardStrategy, VotingStrategy = contest.VotingStrategy, }; user.CreatedContests.Add(newContest); this.Data.SaveChanges(); } TempData["contest"] = contest.Title; return View(); }
public OpenVotingStrategy(Contest contest, Photo photo, string userId) : base(contest, photo, userId) { }
private void CheckIfUserCanVote(Contest contest, ContestFullDetailsModel model) { if (contest.Status == ContestStatusType.Active && contest.OwnerId != this.CurrentUser.Id) { if (contest.VotingStrategyType == VotingStrategyType.Closed && contest.MaxNumberOfParticipants > contest.Participants.Count && contest.Voters.Any(v => v.Id == this.CurrentUser.Id)) { model.CanVote = true; } if (contest.VotingStrategyType == VotingStrategyType.Open && contest.OwnerId != this.CurrentUser.Id) { model.CanVote = true; } } }
private void DeleteContestDataChache(Contest contest) { if (contest == null) { return; } this.DeleteContestData(contest); this.Data.SaveChanges(); this.cache.RemoveContestsFromCache(); }
private void DismissContest(Contest contest) { if (contest != null) { contest.Status = ContestStatusType.Dismissed; contest.Winners.Clear(); } }
private void EditContestData(Contest contest, ContestFullDetailsModel model) { if (contest == null || model == null) { return; } contest.Title = model.Title; contest.Description = model.Description; contest.DeadlineDate = model.DeadlineDate; contest.MaxNumberOfParticipants = model.MaxNumberOfParticipants; contest.ParticipationStrategyType = model.ParticipationStrategyType; contest.VotingStrategyType = model.VotingStrategyType; this.Data.Contests.Update(contest); this.Data.SaveChanges(); this.cache.RemoveContestsFromCache(); }
private void FinalizeContest(Contest contest) { if (contest != null) { contest.ClosedOn = DateTime.Now; contest.Status = ContestStatusType.Finalized; } }
public ActionResult Delete(Contest contest) { var model = Mapper.Map<Contest, ContestBasicDetails>(contest); return this.PartialView("_Delete", model); }
private bool CanEdit(Contest contest) { if (contest == null) { return false; } if (this.CurrentUser == null) { return false; } if (this.User.IsInRole("Administrator")) { return true; } if (contest.OwnerId == this.CurrentUser.Id) { return true; } return false; }
private void CheckIfUserCanParticipate(Contest contest, ContestFullDetailsModel model) { if (contest == null || model == null) { return; } if (contest.Status == ContestStatusType.Active && contest.OwnerId != this.CurrentUser.Id) { if (contest.ParticipationStrategyType == ParticipationStrategyType.Open && contest.MaxNumberOfParticipants > contest.Participants.Count) { model.CanParticipate = true; } if (contest.Participants.Any(u => u.Id == this.CurrentUser.Id)) { model.CanParticipate = true; } } }
protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e) { if (!Permission.Check("contest.modify", false)) return; int problemID = (int)e.Keys[0]; int contestID = (int)ViewState["contestID"]; using (MooDB db = new MooDB()) { contest = (from c in db.Contests where c.ID == contestID select c).Single<Contest>(); Problem problem = (from p in db.Problems where p.ID == problemID select p).Single<Problem>(); contest.Problem.Remove(problem); db.SaveChanges(); Logger.Warning(db, string.Format("删除比赛#{0}的题目#{1}", contest.ID, problem.ID)); } Response.Redirect("~/Contest/?id=" + contestID); }
private void FillPacticipants(Contest contest, ICollection<string> participantsIds, ParticipationType participationType) { if (participantsIds == null || participationType == ParticipationType.Open) { contest.Participants.Clear(); } else { var participants = contest.Participants.ToList(); foreach (var participantId in participantsIds) { if (contest.Participants.All(p => p.Id != participantId)) { var participant = this.ContestsData.Users.Find(participantId); contest.Participants.Add(participant); } } foreach (var participant in participants) { if (!participantsIds.Contains(participant.Id)) { contest.Participants.Remove(participant); } } } }
private void CheckIfUserCanEdit(Contest contest, ContestFullDetailsModel model) { if (contest.OwnerId == this.CurrentUser.Id || this.User.IsInRole("Administrator")) { model.CanEdit = this.CanEdit(contest); } }
protected void validateAdd_ServerValidate(object source, ServerValidateEventArgs args) { using (MooDB db = new MooDB()) { int problemID = int.Parse(txtProblemID.Text); Problem problem = (from p in db.Problems where p.ID == problemID select p).SingleOrDefault<Problem>(); if (problem == null) { args.IsValid = false; validateAdd.Text = "无此题目"; return; } int contestID = (int)ViewState["contestID"]; contest = (from c in db.Contests where c.ID == contestID select c).Single<Contest>(); if (contest.Problem.Contains(problem)) { args.IsValid = false; validateAdd.Text = "不能重复添加题目"; return; } } args.IsValid = true; }
private void FillVoters(Contest contest, ICollection<string> votersIds, VotingType votingType ) { if (votersIds == null || votingType == VotingType.Open) { contest.Voters.Clear(); } else { var voters = contest.Voters.ToList(); foreach (var voterId in votersIds) { if (contest.Voters.All(v => v.Id != voterId)) { var voter = this.ContestsData.Users.Find(voterId); contest.Voters.Add(voter); } } foreach (var voter in voters) { if (!votersIds.Contains(voter.Id)) { contest.Voters.Remove(voter); } } } }
private void AddRewardsToContest(ContestInputModel model, Contest contest) { if (model == null || contest == null) { return; } foreach (var prize in model.Prizes) { var reward = new Reward() { RewardPrice = prize }; contest.Rewards.Add(reward); } }
private void AddWinnersToContest(Contest contest, IEnumerable<User> winners) { foreach (var winner in winners) { contest.Winners.Add(winner); } }
protected void Page_Load(object sender, EventArgs e) { if (!Permission.Check("contest.read", true)) return; if (!Page.IsPostBack) { using (MooDB db = new MooDB()) { if (Request["id"] != null) { int contestID = int.Parse(Request["id"]); contest = (from c in db.Contests where c.ID == contestID select c).SingleOrDefault<Contest>(); } if (contest == null) { PageUtil.Redirect(Resources.Moo.FoundNothing, "~/"); return; } if (User.Identity.IsAuthenticated) { attended = contest.User.Contains(((SiteUser)User.Identity).GetDBUser(db)); } ViewState["contestID"] = contest.ID; grid.DataSource = contest.Problem; Page.DataBind(); } } }
private void AddVotersToContest(ContestInputModel model, Contest contest) { if (model == null || contest == null) { return; } if (model.VotersIds.Count != 0) { foreach (var id in model.UserIds) { var user = this.Data.Users.Find(id); contest.Voters.Add(user); } } }