// main method
        protected double Compute(List <Match> matches, bool isWeighted)
        {
            using (var ctx = new FootballEntities())
            {
                try
                {
                    int    matchesNo = 0;
                    double effective = 0.0;

                    foreach (var m in matches)
                    {
                        var score = ctx.Scores.FirstOrDefault(s => s.MatchId == m.Id);

                        if (score != null)
                        {
                            var pHome = m.HomeGoalsPredicted;
                            var pAway = m.AwayGoalsPredicted;
                            var rHome = score.HomeGoals;
                            var rAway = score.AwayGoals;

                            if (pHome != null && pAway != null)
                            {
                                matchesNo++;

                                if (GetWinner((int)pHome, (int)pAway) == GetWinner(rHome, rAway))
                                {
                                    if (isWeighted)
                                    {
                                        effective += WINNER_RATIO;
                                        if ((int)pHome == rHome && (int)pAway == rAway)
                                        {
                                            effective += EXACT_SCORE_RATIO;
                                        }
                                    }
                                    else
                                    {
                                        effective += 1.0;
                                    }
                                }
                            }
                        }
                    }

                    if (matchesNo == 0)
                    {
                        logger.Warn("Matches count = 0. No effectiveness could be computed");
                        return(0.0);
                    }
                    else
                    {
                        return(effective / (double)matchesNo);
                    }
                }
                catch (Exception e)
                {
                    logger.Error("Error while computing prediction effectiveness.", e);
                    return(-1.0);
                }
            }
        }
        public int InsertMatches(int matchday)
        {
            var matches = GetMatches(matchday);
            int counter = 0;

            using (var ctx = new FootballEntities())
            {
                using (var transaction = ctx.Database.BeginTransaction())
                {
                    try
                    {
                        foreach (var m in matches)
                        {
                            var matchDb = m.ToDbObject();
                            matchDb.HomeId = ctx.Teams.First(t => t.Name == m.HomeTeam).Id;
                            matchDb.AwayId = ctx.Teams.First(t => t.Name == m.AwayTeam).Id;

                            ctx.Matches.Add(m.ToDbObject());
                            counter++;
                        }

                        ctx.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }
            return(counter);
        }
Beispiel #3
0
        private static League CreateLeagueIfNotExists(FootballEntities context, XElement xLeague)
        {
            League league             = null;
            var    xElementLeagueName = xLeague.Element("league-name");

            if (xElementLeagueName != null)
            {
                string leagueName = xElementLeagueName.Value;
                league = context.Leagues.FirstOrDefault(l => l.LeagueName == leagueName);
                if (league != null)
                {
                    Console.WriteLine("Existing league: {0}", leagueName);
                }
                else
                {
                    // Create a new league in the DB
                    league = new League()
                    {
                        LeagueName = leagueName
                    };
                    context.Leagues.Add(league);
                    context.SaveChanges();
                    Console.WriteLine("Created league: {0}", leagueName);
                }
            }
            return(league);
        }
Beispiel #4
0
        public Score SetRatio(Score score)
        {
            try
            {
                using (var ctx = new FootballEntities())
                {
                    var scoreDb = ctx.Scores.SingleOrDefault(s => s.Id == score.Id);
                    var match   = ctx.Matches.First(m => m.Id == scoreDb.MatchId);
                    var home    = ctx.Teams.First(t => t.Id == match.HomeId).Name;
                    var away    = ctx.Teams.First(t => t.Id == match.AwayId).Name;

                    scoreDb.HOR  = CalculateOffensiveRatio(GetArchiveScores(home, scoreDb.Date));
                    scoreDb.HDR  = CalculateDefensiveRatio(GetArchiveScores(home, scoreDb.Date));
                    scoreDb.AOR  = CalculateOffensiveRatio(GetArchiveScores(away, scoreDb.Date));
                    scoreDb.ADR  = CalculateDefensiveRatio(GetArchiveScores(away, scoreDb.Date));
                    scoreDb.HORH = CalculateOffensiveRatio(GetArchiveScores(home, true, scoreDb.Date));
                    scoreDb.HDRH = CalculateDefensiveRatio(GetArchiveScores(home, true, scoreDb.Date));
                    scoreDb.AORA = CalculateOffensiveRatio(GetArchiveScores(away, false, scoreDb.Date));
                    scoreDb.ADRA = CalculateDefensiveRatio(GetArchiveScores(away, false, scoreDb.Date));

                    ctx.SaveChanges();

                    logger.InfoFormat("Ratio for teams: {0} and {1} on date: {2} set successfully", home, away, scoreDb.Date);
                    return(scoreDb);
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while setting team ratio.", e);
                return(null);
            }
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            var context = new FootballEntities();

            var leaguesTeams = context.Leagues
                               .OrderBy(l => l.LeagueName)
                               .Select(l => new
            {
                leagueName = l.LeagueName,
                teams      = l.Teams.OrderBy(t => t.TeamName).Select(t => t.TeamName)
            });

            //foreach (var league in leaguesTeams)
            //{
            //    Console.WriteLine(league.leagueName);
            //    foreach (var team in league.teams)
            //    {
            //        Console.WriteLine(team);
            //    }
            //}

            var JSerializer      = new JavaScriptSerializer();
            var jsonleaguesTeams = JSerializer.Serialize(leaguesTeams);

            File.WriteAllText("../../leagues-and-teams.json", jsonleaguesTeams);
        }
Beispiel #6
0
        public static void Main()
        {
            using (var db = new FootballEntities())
            {
                var xml     = XDocument.Load("../../../Helper.Files/leagues-and-teams.xml");
                var counter = 1;
                foreach (var league in xml.Descendants("league"))
                {
                    Console.WriteLine("Processing league #{0} ...", counter++);
                    var currentLeague = GetOrCreateLeague(league, db);
                    foreach (var team in league.Descendants("team"))
                    {
                        if (team.Attribute("name") == null)
                        {
                            Console.WriteLine("Missing team name attribute.");
                            continue;
                        }

                        var currentTeam = GetOrCreateTeam(team, db);
                        AddTeamToLeague(currentTeam, currentLeague);
                    }

                    db.SaveChanges();
                    Console.WriteLine();
                }
            }
        }
        public int InsertScores(DateTime startDate)
        {
            var scores  = ParseCsvScores(startDate);
            int counter = 0;

            using (var ctx = new FootballEntities())
            {
                using (var transaction = ctx.Database.BeginTransaction())
                {
                    try
                    {
                        //TODO error model

                        foreach (var s in scores)
                        {
                            ctx.Scores.Add(s.ToDbObject());

                            UpdateLeagueTable(s);
                            counter++;
                            ctx.SaveChanges();
                        }

                        ctx.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }
            return(counter);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            var context       = new FootballEntities();
            var doc           = XDocument.Load("../../../leagues-and-teams.xml");
            var leagues       = doc.Root.Elements();
            var leagueCounter = 1;

            try
            {
                foreach (var league in leagues)
                {
                    Console.WriteLine("Processing league #{0} ...", leagueCounter);
                    //League newLeague = new League();
                    var newLeague = ProcessLeague(context, league);

                    var teamsNode = league.Element("teams");
                    if (teamsNode != null)
                    {
                        foreach (var team in teamsNode.Elements())
                        {
                            ProcessTeam(context, team, newLeague);
                        }
                    }

                    leagueCounter++;
                    Console.WriteLine();
                }
            }
            catch (ArgumentException ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }
Beispiel #9
0
        private static League ProcessLeague(FootballEntities context, XElement league)
        {
            League newLeague  = null;
            var    leagueNode = league.Element("league-name");

            if (leagueNode != null)
            {
                newLeague = context.Leagues.FirstOrDefault(l => l.LeagueName == leagueNode.Value);
                if (newLeague == null)
                {
                    newLeague = new League()
                    {
                        LeagueName = leagueNode.Value
                    };
                    context.Leagues.AddOrUpdate(newLeague);
                    context.SaveChanges();
                    Console.WriteLine("Created league: {0}", newLeague.LeagueName);
                }
                else
                {
                    Console.WriteLine("Existing league: {0}", newLeague.LeagueName);
                }
            }

            return(newLeague);
        }
Beispiel #10
0
        static void Main()
        {
            var context = new FootballEntities();

            var data = context.Leagues.OrderBy(l => l.LeagueName).Select(l => new
            {
                leagueName = l.LeagueName,
                teams      = l.Teams.OrderBy(t => t.TeamName).Select(t => t.TeamName)
            });

            JsonSerializer output = new JsonSerializer();

            output.Formatting        = Formatting.Indented;
            output.NullValueHandling = NullValueHandling.Include;

            using (StreamWriter sw = new StreamWriter(@"../../leagues-and-teams.json"))
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    foreach (var entity in data)
                    {
                        output.Serialize(writer, entity);
                    }
                }

            Console.WriteLine("Successfully created JSON file!");
        }
        public Match Predict(Match match)
        {
            try
            {
                using (var ctx = new FootballEntities())
                {
                    var    matchDb = ctx.Matches.First(m => m.Id == match.Id);
                    string home    = ctx.Teams.First(t => t.Id == matchDb.HomeId).Name;
                    string away    = ctx.Teams.First(t => t.Id == matchDb.AwayId).Name;

                    RatioModel ratio = Calculator.CalculateTeamsRatio(home, away, match.Date);

                    var res = Machine.PredictScore(ratio);

                    matchDb.HomeGoalsPredicted = res.Item1;
                    matchDb.AwayGoalsPredicted = res.Item2;

                    ctx.SaveChanges();
                    return(matchDb);
                }
            }
            catch (Exception e)
            {
                logger.Error(string.Format("Error while predicting match: homeId = {0}, awayId = {1}, date = {2}", match.HomeId, match.AwayId, match.Date), e);
                return(null);
            }
        }
        public int InsertAllMatches()
        {
            var matches = GetAllMatches();
            int counter = 0;

            using (var ctx = new FootballEntities())
            {
                using (var transaction = ctx.Database.BeginTransaction())
                {
                    try
                    {
                        foreach (var m in matches)
                        {
                            ctx.Matches.Add(m.ToDbObject());
                            counter++;
                        }

                        ctx.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }
            return(counter);
        }
        public List <Score> GetTrainingScores(DateTime date)
        {
            try
            {
                using (var ctx = new FootballEntities())
                {
                    var result   = new List <Score>();
                    var dbScores = ctx.Scores
                                   .Where(s => s.Date < date)
                                   .OrderByDescending(s => s.Date)
                                   .Take(TRAINING_SET_CARDINALITY);

                    RatioCalculator rc = new RatioCalculator();

                    foreach (var s in dbScores)
                    {
                        if (s.HOR == null)
                        {
                            result.Add(rc.SetRatio(s));
                        }
                        else
                        {
                            result.Add(s);
                        }
                    }
                    logger.InfoFormat("Training scores set (before date: {0}) have been created successfully. Training scores count = {1}", date, result.Count);
                    return(result);
                }
            }
            catch (Exception e)
            {
                logger.Error(string.Format("GetTrainingScores (date = {0}) failed due to exception", date), e);
                return(null);
            }
        }
Beispiel #14
0
        public double GetTeamRatio(int teamId, DateTime date, bool isOffensive)
        {
            try
            {
                using (var ctx = new FootballEntities())
                {
                    var match = ctx.Matches.Where(m => m.Date < date && (m.HomeId == teamId || m.AwayId == teamId))
                                .OrderByDescending(d => d.Date)
                                .FirstOrDefault();

                    if (match == null)
                    {
                        if (isOffensive)
                        {
                            return(DEFENSIVE_RATIO_DEFAULT);
                        }
                        else
                        {
                            return(OFFENSIVE_RATIO_DEFAULT);
                        }
                    }


                    var score = ctx.Scores.FirstOrDefault(s => s.MatchId == match.Id);

                    if (score.HDR == null)
                    {
                        return(0.0);
                    }

                    if (isOffensive)
                    {
                        if (match.HomeId == teamId)
                        {
                            return((double)score.ADR);
                        }
                        else
                        {
                            return((double)score.HDR);
                        }
                    }
                    else
                    {
                        if (match.HomeId == teamId)
                        {
                            return((double)score.AOR);
                        }
                        else
                        {
                            return((double)score.HOR);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(string.Format("Getting ratio for teamId: {0}, date: {1}, isOffesnive: {2} failed due to exception.", teamId, date, isOffensive));
                return(OFFENSIVE_RATIO_DEFAULT);
            }
        }
        private static string GetRandomTeam(string leagueName, string opponentTeam = null)
        {
            using (var db = new FootballEntities())
            {
                League currentLeague = null;
                if (leagueName != "no league")
                {
                    currentLeague = db.Leagues.FirstOrDefault(l => l.LeagueName == leagueName);
                }

                string randomTeam;
                if (currentLeague != null)
                {
                    var randomNumber = RandomGenerator.Next(currentLeague.Teams.Count());
                    randomTeam = currentLeague.Teams.OrderBy(t => t.TeamName).Skip(randomNumber).First().TeamName;
                }
                else
                {
                    var randomNumber = RandomGenerator.Next(db.Teams.Count());
                    randomTeam = db.Teams.OrderBy(t => t.TeamName).Skip(randomNumber).First().TeamName;
                }

                if (randomTeam == opponentTeam)
                {
                    return(GetRandomTeam(leagueName, opponentTeam));
                }

                return(randomTeam);
            }
        }
        public void InsertTeams()
        {
            var teams = GetTeamsFromFile();

            using (var ctx = new FootballEntities())
            {
                if (ctx.Teams.Count() == 0)
                {
                    using (var transaction = ctx.Database.BeginTransaction())
                    {
                        try
                        {
                            if (teams.Count > 0)
                            {
                                foreach (var t in teams)
                                {
                                    ctx.Teams.Add(t);
                                }
                                ctx.SaveChanges();
                                transaction.Commit();
                            }
                            else
                            {
                                transaction.Rollback();
                            }
                        }
                        catch (Exception)
                        {
                            transaction.Rollback();
                        }
                    }
                }
            }
        }
Beispiel #17
0
        private static void AddTeamsToLeagueAndDb(FootballEntities context, XElement leagueNode, Leagues tempLeague)
        {
            // parse teams info and add to league
            var teamNodes = leagueNode.XPathSelectElements("teams/team");

            foreach (var teamNode in teamNodes)
            {
                var    tempTeam    = new Teams();
                var    teamName    = teamNode.Attributes("name").FirstOrDefault().Value;
                string teamCountry = null;
                if (teamNode.Attributes("country").FirstOrDefault() != null)
                {
                    teamCountry = teamNode.Attributes("country").FirstOrDefault().Value;
                }

                var team    = context.Teams.FirstOrDefault(t => t.TeamName == teamName);
                var country = context.Countries.FirstOrDefault(c => c.CountryName == teamCountry);


                var teamCountryCode =
                    context.Countries.Where(c => c.CountryName == teamCountry).Select(c => c.CountryCode).FirstOrDefault();
                var teamCountryCodeInDb =
                    context.Teams.Where(t => t.TeamName == teamName).Select(t => t.CountryCode).FirstOrDefault();


                bool sameCountry = true;
                if (teamCountryCode != null && teamCountryCodeInDb != null)
                {
                    sameCountry = teamCountryCode.Equals(teamCountryCodeInDb);
                }


                // team exists + add team to league
                if (team != null && country != null && sameCountry)
                {
                    Console.WriteLine("Existing team: " + teamName);
                    tempLeague.Teams.Add(team);
                    context.SaveChanges();
                    Console.WriteLine("Added team to league: " + tempLeague.LeagueName);
                }

                // missing team name
                else if (teamName == string.Empty)
                {
                    Console.WriteLine("Team name is mandatory!");
                }

                // creating new team + add team
                else
                {
                    var newTeam = new Teams();
                    newTeam.TeamName    = teamName;
                    newTeam.CountryCode = teamCountryCode;
                    context.Teams.Add(newTeam);
                    Console.WriteLine("Created team: " + teamName);
                    tempLeague.Teams.Add(newTeam);
                    Console.WriteLine("Added team to league: " + tempLeague.LeagueName);
                }
            }
        }
Beispiel #18
0
        public static void Main(string[] args)
        {
            var context = new FootballEntities();

            // Problem 1.Entity Framework Mappings (Database First)
            //var teamsQuery = context.Teams.Select(t => t.TeamName);
            //foreach (var team in teamsQuery)
            //{
            //    Console.WriteLine(team);
            //}

            // Problem 2.Export the Leagues and Teams as JSON
            //var leaguesQuery =
            //    context.Leagues.OrderBy(l => l.LeagueName)
            //        .Select(
            //            l =>
            //            new LeagueDto
            //                {
            //                    LeagueName = l.LeagueName,
            //                    Teams = l.Teams.OrderBy(t => t.TeamName).Select(t => t.TeamName)
            //                })
            //        .ToList();

            //const string FilePathNameJson = "../../leagues-and-teams.json";

            //var jsonExporter = new JsonExporter();
            //jsonExporter.Export(FilePathNameJson, leaguesQuery);

            // Problem 3.Export International Matches as XML
            //var internationalMatchesQuery = context.InternationalMatches
            //    .OrderBy(im => im.MatchDate)
            //    .ThenBy(im => im.Countries)
            //    .ThenBy(im => im.Countries1)
            //    .Select(im => new InternationalMatchesDto()
            //    {
            //        HomeCountry = im.Countries1.CountryName,
            //        AwayCountry = im.Countries.CountryName,
            //        MatchDate = im.MatchDate.ToString(),
            //        Score = im.HomeGoals.ToString() + "-" + im.AwayGoals.ToString(),
            //        League = im.Leagues.LeagueName,
            //        HomeCountryCode = im.HomeCountryCode,
            //        AwayCountryCode = im.AwayCountryCode
            //    }).ToList();

            //const string FilePathNameXml = "../../international-matches.xml ";

            //var xmlExporter = new XmlExporter();
            //xmlExporter.Export(FilePathNameXml, internationalMatchesQuery);

            // Problem 4.Import Leagues and Teams from XML
            // Import rivers from Xml file
            var xmlImporter = new XmlImporter();
            var xmlDoc      = XDocument.Load(@"..\..\leagues-and-teams.xml ");

            xmlImporter.Import(xmlDoc, context);
        }
        public ActionResult Schedule(int selectedRound = -1)
        {
            using (var ctx = new FootballEntities())
            {
                var actualSeason = SeasonHelper.GetCurrentSeason(DateTime.Today);
                var actualRound  = MatchweekHelper.GetMatchweekToDisplayInSchedule();
                var data         = new List <MainPageModel>();
                if (!(selectedRound >= 1 && selectedRound <= 38))
                {
                    selectedRound = actualRound;
                }
                int success   = 0;
                int notPlayed = 0;

                foreach (var x in ctx.Matches.Where(d => (d.Matchweek == selectedRound) && d.Season.Equals(actualSeason)))
                {
                    if (selectedRound <= actualRound)
                    {
                        var score = ctx.Scores.FirstOrDefault(w => w.MatchId == x.Id);
                        int?homeGoals, awayGoals;
                        if (score != null)
                        {
                            homeGoals = score.HomeGoals;
                            awayGoals = score.AwayGoals;
                            bool rightPredicted = CompareScores((int)homeGoals, (int)awayGoals, x.HomeGoalsPredicted,
                                                                x.AwayGoalsPredicted);
                            if (rightPredicted)
                            {
                                success++;
                            }
                        }
                        else
                        {
                            notPlayed++;
                            homeGoals = null;
                            awayGoals = null;
                        }
                        data.Add(new MainPageModel(x.Team1.FullName, x.Team.FullName, x.HomeGoalsPredicted,
                                                   x.AwayGoalsPredicted, awayGoals, homeGoals, x.Date.Date));
                    }
                    else
                    {
                        data.Add(new MainPageModel(x.Team1.FullName, x.Team.FullName, x.HomeGoalsPredicted, x.AwayGoalsPredicted, null, null, x.Date.Date));
                    }
                }

                ViewBag.actualRound   = actualRound;
                ViewBag.selectedRound = selectedRound;
                if (selectedRound <= actualRound && notPlayed < 10)
                {
                    var successPercent = (success / (10.0 - notPlayed)) * 100.0;
                    ViewBag.success = Math.Round(successPercent, 2);
                }
                return(View(data.Distinct()));
            }
        }
Beispiel #20
0
        private static void CreateTeam(FootballEntities context, string teamName, Country country, League league)
        {
            Team team;

            if (country == null)
            {
                team = context.Teams.FirstOrDefault(t => (t.Country == null) && t.TeamName == teamName);
            }
            else
            {
                team = context.Teams.FirstOrDefault(
                    t => t.Country.CountryName == country.CountryName && t.TeamName == teamName);
            }

            if (team == null)
            {
                team = new Team {
                    TeamName = teamName, Country = country
                };

                context.Teams.Add(team);
                context.SaveChanges();
                Console.WriteLine(
                    "Created team: {0} ({1})",
                    team.TeamName,
                    country != null ? team.Country.CountryName : "no country");

                if (league != null)
                {
                    team.Leagues.Add(league);
                    context.SaveChanges();
                    Console.WriteLine("Added team to league: {0}", league.LeagueName);
                }
            }
            else
            {
                Console.WriteLine(
                    "Existing team: {0} ({1})",
                    team.TeamName,
                    country != null ? team.Country.CountryName : "no country");

                if (league != null)
                {
                    if (!team.Leagues.Any(l => l.LeagueName == league.LeagueName))
                    {
                        team.Leagues.Add(league);
                        context.SaveChanges();
                        Console.WriteLine("Added team to league: {0}", league.LeagueName);
                    }
                    else
                    {
                        Console.WriteLine("Existing team in league: {0}", league.LeagueName);
                    }
                }
            }
        }
 public static void Main()
 {
     using (var db = new FootballEntities())
     {
         foreach (var team in db.Teams)
         {
             Console.WriteLine(team.TeamName);
         }
     }
 }
 // before certain date, including exact score
 public double ComputeWeighted(DateTime before)
 {
     using (var ctx = new FootballEntities())
     {
         var    matches = ctx.Matches.Where(m => m.Date < before).ToList();
         double res     = Compute(matches, true);
         logger.InfoFormat("Prediction weighted effectiveness of scores before {0} equals: {1}", before, res);
         return(res);
     }
 }
 // all scores, including exact score
 public double ComputeWeighted()
 {
     using (var ctx = new FootballEntities())
     {
         var    matches = ctx.Matches.ToList();
         double res     = Compute(matches, true);
         logger.InfoFormat("Prediction weighted effectiveness of all scores equals: {0}", res);
         return(res);
     }
 }
Beispiel #24
0
 public void InsertTeams()
 {
     _ds.InsertTeams();
     using (var ctx = new FootballEntities())
     {
         Assert.AreEqual(ctx.Teams.Count(), 20 + 24 + 24 + 24);
         Assert.AreEqual(ctx.Teams.First().FullName, "Arsenal FC");
         Assert.AreEqual(ctx.Teams.First().Name, "Arsenal");
     }
 }
 // season, including exact score
 public double ComputeWeighted(string season)
 {
     using (var ctx = new FootballEntities())
     {
         var    matches = ctx.Matches.Where(m => m.Season == season).ToList();
         double res     = Compute(matches, true);
         logger.InfoFormat("Prediction weighted effectiveness of scores in season {0} equals: {1}", season, res);
         return(res);
     }
 }
 // only one matchweek from season (e.g. "2015/2016")
 public double Compute(int matchweek, string season)
 {
     using (var ctx = new FootballEntities())
     {
         var    matches = ctx.Matches.Where(m => m.Season == season && m.Matchweek == matchweek).ToList();
         double res     = Compute(matches, false);
         logger.InfoFormat("Prediction effectiveness of scores in matchweek {0} of season {1} equals: {2}", matchweek, season, res);
         return(res);
     }
 }
        public int InsertScores(string csvFilePath, DateTime startDate)
        {
            List <ScoreModel> scores = null;

            if (csvFilePath == null)
            {
                scores = ParseCsvScores(startDate);
            }
            else
            {
                scores = ParseCsvScores(csvFilePath, startDate);
            }

            int counter = 0;

            using (var ctx = new FootballEntities())
            {
                using (var transaction = ctx.Database.BeginTransaction())
                {
                    try
                    {
                        foreach (var s in scores)
                        {
                            var dbScore = s.ToDbObject();

                            if (ctx.Scores.Any(sc => sc.MatchId == dbScore.MatchId))
                            {
                                logger.WarnFormat("Score already exists. Date: {0}, match: {1}-{2}", s.Date, s.HomeTeam, s.AwayTeam);
                                continue;
                            }
                            else
                            {
                                ctx.Scores.Add(dbScore);
                                logger.InfoFormat("Score added. Date: {0}, match: {1}-{2}", s.Date, s.HomeTeam, s.AwayTeam);
                            }

                            UpdateLeagueTable(s);
                            counter++;
                            ctx.SaveChanges();
                        }

                        ctx.SaveChanges();
                        transaction.Commit();
                        logger.InfoFormat("{0}/{1} scores inserted to database", counter, scores.Count);
                    }
                    catch (Exception e)
                    {
                        logger.Error("Error while inserting scores. Transaction rollback.", e);
                        transaction.Rollback();
                    }
                }
            }
            return(counter);
        }
        static void Main()
        {
            var context = new FootballEntities();

            var teams = context.Teams;

            foreach (var team in teams)
            {
                System.Console.WriteLine(team.TeamName);
            }
        }
        public void InsertAllMatches()
        {
            var res = _ds.InsertAllMatches();

            Assert.IsTrue(res > 0);
            using (var ctx = new FootballEntities())
            {
                Assert.AreEqual(ctx.Matches.Max(m => m.Matchweek), 38);
                // TODO
            }
        }
        static void Main()
        {
            //To test your EF data model, list all team names.
            // The rest of problem 1 is in separate project.

            var context =  new FootballEntities();

            foreach (var team in context.Teams)
            {
                Console.WriteLine(team.TeamName);
            }
        }
        private Tuple <int, int, int> GetSuccessRateOfPrediction(TeamsInfoModel model)
        {
            int successScorePredictions  = 0;
            int successResultPredictions = 0;
            int allMatches   = 0;
            var teamName     = model.Team1;
            var actualSeason = SeasonHelper.GetCurrentSeason(DateTime.Today);

            using (var ctx = new FootballEntities())
            {
                var actualRound = MatchweekHelper.GetCurrentMatchweek();
                var teamId      = ctx.Teams.FirstOrDefault(e => e.FullName.Equals(teamName)).Id;

                foreach (var match in ctx.Matches.Where(e => (e.HomeId == teamId || e.AwayId == teamId) &&
                                                        DateTime.Compare(e.Date, DateTime.Today) < 0))
                {
                    var scoreOfMatch = match.Scores.FirstOrDefault();
                    if (scoreOfMatch == null)
                    {
                        continue;
                    }

                    if (!SeasonsComapare(model.SeasonSince, model.SeasonTo, match.Season))
                    {
                        continue;
                    }
                    if (match.AwayGoalsPredicted == null || match.HomeGoalsPredicted == null)
                    {
                        continue;
                    }

                    if ((scoreOfMatch.HomeGoals > scoreOfMatch.AwayGoals &&
                         match.HomeGoalsPredicted > match.AwayGoalsPredicted) ||
                        (scoreOfMatch.HomeGoals < scoreOfMatch.AwayGoals &&
                         match.HomeGoalsPredicted < match.AwayGoalsPredicted) ||
                        (scoreOfMatch.HomeGoals == scoreOfMatch.AwayGoals &&
                         match.HomeGoalsPredicted == match.AwayGoalsPredicted))
                    {
                        successResultPredictions++;
                    }

                    if (scoreOfMatch.HomeGoals == match.HomeGoalsPredicted &&
                        scoreOfMatch.AwayGoals == match.AwayGoalsPredicted)
                    {
                        successScorePredictions++;
                    }

                    allMatches++;
                }
            }
            return(Tuple.Create(allMatches, successResultPredictions, successScorePredictions));
        }
        public void UpdateLeagueTable(ScoreModel s)
        {
            using (var ctx = new FootballEntities())
            {
                var home = ctx.FullStatistics
                           .FirstOrDefault(t => t.Team.Name == s.HomeTeam && t.Season == s.Season);

                // jesli nie ma jeszcze teamu w tabeli, to go dodaj z zerowym dorobkiem
                if (home == null)
                {
                    home = AddToLeagueTable(s.HomeTeam, s.Season);
                }

                // jesli nie ma jeszcze teamu w tabeli, to go dodaj z zerowym dorobkiem
                var away = ctx.FullStatistics
                           .FirstOrDefault(t => t.Team.Name == s.AwayTeam && t.Season == s.Season);

                if (away == null)
                {
                    away = AddToLeagueTable(s.AwayTeam, s.Season);
                }

                home.MatchesPlayed++;
                home.GoalsScored += s.HomeGoals;
                home.GoalsLost   += s.AwayGoals;

                away.MatchesPlayed++;
                away.GoalsScored += s.AwayGoals;
                away.GoalsLost   += s.HomeGoals;

                if (s.HomeGoals > s.AwayGoals)
                {
                    home.MatchesWon++;
                    home.Points += 3;
                    away.MatchesLost++;
                }
                else if (s.HomeGoals < s.AwayGoals)
                {
                    away.MatchesWon++;
                    away.Points += 3;
                    home.MatchesLost++;
                }
                else
                {
                    home.MatchesDrawn++;
                    away.MatchesDrawn++;
                    home.Points++;
                    away.Points++;
                }
                ctx.SaveChanges();
            }
        }
        static void Main(string[] args)
        {
            var context = new FootballEntities();

            var leaguesWithTeams = context.Leagues
              .OrderBy(l => l.LeagueName)
              .Select(l => new
              {
                  leagueName = l.LeagueName,
                  teams = l.Teams
                      .OrderBy(t => t.TeamName)
                      .Select(t => t.TeamName)
              })
              .ToList();

            var jsonSerializer = new JavaScriptSerializer();
            var json = jsonSerializer.Serialize(leaguesWithTeams);
            File.WriteAllText("leagues-and-teams.json", json);
            Console.WriteLine("File leagues-and-teams.json exported.");
        }