/// <summary> /// Add the points for finishing in the top <see cref="positionPoint"/>. Start with the /// highest points and work down to 0. /// </summary> /// <param name="resultsTable">reference to current results table</param> /// <param name="currentDate">date of current event</param> private void AddPositionPointsDescending( EventResults resultsTable, DateType currentDate) { int positionPoint = this.resultsConfiguration.ResultsConfigurationDetails.NumberOfScoringPositions; resultsTable.OrderByFinishingTime(); foreach (ResultsTableEntry result in resultsTable.Entries) { if (!result.Time.DNF && !result.Time.Unknown) { if (this.PositionScoreToBeCounted(result.FirstTimer) && !(positionPoint == 0)) { result.Points.PositionPoints = positionPoint; this.Model.CurrentSeason.UpdatePositionPoints(result.Key, currentDate, positionPoint); if (positionPoint > 0) { --positionPoint; } } } } }
private void listAveragePaceRefresh() { listAveragePace.Items.Clear(); string[] averagePaceString = new string[3]; foreach (Participant p in SelectedEvent.Participants) { if (p.EventResults != null && p.EventResults.resultParts.ContainsKey("Total time: ")) { EventResults results = p.EventResults; TimeSpan totalTime = TimeSpan.Parse(results.resultParts["Total time: "], CultureInfo.InvariantCulture); TimeSpan avgPace = CalculateAvgPace(p.RunningLocation.RouteLength, totalTime); averagePaceString[0] = p.EventParticipant.UserName; averagePaceString[1] = results.resultParts["Total time: "].ToString(); averagePaceString[2] = avgPace.Minutes.ToString() + ":" + avgPace.Seconds.ToString(); ListViewItem row = new ListViewItem(averagePaceString); listAveragePace.Items.Add(row); } } listAveragePace.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); listAveragePace.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); }
private void CancelImport() { // TODO verify cancel _importActive = false; EventResults.Clear(); OnPropertyChanged("EventResults"); }
public EventResults UploadEventResults(TimeSpan totalTime, double?maxSpeed, int?avgHeartRate) { EventResultsDirector director = new EventResultsDirector(); EventResultsConcreteBuilder builder = new EventResultsConcreteBuilder(); director.Builder = builder; if (maxSpeed != null && avgHeartRate != null) { director.BuildDetailedResults(totalTime, maxSpeed.Value, avgHeartRate.Value); } else if (maxSpeed != null && avgHeartRate == null) { director.BuildResultsWithMaxSpeed(totalTime, maxSpeed.Value); } else if (maxSpeed == null && avgHeartRate != null) { director.BuildResultsWithHeartRate(totalTime, avgHeartRate.Value); } else if (maxSpeed == null && avgHeartRate == null) { director.BuildSimpleResults(totalTime); } else { throw new InvalidOperationException(); } EventResults = builder.GetResults(); Ctx.UploadEventResults(); return(EventResults); }
private static async Task <EventResults> GetEvents() { APIService srv = new APIService(); EventModel model = new EventModel(); model.CommandModel.SessionToken = await App.GetUsersSession(); model.CommandModel.Action = "GetOpenEvents"; EventResults result = null; var cache = BlobCache.UserAccount; var cachedEventsPromise = cache.GetAndFetchLatest( "events", () => srv.GetEvents(model.CommandModel), offset => { TimeSpan elapsed = DateTimeOffset.Now - offset; return(elapsed > new TimeSpan(hours: 0, minutes: 10, seconds: 0)); }).FirstOrDefaultAsync(); cachedEventsPromise.Subscribe(subscribedEvents => { result = subscribedEvents; }); result = await cachedEventsPromise.FirstOrDefaultAsync(); return(result); }
/// <summary> /// Assign club points from the athlete results. Update the model. /// </summary> /// <param name="resultsTable">reference to current results table</param> /// <param name="currentDate">date of current event</param> /// <param name="scoringPositions">number of scoring positions</param> private void AssignMobTrophyPoints( EventResults resultsTable, DateType currentDate, List <MobTrophyPoints> mobTrophyPointsWorking) { if (!this.resultsConfiguration.ResultsConfigurationDetails.UseTeams) { return; } resultsTable.OrderByFinishingTime(); foreach (ResultsTableEntry result in resultsTable.Entries) { if (result.Club == string.Empty) { continue; } MobTrophyPoints club = mobTrophyPointsWorking.Find(clubName => clubName.ClubName.CompareTo(result.Club) == 0); if (club != null) { club.AddNewResult( result.Points.PositionPoints, result.FirstTimer, result.SB); } } this.SaveMobTrophyPointsToModel( mobTrophyPointsWorking, currentDate); }
static async Task ProcessOrderEvents(long orderId, EventResults results) { foreach (var ev in results.Events) { Console.WriteLine($" {ev.Verb} - {ev.CreatedAt}"); esClient.PublishOrderEvent(ev); } }
private bool ValidateFootballSelection(Selection selection, EventResults results) { var winningCondition = selection.WinningCondition; if (winningCondition.IsOutright) { return(ValidateOutrightResult(winningCondition, results)); } return(ValidateOtherScenarios(winningCondition, results)); }
private bool ValidateOutrightResult(WinningCondition winningCondition, EventResults results) { if (results.TeamAWin) { return(winningCondition.TeamAWin); } else { return(winningCondition.TeamBWin); } }
static async Task ProcessOrders(EventResults eventResults) { Console.WriteLine($"Processing {eventResults.Events.Count} Orders..."); foreach (var ev in eventResults.Events) { Console.WriteLine($"Processing {ev.SubjectType}-{ev.SubjectId}..."); Console.WriteLine("===================="); await GetOrderEvents(ev); Console.WriteLine(); } }
public override void OnShow() { var result = Variables.GetValueOrDefault(Parameters.IdResultEventId); if (result != null) { var closeEventResult = (EventResults)DbRef.FromString($"{result}").GetObject(); _closeResult.Text = closeEventResult.Description; _eventResults = closeEventResult; } InitComponents(); }
private bool ValidateOtherScenarios(WinningCondition winningCondition, EventResults results) { var tennisResults = results.Results as TennisResult; var tennisCondition = winningCondition.CustomCondition as TennisCondition; var set = tennisResults.Sets.FirstOrDefault(s => s.SetNumber == tennisCondition.SetNumber); if (tennisCondition.IsGameValidation) { var game = set.Games.FirstOrDefault(g => g.GameNumber == tennisCondition.GameNumber); return(tennisCondition.Player1Win == game.Player1Win); } return(set.Player1Win == tennisCondition.Player1Win); }
private bool ValidateOtherScenarios(WinningCondition winningCondition, EventResults results) { if (results.TeamAWin) { return(winningCondition.TeamAWin && results.TeamAScore == winningCondition.TeamAScore && winningCondition.TeamBScore == results.TeamBScore); } if (results.TeamBWin) { return(winningCondition.TeamBWin && results.TeamAScore == winningCondition.TeamAScore && winningCondition.TeamBScore == results.TeamBScore); } return(winningCondition.Draw && results.TeamAScore == winningCondition.TeamAScore && winningCondition.TeamBScore == results.TeamBScore); }
public override void OnLoading() { _commentaryMemoEdit = (MemoEdit)GetControl("CommentaryMemoEdit", true); _closeResult = (TextView)GetControl("75097b50211a453883f5e31f4e878c2c", true); if (_eventResults == null) { _eventResults = new EventResults(); } if (_commentaryString == null) { Utils.TraceMessage($"Стока {_commentaryString} пустая"); _commentaryString = string.Empty; } }
private void AddPositionPoints( EventResults resultsTable, DateType currentDate) { if (this.resultsConfiguration.ResultsConfigurationDetails.ScoresAreDescending) { this.AddPositionPointsDescending( resultsTable, currentDate); } else { this.AddPositionPointsAscending( resultsTable, currentDate); } }
private IEnumerable <Selection> ValidateResults(Market market, EventResults results) { var winnerSelections = new List <Selection>(); Parallel.ForEach(market.Selections, selection => { if (ValidateFootballSelection(selection, results)) { Object lockMe = new Object(); lock (lockMe) { winnerSelections.Add(selection); } } }); return(winnerSelections); }
public void startSession() { App.Current.Dispatcher.Invoke(() => BindingOperations.EnableCollectionSynchronization(PersonaList, personaListLock)); App.Current.Dispatcher.Invoke(() => BindingOperations.EnableCollectionSynchronization(EventResults, eventResultsLock)); foreach (Persona persona in Engine.getCurrentPersonaList()) { PersonaList.Add(persona); } ActivePersona = PersonaList[Engine.getDefaultPersonaIdx()]; foreach (EventResult eventResult in Engine.getEventResults()) { EventResults.Add(eventResult); } log.Info("Session started."); }
/// <summary> /// Add the points for finishing in the top <see cref="positionPoint"/>. Find the first girl/boy, second and third /// and make a note. /// </summary> /// <param name="resultsTable">reference to current results table</param> /// <param name="currentDate">date of current event</param> private void AddPositionPointsAscending( EventResults resultsTable, DateType currentDate) { int positionPoint = 1; resultsTable.OrderByFinishingTime(); foreach (ResultsTableEntry result in resultsTable.Entries) { if (!result.Time.DNF && !result.Time.Unknown) { if (this.PositionScoreToBeCounted(result.FirstTimer)) { result.Points.PositionPoints = positionPoint; this.Model.CurrentSeason.UpdatePositionPoints(result.Key, currentDate, positionPoint); ++positionPoint; } } } }
private void listAvgHeartRateRefresh() { listAvgHeartRate.Items.Clear(); string[] avgHeartRateString = new string[2]; foreach (Participant p in SelectedEvent.Participants) { if (p.EventResults != null) { EventResults results = p.EventResults; if (results.resultParts.ContainsKey("Average heart rate: ")) { avgHeartRateString[0] = p.EventParticipant.UserName; avgHeartRateString[1] = results.resultParts["Average heart rate: "].ToString(); ListViewItem row = new ListViewItem(avgHeartRateString); listAvgHeartRate.Items.Add(row); } listAvgHeartRate.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); listAvgHeartRate.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } } }
private void listMaxSpeedRefresh() { listMaxSpeed.Items.Clear(); string[] maxSpeedString = new string[2]; foreach (Participant p in SelectedEvent.Participants) { if (p.EventResults != null) { EventResults results = p.EventResults; if (results.resultParts.ContainsKey("Maximum speed: ")) { maxSpeedString[0] = p.EventParticipant.UserName; maxSpeedString[1] = results.resultParts["Maximum speed: "].ToString(); ListViewItem row = new ListViewItem(maxSpeedString); listMaxSpeed.Items.Add(row); } listMaxSpeed.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); listMaxSpeed.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } } }
/// <summary> /// Reads the athlete season details xml from file and decodes it. /// </summary> /// <param name="seasonName">season name</param> /// <param name="eventName">event name</param> /// <param name="date">event date</param> /// <returns>decoded athlete's details</returns> public IEventResults LoadResultsTable( string seasonName, string eventName, DateType date) { IEventResults resultsTable = new EventResults(); ResultsTableRoot deserialisedResultTable; string resultsPath = ResultsTableReader.GetPath( seasonName, eventName); try { deserialisedResultTable = XmlFileIo.ReadXml <ResultsTableRoot>( resultsPath); } catch (XmlException ex) { this.logger.WriteLog( $"Error reading the results table; {ex.XmlMessage}"); return(resultsTable); } foreach (Row row in deserialisedResultTable) { RaceTimeType time = new RaceTimeType( row.Time); RaceTimeType handicap = new RaceTimeType( row.Handicap); CommonPoints points = new CommonPoints( row.Points, date); int position = resultsTable.Entries.Count + 1; ResultsTableEntry rowEntry = new ResultsTableEntry( row.Key, row.Name, time, row.Order, row.RunningOrder, handicap, row.Club, row.Sex, row.Number, points, row.HarmonyPoints, row.IsPersonalBest, row.IsYearBest, row.Notes, row.ExtraInformation, position); resultsTable.AddEntry(rowEntry); } return(resultsTable); }
public static Event CreateFootballEventTwoMarkets() { var selections = new List <Selection>() { new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(11, 4), WinningCondition = new WinningCondition() { IsOutright = true, TeamAScore = 1, TeamBScore = 0 } }, new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(13, 5), WinningCondition = new WinningCondition() { IsOutright = true, TeamAScore = 0, TeamBScore = 1 } } , new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(4, 6), WinningCondition = new WinningCondition() { IsOutright = true, TeamAScore = 0, TeamBScore = 0 } } }; var scoreSelections = new List <Selection>() { new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(11, 4), WinningCondition = new WinningCondition() { IsOutright = false, TeamAScore = 1, TeamBScore = 0 } }, new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(11, 4), WinningCondition = new WinningCondition() { IsOutright = false, TeamAScore = 0, TeamBScore = 1 } }, new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(11, 4), WinningCondition = new WinningCondition() { IsOutright = false, TeamAScore = 0, TeamBScore = 0 } }, new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(11, 4), WinningCondition = new WinningCondition() { IsOutright = false, TeamAScore = 3, TeamBScore = 0 } } }; var outrightMarket = new Market() { Id = Guid.NewGuid(), Selections = selections }; var scoreMarket = new Market() { Id = Guid.NewGuid(), Selections = scoreSelections }; var bettingEvent = new Event("Paddy Power Cup Final", Sport.Football) { Markets = new List <Market> { outrightMarket, scoreMarket } }; var bets = new List <Bet>() { new Bet() { BetAmmount = 4, SelectionBet = selections[0], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, new Bet() { BetAmmount = 4, SelectionBet = selections[2], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, new Bet() { BetAmmount = 2, SelectionBet = selections[0], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, }; bettingEvent.Bets = bets; var eventResults = new EventResults() { TeamAScore = 2, TeamBScore = 0 }; bettingEvent.Results = eventResults; return(bettingEvent); }
protected Database() { User user1 = new User("Tom", "password"); User user2 = new User("Alex", "password"); User user3 = new User("Lisa", "password"); User user4 = new User("Mario", "password"); User user5 = new User("Lucia", "password"); Users.Add(user1.UserName, user1); Users.Add(user2.UserName, user2); Users.Add(user3.UserName, user3); Users.Add(user4.UserName, user4); Users.Add(user5.UserName, user5); Location route1 = new Location("Ostpark, Munich", 48.112242, 11.630701, 5); Location route2 = new Location("Parco di Villa Borghese, Rome", 41.914614, 12.481987, 6); Location route3 = new Location("Parco degli Acquedotti, Rome", 41.853406, 12.557115, 10); Location route4 = new Location("Englischer Garten, Munich", 48.164334, 11.605598, 8); Location route5 = new Location("Parco Sempione, Milan", 45.474371, 9.171659, 4); RunningLocations.Add(route1.RouteName, route1); RunningLocations.Add(route2.RouteName, route2); RunningLocations.Add(route3.RouteName, route3); RunningLocations.Add(route4.RouteName, route4); RunningLocations.Add(route5.RouteName, route5); Event jogging1 = new InPersonEvent(new DateTime(2020, 08, 01, 08, 30, 00), 11.0, "Jogging in the park", route3); Event jogging2 = new InPersonEvent(new DateTime(2020, 08, 09, 19, 00, 00), 11.5, "After work jogging", route5); Event jogging3 = new VirtualEvent(new DateTime(2020, 8, 21, 09, 00, 00), 10.0, "Jogging as a virtual group", 7.0); Event jogging4 = new InPersonEvent(new DateTime(2020, 06, 01, 10, 00, 00), 12.0, "Morning jogging on 1st June", route1); Event jogging5 = new VirtualEvent(new DateTime(2020, 7, 28, 19, 00, 00), 11.5, "Jogging in different locations", 5.0); Event jogging6 = new InPersonEvent(new DateTime(2020, 5, 15, 11, 00, 00), 10.0, "Speed challenge", route5); Event jogging7 = new VirtualEvent(new DateTime(2020, 7, 31, 18, 30, 00), 13.0, "Evening jogging", 5.0); Events.Add(jogging1.EventTitle, jogging1); Events.Add(jogging2.EventTitle, jogging2); Events.Add(jogging3.EventTitle, jogging3); Events.Add(jogging4.EventTitle, jogging4); Events.Add(jogging5.EventTitle, jogging5); Events.Add(jogging6.EventTitle, jogging6); Events.Add(jogging7.EventTitle, jogging7); Participant part1 = new Participant(user1, jogging1); Participant part2 = new Participant(user1, jogging3); Participant part3 = new Participant(user1, jogging4); Participant part4 = new Participant(user2, jogging4); Participant part5 = new Participant(user3, jogging4); Participant part6 = new Participant(user4, jogging4); Participant part7 = new Participant(user1, jogging5); Participant part8 = new Participant(user1, jogging6); Participant part9 = new Participant(user2, jogging6); Participant part10 = new Participant(user4, jogging6); part7.SetRunningLocation(route4); part8.SetRunningLocation(route2); part3.CheckInAtEvent(); part4.CheckInAtEvent(); part5.CheckInAtEvent(); part6.CheckInAtEvent(); part8.CheckInAtEvent(); part9.CheckInAtEvent(); part10.CheckInAtEvent(); EventResults results1 = part3.UploadEventResults(TimeSpan.Parse("00:32:15", CultureInfo.InvariantCulture), 10.5, 166); EventResults results2 = part4.UploadEventResults(TimeSpan.Parse("00:31:09", CultureInfo.InvariantCulture), null, 170); EventResults results3 = part5.UploadEventResults(TimeSpan.Parse("00:34:38", CultureInfo.InvariantCulture), 9.8, null); EventResults results4 = part6.UploadEventResults(TimeSpan.Parse("00:35:00", CultureInfo.InvariantCulture), null, null); UserGroup group1 = new UserGroup(user1, "Munich Joggers"); UserGroup group2 = new UserGroup(user2, "Milan Joggers"); UserGroup group3 = new UserGroup(user3, "City joggers"); UserGroups.Add(group1.GroupName, group1); UserGroups.Add(group2.GroupName, group2); UserGroups.Add(group3.GroupName, group3); group1.AddMember(user3); group1.AddMember(user4); group2.AddMember(user4); group2.AddMember(user5); group3.AddMember(user1); }
public static Event CreateTennisEventSet2Game1Market() { var selections = new List <Selection>() { new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(4, 7), WinningCondition = new WinningCondition() { IsOutright = false, TeamAScore = 1, TeamBScore = 0, CustomCondition = new TennisCondition() { GameNumber = 1, IsGameValidation = true, Player1Win = true, SetNumber = 2 } } }, new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(5, 4), WinningCondition = new WinningCondition() { IsOutright = false, TeamBScore = 1, TeamAScore = 0, CustomCondition = new TennisCondition() { GameNumber = 1, IsGameValidation = true, Player1Win = false, SetNumber = 2 } } } }; var outrightMarket = new Market() { Id = Guid.NewGuid(), Description = "To win Set 2 1 st game", Selections = selections }; var bettingEvent = new Event("L Harte v C Ryan tennis match", Sport.Tennis); bettingEvent.Markets.Add(outrightMarket); var bets = new List <Bet>() { new Bet() { BetAmmount = 5, SelectionBet = selections[0], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, new Bet() { BetAmmount = 6, SelectionBet = selections[1], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, new Bet() { BetAmmount = 1, SelectionBet = selections[0], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, }; bettingEvent.Bets = bets; var eventResults = new EventResults() { TeamAScore = 3, TeamBScore = 0, Results = new TennisResult() }; bettingEvent.Results = eventResults; return(bettingEvent); }
public static Event CreateTennisEvent() { var selections = new List <Selection>() { new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(9, 4), WinningCondition = new WinningCondition() { IsOutright = true, TeamAScore = 1, TeamBScore = 0 } }, new Selection() { Id = Guid.NewGuid(), Odd = new FractionOdd(3, 10), WinningCondition = new WinningCondition() { IsOutright = true, TeamAScore = 0, TeamBScore = 1 } } }; var outrightMarket = new Market() { Id = Guid.NewGuid(), Description = "Match Betting market", Selections = selections }; var bettingEvent = new Event("L Harte v C Ryan tennis match", Sport.Tennis); bettingEvent.Markets.Add(outrightMarket); var bets = new List <Bet>() { new Bet() { BetAmmount = 5, SelectionBet = selections[0], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, new Bet() { BetAmmount = 6, SelectionBet = selections[1], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, new Bet() { BetAmmount = 1, SelectionBet = selections[0], EventId = bettingEvent.Id, Punter = new Punter() { Balance = 50, Id = Guid.NewGuid() } }, }; bettingEvent.Bets = bets; var eventResults = new EventResults() { TeamAScore = 3, TeamBScore = 0 }; bettingEvent.Results = eventResults; return(bettingEvent); }
/// <summary> /// Generate the results table from the raw results and return it. /// </summary> /// <param name="rawResults">raw results</param> /// <returns>event results table</returns> private EventResults GenerateResultsTable( List <IRaw> rawResults) { EventResults resultsTable = new EventResults(); DateType eventDate = this.Model.CurrentEvent.Date; foreach (Raw raw in rawResults) { CommonPoints pointsEarned = new CommonPoints(eventDate); // Get athlete key. int key = this.Model.Athletes.GetAthleteKey(raw.RaceNumber) ?? 0; // Note the current handicap. RaceTimeType athleteHandicap = this.GetAthleteHandicap( key); // Loop through all the entries in the raw results. ResultsTableEntry singleResult = new ResultsTableEntry( key, this.Model.Athletes.GetAthleteName(key), raw.TotalTime, raw.Order, athleteHandicap, this.Model.Athletes.GetAthleteClub(key), this.Model.Athletes.GetAthleteSex(key), raw.RaceNumber, this.Model.CurrentEvent.Date, this.Model.Athletes.GetAthleteAge(key), resultsTable.Entries.Count + 1, 999999); if (!raw.TotalTime.DNF && !raw.TotalTime.Unknown) { if (this.Model.Athletes.IsFirstTimer(key)) { singleResult.FirstTimer = true; } pointsEarned.FinishingPoints = this.resultsConfiguration.ResultsConfigurationDetails.FinishingPoints; // Work out the season best information if (this.Model.CurrentSeason.GetSB(key) > singleResult.RunningTime) { // Can only count as season best if one time has been set. if (this.Model.CurrentSeason.GetAthleteAppearancesCount(key) > 0) { pointsEarned.BestPoints = this.resultsConfiguration.ResultsConfigurationDetails.SeasonBestPoints; singleResult.SB = true; this.RecordNewSB(); } } singleResult.Points = pointsEarned; // Work out the personal best information. if (this.Model.Athletes.GetPB(key) > singleResult.RunningTime) { // Only not as PB if not the first run. if (!singleResult.FirstTimer) { singleResult.PB = true; this.RecordNewPB(); } } this.CheckForFastestTime(this.Model.Athletes.GetAthleteSex(key), key, this.Model.Athletes.GetAthleteName(key), raw.TotalTime - athleteHandicap, eventDate); this.UpdateNumberStatistics(this.Model.Athletes.GetAthleteSex(key), singleResult.FirstTimer); } this.Model.Athletes.AddNewTime(key, new Appearances(singleResult.RunningTime, eventDate)); this.Model.CurrentSeason.AddNewTime(key, new Appearances(singleResult.RunningTime, eventDate)); this.Model.CurrentSeason.AddNewPoints(key, pointsEarned); // End loop through all the entries in the raw results. resultsTable.AddEntry(singleResult); } return(resultsTable); }
/// <summary> /// Loop through the results and work out all the points for the Team Trophy. /// </summary> /// <param name="resultsTable">results table</param> /// <param name="currentDate">date of the event</param> private void CalculateTeamTrophyPoints( EventResults resultsTable, DateType currentDate) { // Next score is used to complete the Team Trophy by filling in any blank spots. // The position is used to assign points to an athlete in the Team Trophy. int teamTrophyCompetitionPosition = 0; int nextScore = 1; resultsTable.OrderByFinishingTime(); Dictionary <string, ITeamTrophyEvent> eventDictionary = new Dictionary <string, ITeamTrophyEvent>(); foreach (IClubSeasonDetails club in this.Model.CurrentSeason.Clubs) { ITeamTrophyEvent newEvent = new TeamTrophyEvent( currentDate, this.resultsConfiguration.ResultsConfigurationDetails.NumberInTeamTrophyTeam); eventDictionary.Add( club.Name, newEvent); } foreach (ResultsTableEntry result in resultsTable.Entries) { IAthleteTeamTrophyPoints athletePoints; IAthleteSeasonDetails athlete = this.Model.CurrentSeason.Athletes.Find( a => a.Key == result.Key); if (athlete == null) { this.logger.WriteLog( $"Calculate Results Manager - Can'f find athlete {result.Key}"); continue; } if (result.Club == string.Empty || result.FirstTimer) { result.TeamTrophyPoints = TeamTrophyNoScore; athletePoints = new AthleteTeamTrophyPoints( TeamTrophyNoScore, currentDate); athlete.TeamTrophyPoints.AddNewEvent(athletePoints); // Not part of the Team Trophy, move onto the next loop. continue; } ++teamTrophyCompetitionPosition; ITeamTrophyEvent clubEvent = eventDictionary[result.Club]; ICommonTeamTrophyPoints clubPoint = new CommonTeamTrophyPoints( teamTrophyCompetitionPosition, result.Name, result.Key, true, currentDate); // Attempt to add point to the club. It will fail if the team is already full. bool success = clubEvent.AddPoint(clubPoint); if (success) { nextScore = teamTrophyCompetitionPosition + 1; result.TeamTrophyPoints = teamTrophyCompetitionPosition; } else { // Add points failed, revert the Team Trophy position. --teamTrophyCompetitionPosition; result.TeamTrophyPoints = TeamTrophyNoScore; } athletePoints = new AthleteTeamTrophyPoints( result.TeamTrophyPoints, currentDate); athlete.TeamTrophyPoints.AddNewEvent(athletePoints); } List <ITeamTrophyEvent> orderedEvent = new List <ITeamTrophyEvent>(); foreach (KeyValuePair <string, ITeamTrophyEvent> entry in eventDictionary) { entry.Value.Complete( this.resultsConfiguration.ResultsConfigurationDetails.NumberInTeamTrophyTeam, nextScore); orderedEvent.Add(entry.Value); } // Apply the score for each team as defined by the configuration file. // To order the teams, they've needed to be pulled out from the dictionary into a list. orderedEvent = orderedEvent.OrderBy(e => e.TotalAthletePoints).ToList(); int lastPoints = -1; int lastScoringIndex = 0; for (int index = 0; index < orderedEvent.Count; ++index) { if (orderedEvent[index].NumberOfAthletes == 0) { break; } if (orderedEvent[index].TotalAthletePoints == lastPoints) { orderedEvent[index].Score = this.resultsConfiguration.ResultsConfigurationDetails.TeamTrophyPoints[lastScoringIndex]; } else if (index < this.resultsConfiguration.ResultsConfigurationDetails.TeamTrophyPoints.Count) { orderedEvent[index].Score = this.resultsConfiguration.ResultsConfigurationDetails.TeamTrophyPoints[index]; lastScoringIndex = index; } lastPoints = orderedEvent[index].TotalAthletePoints; } foreach (KeyValuePair <string, ITeamTrophyEvent> entry in eventDictionary) { this.Model.CurrentSeason.AddNewClubPoints(entry.Key, entry.Value); } }
/// <summary> /// Add the points for finishing in the top <see cref="positionPoint"/>. Find the first girl/boy, second and third /// and make a note. /// </summary> /// <param name="resultsTable">reference to current results table</param> private void AddPlacings( EventResults resultsTable) { bool firstBoyFound = false; bool firstGirlFound = false; bool secondFound = false; bool thirdFound = false; bool secondBoyFound = false; bool secondGirlFound = false; bool thirdBoyFound = false; bool thirdGirlFound = false; foreach (ResultsTableEntry result in resultsTable.Entries) { if (result.Time.DNF) { continue; } if (result.Time.Unknown) { continue; } if (result.FirstTimer && this.resultsConfiguration.ResultsConfigurationDetails.ScoresAreDescending) { continue; } if ( !(firstBoyFound && firstGirlFound && secondFound && thirdFound)) { if (!firstBoyFound && result.Sex == SexType.Male) { result.ExtraInfo = "First Boy"; firstBoyFound = true; } else if (!firstGirlFound && result.Sex == SexType.Female) { result.ExtraInfo = "First Gal"; firstGirlFound = true; } else if (!this.seriesConfiguration.AllPositionsShown && !secondFound && result.Sex != SexType.NotSpecified) { result.ExtraInfo = "Second"; secondFound = true; } else if (!this.seriesConfiguration.AllPositionsShown && !thirdFound && result.Sex != SexType.NotSpecified) { result.ExtraInfo = "Third"; thirdFound = true; } else if (this.seriesConfiguration.AllPositionsShown && !secondBoyFound && result.Sex == SexType.Male) { result.ExtraInfo = "Second Boy"; secondBoyFound = true; } else if (this.seriesConfiguration.AllPositionsShown && !secondGirlFound && result.Sex == SexType.Female) { result.ExtraInfo = "Second Gal"; secondGirlFound = true; } else if (this.seriesConfiguration.AllPositionsShown && !thirdBoyFound && result.Sex == SexType.Male) { result.ExtraInfo = "Third Boy"; thirdBoyFound = true; } else if (this.seriesConfiguration.AllPositionsShown && !thirdGirlFound && result.Sex == SexType.Female) { result.ExtraInfo = "Third Gal"; thirdGirlFound = true; } } } }
/// <summary> /// Calculate the results for the loaded event. /// </summary> public void CalculateResults() { this.logger.WriteLog("Calculate results"); HandicapProgressMessage startMessage = new HandicapProgressMessage("Calculate Results"); Messenger.Default.Send(startMessage); if (this.resultsConfiguration == null) { this.logger.WriteLog("Error reading the results config file. Results not generated"); HandicapErrorMessage faultMessage = new HandicapErrorMessage( "Can't calculate results - invalid config"); Messenger.Default.Send(faultMessage); HandicapProgressMessage terminateMessage = new HandicapProgressMessage("Calculate Results - Terminated"); Messenger.Default.Send(terminateMessage); return; } if (this.resultsConfiguration.ResultsConfigurationDetails.TeamTrophyPoints == null) { this.logger.WriteLog("Can't calculate results, Team Trophy points are invalid"); HandicapErrorMessage faultMessage = new HandicapErrorMessage( "Can't calculate results - check config"); Messenger.Default.Send(faultMessage); HandicapProgressMessage terminateMessage = new HandicapProgressMessage("Calculate Results - Terminated"); Messenger.Default.Send(terminateMessage); return; } List <IRaw> rawResults = this.Model.CurrentEvent.LoadRawResults(); // Set up the array to work out the points table List <MobTrophyPoints> mobTrophyPoints = this.SetupMobTrophyPoints(); // ensure that each athlete is registered for season. this.RegisterAllAthletesForTheCurrentSeason(rawResults); // Analyse results EventResults resultsTable = this.GenerateResultsTable( rawResults); // Sort by running time to work out the speed order. resultsTable.ApplySpeedOrder(); // Sort by time: Add position points, note first boy, first girl, second and third. this.AddPositionPoints( resultsTable, this.Model.CurrentEvent.Date); resultsTable.OrderByFinishingTime(); this.AddPlacings(resultsTable); this.AssignMobTrophyPoints( resultsTable, this.Model.CurrentEvent.Date, mobTrophyPoints); this.CalculateTeamTrophyPoints( resultsTable, this.Model.CurrentEvent.Date); this.Model.CurrentEvent.SetResultsTable(resultsTable); this.SaveAll(); this.logger.WriteLog("Calculate results completed."); HandicapProgressMessage finishedMessage = new HandicapProgressMessage("Calculate Results - Completed"); Messenger.Default.Send(finishedMessage); }
internal void FinishButton_OnClick(object sender, EventArgs eventArgs) { if (_eventResults.Id == null) { Toast.MakeToast("Результат завершения не может быть пустым"); return; } Utils.TraceMessage($"_eventResult.Id.Empty: {_eventResults.Id.EmptyRef()} not {!_eventResults.Id.EmptyRef()}{Environment.NewLine}" + $"_evenResult.Negative {_eventResults.Negative} {Environment.NewLine}" + $"string.IsNullOrEmpty(_commentaryMemoEdit.Text) {string.IsNullOrEmpty(_commentaryMemoEdit.Text)}{Environment.NewLine}" + $"Total Result: {!_eventResults.Id.EmptyRef() && _eventResults.Negative && string.IsNullOrEmpty(_commentaryMemoEdit.Text)}"); if (!_eventResults.Id.EmptyRef() && _eventResults.Negative && string.IsNullOrEmpty(_commentaryMemoEdit.Text)) { Toast.MakeToast("Комментарий не может быть пустым"); return; } var eventRef = DbRef.FromString((string)BusinessProcess.GlobalVariables[Parameters.IdCurrentEventId]); var entitiesList = new ArrayList(); var @event = (Event)eventRef.GetObject(); if (((TypesEvents)@event.KindEvent.GetObject()).Name == "Visit") { var result = DBHelper.GetCoordinate(TimeRangeCoordinate.DefaultTimeRange); var latitude = Converter.ToDouble(result["Latitude"]); var longitude = Converter.ToDouble(result["Longitude"]); @event.Latitude = Converter.ToDecimal(latitude); @event.Longitude = Converter.ToDecimal(longitude); var text = ""; Utils.TraceMessage($"lat:{latitude} long:{longitude}"); if (latitude.Equals(0) & longitude.Equals(0)) { text += "Не удалось сохранить координаты встречи"; } else { text += "Координаты встречи успешно сохранены"; } Toast.MakeToast(text); } if (!string.IsNullOrEmpty(_commentaryMemoEdit.Text)) { @event.CommentContractor = _commentaryMemoEdit.Text; } if (!_eventResults.Id.EmptyRef()) { @event.EventResult = _eventResults.Id; } if (!string.IsNullOrEmpty(@event.CommentContractor) || [email protected]()) { entitiesList.Add(@event); } DBHelper.SaveEntities(entitiesList); _eventResults = null; _commentaryString = null; Navigation.CleanStack(); Navigation.ModalMove("EventListScreen"); }