public async Task <IHttpActionResult> AddTeamAsync(int id, [FromBody] AddTeamRequest request) { if (request.Teams.Distinct().Count() != 8) { throw new ActionCannotBeExecutedException(ExceptionMessages.InvalidTeamsCount); } Tourney tourney = await UnitOfWork.GetTourneyRepository().SelectByIdAsync(id) ?? throw new ActionCannotBeExecutedException(ExceptionMessages.TourneyNotFound); if (tourney.EndDt < DateTime.Now) { throw new ActionCannotBeExecutedException(ExceptionMessages.TourenyFinished); } IEnumerable <Team> teams = await UnitOfWork.GetTeamRepository().SelectAsync(t => request.Teams.Contains(t.Id)); foreach (Team team in teams) { tourney.Teams.Add(new TourneyTeam { Team = team, Status = TourneyTeamStatus.Participating }); } await UnitOfWork.SaveChangesAsync(); return(Ok()); }
public async Task <IActionResult> Edit(int id, [Bind("TourneyID,Name,Description,FechaInicio,FechaFin,Price")] Tourney tourney) { if (id != tourney.TourneyID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(tourney); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TourneyExists(tourney.TourneyID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(tourney)); }
private TourneyViewModel SaveTourney(TourneyViewModel tourneyView) { Tourney tourney = tourneyView.ToBaseModel(); Tourney savedTourney = tourneyBll.SaveTourney(tourney); return(savedTourney.ToViewModel()); }
public JsonResult GetTorneo(string _id) { int id = Int32.Parse(_id); Tourney torneo = _context.Tourneys.Where(t => t.TourneyID == id).FirstOrDefault(); return(Json(torneo)); }
private void BTN_StartTourney_Click(object sender, RoutedEventArgs e) { if (Contestants.Count <= 1) { MessageBox.Show("Please Select the contestants for the tourney.", "Select Contestants", MessageBoxButton.OK, MessageBoxImage.Information); } else { // get the contestants List <Player> contestants = new List <Player>(); foreach (PlayerCell pc in Contestants) { contestants.Add(pc.GetPlayer()); } // set up the tourney Tourney = new Tourney(contestants); //set the GUI SetGameScreen(); PopulateGameView(); PopulatePlayerView(); foreach (PlayerCell pc in Contestants) { pc.SwitchOffNewChallengerShroud(); } } }
public void Constructor_ShouldSetName_Correctly(string name) { var mockUser = new Mock <User>(); var category = new Tourney(name, mockUser.Object); Assert.AreSame(category.Name, name); }
private void TestTourney() { var pop = new Population(121, Vertices.Count); var split = pop.Split(3); var t1 = Tourney.Eliminate(split[0], MakePermutationsMatrix(0)); var t2 = Tourney.Eliminate(split[1], MakePermutationsMatrix(1)); var t3 = Tourney.Eliminate(split[2], MakePermutationsMatrix(2)); }
public Tourney GetTourney(int tourneyId) { Tourney tourney = Context.Tourney.FirstOrDefault(t => t.Id == tourneyId); FillRelations(new Tourney[] { tourney }); return(tourney); }
public Tourney GetTourneyByRoundId(int roundId) { Tourney tourney = Context.Tourney.FirstOrDefault(t => t.Round.Any(r => r.Id == roundId)); FillRelations(new Tourney[] { tourney }); return(tourney); }
protected override async ValueTask BeforeExecutedAsync() { var currentTourneyId = await Database.Config.FindAsync("CURRENT_TOURNEY_ID"); var id = int.Parse(currentTourneyId.Value); _tourney = await Database.Tourneys.FirstOrDefaultAsync(x => x.Id == id); }
public IEnumerable <PersonStatistics> CalculateTourneyStatistics(int tourneyId, IEnumerable <Person> persons) { DalTourney.FillProtocols = true; Tourney tourney = DalTourney.GetTourney(tourneyId); var statsCalculator = new PersonTourneyStatsCalculator(tourney, persons); return(statsCalculator.PersonStatistics); }
public RankingTableViewModel Put(int id) { Tourney tourney = tourneyBll.GetTourney(id); if (tourney == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(null); } IEnumerable <TableRecord> tableRecords = ranking.CalculateTable(id); if (!tableRecords.Any()) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(null); } tableRecordBll.SaveTourneyTable(tourney.Id, tableRecords); StringBuilder sb = new StringBuilder(); sb.AppendLine($"DELETE FROM [dbo].[TableRecords] WHERE [tournamentId] = {tourney.Id};"); sb.AppendLine(); sb.AppendLine("INSERT INTO [dbo].[TableRecords]"); sb.AppendLine("([teamId],[tournamentId],[games],[wins],[draws],[loses],[goalsFor],[goalsAgainst],[points],[virtualPoints],[active],[position])"); sb.AppendLine("VALUES"); List <string> values = new List <string>(); foreach (TableRecord tr in tableRecords) { int active = tr.Active ? 1 : 0; values.Add($"({tr.teamId},{tr.tourneyId},{tr.Games},{tr.Wins},{tr.Draws},{tr.Loses},{tr.GoalsFor},{tr.GoalsAgainst},{tr.Points}," + $"{tr.PointsVirtual},{active},{tr.Position})"); } sb.AppendLine(string.Join(",", values)); RankingTableViewModel result = Get(tourney.Id); //try //{ // System.IO.File.WriteAllText("D:\\updTable.sql", sb.ToString()); //} //finally //{ // result.data = sb.ToString(); //} result.data = sb.ToString(); return(result); }
public async Task <IActionResult> Create([Bind("TourneyID,Name,Description,FechaInicio,FechaFin,Price")] Tourney tourney) { if (ModelState.IsValid) { _context.Add(tourney); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(tourney)); }
public IEnumerable <TableRecord> CalculateTable(int tourneyId) { var tourneyBll = new TourneyBll(); Tourney tourney = tourneyBll.GetTourney(tourneyId); if (tourney == null) { return(new TableRecord[] { }); } return(CalculateTable(tourney)); }
private void FillRelations(IEnumerable <PersonStatistics> personStatistics) { IEnumerable <Team> teams = new Team[0]; IEnumerable <Tourney> toureys = new Tourney[0]; if (FillTeams) { var teamDal = new TeamDal(); teamDal.SetContext(Context); var teamIds = new List <int>(); teamIds.AddRange(personStatistics.Select(r => r.teamId).Distinct()); teams = teamDal.GetTeams(teamIds).ToList(); } if (FillTourneys) { var tourneyDal = new TourneyDal(); tourneyDal.SetContext(Context); var tourneyIds = new List <int>(); tourneyIds.AddRange(personStatistics.Select(r => (int)r.tourneyId).Distinct()); toureys = tourneyDal.GetTourneys(tourneyIds).ToList(); } if (teams.Any() || toureys.Any()) { foreach (PersonStatistics ps in personStatistics) { if (FillTeams && teams.Any()) { ps.team = teams.FirstOrDefault(t => t.Id == ps.teamId); if (ps.team == null) { throw new DalMappingException(nameof(ps.team), typeof(PersonStatistics)); } } if (FillTourneys && toureys.Any()) { ps.tourney = toureys.FirstOrDefault(t => t.Id == ps.tourneyId); if (ps.tourney == null) { throw new DalMappingException(nameof(ps.tourney), typeof(PersonStatistics)); } } } } }
public ResultsView(Tourney tourney, TourneyConfig config) { InitializeComponent(); Tourney = tourney; Config = config; PlayerScores = new Dictionary <Player, int>(); GetPlayerScores(); DisplayResults(); }
private void FillRelations(IEnumerable <TableRecord> tableRecords) { if (Guard.IsEmptyIEnumerable(tableRecords)) { return; } Tourney tourney = null; IEnumerable <Team> teams = new Team[0]; if (FillTeams) { var teamDal = new TeamDal(); teamDal.SetContext(Context); teams = teamDal.GetTeams(tableRecords.Select(r => r.teamId)); } if (FillTourney) { var tourneyDal = new TourneyDal(); tourneyDal.SetContext(Context); tourney = tourneyDal.GetTourney(tableRecords.First().tourneyId); if (tourney == null) { throw new DalMappingException(nameof(tourney), typeof(TableRecord)); } } if (teams.Any() || tourney != null) { foreach (TableRecord record in tableRecords) { if (FillTeams && teams.Any()) { record.Team = teams.FirstOrDefault(t => t.Id == record.teamId); if (record.Team == null) { throw new DalMappingException(nameof(record.Team), typeof(TableRecord)); } } record.tourney = FillTourney ? tourney : null; } } }
public Tourney SaveTourney(Tourney entity) { if (entity.Id > 0) { Context.Tourney.Update(entity); } else { Context.Tourney.Add(entity); } Context.SaveChanges(); return(entity); }
public RankingTableViewModel Get(int id) { Tourney tourney = tourneyBll.GetTourney(id); if (tourney == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(null); } string tourneyName = tourney?.Name ?? string.Empty; tableRecordBll.FillTeams = true; return(tableRecordBll.GetTourneyTable(id).ToViewModel(tourneyName)); }
public IEnumerable <TableRecord> CalculateTable(Tourney tourney) { if (tourney == null) { return(new TableRecord[] { }); } var gameBll = new GameBll(); IEnumerable <Game> games = gameBll.GetGamesByTourney(tourney.Id); short rule = tourney?.tourneyTypeId ?? 1; return(CalculateTable(rule, games, tourney.Id)); }
/// <summary> /// Constructor. Should be filled rounds, games, protocol records and persons career /// </summary> /// <param name="tourney">Tourney. Should be filled with rounds, games and protocol records</param> /// <param name="persons">Persons. Should be filled with person career</param> public PersonTourneyStatsCalculator(Tourney tourney, IEnumerable <Person> persons) { this.tourney = tourney; if (tourney.Round == null) { throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "Unable to calculate statistic of the tournament (ID:{0}, Name:{1}). {2} are not set!", tourney.Id, tourney.Name, nameof(tourney.Round))); } this.persons = persons; }
private IEnumerable <RankingTableViewModel> GetRankingTable() { int tourneyId = MainCfg.MainTableTourneyId; Tourney tourney = tourneyBll.GetTourney(tourneyId); if (tourney == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; logger.LogWarning("Ranking table of tourney ID='{0}' is not found!", tourneyId); return(null); } string tourneyName = tourney?.Name ?? string.Empty; tableRecordBll.FillTeams = true; RankingTableViewModel mainTable = tableRecordBll.GetTourneyTable(tourneyId).ToViewModel(tourneyName); return(new RankingTableViewModel[] { mainTable }); }
public static TourneyViewModel ToViewModel(this Tourney tourney) { if (tourney == null) { return(null); } return(new TourneyViewModel() { cityId = tourney.cityId, dateEnd = tourney.DateEnd, dateStart = tourney.DateStart, description = tourney.Description, id = tourney.Id, name = tourney.Name, nameFull = tourney.NameFull, tourneyTypeId = tourney.tourneyTypeId, rounds = tourney.Round.ToViewModel() }); }
//[HttpGet] //[Route("create")] //public async Task<IHttpActionResult> CreateAsync([FromUri]string request) //{ // int year = Random.Next(2015, 2017); // int month = Random.Next(1, 12); // int day = Random.Next(1, 28); // Tourney tourney = new Tourney // { // StartDt = new DateTime(year, month, day), // Name = request // }; // tourney.EndDt = tourney.StartDt.AddMonths(3); // UnitOfWork.GetTourneyRepository().Insert(tourney); // await UnitOfWork.SaveChangesAsync(); // int count = await UnitOfWork.GetTeamRepository().CountAsync(t => true); // List<int> teams = new List<int>(); // while (teams.Count < 16) // { // int teamId = Random.Next(1, count); // if (!teams.Contains(teamId)) // { // teams.Add(teamId); // } // } // foreach(var v in teams) // { // tourney.Teams.Add(new TourneyTeam // { // Status = Enums.TourneyTeamStatus.Participating, // TeamId = v, // TourneyId = tourney.Id // }); // } // await UnitOfWork.SaveChangesAsync(); // return Ok(); //} private int GetScoreOntourney(Team team, Tourney tourney) { int score = 0; IEnumerable <Match> matches = tourney.Matches.Where(t => t.GuestId == team.Id | t.HomeId == team.Id); foreach (var teamMatch in matches) { int teamGoals = teamMatch.Goals.Select(g => g.TeamId == team.Id).Count(); int goals = teamMatch.Goals.Select(g => g.TeamId != team.Id).Count(); if (teamGoals == goals) { score = +1; } else if (teamGoals > goals) { score += 3; } } return(score); }
public async Task <IHttpActionResult> GetAsync([FromUri] int id) { Tourney tourney = await UnitOfWork.GetTourneyRepository().SelectByIdAsync(id) ?? throw new ActionCannotBeExecutedException(ExceptionMessages.TourneyNotFound); GetResponse response = new GetResponse { Id = tourney.Id, Name = tourney.Name, StartDt = tourney.StartDt, EndDt = tourney.EndDt, Items = tourney.Teams.Select(t => new GetItem { Id = t.TeamId, Image = t.Team.Logotype, Name = t.Team.Name, Position = GetScoreOntourney(team: t.Team, tourney: tourney), Status = t.Status }) }; return(Ok(response)); }
public async Task ModCP() { try { await ReplyAndDeleteAsync($"Hey {Context.User.Mention}! I've send you a PM with the info!", false, null, TimeSpan.FromSeconds(15)); await Context.Message.DeleteAsync(); } catch { } IDMChannel channel = await Context.User.GetOrCreateDMChannelAsync(); MySqlConnection conn = DatabaseHelper.GetClosedConnection(); Tourney tourney = await DatabaseHelper.GetLatestTourneyAsync(); Restart: EmbedBuilder builder = new EmbedBuilder() { Title = "Mod CP", Color = Color.DarkGrey, Footer = new EmbedFooterBuilder() { Text = "If you do not answer within 2 minutes you will need to use `?modcp` again." } }; builder.Description = $"Hey there {Context.User.Username}! You're currently editing tourney #{tourney.ID} - {tourney.Name}\nPlease choose one of these options by sending their number to me.\n" + $"1. Show/Change Signup Date\n" + $"2. Show/Change Min player amount\n" + $"3. Show/Change max player amount\n" + $"4. Remove a user from the Tournament.\n" + $"5. Change Tourney - Current tourney: {tourney.Name}\n" + $"6. Start New Tourney\n" + $"7. Close Menu"; await channel.SendMessageAsync("", false, builder.Build()); SocketMessage response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); if (Int32.TryParse(response.Content, out int choice)) { switch (choice) { case 1: goto SignupDate; case 2: goto MinPlayer; case 3: goto MaxPlayer; case 4: goto RemoveUser; case 5: goto ChangeTourney; case 6: goto ResetTourney; case 7: return; } } else { await channel.SendMessageAsync("Please choose one of the options."); goto Restart; } #region SignupDate SignupDate: try { await conn.OpenAsync(); MySqlCommand cmd = new MySqlCommand("SELECT `regend` FROM `tournaments` WHERE `tid` = " + tourney.ID, conn); long UNIXTime = 0; using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { UNIXTime = reader.GetInt64(0); } } DateTimeOffset offset = DateTimeOffset.FromUnixTimeSeconds(UNIXTime); await conn.CloseAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Registration End Date", Description = $"The current registration end date is set to: {offset.ToString("dd-MM-yyyy")}\n" + $"If you would like to alter it, please send `edit`. Send anything else to return to the main menu." }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); if (response.Content.ToLower().StartsWith("edit")) { Date_Time: await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Registration End Date", Description = "Please provide the end date in the following format: DD-MM-YYYY" }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); try { DateTimeOffset date = Convert.ToDateTime(response.Content); date = date.AddHours(date.Offset.Hours); if (date.DayOfYear < DateTime.Now.DayOfYear || date.Year < DateTime.Now.Year) { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Wrong Input!", Color = Color.Red, Description = "The date needs to be today or later!" }); goto Date_Time; } try { await conn.OpenAsync(); cmd = new MySqlCommand($"UPDATE `tournaments` SET `regend` = {date.ToUnixTimeSeconds()} WHERE `tid` = " + tourney.ID, conn); await cmd.ExecuteNonQueryAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Edit Succesfull!", Color = Color.Green, Description = "Successfully changed the date. Returning to menu." }); await Task.Delay(1000); } catch (Exception e) { await Program.Log(e.ToString(), "SignupDate SQL", LogSeverity.Error); await channel.SendMessageAsync("An error occured. Please contact an administrator."); } } catch (Exception e) { await Program.Log(e.ToString(), "DateTime Convesion", LogSeverity.Warning); goto Date_Time; } } } catch (Exception e) { await Program.Log(e.ToString(), "SignupDate SQL", LogSeverity.Error); } finally { await conn.CloseAsync(); } goto Restart; #endregion #region MinPlayer MinPlayer: try { await conn.OpenAsync(); MySqlCommand cmd = new MySqlCommand("SELECT `minplayers` FROM `tournaments` WHERE `tid` = " + tourney.ID, conn); int min_players = 0; using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { min_players = reader.GetInt16(0); } } await conn.CloseAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Registration Min Players", Description = $"The current minimum amount of players is {min_players} (minimum minimum is 2)\n" + $"If you would like to alter it, please send `edit`. Send anything else to return to the main menu." }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); if (response.Content.ToLower().StartsWith("edit")) { Min_Players: await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Registration Min Players", Description = "What will be the minimum amount of players? (min 2)" }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); try { if (Int32.TryParse(response.Content, out int input)) { if (input >= 2) { try { await conn.OpenAsync(); cmd = new MySqlCommand($"UPDATE `tournaments` SET `minplayers` = {input} WHERE `tid` = " + tourney.ID, conn); await cmd.ExecuteNonQueryAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Edit Succesfull!", Color = Color.Green, Description = "Successfully changed the min player amount. Returning to menu." }); await Task.Delay(1000); } catch (Exception e) { await Program.Log(e.ToString(), "MinPlayer SQL", LogSeverity.Error); await channel.SendMessageAsync("An error occured. Please contact an administrator."); } } else { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Wrong Input!", Color = Color.Red, Description = "Please input a number higher than 1." }); goto Min_Players; } } else { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Wrong Input!", Color = Color.Red, Description = "Please input just a number." }); goto Min_Players; } } catch (Exception e) { await Program.Log(e.ToString(), "TryParse Convesion", LogSeverity.Warning); } } } catch (Exception e) { await Program.Log(e.ToString(), "MinPlayers SQL", LogSeverity.Error); } finally { await conn.CloseAsync(); } goto Restart; #endregion #region MaxPlayer MaxPlayer: try { await conn.OpenAsync(); MySqlCommand cmd = new MySqlCommand("SELECT `maxplayers` FROM `tournaments` WHERE `tid` = " + tourney.ID, conn); int max_players = 0; using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { max_players = reader.GetInt16(0); } } await conn.CloseAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Registration Max Players", Description = $"The current maximum amount of players is {max_players} (minimum maximum is 2)\n" + $"If you would like to alter it, please send `edit`. Send anything else to return to the main menu." }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); if (response.Content.ToLower().StartsWith("edit")) { Min_Players: await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Registration Max Players", Description = "What will be the maximum amount of players? (min 2)" }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); try { if (Int32.TryParse(response.Content, out int input)) { if (input >= 2) { try { await conn.OpenAsync(); cmd = new MySqlCommand($"UPDATE `tournaments` SET `maxplayers` = {input} WHERE `tid` = " + tourney.ID, conn); await cmd.ExecuteNonQueryAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Edit Succesfull!", Color = Color.Green, Description = "Successfully changed the max player amount. Returning to menu." }); await Task.Delay(1000); } catch (Exception e) { await Program.Log(e.ToString(), "MaxPlayer SQL", LogSeverity.Error); await channel.SendMessageAsync("An error occured. Please contact an administrator."); } } else { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Wrong Input!", Color = Color.Red, Description = "Please input a number higher than 1." }); goto Min_Players; } } else { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Wrong Input!", Color = Color.Red, Description = "Please input just a number." }); goto Min_Players; } } catch (Exception e) { await Program.Log(e.ToString(), "TryParse Convesion", LogSeverity.Warning); } } } catch (Exception e) { await Program.Log(e.ToString(), "MaxPlayers SQL", LogSeverity.Error); } finally { await conn.CloseAsync(); } goto Restart; #endregion #region RemoveUser RemoveUser: await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Remove User from Tournament", Color = Color.DarkOrange, Description = "Please provide the Discord ID or Discord Username (with discriminator) of the user you're trying to kick." }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); try { await conn.OpenAsync(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `participants` WHERE `uid` = @id OR `discordusername` = @name", conn); cmd.Parameters.Add("@id", MySqlDbType.Int64).Value = long.TryParse(response.Content, out long value) ? value : 000000000000000000; cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = response.Content; Player player = new Player(); using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { player.Id = reader.GetUInt64(2); player.DiscordName = reader.GetString(3); player.ShowdownName = reader.GetString(4); } } if (string.IsNullOrEmpty(player.DiscordName)) { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "User not Found", Color = Color.Red, Description = "User not found. Returning to main menu." }); await Task.Delay(500); goto Restart; } await conn.CloseAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Remove User", Color = Color.DarkOrange, Description = $"Is this the user you're looking for?\n" + $"**Discord ID:** {player.Id}\n" + $"**Discord Name:** {player.DiscordName}\n" + $"**Showdown Name:** {player.ShowdownName}\n" + $"Please respond with yes/no" }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); if (response.Content.ToLower().Equals("yes")) { try { await conn.OpenAsync(); cmd = new MySqlCommand("DELETE FROM `participants` WHERE `uid` = " + player.Id, conn); await cmd.ExecuteNonQueryAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Success!", Color = Color.LightOrange, Description = $"Successfully kicked {player.DiscordName} from the game.\nReturning to main menu." }); await Task.Delay(500); } catch (Exception e) { await Program.Log(e.ToString(), "RemoveUser => Deletion", LogSeverity.Error); } } else { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Cancelled.", Color = Color.Red, Description = "Process Cancelled. Returning to main menu." }); await Task.Delay(500); goto Restart; } } catch (Exception e) { await Program.Log(e.ToString(), "RemoveUser => Lookup", LogSeverity.Error); } finally { await conn.CloseAsync(); } goto Restart; #endregion #region ChangeTourney ChangeTourney: try { await conn.OpenAsync(); MySqlCommand cmd = new MySqlCommand("SELECT `tid`, `tournament` FROM `tournaments`", conn); string tourneyData = ""; using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { tourneyData += $"{reader.GetInt32(0)} - {reader.GetString(1)}\n"; } } await channel.SendMessageAsync($"Tournament ID - Tournament Name:\n" + $"```{tourneyData}```\n" + $"Please send the ID of the tourney you wish to edit."); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); if (int.TryParse(response.Content, out int id) && id != tourney.ID) { Tourney newTourney = await DatabaseHelper.GetTourneyByIDAsync(id); if (!string.IsNullOrEmpty(newTourney.Name)) { tourney = newTourney; await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Success!", Color = Color.Green, Description = $"Successfully switched to tournament #{tourney.ID} - {tourney.Name}\n" + $"Returning to main menu." }); await Task.Delay(500); } else { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Failed.", Color = Color.Green, Description = $"Failed to switch. Returning to main menu." }); await Task.Delay(500); } } else { await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Invalid Input.", Color = Color.Green, Description = $"Invalid Input. Returning to main menu." }); await Task.Delay(500); } } catch (Exception e) { await Program.Log(e.ToString(), "ChangeTourney => SQL", LogSeverity.Error); } finally { await conn.CloseAsync(); } goto Restart; #endregion #region ResetTourney ResetTourney: await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "**New Tourney**", Color = Color.DarkRed, Description = "A new tournament will be created. After creation you will automatically switch to it and you can edit it after that.\n" + "To continue type the name of the to-be-created tournament. Otherwise type `exit`" }); response = await NextMessageAsync(new EnsureChannelCriterion(channel.Id), TimeSpan.FromMinutes(2)); if (!response.Content.Equals("exit")) { try { await conn.OpenAsync(); MySqlCommand newTourney = new MySqlCommand($"INSERT INTO `tournaments`(`tournament`, `regstart`, `regend`) VALUES (@tourneyName, \"{DateTimeOffset.Now.ToUnixTimeSeconds()}\", \"{DateTimeOffset.Now.ToUnixTimeSeconds()}\")", conn); newTourney.Parameters.Add("@tourneyName", MySqlDbType.VarChar).Value = response.Content; await newTourney.ExecuteNonQueryAsync(); tourney = await DatabaseHelper.GetLatestTourneyAsync(); await channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "Tournament Creation Complete", Color = Color.DarkRed, Description = $"Tournament {tourney.Name} has been created and switched to." }); await Task.Delay(500); } catch (Exception e) { await Program.Log(e.ToString(), "ResetTourney SQL", LogSeverity.Error); await channel.SendMessageAsync("An error occured. Please contact an admin"); } finally { await conn.CloseAsync(); } } goto Restart; #endregion }
public void EditTourney(Tourney tourney) { this.tourneyRepository.Update(tourney); this.unitOfWork.Commit(); }
public static IEnumerable <ScheduleItemViewModel> GetTourneysShcedule(DateTime startDate, DateTime endDate, IEnumerable <int> tourneyIds) { ILogger <ScheduleHelper> logger = MainCfg.ServiceProvider.GetService <ILogger <ScheduleHelper> >(); logger.LogTrace("Getting schedule. Tournaments count: {0}.", tourneyIds.Count()); IList <ScheduleItemViewModel> schedule = new List <ScheduleItemViewModel>(); ITourneyBll tourneyBll = MainCfg.ServiceProvider.GetService <ITourneyBll>(); IEnumerable <Tourney> tourneys = tourneyBll.GetTourneys(tourneyIds); if (!tourneyIds.Any()) { return(schedule); } logger.LogTrace("Tournaments ids: {0}.", string.Join(", ", tourneyIds)); IRoundBll roundBll = MainCfg.ServiceProvider.GetService <IRoundBll>(); IEnumerable <Round> rounds = roundBll.GetRoundsOfTourneys(tourneys.Select(t => (int)t.Id)); if (!rounds.Any()) { return(schedule); } IGameBll gameBll = MainCfg.ServiceProvider.GetService <IGameBll>(); IEnumerable <Game> games = gameBll.GetGamesByRoundsForPeriod(startDate, endDate, rounds.Select(r => (int)r.Id)).OrderByDescending(d => d.GameDate); if (!games.Any()) { return(schedule); } var allTeamIds = new List <int>(); allTeamIds.AddRange(games.Select(g => g.homeId)); allTeamIds.AddRange(games.Select(g => g.awayId)); ITeamBll teamBll = MainCfg.ServiceProvider.GetService <ITeamBll>(); IEnumerable <Team> teams = teamBll.GetTeams(allTeamIds.Distinct()); if (!teams.Any()) { return(schedule); } int prevRoundId = 0; int nextRoundId = 0; Round round = null; Tourney tourney = null; IList <ScheduleGameViewModel> gameGroups = new List <ScheduleGameViewModel>(); for (int i = 0; i < games.Count(); i++) { Game game = games.ElementAt(i); prevRoundId = games.ElementAtOrDefault(i - 1)?.roundId ?? 0; nextRoundId = games.ElementAtOrDefault(i + 1)?.roundId ?? 0; if (prevRoundId != game.roundId) { round = rounds.FirstOrDefault(r => r.Id == game.roundId); if (round == null) { logger.LogWarning("Couldn't get round (Id: {0}) of the game (Id: {1}) for scheduler. Round is NOT found!", game.roundId, game.Id); continue; } tourney = tourneys.First(t => t.Id == round.tourneyId); if (tourney == null) { logger.LogWarning("Couldn't get tournament (Id: {0}) of the round (Id: {1}) of the game (Id: {2}) for scheduler. Tournament is NOT found!", round.tourneyId, game.roundId, game.Id); continue; } } Team home = teams.FirstOrDefault(t => t.Id == game.homeId); Team away = teams.FirstOrDefault(t => t.Id == game.awayId); if (home == null || away == null) { logger.LogWarning("Couldn't get game (Id: {0}) for scheduler of tourney (Id: {1}). Home (Id: {2}) is {3}found. Away (Id: {4}) is {5}found.", game.Id, tourney.Id, game.homeId, home == null ? "NOT " : string.Empty, game.awayId, away == null ? "NOT " : string.Empty); continue; } gameGroups.Add(new ScheduleGameViewModel() { id = game.Id, away = new EntityLinkViewModel() { id = game.awayId.ToString(), text = away.Name, title = away.Name, image = away.Image }, awayAddScore = game.AwayAddScore, awayPenalties = game.AwayPenalties, awayScore = game.awayScore, date = game.GameDate, home = new EntityLinkViewModel() { id = game.homeId.ToString(), text = home.Name, title = home.Name, image = home.Image }, homeAddScore = game.HomeAddScore, homePenalties = game.HomePenalties, homeScore = game.homeScore, roundId = game.roundId, showTime = game.ShowTime, played = game.Played }); if (nextRoundId != game.roundId) { var dayGamseViews = new List <DayGamesViewModel>(); IEnumerable <IGrouping <DayOfWeek, ScheduleGameViewModel> > grouppedGamesByDay = gameGroups.GroupBy(g => g.date.DayOfWeek); foreach (var dayGames in grouppedGamesByDay) { var dayGameInfo = dayGames.First(); dayGamseViews.Add(new DayGamesViewModel() { day = dayGames.Key.ToString().ToUpper(), games = dayGames }); } schedule.Add(new ScheduleItemViewModel() { date = game.GameDate, round = new EntityLinkViewModel() { id = round.Id.ToString(), text = round.Name, title = round.NameFull }, tourney = new EntityLinkViewModel() { id = tourney.Id.ToString(), text = tourney.Name, title = tourney.NameFull }, daysGames = dayGamseViews }); gameGroups = new List <ScheduleGameViewModel>(); } } return(schedule); }
public Tourney SaveTourney(Tourney entity) { return(DalTourney.SaveTourney(entity)); }
private void FillRelations(IEnumerable <Round> rounds) { if (Guard.IsEmptyIEnumerable(rounds)) { return; } IEnumerable <Tourney> tourneys = new Tourney[0]; GameDal dalGames = null; if (FillTourneys) { var tourneyDal = new TourneyDal(); tourneyDal.SetContext(Context); var tourneyIds = new List <int>(); tourneyIds.AddRange(rounds.Select(r => (int)r.tourneyId)); tourneys = tourneyDal.GetTourneys(tourneyIds.Distinct()).ToList(); if (!tourneys.Any()) { throw new DalMappingException(nameof(tourneys), typeof(Round)); } } if (FillProtocols) { FillGames = true; } if (FillGames) { dalGames = new GameDal(); dalGames.FillProtocols = FillProtocols; dalGames.SetContext(Context); } if (tourneys.Any() || dalGames != null) { foreach (Round round in rounds) { if (FillTourneys && tourneys.Any()) { round.tourney = tourneys.FirstOrDefault(t => t.Id == round.tourneyId); if (round.tourney == null) { throw new DalMappingException(nameof(round.tourney), typeof(Round)); } } else { round.tourney = null; } if (dalGames != null) { round.Game = dalGames.GetRoundGames(round.Id).ToArray(); } else { round.Game = null; } } } }