public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { Fixture fixture = await FindFixtureAsync(fixtureEvent); if (fixture.Status is FixtureStatus.ExternalCheckoutApprove or FixtureStatus.InternalCheckoutApply) { fixture.Status = FixtureStatus.CheckedOut; FixtureEventInDatabase?applyEventInDatabase = Repository.FixtureEventsInDatabase .LastOrDefault(item => item.ContentTypeFullName == typeof(FixtureExternalCheckoutApplyEvent).FullName || item.ContentTypeFullName == typeof(FixtureInternalCheckoutApplyEvent).FullName); FixtureEvent?applyEvent = applyEventInDatabase?.GetEvent(); string?applicantUserId = null; if (applyEvent is FixtureInternalCheckoutApplyEvent internalCheckoutApplyEvent) { applicantUserId = internalCheckoutApplyEvent.ApplicantUserId; } else if (applyEvent is FixtureExternalCheckoutApplyEvent externalCheckoutApplyEvent) { applicantUserId = externalCheckoutApplyEvent.ApplicantUserId; } fixture.StorageInformation = $"Fixture No:${fixtureEvent.FixtureNo} is checked out by ${applicantUserId} at {DateTimeOffset.Now}"; }
protected async ValueTask <Fixture> FindFixtureAsync(FixtureEvent fixtureEvent) { Fixture?fixture = await Repository.Fixtures.FindAsync(fixtureEvent.FixtureNo); return(fixture ?? throw new InvalidOperationException( $"Fixture No: {fixtureEvent.FixtureNo} doesn't exist")); }
public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { FixtureMoveInOutOfFixtureRoomEvent moveInOutOfEvent = (fixtureEvent as FixtureMoveInOutOfFixtureRoomEvent) !; Fixture fixture = await FindFixtureAsync(fixtureEvent); fixture.StorageInformation = moveInOutOfEvent.MoveIn ? "Fixture Room" : null; fixture.Status = moveInOutOfEvent.MoveIn ? FixtureStatus.FixtureRoom : FixtureStatus.Unknown; }
// TEAM IS REQUIRED (API FIXTURE ID 131874) private (int, int, int, int, string, string) GetFixtureEventKey(FixtureEvent fixtureEvent) { return(fixtureEvent.EventTime, fixtureEvent.EventTimePlus ?? NullIntDictKey, fixtureEvent.PlayerSeasonId ?? NullIntDictKey, fixtureEvent.TeamSeasonId, fixtureEvent.EventType, fixtureEvent.EventDetail); }
public void AddCorrectFixtureEventToTargetFixturesEvents_WhenPlayerIdAndFixtureIdAreValid() { // arrange var fixtureRepo = new Mock <IEfRepository <Fixture> >(); var teamsRepo = new Mock <IEfRepository <Team> >(); var playersRepo = new Mock <IEfRepository <Player> >(); var fixturesFactory = new Mock <IFixturesFactory>(); var mailService = new Mock <IFixtureMailService>(); var fixtureId = Guid.NewGuid(); var fixtureEventType = FixtureEventType.Goal; int minute = 22; var playerId = Guid.NewGuid(); var players = new List <Player>() { new Player() { Id = playerId } }; playersRepo.Setup(pr => pr.All).Returns(players.AsQueryable()); var fixtures = new List <Fixture>() { new Fixture() { Id = fixtureId, FixtureEvents = new List <FixtureEvent>(), HomeTeam = new Team() { Players = players }, } }.AsQueryable(); fixtureRepo.Setup(x => x.All).Returns(fixtures); var fixtureEvent = new FixtureEvent(); fixturesFactory.Setup(f => f.GetFixtureEvent(fixtureEventType, minute, players[0])).Returns(fixtureEvent); var fixtureService = new FixtureService( fixtureRepo.Object, teamsRepo.Object, playersRepo.Object, fixturesFactory.Object, mailService.Object); // act fixtureService.AddFixtureEvent(fixtureId, fixtureEventType, minute, playerId); // assert fixtureRepo.Verify(r => r.Update(It.Is <Fixture>(f => f.FixtureEvents.First() == fixtureEvent))); }
public void CallFixtureFactoriesGetFixtureEventMethodWithCorrectParameters_WhenPlayerIdAndFixtureIdAreValid() { // arrange var fixtureRepo = new Mock <IEfRepository <Fixture> >(); var teamsRepo = new Mock <IEfRepository <Team> >(); var playersRepo = new Mock <IEfRepository <Player> >(); var fixturesFactory = new Mock <IFixturesFactory>(); var mailService = new Mock <IFixtureMailService>(); var fixtureId = Guid.NewGuid(); var fixtureEventType = FixtureEventType.Goal; int minute = 22; var playerId = Guid.NewGuid(); var players = new List <Player>() { new Player() { Id = playerId } }; playersRepo.Setup(pr => pr.All).Returns(players.AsQueryable()); var fixtures = new List <Fixture>() { new Fixture() { Id = fixtureId, FixtureEvents = new List <FixtureEvent>(), HomeTeam = new Team() { Players = players }, } }.AsQueryable(); fixtureRepo.Setup(x => x.All).Returns(fixtures); var fixtureEvent = new FixtureEvent(); fixturesFactory.Setup(f => f.GetFixtureEvent(fixtureEventType, minute, players[0])).Returns(fixtureEvent); var fixtureService = new FixtureService( fixtureRepo.Object, teamsRepo.Object, playersRepo.Object, fixturesFactory.Object, mailService.Object); // act fixtureService.AddFixtureEvent(fixtureId, fixtureEventType, minute, playerId); // assert fixturesFactory.Verify(f => f.GetFixtureEvent(fixtureEventType, minute, players[0]), Times.Once); }
public void IncreaseAwayTeamsScoreByOne_WhenPlayerIsNotFoundInHomeTeamsPlayers() { // arrange var fixtureRepo = new Mock <IEfRepository <Fixture> >(); var teamsRepo = new Mock <IEfRepository <Team> >(); var playersRepo = new Mock <IEfRepository <Player> >(); var fixturesFactory = new Mock <IFixturesFactory>(); var mailService = new Mock <IFixtureMailService>(); var fixtureId = Guid.NewGuid(); var fixtureEventType = FixtureEventType.Goal; int minute = 22; var playerId = Guid.NewGuid(); var players = new List <Player>() { new Player() { Id = playerId } }; playersRepo.Setup(pr => pr.All).Returns(players.AsQueryable()); var fixtures = new List <Fixture>() { new Fixture() { Id = fixtureId, FixtureEvents = new List <FixtureEvent>(), HomeTeam = new Team() { Players = new List <Player>() }, } }.AsQueryable(); fixtureRepo.Setup(x => x.All).Returns(fixtures); var fixtureEvent = new FixtureEvent(); fixturesFactory.Setup(f => f.GetFixtureEvent(fixtureEventType, minute, players[0])).Returns(fixtureEvent); var fixtureService = new FixtureService( fixtureRepo.Object, teamsRepo.Object, playersRepo.Object, fixturesFactory.Object, mailService.Object); // act fixtureService.AddFixtureEvent(fixtureId, fixtureEventType, minute, playerId); // assert fixtureRepo.Verify(r => r.Update(It.Is <Fixture>(f => f.ScoreAwayTeam == 1))); }
public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { Fixture fixture = await FindFixtureAsync(fixtureEvent); FixtureAssignLocationNoEvent assignLocationNoEvent = (fixtureEvent as FixtureAssignLocationNoEvent) !; fixture.ShelfNo = assignLocationNoEvent.FixtureNo; fixture.FloorNo = assignLocationNoEvent.FloorNo; }
private async ValueTask <IActionResult> HandleAsync(FixtureEvent fixtureEvent) { string eventHandlerTypeName = $"{fixtureEvent.GetType().Name}Handler"; string eventHandlerTypeFullName = $"LabCMS.FixtureDomain.Server.EventHandles.{eventHandlerTypeName}"; Type eventHandlerType = _fixtureEventAssembly.GetType(eventHandlerTypeFullName) !; FixtureEventHandler eventHandler = _handlersFactory.Create(eventHandlerType, _repository); await eventHandler.HandleAsync(fixtureEvent); return(Ok()); }
public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { Fixture fixture = await FindFixtureAsync(fixtureEvent); if (fixture !.Status != FixtureStatus.Registered) { throw new ArgumentException( $"Fixture No: {fixtureEvent.FixtureNo} is not registered", nameof(fixtureEvent)); } fixture.Status = FixtureStatus.AcceptanceChecked; fixture.StorageInformation = "已验收"; }
public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { Fixture fixture = await FindFixtureAsync(fixtureEvent); if (fixture.Status is FixtureStatus.CheckedOut) { fixture.Status = FixtureStatus.FixtureRoom; fixture.StorageInformation = "Fixture Room"; } else { throw new InvalidOperationException($"Fixture No: ${fixtureEvent.FixtureNo} is not in waiting for Checkin scan status."); } }
private async ValueTask InterceptAsync(IInvocation invocation) { var proceed = invocation.CaptureProceedInfo(); FixtureEventHandler target = (invocation.InvocationTarget as FixtureEventHandler) !; FixtureEvent fixtureEvent = (invocation.Arguments[0] as FixtureEvent) !; await target.HandleAsync(fixtureEvent); await target.Repository.FixtureEventsInDatabase.AddAsync( FixtureEventInDatabase.GetEntity(fixtureEvent)); await target.Repository.SaveChangesAsync(); proceed.Invoke(); }
public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { Fixture fixture = await FindFixtureAsync(fixtureEvent); if (fixture.CanCheckout()) { fixture.Status = FixtureStatus.InternalCheckoutApply; } else { throw new InvalidOperationException( $"Fixture No: ${fixtureEvent.FixtureNo} is in checkout procedure"); } }
public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { Fixture fixture = await FindFixtureAsync(fixtureEvent); if (fixture.CanCheckout()) { fixture.Status = FixtureStatus.ExternalCheckoutApply; await EmailChannel.AddNotificationEmailAsync( "*****@*****.**", Repository.AdminRoles.Select(item => item.Email), $"no-reply: Fixture{fixtureEvent.FixtureNo} need to checkout", "<div>Check the link:</div><a href=\"http://10.99.159.149:83/\">link</a>"); } else { throw new InvalidOperationException( $"Fixture No: ${fixtureEvent.FixtureNo} is in checkout procedure"); } }
public override async ValueTask HandleAsync(FixtureEvent fixtureEvent) { Fixture fixture = await FindFixtureAsync(fixtureEvent); if (fixture.Status is FixtureStatus.ExternalCheckoutApply) { fixture.Status = FixtureStatus.ExternalCheckoutApprove; //Todo Send email notification here FixtureExternalCheckoutApplyEvent?applyEvent = Repository.FixtureEventsInDatabase.Where(item => item.FixtureNo == fixtureEvent.FixtureNo) .LastOrDefault(item => item.ContentTypeFullName == typeof(FixtureExternalCheckoutApplyEvent).FullName)? .GetEvent() as FixtureExternalCheckoutApplyEvent; if (applyEvent == null) { throw new InvalidOperationException( $"Can't find apply event for this approve event! Fixture No:{fixtureEvent.FixtureNo}"); } Role?role = (await Repository.Roles.FindAsync(applyEvent?.ApplicantUserId)); if (role == null) { throw new InvalidOperationException($"Applicant: {applyEvent.ApplicantUserId} doesn't exist!"); } await EmailChannel.AddNotificationEmailAsync( "*****@*****.**", new[] { role.Email }, $"no-reply: Fixture {fixtureEvent.FixtureNo} checkout approved", "<div>Check the link:</div><a href=\"http://10.99.159.149:83/\">link</a>"); } else { throw new InvalidOperationException($"Fixture No: ${fixtureEvent.FixtureNo} is not in Apply status."); } }
public static void StartPull(ref int workingTimerInterval) { ConfigurationManager.RefreshSection("appSettings"); int canUpdate = 0, insertSkip = 1; List <string> goalEvents = new List <string> { "own_goal", "penalty", "goal" }; string xmlDocInnerXml = ""; DateTime feedTime = DateTime.Now; db = new GoalAlertEntities(); try { if (AllEnabledLeague > 0) { string[] leagues = (from s in wdb.Leagues.Where(f => f.IsEnabled == 1) select s.LeagueName).ToArray(); ReturnLeague = AllEnabledLeague; XmlDocument xmlDoc = new XmlDocument(); //AppUtil.LogFileWrite(AppUtil.RequestUrl(leagues)); xmlDoc.Load(AppUtil.RequestUrl(leagues)); //xmlDoc.Load(@"C:\XmlScore\LiveScore.xml"); // = new FixtureEvent(); /* Modified 03082016 */ XmlSerializer serializer = new XmlSerializer(typeof(livescorefeed)); //XmlSerializer serializer = XmlSerializer.FromTypes(new[] { typeof(livescorefeed) })[0]; MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlDoc.InnerXml)); //if (xmlDoc != null) AppUtil.LogFileWrite(xmlDoc.InnerXml); Fixture fx; // = new Fixture(); /* Modified 03082016 */ FixtureEvent matchfx_event; if (xmlDoc != null) { xmlDocInnerXml = xmlDoc.InnerXml; } livescorefeed resultingFeeds = (livescorefeed)serializer.Deserialize(memStream); if (resultingFeeds != null && resultingFeeds.matches != null && resultingFeeds.matches.totalcount > 0) { foreach (livescorefeedMatchesItem match in resultingFeeds.matches.item) { //fx = new Fixture(); #region "PULL MATCH FIXTURES" fx = db.Fixtures.FirstOrDefault(f => f.MatchID.ToLower() == match.id.ToLower()); if (fx == null) // || fx.ID <= 0) /* Modified 03082016 */ { if (match.status.ToLower() != "finished") { fx = new Fixture(); fx.Guest = match.teams.guests.name; fx.Host = match.teams.hosts.name; fx.IsDailySummSent = 0; fx.IsMatchSummSent = 0; fx.IsPreKickOffSent = 0; fx.IsScoreAET = false; foreach (League _league in wdb.Leagues.Where(l => l.LeagueName == match.contest)) { fx.LeaugeID = _league.LeagueID; } fx.Local_KickOff = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(match.timestampstarts)).AddHours(AppUtil.GMTValue); fx.MatchID = match.id; fx.Pre_Local_KickOff = fx.Local_KickOff.GetValueOrDefault().Subtract(new TimeSpan(0, AppUtil.MinutesBeforeKickoff, 0)); fx.Score = match.score; fx.Status = match.status; fx.Unix_KickOff = match.timestampstarts.ToString(); //if (match.status.ToLower() == "finished") // fx.Local_Finish = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(Convert.ToInt32(resultingFeeds.timestamp_created))).AddHours(AppUtil.GMTValue); //else // fx.Local_Finish = fx.Local_Finish; db.Fixtures.Add(fx); db.SaveChanges(); insertSkip = 0; } else { insertSkip = 1; } } else { //fx.IsDailySummSent = false; //fx.IsMatchSummSent = false; //fx.IsPreKickOffSent = false; //fx.IsScoreAET = false; if (fx.Status == match.status & (fx.Status.ToLower() == "not_started" | fx.Status.ToLower() == "postponed") & fx.Unix_KickOff != match.timestampstarts.ToString()) //in case of change of start time { fx.Local_KickOff = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(match.timestampstarts)).AddHours(AppUtil.GMTValue); fx.Pre_Local_KickOff = fx.Local_KickOff.GetValueOrDefault().Subtract(new TimeSpan(0, AppUtil.MinutesBeforeKickoff, 0)); fx.Status = match.status; fx.Unix_KickOff = match.timestampstarts.ToString(); db.SaveChanges(); } if (fx.Status != match.status & fx.Unix_KickOff != match.timestampstarts.ToString()) //in case of postponement { fx.Local_KickOff = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(match.timestampstarts)).AddHours(AppUtil.GMTValue); fx.Pre_Local_KickOff = fx.Local_KickOff.GetValueOrDefault().Subtract(new TimeSpan(0, AppUtil.MinutesBeforeKickoff, 0)); fx.Status = match.status; fx.Unix_KickOff = match.timestampstarts.ToString(); canUpdate = 1; } if (fx.Status.ToLower() != match.status.ToLower() & fx.Unix_KickOff == match.timestampstarts.ToString()) { if (match.status.ToLower() == "finished" & fx.Status.ToLower() != "finished") { fx.Local_Finish = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(Convert.ToInt32(resultingFeeds.timestampcreated))).AddHours(AppUtil.GMTValue); } fx.Status = match.status; canUpdate = 1; } if (fx.Score != match.score) { fx.Score = match.score; //XX - XX, canUpdate = 1; } if (canUpdate == 1) { db.SaveChanges(); } } #endregion //goal|own_goal|penalty|red_card|yellow_card|ps //goal - goal //penalty - goal scored from penalty //own_goal - own goal //yellow_card - yellow card //red_card - red card //ps - penalty shootout kick* #region "EVENTS UPDATES" if (match.events != null && match.events.Length > 0) //if (canUpdate == 1 | insertSkip == 0) { //livescorefeedMatchesItemEventsEvent aetMatch = match.events.Where(w => goalEvents.Contains(w.type) == true).OrderByDescending(m => m.minute).FirstOrDefault(); livescorefeedMatchesItemCurrentstate et = new livescorefeedMatchesItemCurrentstate(); if (et.period != null && et.period.Length > 0) { if (et.period == "extra_time") { fx.IsScoreAET = true; db.SaveChanges(); } } //if (aetMatch != null) //if (fx.IsScoreAET.GetValueOrDefault() != true & Convert.ToInt32(match.events.Where(w => goalEvents.Contains(w.type) == true).OrderByDescending(m => m.minute).FirstOrDefault().minute) > 90) //{ // fx.IsScoreAET = true; // db.SaveChanges(); //} foreach (livescorefeedMatchesItemEventsEvent fx_event in match.events) { int thisEventID = (wdb.Notifications.FirstOrDefault(f => f.Name.ToLower() == fx_event.type) != null) ? wdb.Notifications.FirstOrDefault(f => f.Name.ToLower() == fx_event.type).ID : 7; string team = fx_event.team == "guests" ? match.teams.guests.name : match.teams.hosts.name; //Get Team Name if (fx_event.score != null) { var goal = db.FixtureEvents.Where(g => g.MatchID == match.id && g.ScoreLine == fx_event.score).FirstOrDefault(); if (goal == null) { matchfx_event = new FixtureEvent(); matchfx_event.IsPushed = 0; matchfx_event.MatchID = match.id; matchfx_event.Minute = fx_event.minute; matchfx_event.NotificationID = thisEventID; if (matchfx_event.NotificationID == 7) { AppUtil.LogFileWrite(fx_event.type); AppUtil.LogFileWrite(xmlDoc.InnerXml); } matchfx_event.Player = fx_event.player; matchfx_event.ScoreLine = fx_event.score; matchfx_event.Team = team; matchfx_event.Timestamped = DateTime.Now; db.FixtureEvents.Add(matchfx_event); db.SaveChanges(); } else { if (goal.Player != fx_event.player || goal.Minute != fx_event.minute) { goal.Player = fx_event.player; goal.Minute = fx_event.minute; db.SaveChanges(); } } } else { if (fx_event.score == null) { var card = db.FixtureEvents.Where(c => c.MatchID == match.id && c.Player == fx_event.player && c.Team == team && c.Minute == fx_event.minute).FirstOrDefault(); if (card == null) { matchfx_event = new FixtureEvent(); matchfx_event.IsPushed = 0; matchfx_event.MatchID = match.id; matchfx_event.Minute = fx_event.minute; matchfx_event.NotificationID = thisEventID; if (matchfx_event.NotificationID == 7) { AppUtil.LogFileWrite(fx_event.type); AppUtil.LogFileWrite(xmlDoc.InnerXml); } matchfx_event.Player = fx_event.player; //matchfx_event.ScoreLine = fx_event.score; //matchfx_event.Team = fx_event.team; //value="guests"/"hosts" matchfx_event.Team = team;//fx_event.team == "guests" ? match.teams.guests.name : match.teams.hosts.name; matchfx_event.Timestamped = DateTime.Now; db.FixtureEvents.Add(matchfx_event); db.SaveChanges(); } } } } } #endregion } } else //there is no feed at all { ReturnLeague -= 1; } if (ReturnLeague == 0) { workingTimerInterval = AppUtil.NoFeedSecondInterval * 1000; //wait for 1 minute AppUtil.LogFileWrite(string.Format("No Feed Return For All Enabled League! Live Feed Service Waiting for {0} minute......", (AppUtil.NoFeedSecondInterval / 60).ToString())); } else { workingTimerInterval = AppUtil.RequestSecondInterval * 1000; } // "http://pi.xmlscores.com/feed.html?f=xml&type=matches&contest=eng_pl&t1=1412509500&t2=1414237500&s=1&l=7&events=1&open=b4d88044654d82c4eccf19f8ae9c024f"; //string cmdText = "Insert into Fixture(MatchId,LeagueId,Host,Guest,Status,Unix_KickOff,IsPreKickOffSent,IsMatchSummSent,IsDailySummSent])VALUES(@matchid,@leagueid,@host,@guest,@status,@kickoff,@sent1,@sent2,@sent3)"; } else { workingTimerInterval = AppUtil.NoLeagueSecondInterval * 1000; //wait for 1 hour AppUtil.LogFileWrite(string.Format("No League Enabled Yet! Live Feed Service Waiting for {0} minute......", (AppUtil.NoLeagueSecondInterval / 60).ToString())); } ////////////***********START INSERT, DELETE FIXTURE,PASTFIXTURE, ETC HERE********************///////////// #region "START INSERT, DELETE FIXTURE,PASTFIXTURE, ETC HERE" // db = new GoalAlertEntities(); // qry = "delete from PastFixture where MatchID in (select MatchID from Fixture)"; // db.Database.ExecuteSqlCommand(qry); // qry = "delete PastFixtureEvent where MatchID in (select MatchID from FixtureEvent)"; // db.Database.ExecuteSqlCommand(qry); // foreach (Fixture finishedMatch in db.Fixtures.ToList()) // { // switch (finishedMatch.Status.ToLower()) //not_started, finished, active, postponed; // { // case "active": // //update/ or add events // if (feedTime.Subtract(finishedMatch.Local_KickOff.GetValueOrDefault()).TotalMinutes > new TimeSpan(AppUtil.LastActiveHour, 0, 0).TotalMinutes) // { // qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) // SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [MatchID] ={0} // AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] // AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) // SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] // WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} //AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] // AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0}"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // } // break; // case "finished": // //update or add events // //prepare for archive // if (feedTime.Subtract(finishedMatch.Local_Finish.GetValueOrDefault()).TotalMinutes > PastActiveMinutes.TotalMinutes) // { // qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) // SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [IsPushed] >0 AND [MatchID] ={0} // AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] // AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) // SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] // WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [IsPushed] =0 AND [MatchID] ={0} //AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] // AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [IsPushed] >0 AND [MatchID] ={0}"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // } // db.SaveChanges(); // break; // case "not_started": // //do nothing for now // if (feedTime.Subtract(finishedMatch.Local_KickOff.GetValueOrDefault()).TotalMinutes > new TimeSpan(AppUtil.LastActiveHour, 0, 0).TotalMinutes) // { // qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) // SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [MatchID] ={0} // AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] // AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) // SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] // WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} //AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] // AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0}"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // } // break; // case "postponed": // //update or add events // if (feedTime.Subtract(finishedMatch.Local_KickOff.GetValueOrDefault()).TotalMinutes > new TimeSpan(AppUtil.LastActiveHour, 0, 0).TotalMinutes) // { // qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) // SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [MatchID] ={0} // AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] // AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) // SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] // WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} //AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] // AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0}"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); // qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; // db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); // } // break; // default: // break; // } // } #endregion ////////////***********END INSERT, DELETE FIXTURE,PASTFIXTURE, ETC HERE********************///////////// } catch (DbEntityValidationException exception) { foreach (DbValidationError validationError in exception.EntityValidationErrors.SelectMany(error => error.ValidationErrors)) { AppUtil.LogFileWrite(string.Format("{0} - {1}", validationError.PropertyName, validationError.ErrorMessage)); } if (!string.IsNullOrEmpty(xmlDocInnerXml)) { AppUtil.LogFileWrite(xmlDocInnerXml); } workingTimerInterval = AppUtil.NoFeedSecondInterval * 1000; } catch (Exception rex) { AppUtil.LogFileWrite("Live Feed Service Run Error: " + rex.ToString()); //AppUtil.LogFileWrite("Live Feed Service Run Error(StackTrace): " + rex.StackTrace); //if (rex.InnerException != null) AppUtil.LogFileWrite("Live Feed Service Run Error:(InnerException) " + rex.InnerException.ToString()); if (!string.IsNullOrEmpty(xmlDocInnerXml)) { AppUtil.LogFileWrite(xmlDocInnerXml); } //Log detail to db workingTimerInterval = AppUtil.RequestSecondInterval * 1000; } finally { db.Dispose(); } }
public abstract ValueTask HandleAsync(FixtureEvent fixtureEvent);
public static void StartPull(ref int workingTimerInterval) { ConfigurationManager.RefreshSection("appSettings"); int canUpdate = 0, insertSkip = 1; List <string> goalEvents = new List <string> { "og", "pen", "goal" }; string xmlDocInnerXml = ""; DateTime feedTime = DateTime.Now; db = new GoalAlertEntities(); try { if (AllEnabledLeague > 0) { ReturnLeague = AllEnabledLeague; foreach (League _league in wdb.Leagues.Where(f => f.IsEnabled == 1).ToList()) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppUtil.RequestUrl(_league.LeagueName)); Fixture fx = new Fixture(); FixtureEvent matchfx_event = new FixtureEvent(); XmlSerializer serializer = new XmlSerializer(typeof(LiveScoreFeed)); MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlDoc.InnerXml)); //if (xmlDoc != null) AppUtil.LogFileWrite(xmlDoc.InnerXml); if (xmlDoc != null) { xmlDocInnerXml = xmlDoc.InnerXml; } LiveScoreFeed resultingFeeds = (LiveScoreFeed)serializer.Deserialize(memStream); if (resultingFeeds != null && resultingFeeds.matcheslist != null && resultingFeeds.matcheslist.totalcount > 0) { foreach (Match match in resultingFeeds.matcheslist.match) { fx = new Fixture(); fx = db.Fixtures.FirstOrDefault(f => f.MatchID.ToLower() == match.id.ToLower()); if (fx == null || fx.ID <= 0) { if (match.status.ToLower() != "finished") { fx = new Fixture(); fx.Guest = match.teams.guests; fx.Host = match.teams.hosts; fx.IsDailySummSent = 0; fx.IsMatchSummSent = 0; fx.IsPreKickOffSent = 0; fx.IsScoreAET = false; fx.LeaugeID = _league.LeagueID; fx.Local_KickOff = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(match.timestampstarts)).AddHours(AppUtil.GMTValue); fx.MatchID = match.id; fx.Pre_Local_KickOff = fx.Local_KickOff.GetValueOrDefault().Subtract(new TimeSpan(0, AppUtil.MinutesBeforeKickoff, 0)); fx.Score = match.score; fx.Status = match.status; fx.Unix_KickOff = match.timestampstarts.ToString(); //if (match.status.ToLower() == "finished") // fx.Local_Finish = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(Convert.ToInt32(resultingFeeds.timestamp_created))).AddHours(AppUtil.GMTValue); //else // fx.Local_Finish = fx.Local_Finish; db.Fixtures.Add(fx); db.SaveChanges(); insertSkip = 0; } else { insertSkip = 1; } } else { //fx.IsDailySummSent = false; //fx.IsMatchSummSent = false; //fx.IsPreKickOffSent = false; //fx.IsScoreAET = false; if (fx.Status == match.status & (fx.Status.ToLower() == "not_started" | fx.Status.ToLower() == "postponed") & fx.Unix_KickOff != match.timestampstarts.ToString()) //in case of change of start time { fx.Local_KickOff = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(match.timestampstarts)).AddHours(AppUtil.GMTValue); fx.Pre_Local_KickOff = fx.Local_KickOff.GetValueOrDefault().Subtract(new TimeSpan(0, AppUtil.MinutesBeforeKickoff, 0)); fx.Status = match.status; fx.Unix_KickOff = match.timestampstarts.ToString(); db.SaveChanges(); } if (fx.Status != match.status & fx.Unix_KickOff != match.timestampstarts.ToString()) //in case of postponement { fx.Local_KickOff = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(match.timestampstarts)).AddHours(AppUtil.GMTValue); fx.Pre_Local_KickOff = fx.Local_KickOff.GetValueOrDefault().Subtract(new TimeSpan(0, AppUtil.MinutesBeforeKickoff, 0)); fx.Status = match.status; fx.Unix_KickOff = match.timestampstarts.ToString(); canUpdate = 1; } if (fx.Status.ToLower() != match.status.ToLower() & fx.Unix_KickOff == match.timestampstarts.ToString()) { if (match.status.ToLower() == "finished" & fx.Status.ToLower() != "finished") { fx.Local_Finish = Convert.ToDateTime(AppUtil.ConvertUNIXToDateTime(Convert.ToInt32(resultingFeeds.timestamp_created))).AddHours(AppUtil.GMTValue); } fx.Status = match.status; canUpdate = 1; } if (fx.Score != match.score) { fx.Score = match.score; //XX - XX, canUpdate = 1; } if (canUpdate == 1) { db.SaveChanges(); } } //goal|own_goal|penalty==red_card|yellow_card==ps== //goal - goal //pen - goal scored from penalty //og - own goal //yc - yellow card //rc - red card //ps - penalty shootout kick* if (match.matchevents != null && match.matchevents.Length > 0) { if (canUpdate == 1 | insertSkip == 0) { MatchEvent aetMatch = match.matchevents.Where(w => goalEvents.Contains(w.type) == true).OrderByDescending(m => m.minute).FirstOrDefault(); if (aetMatch != null) { if (fx.IsScoreAET.GetValueOrDefault() != true & Convert.ToInt32(match.matchevents.Where(w => goalEvents.Contains(w.type) == true).OrderByDescending(m => m.minute).FirstOrDefault().minute) > 90) { fx.IsScoreAET = true; db.SaveChanges(); } } foreach (MatchEvent fx_event in match.matchevents) { int thisEventID = (wdb.Notifications.FirstOrDefault(f => f.Name.ToLower() == fx_event.type) != null) ? wdb.Notifications.FirstOrDefault(f => f.Name.ToLower() == fx_event.type).ID : 7; matchfx_event = new FixtureEvent(); matchfx_event = db.FixtureEvents.FirstOrDefault(f => (f.MatchID == match.id & f.ScoreLine == fx_event.score & goalEvents.Contains(fx_event.type)) | (f.MatchID == match.id & f.NotificationID == thisEventID & f.Team == fx_event.team.Value & f.Player == fx_event.player & goalEvents.Contains(fx_event.type) == false)); //f.Minute == fx_event.minute & if (matchfx_event == null || matchfx_event.EventID <= 0) { matchfx_event = new FixtureEvent(); matchfx_event.IsPushed = 0; matchfx_event.MatchID = fx.MatchID; matchfx_event.Minute = fx_event.minute; matchfx_event.NotificationID = thisEventID; if (matchfx_event.NotificationID == 7) { AppUtil.LogFileWrite(fx_event.type); AppUtil.LogFileWrite(xmlDoc.InnerXml); } matchfx_event.Player = fx_event.player; matchfx_event.ScoreLine = fx_event.score; matchfx_event.Team = fx_event.team.Value; //value="guests"/"hosts" matchfx_event.Timestamped = DateTime.Now; db.FixtureEvents.Add(matchfx_event); db.SaveChanges(); //HttpContext.Current.Request.ServerVariables("LOGON_USER") } else //Change in event mostly Goal Scorer { if (matchfx_event.Notification.Name.ToLower() != fx_event.type && matchfx_event.Player.ToLower() != fx_event.player.ToLower() && matchfx_event.ScoreLine != fx_event.score) { matchfx_event.NotificationID = wdb.Notifications.FirstOrDefault(f => f.Name.ToLower() == fx_event.type).ID; matchfx_event.Player = fx_event.player; //matchfx_event.Timestamped = DateTime.Now; matchfx_event.ScoreLine = fx_event.score; matchfx_event.Team = fx_event.team.Value; //value="guests"/"hosts" db.SaveChanges(); } else if (goalEvents.Contains(fx_event.type) & (matchfx_event.ScoreLine != fx_event.score | matchfx_event.Notification.Name.ToLower() != fx_event.type | matchfx_event.Player.ToLower() != fx_event.player.ToLower() | matchfx_event.Minute != fx_event.minute)) { matchfx_event.NotificationID = wdb.Notifications.FirstOrDefault(f => f.Name.ToLower() == fx_event.type).ID; matchfx_event.Player = fx_event.player; //matchfx_event.Timestamped = DateTime.Now; matchfx_event.ScoreLine = fx_event.score; matchfx_event.Minute = fx_event.minute; matchfx_event.Team = fx_event.team.Value; //value="guests"/"hosts" db.SaveChanges(); } } } } } } } else //there is no feed at all { ReturnLeague -= 1; } if (ReturnLeague == 0) { workingTimerInterval = AppUtil.NoFeedSecondInterval * 1000; //wait for 1 minute AppUtil.LogFileWrite(string.Format("No Feed Return For All Enabled League! Live Feed Service Waiting for {0} minute......", (AppUtil.NoFeedSecondInterval / 60).ToString())); } else { workingTimerInterval = AppUtil.RequestSecondInterval * 1000; } } // "http://pi.xmlscores.com/feed.html?f=xml&type=matches&contest=eng_pl&t1=1412509500&t2=1414237500&s=1&l=7&events=1&open=b4d88044654d82c4eccf19f8ae9c024f"; //string cmdText = "Insert into Fixture(MatchId,LeagueId,Host,Guest,Status,Unix_KickOff,IsPreKickOffSent,IsMatchSummSent,IsDailySummSent])VALUES(@matchid,@leagueid,@host,@guest,@status,@kickoff,@sent1,@sent2,@sent3)"; } else { workingTimerInterval = AppUtil.NoLeagueSecondInterval * 1000; //wait for 1 hour AppUtil.LogFileWrite(string.Format("No League Enabled Yet! Live Feed Service Waiting for {0} minute......", (AppUtil.NoLeagueSecondInterval / 60).ToString())); } db = new GoalAlertEntities(); qry = "delete from PastFixture where MatchID in (select MatchID from Fixture)"; db.Database.ExecuteSqlCommand(qry); qry = "delete PastFixtureEvent where MatchID in (select MatchID from FixtureEvent)"; db.Database.ExecuteSqlCommand(qry); foreach (Fixture finishedMatch in db.Fixtures.ToList()) { switch (finishedMatch.Status.ToLower()) //not_started, finished, active, postponed; { case "active": //update/ or add events if (feedTime.Subtract(finishedMatch.Local_KickOff.GetValueOrDefault()).TotalMinutes > new TimeSpan(AppUtil.LastActiveHour, 0, 0).TotalMinutes) { qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))" ; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0}"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); } break; case "finished": //update or add events //prepare for archive if (feedTime.Subtract(finishedMatch.Local_Finish.GetValueOrDefault()).TotalMinutes > PastActiveMinutes.TotalMinutes) { qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [IsPushed] >0 AND [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [IsPushed] =0 AND [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))" ; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [IsPushed] >0 AND [MatchID] ={0}"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); } db.SaveChanges(); break; case "not_started": //do nothing for now if (feedTime.Subtract(finishedMatch.Local_KickOff.GetValueOrDefault()).TotalMinutes > new TimeSpan(AppUtil.LastActiveHour, 0, 0).TotalMinutes) { qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))" ; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0}"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); } break; case "postponed": //update or add events if (feedTime.Subtract(finishedMatch.Local_KickOff.GetValueOrDefault()).TotalMinutes > new TimeSpan(AppUtil.LastActiveHour, 0, 0).TotalMinutes) { qry = @"INSERT INTO [dbo].[PastFixtureEvent] ([MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped]) SELECT [MatchID],[NotificationID],[Team],[Player],[Minute],[ScoreLine],[IsPushed],[Timestamped] FROM [dbo].[FixtureEvent] FE WHERE [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =FE.[MatchID] AND PE.[NotificationID]=FE.[NotificationID] AND PE.[Team]=FE.[Team] AND PE.[Player]=FE.[Player] AND PE.[Minute]=FE.[Minute] AND PE.[ScoreLine]=FE.[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"INSERT INTO PastFixture ([MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET]) SELECT [MatchID],[LeaugeID],[Host],[Guest],[Unix_KickOff],[Status],[Local_KickOff],[Pre_Local_KickOff],[Local_Finish],[IsPreKickOffSent],[IsMatchSummSent],[IsDailySummSent],[Score],[IsScoreAET] FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND NOT EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE P.[MatchID] ={0}))" ; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0} AND EXISTS(SELECT ID FROM [dbo].[PastFixtureEvent] PE WHERE PE.[MatchID] =[MatchID] AND PE.[NotificationID]=[NotificationID] AND PE.[Team]=[Team] AND PE.[Player]=[Player] AND PE.[Minute]=[Minute] AND PE.[ScoreLine]=[ScoreLine])"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND EXISTS(SELECT ID FROM [dbo].[PastFixture] P WHERE p.[MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); qry = @"DELETE FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0}"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID); qry = @"DELETE FROM [dbo].[Fixture] WHERE [MatchID] ={0} AND [Status] ={1} AND NOT EXISTS(SELECT ID FROM [dbo].[FixtureEvent] WHERE [MatchID] ={0})"; db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); //db.Database.ExecuteSqlCommand(qry, finishedMatch.MatchID, finishedMatch.Status); } break; default: break; } } } catch (DbEntityValidationException exception) { foreach (DbValidationError validationError in exception.EntityValidationErrors.SelectMany(error => error.ValidationErrors)) { AppUtil.LogFileWrite(string.Format("{0} - {1}", validationError.PropertyName, validationError.ErrorMessage)); } if (!string.IsNullOrEmpty(xmlDocInnerXml)) { AppUtil.LogFileWrite(xmlDocInnerXml); } workingTimerInterval = AppUtil.NoFeedSecondInterval * 1000; } catch (Exception rex) { AppUtil.LogFileWrite("Live Feed Service Run Error: " + rex.ToString()); //AppUtil.LogFileWrite("Live Feed Service Run Error(StackTrace): " + rex.StackTrace); //if (rex.InnerException != null) AppUtil.LogFileWrite("Live Feed Service Run Error:(InnerException) " + rex.InnerException.ToString()); if (!string.IsNullOrEmpty(xmlDocInnerXml)) { AppUtil.LogFileWrite(xmlDocInnerXml); } //Log detail to db workingTimerInterval = AppUtil.RequestSecondInterval * 1000; } finally { db.Dispose(); } }
public void Run(SoccerDataContext dbContext) { var dbFixture = dbContext.Fixtures.Single(x => x.ApiFootballId == this.ApiFootballFixtureId); var isFixtureFinal = string.Equals("Match Finished", dbFixture.Status, StringComparison.CurrentCultureIgnoreCase); if (!dbFixture.HomeTeamSeasonId.HasValue || !dbFixture.AwayTeamSeasonId.HasValue || !isFixtureFinal) { return; } var url = Feeds.FixtureFeed.GetFeedUrlByFixtureId(this.ApiFootballFixtureId); var rawJson = JsonUtility.GetRawJsonFromUrl(url); var feed = Feeds.FixtureFeed.FromJson(rawJson); Feeds.FixtureFeed.ApiFixture feedFixture = feed.Result.Fixtures.SingleOrDefault(); if (feedFixture == null) { return; } int dbFixtureId = dbFixture.FixtureId; int dbHomeTeamSeasonId = dbFixture.HomeTeamSeasonId.Value; int dbAwayTeamSeasonId = dbFixture.AwayTeamSeasonId.Value; int apiAwayTeamId = feedFixture.AwayTeam.TeamId; int apiHomeTeamId = feedFixture.HomeTeam.TeamId; int?homeCoachId = null; int?awayCoachId = null; var apiPlayerBases = GetApiPlayerBases(feedFixture); var dbPlayerSeasonDict = GetDbPlayerSeasonDict(dbContext, apiPlayerBases, dbFixture.CompetitionSeasonId); bool hasUpdate = false; Feeds.FixtureFeed.ApiLineup homeLineup = null; Feeds.FixtureFeed.ApiLineup awayLineup = null; #region GET FORMATIONS string homeFormation = null; string awayFormation = null; if (feedFixture.Lineups != null && feedFixture.Lineups.Count == 2) { string homeTeamName = feedFixture.HomeTeam.TeamName; string awayTeamName = feedFixture.AwayTeam.TeamName; // MISMATCH BETWEEN PLAYING TEAM NAMES AND LINEUP DICT KEYS HAS OCCURRED (API fixtureID: 188155) bool hasHomeTeamName = feedFixture.Lineups.Any(x => string.Equals(x.Key, homeTeamName, StringComparison.InvariantCultureIgnoreCase)); bool hasAwayTeamName = feedFixture.Lineups.Any(x => string.Equals(x.Key, awayTeamName, StringComparison.InvariantCultureIgnoreCase)); if (!hasHomeTeamName || !hasAwayTeamName) { if (hasHomeTeamName && !hasAwayTeamName) { awayTeamName = feedFixture.Lineups.Keys.Single(x => !string.Equals(x, homeTeamName, StringComparison.InvariantCultureIgnoreCase)); } else if (!hasHomeTeamName && hasAwayTeamName) { homeTeamName = feedFixture.Lineups.Keys.Single(x => !string.Equals(x, awayTeamName, StringComparison.InvariantCultureIgnoreCase)); } else { throw new KeyNotFoundException("INVALID KEYS FOUND FOR FIXTURE LINEUPS"); } } homeLineup = feedFixture.Lineups.Single(x => string.Equals(x.Key, homeTeamName, StringComparison.InvariantCultureIgnoreCase)).Value; awayLineup = feedFixture.Lineups.Single(x => string.Equals(x.Key, awayTeamName, StringComparison.InvariantCultureIgnoreCase)).Value; homeFormation = homeLineup.Formation; awayFormation = awayLineup.Formation; } #endregion GET FORMATIONS #region ENSURE COACHES EXIST if (this.CheckEntitiesExist) { if (homeLineup != null || awayLineup != null) { var apiCoachIds = new[] { homeLineup.CoachId, awayLineup.CoachId }; var dbCoaches = dbContext.Coaches.Where(x => apiCoachIds.Contains(x.ApiFootballId)).ToDictionary(x => x.ApiFootballId, y => y); if (homeLineup?.CoachId != null) { if (!dbCoaches.TryGetValue(homeLineup.CoachId.Value, out Coach dbHomeCoach)) { dbHomeCoach = new Coach { ApiFootballId = homeLineup.CoachId.Value, CoachName = homeLineup.Coach }; dbContext.Coaches.Add(dbHomeCoach); dbContext.SaveChanges(); dbCoaches.Add(dbHomeCoach.CoachId, dbHomeCoach); // DUE TO BAD DATA, HOME COACH AND AWAY COACH MAY BE THE SAME (API GAME 126635) } homeCoachId = dbHomeCoach.CoachId; } if (awayLineup?.CoachId != null) { if (!dbCoaches.TryGetValue(awayLineup.CoachId.Value, out Coach dbAwayCoach)) { dbAwayCoach = new Coach { ApiFootballId = awayLineup.CoachId.Value, CoachName = awayLineup.Coach }; dbContext.Coaches.Add(dbAwayCoach); dbContext.SaveChanges(); } awayCoachId = dbAwayCoach.CoachId; } } } #endregion ENSURE COACHES EXIST #region ENSURE PLAYERS EXIST if (this.CheckEntitiesExist) { var missingApiPlayerIds = apiPlayerBases?.Select(x => x.PlayerId).Where(x => !dbPlayerSeasonDict.ContainsKey(x)).ToList(); if (missingApiPlayerIds != null && missingApiPlayerIds.Count > 0) { foreach (var missingApiPlayerId in missingApiPlayerIds) { var apiPlayerBase = apiPlayerBases.Single(x => x.PlayerId == missingApiPlayerId); var dbPlayer = dbContext.Players.SingleOrDefault(x => x.ApiFootballId == missingApiPlayerId); if (dbPlayer == null) { dbPlayer = new Player { ApiFootballId = missingApiPlayerId, ApiFootballName = apiPlayerBase.PlayerName, PlayerName = apiPlayerBase.PlayerName }; } var dbPlayerSeason = new PlayerSeason { Player = dbPlayer, CompetitionSeasonId = dbFixture.CompetitionSeasonId }; dbContext.Add(dbPlayerSeason); } dbContext.SaveChanges(); dbPlayerSeasonDict = GetDbPlayerSeasonDict(dbContext, apiPlayerBases, dbFixture.CompetitionSeasonId); } } #endregion ENSURE PLAYERS EXIST #region UPDATE FORAMATION AND COACH IF NECESSARY if (homeCoachId.HasValue && dbFixture.HomeCoachId != homeCoachId) { dbFixture.HomeCoachId = homeCoachId; hasUpdate = true; } if (awayCoachId.HasValue && dbFixture.AwayCoachId != awayCoachId) { dbFixture.AwayCoachId = awayCoachId; hasUpdate = true; } if (!string.IsNullOrEmpty(homeFormation) && dbFixture.HomeFormation != homeFormation) { dbFixture.HomeFormation = homeFormation; hasUpdate = true; } if (!string.IsNullOrEmpty(awayFormation) && dbFixture.AwayFormation != awayFormation) { dbFixture.AwayFormation = awayFormation; hasUpdate = true; } #endregion UPDATE FORAMATION AND COACH IF NECESSARY #region FIXTURE EVENTS // HAVE EACH dbFixtureEvent AVAILABLE. ILookup IS AN IMMUTABLE TYPE, SO A DICTIONARY WITH THE COUNT IS ALSO NEEDED TO TRACK THE NUMBER OF OCCURANCES OF EACH EVENT. // THE ILookup IS JUST TO FIND FIND THE DB REFERENCE FOR EACH EVENT TO MANIPULATE var dbFixtureEventLookup = dbContext.FixtureEvents.Where(x => x.FixtureId == dbFixtureId).ToLookup(x => GetFixtureEventKey(x)); var dbFixtureEventToDeleteCountDict = dbContext.FixtureEvents.Where(x => x.FixtureId == dbFixtureId).ToList().GroupBy(x => GetFixtureEventKey(x)).ToDictionary(x => x.Key, y => y.Count()); var apiFixtureEvents = feedFixture.Events?.Where(x => x.TeamId.HasValue).ToList(); if (apiFixtureEvents != null && apiFixtureEvents.Count > 0) { foreach (var apiFixtureEvent in apiFixtureEvents) { int dbTeamSeasonId = apiFixtureEvent.TeamId == apiAwayTeamId ? dbAwayTeamSeasonId : dbHomeTeamSeasonId; int?dbPlayerSeasonId = null; if (dbPlayerSeasonDict != null && apiFixtureEvent.PlayerId.HasValue && dbPlayerSeasonDict.TryGetValue(apiFixtureEvent.PlayerId.Value, out int intPlayerSeasonId)) { dbPlayerSeasonId = intPlayerSeasonId; } int?dbSecondaryPlayerSeasonId = null; if (dbPlayerSeasonDict != null && apiFixtureEvent.SecondaryPlayerId.HasValue && dbPlayerSeasonDict.TryGetValue(apiFixtureEvent.SecondaryPlayerId.Value, out intPlayerSeasonId)) { dbSecondaryPlayerSeasonId = intPlayerSeasonId; } // IT IS POSSIBLE TO HAVE MULTIPLE IDENTICAL EVENTS IN THE SAME MINUTE // API FIXTURE ID 185030 - 2 GOALS BY SAME PLAYER IN SAME MINUTE // USE LOOKUP TO DETERMINE CORRECT AMOUNT OF EXISTENCE var eventKey = GetFixtureEventKey(apiFixtureEvent.Elapsed, apiFixtureEvent.ElapsedPlus, dbPlayerSeasonId, dbTeamSeasonId, apiFixtureEvent.EventType, apiFixtureEvent.EventDetail); var dbCount = dbFixtureEventToDeleteCountDict.TryGetValue(eventKey, out int tempInt) ? tempInt : 0; FixtureEvent dbFixtureEvent; if (dbCount == 0) { dbFixtureEvent = new FixtureEvent { EventComment = apiFixtureEvent.EventComments, EventDetail = apiFixtureEvent.EventDetail, EventType = apiFixtureEvent.EventType, FixtureId = dbFixtureId, EventTime = apiFixtureEvent.Elapsed, EventTimePlus = apiFixtureEvent.ElapsedPlus, PlayerSeasonId = dbPlayerSeasonId, SecondaryPlayerSeasonId = dbSecondaryPlayerSeasonId, TeamSeasonId = dbTeamSeasonId }; dbContext.FixtureEvents.Add(dbFixtureEvent); hasUpdate = true; } else { dbFixtureEvent = dbFixtureEventLookup[eventKey].Skip(dbCount - 1).First(); // TAKE LAST ENTRY IN LOOKUP. AS THE COUNT IN THE dbFixtureEventCount DICTIONARY IS DECREMENTED, THE SELECTED EVENT WILL MOVE DOWN THE LIST if (dbCount == 1) { dbFixtureEventToDeleteCountDict.Remove(eventKey); } else { dbFixtureEventToDeleteCountDict[eventKey] = dbCount - 1; } if ((!string.IsNullOrEmpty(apiFixtureEvent.EventComments) && dbFixtureEvent.EventComment != apiFixtureEvent.EventComments) || (!string.IsNullOrEmpty(apiFixtureEvent.EventDetail) && dbFixtureEvent.EventDetail != apiFixtureEvent.EventDetail) || (dbSecondaryPlayerSeasonId.HasValue && (!dbFixtureEvent.SecondaryPlayerSeasonId.HasValue || dbFixtureEvent.SecondaryPlayerSeasonId != dbSecondaryPlayerSeasonId)) || (!dbSecondaryPlayerSeasonId.HasValue && dbFixtureEvent.SecondaryPlayerSeasonId.HasValue)) { dbFixtureEvent.EventComment = apiFixtureEvent.EventComments; dbFixtureEvent.EventDetail = apiFixtureEvent.EventDetail; dbFixtureEvent.SecondaryPlayerSeasonId = dbSecondaryPlayerSeasonId; hasUpdate = true; } } } if (dbFixtureEventToDeleteCountDict.Count > 0) { foreach (var dbFixtureEventCountEntry in dbFixtureEventToDeleteCountDict) { var dbFixtureEventLookupEntry = dbFixtureEventLookup[dbFixtureEventCountEntry.Key]; int dbFixtureEventCount = dbFixtureEventLookupEntry.Count(); if (dbFixtureEventCount >= 1) { for (int i = dbFixtureEventCount; i >= 1; i--) { var dbFixtureEvent = dbFixtureEventLookupEntry.Skip(i - 1).First(); dbContext.FixtureEvents.Remove(dbFixtureEvent); } } } hasUpdate = true; } } #endregion FIXTURE EVENTS #region TEAM BOXSCORE var apiTeamStatsDict = feedFixture.TeamStatistics; if (apiTeamStatsDict == null) { if (!dbFixture.HasTeamBoxscores.HasValue || dbFixture.HasTeamBoxscores.Value) { hasUpdate = true; } dbFixture.HasTeamBoxscores = false; } else { var dbTeamBoxscores = dbContext.TeamBoxscores.Where(x => x.FixtureId == dbFixtureId); var dbHomeBoxscore = dbTeamBoxscores?.SingleOrDefault(x => x.TeamSeasonId == dbHomeTeamSeasonId); var dbAwayBoxscore = dbTeamBoxscores?.SingleOrDefault(x => x.TeamSeasonId == dbAwayTeamSeasonId); if (dbHomeBoxscore == null) { dbHomeBoxscore = new TeamBoxscore { FixtureId = dbFixtureId, TeamSeasonId = dbHomeTeamSeasonId, OppTeamSeasonId = dbAwayTeamSeasonId, IsHome = true }; dbContext.TeamBoxscores.Add(dbHomeBoxscore); hasUpdate = true; } if (dbAwayBoxscore == null) { dbAwayBoxscore = new TeamBoxscore { FixtureId = dbFixtureId, TeamSeasonId = dbAwayTeamSeasonId, OppTeamSeasonId = dbHomeTeamSeasonId, IsHome = false, }; dbContext.TeamBoxscores.Add(dbAwayBoxscore); hasUpdate = true; } if (PopulateTeamBoxscore(apiTeamStatsDict, x => x.Home, ref dbHomeBoxscore)) { hasUpdate = true; dbFixture.HasTeamBoxscores = true; } if (PopulateTeamBoxscore(apiTeamStatsDict, x => x.Away, ref dbAwayBoxscore)) { hasUpdate = true; dbFixture.HasTeamBoxscores = true; } if (!dbFixture.HasTeamBoxscores.HasValue) { dbFixture.HasTeamBoxscores = false; } } #endregion TEAM BOXSCORE #region PLAYER BOXSCORE if (apiPlayerBases != null && apiPlayerBases.Count > 0) { var dbPlayerBoxscores = dbContext.PlayerBoxscores .Include(x => x.PlayerSeason) .ThenInclude(y => y.Player) .Where(x => x.FixtureId == dbFixtureId && x.PlayerSeason != null && x.PlayerSeason.Player != null) .ToDictionary(x => x.PlayerSeason.Player.ApiFootballId, y => y); bool hasApiPlayerBoxscores = feedFixture?.PlayerBoxscores != null; bool hasApiLineups = feedFixture?.AllLineupPlayers != null; foreach (var apiPlayerBase in apiPlayerBases) { var dbPlayerSeasonId = dbPlayerSeasonDict[apiPlayerBase.PlayerId]; if (!dbPlayerBoxscores.TryGetValue(apiPlayerBase.PlayerId, out PlayerBoxscore dbPlayerBoxscore)) { dbPlayerBoxscore = new PlayerBoxscore { PlayerSeasonId = dbPlayerSeasonId, IsStarter = apiPlayerBase.IsStarter, FixtureId = dbFixtureId, TeamSeasonId = apiPlayerBase.TeamId == feedFixture.HomeTeam.TeamId ? dbHomeTeamSeasonId : dbAwayTeamSeasonId }; dbContext.PlayerBoxscores.Add(dbPlayerBoxscore); hasUpdate = true; } if (hasApiPlayerBoxscores || hasApiLineups) { Feeds.FixtureFeed.ApiPlayerBoxscore apiPlayerBoxscore = null; if (apiPlayerBase.BoxscorePlayerId.HasValue && apiPlayerBase.JerseyNumber.HasValue) { apiPlayerBoxscore = feedFixture.PlayerBoxscores.Where(x => x.PlayerId.HasValue).FirstOrDefault(x => x.Number == apiPlayerBase.JerseyNumber && x.TeamId == apiPlayerBase.TeamId); } Feeds.FixtureFeed.ApiLineupPlayerWithStarterStatus apiPlayerLineup = null; if (apiPlayerBase.LineupPlayerId.HasValue && apiPlayerBase.JerseyNumber.HasValue) { apiPlayerLineup = feedFixture.AllLineupPlayers.Where(x => x.PlayerId.HasValue).FirstOrDefault(x => x.Number == apiPlayerBase.JerseyNumber && x.TeamId == apiPlayerBase.TeamId); } if (apiPlayerBoxscore != null || apiPlayerLineup != null) { if (PopulatePlayerBoxscore(apiPlayerBoxscore, apiPlayerLineup, ref dbPlayerBoxscore)) { hasUpdate = true; } } } } } #endregion PLAYER BOXSCORE if (hasUpdate) { dbContext.SaveChanges(); } }
public MatchUpBuilder(FixtureEvent item) { if (item == null) throw new ArgumentNullException("item"); _item = item; }