// GET api/<controller> public IEnumerable<Game> Get() { using (var repository = new GameRepository()) { return repository.GetAll().ToList(); } }
public void Games_Have_Territories_That_Can_Be_Updated() { var gameRepo = new GameRepository(NHibernateSession); var g = new Game { Owner = new Player(), }; var t = g.GetTerritory(Territory.WesternUsa); t.ControlledBy = Nationality.UnitedStates; t.AddUnits(Nationality.UnitedStates, MilitaryUnit.Infantry, 5); gameRepo.Save(g); FlushSessionAndEvict(g); var g2 = gameRepo.Get(g.Id); Assert.That(g2.TerritoryStates.Count, Is.EqualTo(1)); var t2 = g.GetTerritory(Territory.WesternUsa); var army = t2.Armies[Nationality.UnitedStates]; army.Infantry = 7; gameRepo.Save(g2); FlushSessionAndEvict(g2); var g3 = gameRepo.Get(g.Id); Assert.That(g3.TerritoryStates.Count, Is.EqualTo(1)); var t3 = g.GetTerritory(Territory.WesternUsa); var army3 = t3.Armies[Nationality.UnitedStates]; Assert.That(army3.Infantry, Is.EqualTo(7)); Assert.That(army3.Nationality,Is.EqualTo(Nationality.UnitedStates)); Assert.That(t3.ControlledBy, Is.EqualTo(Nationality.UnitedStates)); }
public void SaveNewGameAndExistingTeamsTest() { // setup Game saved = null; string homeTeam = "TestTeam1", awayTeam = "TestTeam2"; long homeId = -1, awayId = -1, gameId = -1; using (var repository = new TeamRepository()) { homeId = repository.Add(new Team() { Name = homeTeam }); awayId = repository.Add(new Team() { Name = awayTeam }); } Game game = new Game() { Start = new DateTime(2014, 1, 1), HomeTeamId = homeId, AwayTeamId = awayId, TweetsRetrieved = RetrievalStatus.NONE }; // execute using (var repository = new GameRepository()) { gameId = repository.Save(game).Id; saved = (from g in repository.DataSet.Include("HomeTeam").Include("AwayTeam") where g.Id == gameId select g).FirstOrDefault(); } // validate Assert.IsNotNull(saved); Assert.IsNotNull(saved.HomeTeam); Assert.IsNotNull(saved.AwayTeam); Assert.AreEqual(homeTeam, saved.HomeTeam.Name); Assert.AreEqual(awayTeam, saved.AwayTeam.Name); }
public void Initialize() { _gameRepository = new GameRepository(); _playerRepository = new PlayerRepository(); _playerGameStatisticsRepository = new PlayerGameStatisticsRepository(); _transaction = new TransactionScope(TransactionScopeOption.RequiresNew); }
public void UpdateAll() { List<Game> games = new List<Game>(); using (var repository = new GameRepository()) { // get the list of games that havent had the activity points generated games = (from game in repository.DataSet.Include("HomeTeam").Include("AwayTeam") where game.TweetsRetrieved == RetrievalStatus.COMPLETED && game.TweetCount > 0 && repository.ActivityPoints.Where(point => point.GameId == game.Id).Count() == 0 select game).ToList(); } Console.Out.WriteLine(String.Format("Found {0} games to update{1}", games.Count, Environment.NewLine)); foreach (var game in games) { Console.Out.WriteLine(String.Format("Creating activity points for {0} vs {1}{2}Start: {3} End:{4}{2}", game.HomeTeam.Name, game.AwayTeam.Name, Environment.NewLine, game.Start, game.End)); UpdateGame(game); Console.Out.WriteLine(String.Format("Completed creating activity points for {0} vs {1}{2}", game.HomeTeam.Name, game.AwayTeam.Name, Environment.NewLine)); } }
public void Initialize() { _gameRepository = new GameRepository(); _holeRepository = new HoleRepository(); _playerRepository = new PlayerRepository(); _shotTypeRepository = new ShotTypeRepository(); _playerRivalryStatisticsRepository = new PlayerRivalryStatisticsRepository(); _transaction = new TransactionScope(TransactionScopeOption.RequiresNew); }
public GameManager( GameRepository games, PublisherRepository publishers) { if (games == null || publishers == null) { throw (new NullReferenceException()); } _publishers = publishers; _games = games; }
protected override async Task OnInitializedAsync() { Games = await GameRepository.GetList(); GameRequests = await GameRequestRepository.GetList(); Objectives = await ObjectiveRepository.GetList(); CurrentDate = DateTime.Today; GetDates(); }
public JsonResult AlterarJogoJquery(GameDataView dados) { ValidacaoGameMessage validacao = ValidacaoGameService.Validar(dados); if (validacao.Valido) { GameRepository gameRepository = new GameRepository(); gameRepository.Alterar(dados); } return(Json(validacao)); }
public IHttpActionResult DeleteLive(SetWinnerReq swq) { bool isOK = new GameRepository().DeleteLtopic(swq.topicSn); if (!isOK) { return(NotFound()); } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult Getgame(int id) { gameDto gamedto = new GameRepository().GetGame(id); if (gamedto.sn == 0) { return(NotFound()); } return(Ok(gamedto)); }
public void DoesNotAddInvalidDatePlayed() { var gameId = 0; var playedDate = new DateTime(2016, 1, 1); var context = _fixture.Context .GamesContain(new List <Game>()); var gameRepository = new GameRepository(context); Assert.Throws <ArgumentException>(() => gameRepository.AddPlayedDate(gameId, playedDate)); }
public BasegameView() { gameRepository = new GameRepository(); CloudnaryUrl = "https://images.igdb.com/igdb/image/upload/t_"; BigCoverUrl = CloudnaryUrl + "cover_big/"; BigCoverUrl2x = CloudnaryUrl + "cover_big_2x/"; MicroCoverUrl = CloudnaryUrl + "micro"; MicroCoverUrl2x = CloudnaryUrl + "thumb/"; SmallCoverUrl = CloudnaryUrl + "cover_small_2x/"; Imagesfolder = AppDomain.CurrentDomain.BaseDirectory + "images\\"; }
public GameType(GameRepository gameRepository) { Name = "Game"; Field(x => x.Id); Field(x => x.Name).Description("Game's name"); Field(x => x.StartTime).Description("Game's start date time"); Field(x => x.Link).Description("Game's link"); Field(x => x.PlayersNumber).Description("Game's players number"); Field(x => x.GettedNumbers).Description("Game's getted numbers"); Field(x => x.Finished).Description("Game's status"); }
public void GetAll_ShouldReturnCorrectCollection_WhenContextNotEmpty() { // Arrange var data = new List <GameDataModel> { new GameDataModel { Id = 1, Name = "BBB", Key = "k1" }, new GameDataModel { Id = 2, Name = "ZZZ", Key = "k2" }, new GameDataModel { Id = 3, Name = "AAA", Key = "k3" }, }.AsQueryable(); var mockSet = new Mock <DbSet <GameDataModel> >(); mockSet.As <IQueryable <GameDataModel> >().Setup(m => m.Provider).Returns(data.Provider); mockSet.As <IQueryable <GameDataModel> >().Setup(m => m.Expression).Returns(data.Expression); mockSet.As <IQueryable <GameDataModel> >().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As <IQueryable <GameDataModel> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator); var mockContext = new Mock <GameStoreDbContext>(); mockContext.Setup(c => c.Set <GameDataModel>()).Returns(mockSet.Object); mockContext.Object.Games = mockSet.Object; mockContext.Object.Games.Add(new GameDataModel { Id = 1, Name = "BBB", Key = "k1" }); mockContext.Object.Games.Add(new GameDataModel { Id = 2, Name = "ZZZ", Key = "k2" }); mockContext.Object.Games.Add(new GameDataModel { Id = 3, Name = "AAA", Key = "k3" }); //Act var service = new GameRepository(mockContext.Object); var result = service.GetAll().ToList(); //Assert //Assert.AreEqual(data, result.ToList()); Assert.AreEqual(3, result.Count); Assert.AreEqual("BBB", result[0].Name); Assert.AreEqual("ZZZ", result[1].Name); Assert.AreEqual("AAA", result[2].Name); Assert.AreEqual(1, result[0].Id); Assert.AreEqual(2, result[1].Id); Assert.AreEqual(3, result[2].Id); Assert.AreEqual("k1", result[0].Key); Assert.AreEqual("k2", result[1].Key); Assert.AreEqual("k3", result[2].Key); }
public void Setup() { _gameRepo = new GameRepository(); _playerRepo = new PlayerRepository(); _achievementRepo = new AchievementRepository(); totalGames = _gameRepo.GetTotalGames(); GetPlayersData(); GetOverallData(); }
public UnitOfWork(ApplicationDbContext context) { _context = context; Coops = new CoopRepository(_context); Attendances = new AttendanceRepository(_context); Games = new GameRepository(_context); Followings = new FollowingRepository(_context); Users = new ApplicationUserRepository(_context); Notifications = new NotificationRepository(_context); UserNotifications = new UserNotificationRepository(_context); }
public void GetElectedCategoriesBy() { var games = new List <Game> { new Game { Id = 1, Name = "Game 1" }, new Game { Id = 2, Name = "Game 2" } }; var categories = new List <Category> { new Category { Id = 1, Description = "Category 1" }, new Category { Id = 2, Description = "Category 2" }, new Category { Id = 3, Description = "Category 3" } }; var gameCategories = new List <GameCategory> { new GameCategory { CategoryId = 1, GameId = 1 }, new GameCategory { CategoryId = 2, GameId = 1 }, new GameCategory { CategoryId = 3, GameId = 1 }, new GameCategory { CategoryId = 2, GameId = 2 } }; var context = _fixture.Context .GamesContain(games) .CategoriesContain(categories) .GameCategoriesContain(gameCategories); var gameRepository = new GameRepository(context); var resultGameCategory = gameRepository.GetGameCategoryBy(1, 2); Assert.Equal(2, resultGameCategory.Id); Assert.Equal(1, resultGameCategory.GameId); Assert.Equal(2, resultGameCategory.CategoryId); }
public void Create() { var gameRepository = new GameRepository(Database.Context.Instance); var requestObject = new Game() { Id = 0, Name = "Game2" }; gameRepository.Create(requestObject); }
public void IsDuplicatedGame_should_return_FALSE_when_new_game() { // Arrange var fixture = new TestFixture(); var repo = new GameRepository(TestFixture.ConnectionString); // Act var result = repo.IsDuplicated(fixture.GetGame()); // Assert result.ShouldBeFalse(); }
private static void GameListenersHanlder(HttpListenerRequest req, HttpListenerResponse res, ResponseData data, MatchCollection matches) { var list = GameRepository .GetGames() .FindAll(game => game.isListen()) .Select(game => new PlayerInfo(game.Id, game.Player1Name)) .ToList(); var listenersPacket = new ListenersPacket(list); data.Data = JsonConvert.SerializeObject(listenersPacket); }
public void GetGames_HappyPath() { // Arrange var dbContext = A.Fake <ProFootballEntities>(); var repository = new GameRepository(dbContext); // Act var result = repository.GetEntities(); // Assert Assert.IsInstanceOf <IEnumerable <Game> >(result); }
public IHttpActionResult reopen(StartBetReq sbr) { GameRepository gr = new GameRepository(); byte? gameclosestatus = gr.getGameCloseStatus(sbr.gameSn); if (gameclosestatus == 3) { return(BadRequest("已完成派彩,無法重新開啟")); } new GameRepository().setGameCloseStatus(sbr.gameSn, 1); return(Ok()); }
public void GetGame() { const int targetId = 101; using (SpeedRunDatabaseContext context = new SpeedRunDatabaseContext()) { GameRepository gameRepository = new GameRepository(context); Game superMetroid = gameRepository.GetItem(targetId); Assert.IsTrue(superMetroid != null && superMetroid.Name.Contains("Metroid")); } }
public void TestPostGames() { GameRepository gameRepo = new GameRepository(DatabaseDummy.DatabaseDummyCreate("TestPostGames")); GameController gameController = new GameController(gameRepo); Game game = new Game() { UniqueKey = 8, }; var actionResult = gameController.PostGames(game); Assert.IsNotType <BadRequestObjectResult>(actionResult); }
public void GetAll_AllGamesReturned_CountEqualsActual() { const int expectedCount = 45; int actualCount; using (var gameRepo = new GameRepository(DataContextCreator.CreateTestContext())) { actualCount = gameRepo.GetAll().Count(); } Assert.AreEqual(expectedCount, actualCount); }
public IHttpActionResult gamereturn(StartBetReq sbr) { GameRepository gr = new GameRepository(); byte? gameclosestatus = gr.getGameCloseStatus(sbr.gameSn); if (gameclosestatus != 4) { return(BadRequest("此遊戲無法重設")); } gr.setGameCloseStatus(sbr.gameSn, 2); return(Ok()); }
public int Get() { using (var repository = new GameRepository()) { return repository.GetAll() .Select(game => game.MatchDay) .Distinct() .OrderByDescending(game => game.Value) .First() .Value; } }
public UnitOfWork(LiveBotDBContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); GuildRepository = new GuildRepository(context); ChannelRepository = new ChannelRepository(context); RoleRepository = new RoleRepository(context); SubscriptionRepository = new SubscriptionRepository(context); UserRepository = new UserRepository(context); NotificationRepository = new NotificationRepository(context); GameRepository = new GameRepository(context); AuthRepository = new AuthRepository(context); }
public ActionResult Delete(int id) { GameRepository gameRepository = new GameRepository(); Game game = new Game(); using (gameRepository) { game = gameRepository.SelectOne(id); } return(View(game)); }
// POST: api/Game public HttpResponseMessage Post(Game value) { GameRepository.InsertGame(value); var response = Request.CreateResponse <Game>(HttpStatusCode.Created, value); string uri = Url.Link("DefaultApi", new { id = value.Id }); response.Headers.Location = new Uri(uri); return(response); }
public async Task <Stream> Handle(ToScvRequest request, CancellationToken cancellationToken) { using (var context = _contextFactory.CreateContext()) { var tournamentRepository = new DbRepository <Tournament>(context); var tournament = await tournamentRepository .SingleOrDefaultAsync(x => x.Name == request.TournamentName); if (tournament == null) { return(null); } var gamesRepository = new GameRepository(context); var games = await gamesRepository.GetPlayedTournamentGames(tournament.Id); var getTableRequest = new GetTournamentTableRequest(request.TournamentName); var table = await _mediator.Send(getTableRequest); var stringBuilder = new StringBuilder(); // header stringBuilder.AppendLine("Team;Meets;Wins;Draws;Loses;Point"); // table foreach (var tournamentRow in table.Table) { stringBuilder.AppendLine($"{tournamentRow.TeamName};{tournamentRow.Meets};" + $"{tournamentRow.Win};{tournamentRow.Draw};" + $"{tournamentRow.Lose};{tournamentRow.Points}"); } stringBuilder.AppendLine(); // rounds foreach (var round in games.GroupBy(x => x.Round).OrderBy(x => x.Key.Number)) { stringBuilder.AppendLine($";round {round.Key.Number}"); //games foreach (var game in round.ToList()) { stringBuilder.AppendLine($"{game.HomeTeam.Name};{game.GuestTeam.Name}" + $";{game.Result.HomeTeamResult}:{game.Result.GuestTeamResult}"); } stringBuilder.AppendLine(); } return(new MemoryStream(Encoding.UTF8.GetBytes(stringBuilder.ToString()))); } }
public static async Task Initialize(WriteDatabaseConfiguration configuration) { await _semaphore.WaitAsync(); try { var databaseFilePath = Path.Combine(configuration.DirectoryPath, configuration.FileName); var encryptionService = new EncryptionService(new SecuredText(configuration.EncryptionKey)); var databaseContext = new FileDatabaseContext(databaseFilePath, encryptionService); databaseContext.Initialize(); using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await AddApplicationSettings(databaseContext); await AddTextureConverterSettings(databaseContext); await AddUsageStatistics(databaseContext); if (databaseContext.Games.IsNullOrEmpty()) { var gameRepository = new GameRepository(databaseContext); foreach (GameType gameType in Enum.GetValues(typeof(GameType))) { try { await AddGame(gameType, gameRepository); } catch (GameTemplateNotFoundException) { } } var gameId = ((GameType)typeof(GameType).GetDefaultValue().GetValueOrDefault()).GetAggregateId(); var game = databaseContext.Games.SingleOrDefault(entity => entity.Id == gameId); if (game == null) { throw new AggregateRootNotFoundException($"game with id: {gameId} could not be found"); } await gameRepository.ChangeGameProfileAsync(game.Profiles.First().Id); } transaction.Complete(); } DatabaseContext = databaseContext; } finally { _semaphore.Release(); } }
public UnitOfWork(DatabaseContext context) { _context = context; Users = new UserRepository(_context); UsersInfo = new UserInfoRepository(_context); Roles = new RoleRepository(_context); UsersHasRoles = new UserHasRoleRepository(_context); Messages = new MessageRepository(_context); Friendships = new FriendshipRepository(_context); Games = new GameRepository(_context); UsersGames = new UserHasGameRepository(_context); }
public void UpdatesPivotalWhenGameReachesConsensus() { const int projectId = 123, storyId = 456, points = 0; var pivotalMock = new Mock <IPivotal>(); var gameRepository = new GameRepository(pivotalMock.Object); var game = gameRepository.Get(projectId, storyId); OM.GameM.Play(game, "Rumples", points); OM.GameM.Play(game, "HappyCat", points); pivotalMock.Verify(p => p.EstimateStory(projectId, storyId, points)); }
public void AddGame_CallsAddGameInRepository() { var dataContext = new DataContext(); var game = new Game { GameId = 1, GameLevel = 1, BoardDimension = 3, IsGameOver = false, IsGameWon = false, TurnChoice = 1 }; var gameRepository = new GameRepository(dataContext); gameRepository.AddGame(game); Assert.Equal(1, dataContext.Games.Count()); }
public virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { Context?.Dispose(); GameRepository?.Dispose(); GenreRepository?.Dispose(); } } this._disposed = true; }
public SessionController( ILogger <SessionController> logger, IConfiguration config, SessionRepository sessions, IUserRepository users, GameRepository games) { _logger = logger; _botPlay = config.GetValue("Simple-Bot", false); _sessions = sessions; _users = users; _games = games; }
public Game Get(long id, bool includeTeams) { using (var repository = new GameRepository()) { if (includeTeams) return (from game in repository.DataSet.Include("HomeTeam").Include("AwayTeam") where game.Id == id select game).FirstOrDefault(); else return (from game in repository.GetAll() where game.Id == id select game).FirstOrDefault(); } }
// GET api/<controller>/5 public IEnumerable<Game> Get(int matchday, bool includeTeams) { using (var repository = new GameRepository()) { if (includeTeams) return (from game in repository.DataSet.Include("HomeTeam").Include("AwayTeam") where game.MatchDay == matchday select game).ToList(); else return (from game in repository.GetAll() where game.MatchDay == matchday select game).ToList(); } }
protected override void Given() { base.Given(); var settingsProvider = new StubCabalSettingsProvider(50); GameRepository = new GameRepository(NHibernateSession); PlayerRepository = new PlayerRepository(NHibernateSession, settingsProvider); ServiceUnderTest = new GameService(GameRepository, PlayerRepository); ExpectedGame = Build.Game(); ExpectedGame.Owner.UserName = OwnerName; ExpectedGame.Start(ExpectedGame.Owner); GameRepository.Save(ExpectedGame); FlushSessionAndEvict(ExpectedGame); }
public void UpdateAll() { using (var repository = new GameRepository()) { var gameCounts = (from game in repository.GetAll() where game.TweetsRetrieved == RetrievalStatus.COMPLETED && game.TweetCount == 0 select new { Game = game, Tweets = (from tweet in repository.Tweets where tweet.GameId == game.Id select tweet).Count() }).ToList(); foreach (var gameCount in gameCounts) { gameCount.Game.TweetCount = gameCount.Tweets; repository.Update(gameCount.Game); } } }
public void Verify() { var gameRepo = new GameRepository(NHibernateSession); var g = new Game {Owner = new Player()}; gameRepo.Save(g); FlushSessionAndEvict(g); new PersistenceSpecification<TerritoryStateArmy>(CurrentSession) .CheckReference(x => x.TerritoryState, new TerritoryState {ControlledBy = Nationality.Germany, Game = g, TerritoryId = 50}) .CheckProperty(x => x.Nationality, Nationality.Japan) .CheckProperty(x => x.Antiaircraft, 1) .CheckProperty(x => x.Armor, 2) .CheckProperty(x => x.Fighters, 3) .CheckProperty(x => x.Bombers, 4) .CheckProperty(x => x.Battleships, 5) .CheckProperty(x => x.Submarines, 6) .CheckProperty(x => x.Transports, 7) .CheckProperty(x => x.AircraftCarriers, 8) .CheckProperty(x => x.IndustrialComplexes, 1) .CheckProperty(x => x.Infantry, 10) .VerifyTheMappings(); }
public void Games_Have_Territories() { var gameRepo = new GameRepository(NHibernateSession); var owner = new Player(); var g = new Game { Owner = owner }; var t = g.GetTerritory(Territory.WesternUsa); t.ControlledBy = Nationality.UnitedStates; t.AddUnits(Nationality.UnitedStates, MilitaryUnit.Infantry, 5); gameRepo.Save(g); FlushSessionAndEvict(g); Assert.That(g.Id, Is.Not.EqualTo(0)); var g2 = gameRepo.Get(g.Id); Assert.That(g2.TerritoryStates, Is.Not.Empty); var t2 = g.GetTerritory(Territory.WesternUsa); var army = t2.Armies[Nationality.UnitedStates]; Assert.That(army.Infantry, Is.EqualTo(5)); Assert.That(t2.ControlledBy, Is.EqualTo(Nationality.UnitedStates)); Assert.That(army.Nationality, Is.EqualTo(Nationality.UnitedStates)); }
public bool Mine() { // Get all games whos tweets need indexing using (var repository = new GameRepository()) { Games = (from game in repository.DataSet.Include("HomeTeam.Hashtags").Include("AwayTeam.Hashtags") where game.TweetsRetrieved != RetrievalStatus.COMPLETED && game.EventsRetrieved == RetrievalStatus.COMPLETED && game.MatchDay >= MinGameDay select game).OrderByDescending(g => g.Start).ToList(); } foreach (Game game in Games) { long tweetCount = 0; _statuses = new ConcurrentQueue<List<Status>>(); _completed = false; Console.Out.WriteLine(String.Format("Mining tweets from {0} vs {1}{2}Start Time: {3}{2}", game.HomeTeam.Name, game.AwayTeam.Name, Environment.NewLine, game.Start)); ScrapeTweets(game); while (!_completed) { List<Status> recieved = null; if (_statuses.TryDequeue(out recieved)) { // work to do var tweets = from status in recieved select new Tweet() { Timestamp = BSTDateTime.FromBSTDateTime(status.CreatedAt), Text = status.Text, TwitterId = (long)status.StatusID, Longitude = status.Coordinates.Longitude, Latitude = status.Coordinates.Latitude, RetweetCount = status.RetweetCount, Images = (from media in status.Entities.MediaEntities select new Image() { Url = media.MediaUrl, GameId = game.Id }).ToList(), GameId = game.Id }; tweetCount += tweets.Count(); if (game.TweetsRetrieved == RetrievalStatus.NONE) { // update game status if nessessary game.TweetsRetrieved = RetrievalStatus.IN_PROGRESS; using (var repository = new GameRepository()) { repository.Update(game); } } using (var repository = new TweetRepository()) { repository.AddRange(tweets); } } else { // no work to do Thread.Sleep(2500); } } // update the game status game.TweetsRetrieved = RetrievalStatus.COMPLETED; game.TweetCount = tweetCount; using (var repository = new GameRepository()) { repository.Update(game); } // update the activity chart try { ActivityChartManager.UpdateGame(game); } catch (Exception e) { Console.Out.WriteLine(String.Format("An error occured while creating chart points:{0}{1}", Environment.NewLine, e.Message)); } Console.Out.WriteLine(String.Format("{0} vs {1} tweet mining compeleted{2}", game.HomeTeam.Name, game.AwayTeam.Name, Environment.NewLine)); } return true; }
public GameController() { this.repo = new GameRepository(); }
public DataService(string serviceUrl) { Games = new GameRepository("games", serviceUrl); User = new UserRepository("users", serviceUrl); }
static void Main(string[] args) { if (args[0] == "fixture") { int start = Int32.Parse(args[1]); int end = Int32.Parse(args[2]); var miner = new FixtureMiner() { StartWeek = start, EndWeek = end }; miner.Mine(); } else if (args[0] == "event") { int matchId = -1; int dayIdStart = -1; int dayIdEnd = -1; if (args.Length == 4) { matchId = Int32.Parse(args[1]); dayIdStart = Int32.Parse(args[2]); dayIdEnd = Int32.Parse(args[3]); } else if (args.Length == 2) { dayIdEnd = Int32.Parse(args[1]); using (var repository = new GameRepository()) { var game = repository.GetAll() .Where(g => g.MatchDay == dayIdEnd - 1) .OrderByDescending(g => g.LiveMatchId ?? -1).Take(1).First(); matchId = (int)game.LiveMatchId + 1; dayIdStart = dayIdEnd; } } else { using (var repository = new GameRepository()) { var game = repository.GetAll().OrderByDescending(g => g.LiveMatchId ?? -1).Take(1).First(); matchId = (int)game.LiveMatchId + 1; dayIdStart = (int)game.MatchDay; dayIdEnd = 38; // assume 38 weeks in season } } GameEventMiner miner = new GameEventMiner() { StartMatchId = matchId, StartMatchDayId = dayIdStart, EndMatchDayId = dayIdEnd }; miner.Mine(); } else if (args[0] == "twitter") { int minMatchDay = 0; if (args.Length == 2) { minMatchDay = Int32.Parse(args[1]); } TweetMiner miner = new TweetMiner() { MinGameDay = minMatchDay }; var task = miner.Mine(); Console.Out.WriteLine("Complete!"); } else if (args[0] == "print") { long id = 0; DateTime time; if (args.Length == 3) { time = DateTime.Parse(args[1]); DateTimeOffset offset = new DateTimeOffset(time, new TimeSpan(0, 0, 0)); id = long.Parse(args[2]); TweetMiner miner = new TweetMiner(); miner.PrintTweetsAfterTime(time, id); } } else if (args[0] == "activity") { ActivityChartManager manager = new ActivityChartManager(); manager.UpdateAll(); Console.Out.WriteLine("Complete!"); } else if (args[0] == "counts") { TweetCountManager manager = new TweetCountManager(); manager.UpdateAll(); Console.Out.WriteLine("Complete!"); } else if (args[0] == "topevents") { TopEventManager top = new TopEventManager(); top.Update(); Console.Out.WriteLine("Complete!"); } }
public GameManager() { var unitOfWork = new UnitOfWork(); _games = new GameRepository(unitOfWork); _publishers = new PublisherRepository(unitOfWork); }
public void PrintTweetsAfterTime(DateTime time, long gameId) { Game game = null; using (var repository = new GameRepository()) { game = (from g in repository.DataSet.Include("HomeTeam.Hashtags").Include("AwayTeam.Hashtags") where g.Id == gameId select g).First(); } string query = BuildQuery(game); Console.Out.WriteLine(String.Format("Printing tweets from {0} vs {1}{2}Start Time: {3}{2}", game.HomeTeam.Name, game.AwayTeam.Name, Environment.NewLine, game.Start)); var bstTime = BSTDateTime.ToBSTDateTime(game.Start); var lastStatus = FindClosestTweetToTime(bstTime, query); if (lastStatus == null) { Console.Out.WriteLine(String.Format("Unable to find starting point for game.. Skipping..{0}", Environment.NewLine)); _completed = true; return; } ulong maxId = lastStatus.StatusID; DateTime pointerTime = lastStatus.CreatedAt; while (true) { var task = Search(query, 100, maxId); task.Wait(); if (task.Result != null) { List<Status> statuses = task.Result; // update loop Status earliest = statuses[statuses.Count - 1]; maxId = (ulong)earliest.StatusID; pointerTime = earliest.CreatedAt; Console.Out.WriteLine(String.Format("Tweet: {0}{1}At: {2}{1}", statuses[0].Text, Environment.NewLine, BSTDateTime.FromBSTDateTime(statuses[0].CreatedAt))); } else { break; } } }
public void Initialize() { _repository = new GameRepository(DatabaseFactory, QueryFactory); _transaction = new TransactionScope(TransactionScopeOption.RequiresNew); }
public void Mine() { Console.Out.WriteLine(String.Format("Mining fixtures from week {0} to {1}", StartWeek, EndWeek)); for (int week = StartWeek; week <= EndWeek; week++) { Console.Out.WriteLine(String.Format("Mining week {0}", week)); string data = GetFixtureData(week); var games = JsonConvert.DeserializeObject<string[][]>(data); foreach (string[] line in games) { Game game = GameFromArray(line); Game saved = null; using (var repository = new GameRepository()) { long id = repository.Save(game).Id; saved = (from g in repository.DataSet.Include("HomeTeam").Include("AwayTeam") where g.Id == id select g).SingleOrDefault(); } Console.Out.WriteLine(String.Format("Saved game {0} vs {1} at {2}", saved.HomeTeam.Name, saved.AwayTeam.Name, saved.Start)); } } }
public void Initialize() { _repository = new GameRepository(); _transaction = new TransactionScope(TransactionScopeOption.RequiresNew); }
public void Mine() { bool notFound = false; int dayId = StartMatchDayId; int oldDayId = 0; int matchId = StartMatchId; while (dayId <= EndMatchDayId) { if (oldDayId != dayId) { Console.Out.WriteLine(String.Format("Mining game events from matchday {0}", dayId)); oldDayId = dayId; } try { string data = GetUrlData(detailsUrl, dayId, matchId); Game game = GetGameFromDetailsData(data); bool valid = true; // check for parse errors if (game == null) { Console.Out.WriteLine(String.Format("Unable to match game id {0}", matchId)); valid = false; } else { // check to see if game exists using (var repository = new GameRepository()) { var existing = from g in repository.GetAll() where g.MatchDay == dayId && g.HomeTeamId == game.HomeTeamId && g.AwayTeamId == game.AwayTeamId && g.EventsRetrieved == RetrievalStatus.COMPLETED select g; if (existing.Count() > 0) valid = false; } } if (valid) { // add more identity information to the game game.LiveMatchId = matchId; game.MatchDay = dayId; game.EventsRetrieved = RetrievalStatus.IN_PROGRESS; using (var repository = new GameRepository()) { repository.Save(game); } Team home = null; Team away = null; using (var repository = new TeamRepository()) { home = repository.GetAll().Where(t => t.Id == game.HomeTeamId).First(); away = repository.GetAll().Where(t => t.Id == game.AwayTeamId).First(); } Console.Out.WriteLine(String.Format("Matched data from {0} vs {1}", home.Name, away.Name)); // get the events and save them to the db List<GameEvent> gameEvents = new List<GameEvent>(); if (BSTDateTime.FromBSTDateTime(game.Start.AddHours(2)) <= DateTime.UtcNow) { gameEvents = GetGameEvents(game); } if (gameEvents.Count > 0) { using (var repository = new GameEventRepository()) { repository.AddRange(gameEvents); } // update the game event retrieval status game.EventsRetrieved = RetrievalStatus.COMPLETED; } else { // no events found game.EventsRetrieved = RetrievalStatus.NONE; } using (var repository = new GameRepository()) { repository.Save(game); } Console.Out.WriteLine(String.Format("Mined {0} events from game", gameEvents.Count)); } else { Console.Out.WriteLine(String.Format("Unable to match game id {0}", matchId)); } // update loop variants notFound = false; matchId++; } catch { if (notFound) break; notFound = true; dayId++; } } }