Beispiel #1
0
        private static IEnumerable <SportEvent> List()
        {
            var events = new List <SportEvent>();

            var e1 = new SportEvent {
                Description = "Test", SportEventId = 1, MaxAttendees = 10, MinAttendees = 5
            };
            var e2 = new SportEvent {
                Description = "Test", SportEventId = 2, MaxAttendees = 10, MinAttendees = 5
            };
            var e3 = new SportEvent {
                Description = "Test", SportEventId = 3, MaxAttendees = 10, MinAttendees = 5
            };
            var e4 = new SportEvent {
                Description = "Test", SportEventId = 4, MaxAttendees = 10, MinAttendees = 5
            };
            var e5 = new SportEvent {
                Description = "Test", SportEventId = 5, MaxAttendees = 10, MinAttendees = 5, Reservation = new Reservation {
                    ReservationId = 1, SportEventId = 5
                }
            };

            events.Add(e1);
            events.Add(e2);
            events.Add(e3);
            events.Add(e4);
            events.Add(e5);

            return(events);
        }
Beispiel #2
0
        public void UpdateSportEventReturnsTrueOnSuccessfullyUpdatingSportEvent()
        {
            //Arrange
            var events            = List();
            var updatedSportEvent = new SportEvent
            {
                SportEventId = 2,             //Existing item ID
                Description  = "Test",
                MaxAttendees = 10,
                MinAttendees = 5
            };


            var mockRepo = new Mock <ISportEventRepository>();

            mockRepo.Setup(a => a.GetAllEvents()).Returns(events);
            mockRepo.Setup(a => a.UpdateSportEvent(It.IsAny <SportEvent>()));
            var manager = new SportEventManager(mockRepo.Object);

            //Act
            var result = manager.EditSportEvent(updatedSportEvent);

            //Assert
            Assert.True(result);
        }
Beispiel #3
0
        public void DeleteSportEventReturnsFalseOnFailedDeletingSportEvent()
        {
            //Arrange
            var events             = List();
            var sportEventToDelete = new SportEvent
            {
                SportEventId = 234,             //id does not exists
                Description  = "Test",
                MaxAttendees = 10,
                MinAttendees = 5
            };


            var mockRepo = new Mock <ISportEventRepository>();

            mockRepo.Setup(a => a.GetAllEvents()).Returns(events);
            mockRepo.Setup(a => a.DeleteSportEvent(It.IsAny <SportEvent>()));
            var manager = new SportEventManager(mockRepo.Object);

            //Act
            var result = manager.DeleteSportEvent(sportEventToDelete.SportEventId);

            //Assert
            Assert.False(result);
        }
Beispiel #4
0
        public void ViewSportEventReturnsSportEvent()
        {
            //Arrange
            var events           = List();
            var sportEventToRead = new SportEvent
            {
                SportEventId = 3,             //id  exists
                Description  = "Test",
                MaxAttendees = 10,
                MinAttendees = 5
            };


            var mockRepo = new Mock <ISportEventRepository>();

            mockRepo.Setup(a => a.GetAllEvents()).Returns(events);
            mockRepo.Setup(a => a.ReadSportEvent(It.IsAny <int>())).Returns(sportEventToRead);
            var manager = new SportEventManager(mockRepo.Object);

            //Act
            var result = manager.ViewSportEvent(3);

            //Assert
            Assert.IsType(sportEventToRead.GetType(), result);
        }
Beispiel #5
0
        public void AddSportEventSportEventManagerReturnsTrue()
        {
            //Arrange
            var events      = List();
            var eventToTest = new SportEvent
            {
                SportEventId = 0,                 // new SportEvent doesnt have an id assigned to it yet
                Description  = "Test",
                MaxAttendees = 10,
                MinAttendees = 5,
                Reservation  = new Reservation()
            };

            var mockRepo = new Mock <ISportEventRepository>();

            mockRepo.Setup(a => a.GetAllEvents()).Returns(events);
            mockRepo.Setup(a => a.AddSportEvent(It.IsAny <SportEvent>()));
            var manager = new SportEventManager(mockRepo.Object);

            //Act
            var result = manager.AddSportEvent(eventToTest);

            //Assert
            Assert.True(result);
        }
Beispiel #6
0
        public void Test()
        {
            var container   = EventAggregatorContainer.Instance;
            var sportEvent1 = new SportEvent
            {
                Bookmaker   = Bookmaker.Fonbet,
                TitleOrigin = "Калуга U17 — Ротор-Волгоград U17",
                Id          = "123123"
            };

            var sportEvent2 = new SportEvent
            {
                Bookmaker   = Bookmaker.Marathon,
                TitleOrigin = "Калуга до 17 - Ротор до 17",
                Id          = "444555"
            };

            container.AddEvents(new SportEvent[] { sportEvent1 });
            container.AddEvents(new SportEvent[] { sportEvent2 });

            var aggregator = container.GetEventAggregator(EventNameHelper.GetEventId(sportEvent1));

            Assert.NotNull(aggregator);

            Assert.Equal("Калуга", aggregator.Team1);
            Assert.Equal("Ротор-Волгоград", aggregator.Team2);
        }
        public async void EventsController_GetById_PositiveResult()
        {
            var logMock    = new Mock <ILogger <EventsController> >();
            var evRepoMock = new Mock <IEventsRepository>();

            var expectedEvent =
                new SportEvent()
            {
                EventId    = 1,
                SportId    = 2,
                EventName  = "Fake Event",
                EventDate  = new DateTime(1870, 4, 22),
                Team1Price = 1.23M,
                Team2Price = 4.56M,
                DrawPrice  = 7.89M
            };

            evRepoMock.Setup(
                r => r.GetEventById(It.IsAny <int>()))
            .ReturnsAsync(expectedEvent);

            var evControl = new EventsController(logMock.Object, evRepoMock.Object);
            var result    = await evControl.Get(1);

            Assert.NotNull(result);
            Assert.True(result.Result == null);
            Assert.IsType <ActionResult <SportEvent> >(result);
            Assert.IsType <SportEvent>(result.Value);
            Assert.NotNull(result.Value);

            Assert.Equal(expectedEvent, result.Value);
        }
Beispiel #8
0
        public void UpdateSportEventReturnsFalseOnFailedUpdatingSportEvent()
        {
            //Arrange
            var events            = List();
            var updatedSportEvent = new SportEvent
            {
                SportEventId = 324,             //id does not exist
                Description  = "Test",
                MaxAttendees = 10,
                MinAttendees = 5
            };


            var mockRepo = new Mock <ISportEventRepository>();

            mockRepo.Setup(a => a.GetAllEvents()).Returns(events);
            mockRepo.Setup(a => a.UpdateSportEvent(It.IsAny <SportEvent>()));
            var manager = new SportEventManager(mockRepo.Object);

            //Act
            var result = manager.EditSportEvent(updatedSportEvent);

            //Assert
            Assert.False(result);
        }
Beispiel #9
0
        //TODO: use IndexSportEvent
        public static List <Fork> GetFork(SportEvent sportEvent1, SportEvent sportEvent2)
        {
            if (sportEvent1 == null)
            {
                throw new ArgumentNullException(nameof(sportEvent1));
            }

            if (sportEvent2 == null)
            {
                throw new ArgumentNullException(nameof(sportEvent2));
            }

            //TODO: add
            //12 vs x
            //x vs 12+

            var res = new List <Fork>();

            //1 vs x2
            res.Add(Win1VSwin2OrDraw(sportEvent1, sportEvent2));

            //2 vs 1x
            res.Add(Win2VSWin1OrDraw(sportEvent1, sportEvent2));

            //1x vs 2
            res.Add(Win1OrDrawVSwin2(sportEvent1, sportEvent2));

            //2x vs 1
            res.Add(Win2OrDrawVSwin1(sportEvent1, sportEvent2));

            res = res.Where(u => u != null).ToList();

            return(res);
        }
Beispiel #10
0
        public List <Rate> GetUsersRates(string userId)
        {
            List <Rate> rates = new List <Rate>();

            using (SqlConnection connection = new SqlConnection(_connectingString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand
                {
                    CommandText = "GetUsersRates",
                    CommandType = System.Data.CommandType.StoredProcedure,
                    Connection  = connection
                };
                command.Parameters.AddWithValue("@userId", userId);
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        int      id      = (int)reader["Id"];
                        DateTime date    = (DateTime)reader["DateTime"];
                        int      eventId = (int)reader["EventId"];

                        SportEvent sportEvent = GetSportEvent(eventId);

                        rates.Add(new Rate()
                        {
                            Id = id, DateTime = date, Event = sportEvent, UserId = userId
                        });
                    }
                }
                reader.Close();
            }
            return(rates);
        }
        public void CheckNullFields()
        {
            SportEvent nullDateEvent = new SportEvent();

            nullDateEvent.SportType = this.sportType;
            nullDateEvent.Results   = new List <Result>();
            nullDateEvent.Results.Add(this.res1);
            nullDateEvent.Results.Add(this.res2);

            SportEvent nullSportTypeEvent = new SportEvent();

            nullSportTypeEvent.Date    = new DateTime(2016, 11, 21, 16, 30, 0);
            nullSportTypeEvent.Results = new List <Result>();
            nullSportTypeEvent.Results.Add(this.res1);
            nullSportTypeEvent.Results.Add(this.res2);

            SportEvent nullResultsEvent = new SportEvent();

            nullResultsEvent.Date      = new DateTime(2016, 11, 21, 16, 30, 0);
            nullResultsEvent.SportType = this.sportType;

            Assert.IsFalse(this.sportEvent1.Equals(nullDateEvent) || nullDateEvent.Equals(this.sportEvent1) ||
                           this.sportEvent1.Equals(nullSportTypeEvent) || nullSportTypeEvent.Equals(this.sportEvent1) ||
                           this.sportEvent1.Equals(nullResultsEvent) || nullResultsEvent.Equals(this.sportEvent1));
        }
Beispiel #12
0
        public void AddEventSavesToDbWithCorrectId()
        {
            // Arrange
            int        sportEventId = 234;
            SportEvent sportEvent   = new SportEvent()
            {
                ID                = sportEventId,
                EventTime         = DateTime.Now,
                EventSport        = "Cricket",
                IsTentative       = false,
                Longitude         = 30.45,
                Latitude          = -80.24,
                PplAttendingCount = 3,
                MaxPeopleAllowed  = 15,
                EquipmentList     = "none"
            };
            var beforeEventCount = _context.SportEvent.Count();

            // Act
            var result = _controller.Create(sportEvent);

            // Assert
            SportEvent savedSportEvent = _context.SportEvent.Single(x => x.EventSport == "Cricket" && x.PplAttendingCount == 3);

            Assert.Equal(sportEventId, savedSportEvent.ID);
            Assert.Equal(beforeEventCount + 1, _context.SportEvent.Count());
        }
Beispiel #13
0
        public void AddsNewRecord()
        {
            // Arrange
            var repository         = this.fixture.ServiceProvider.GetService <IRepository <SportEvent> >();
            var readonlyRepository = this.fixture.ServiceProvider.GetService <IReadonlyRepository <SportEvent> >();
            var unitOfWork         = this.fixture.ServiceProvider.GetService <IUnitOfWork>();

            var newEvent = new SportEvent()
            {
                Name              = "New Event",
                OddsForDraw       = 1,
                OddsForFirstTeam  = 1,
                OddsForSecondTeam = 1,
                StartDate         = DateTime.Now
            };

            // Act
            var previousCount = readonlyRepository.GetAll().Count();

            newEvent = repository.Add(newEvent);
            unitOfWork.CommitChanges();
            var count = readonlyRepository.GetAll().Count();

            // Assert
            Assert.Equal(previousCount + 1, count); // The new event was inserted
            Assert.True(newEvent.Id > 0);           // Id was assigned
        }
Beispiel #14
0
        public async Task <IActionResult> AddSportEvent([FromBody] SportEvent sportEvent)
        {
            if (!TryValidateModel(sportEvent))
            {
                return(BadRequest(ModelState));
            }

            SportEvent sportEventToAdd = sportEvent;
            var        authId          = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
            User       loggedInUser    = await _sportEventRepository.GetUserFromAuthId(authId);

            sportEventToAdd.Admins = new List <SportEventAdmins>();
            sportEventToAdd.Admins.Add(new SportEventAdmins {
                User = loggedInUser
            });
            sportEventToAdd.Participants = new List <SportEventParticipants>();
            sportEventToAdd.Participants.Add(new SportEventParticipants {
                User = loggedInUser
            });


            _sportEventRepository.AddSportEvent(sportEventToAdd);

            return(Created(Request.Path, sportEvent));
        }
        public void TestDeleteSportEventFailAndThrowsExceptionAndReturnsActionResult()
        {
            //Arrange
            var dummySportEvent = new SportEvent
            {
                Name           = "Voetbaltoernooi",
                Description    = "Potje voetballen voor de starters",
                MaxAttendees   = 5,
                MinAttendees   = 20,
                SportId        = 2,
                EventStartTime = DateTime.Today.AddHours(11),
                EventEndTime   = DateTime.Today.AddHours(13)
            };

            var mockSportManager      = new Mock <ISportManager>();
            var mockSportEventManager = new Mock <ISportEventManager>();
            var mockTempData          = new Mock <ITempDataDictionary>();
            var controller            = new SportEventController(mockSportEventManager.Object, mockSportManager.Object)
            {
                TempData = mockTempData.Object
            };

            mockSportEventManager.Setup(sm => sm.DeleteSportEvent(It.IsAny <int>())).Throws <Exception>();

            //Act
            var result = controller.Delete(dummySportEvent);

            //Assert
            Assert.IsType(typeof(RedirectToActionResult), result);
        }
Beispiel #16
0
        public SportEventDetailDTO MapToDTO(SportEvent source)
        {
            SportEventDetailDTO target = new SportEventDetailDTO();

            target.Id          = source.Id;
            target.Date        = source.Date;
            target.Description = source.Description;
            target.Title       = source.Title;
            target.ImagePath   = source.ImagePath;

            AccountMapper accountMapper = new AccountMapper();

            target.Owner = accountMapper.MapToDTO(source.Owner);

            AdressMapper adressMapper = new AdressMapper();

            target.Adress = adressMapper.MapToDTO(source.Adress);

            SportMapper sportMapper = new SportMapper();

            target.Category = sportMapper.MapToDTO(source.Category);

            AccountSimpleMapper accountSimpleMapper = new AccountSimpleMapper();

            target.Attendees = new HashSet <AccountSimpleDTO>();

            foreach (var ac in source.Attendees)
            {
                target.Attendees.Add(accountSimpleMapper.MapToDTO(ac));
            }

            return(target);
        }
        public async Task <ActionResult> CreateEvent(SportEventViewModel newEvent)
        {
            if (ModelState.IsValid)
            {
                string wwRootPath = _hostEnvironment.WebRootPath;
                string fileName   = Path.GetFileNameWithoutExtension(newEvent.imagefile.FileName);
                string extension  = Path.GetExtension(newEvent.imagefile.FileName);
                fileName     = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                newEvent.img = fileName;
                string path = Path.Combine(wwRootPath + "/Image/", fileName);
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await newEvent.imagefile.CopyToAsync(fileStream);
                }
            }
            var _event = new SportEvent()
            {
                title       = newEvent.title,
                description = newEvent.description,
                date        = newEvent.date,
                img         = newEvent.img
            };

            _SportEventRepository.Save(_event);

            return(RedirectToAction("Index"));
        }
Beispiel #18
0
        /// <summary>
        /// Deletes from favorites.
        /// </summary>
        /// <param name="userLogin">The user login.</param>
        /// <param name="sportEventId">The sport event identifier.</param>
        /// <exception cref="FavoriteNotExistsException"></exception>
        /// <exception cref="InternalProblemException"></exception>
        public void DeleteFromFavorites(string userLogin, long sportEventId)
        {
            UserProfile user = CheckUser(userLogin);

            SportEvent sportEvent = CheckSportEvent(sportEventId);

            Favorite favorite = FavoritesDao.FindFavoriteByUserIdAndEventId(user.userId, sportEventId);

            //foreach(Favorite element in user.Favorites)
            //{
            //    if (element.fv_event == sportEventId)
            //    {
            //        favorite = element;
            //        break;
            //    }
            //}

            if (favorite == null)
            {
                throw new FavoriteNotExistsException(userLogin, sportEventId);
            }
            else
            {
                try
                {
                    user.Favorites.Remove(favorite);
                    sportEvent.Favorites.Remove(favorite);
                    FavoritesDao.Remove(favorite.fv_Id);
                }
                catch (NotSupportedException e)
                {
                    throw new InternalProblemException(e);
                }
            }
        }
        public IActionResult UpdateNumbers(
            [FromServices] AppDatabase db,
            [FromBody] SportEventViewModel viewModel,
            [FromQuery, FromForm] long?id = null
            )
        {
            long queryId = id ?? (long)viewModel.Id;

            SportEvent model = db.Events.Where(x => x.Id == queryId).FirstOrDefault();

            if (model is null)
            {
                return(NotFound());
            }

            model.AwayTeamOdds = viewModel.AwayTeamOdds;
            model.HomeTeamOdds = viewModel.HomeTeamOdds;
            model.DrawOdds     = viewModel.DrawOdds;

            model.AwayTeamScore = viewModel.AwayTeamScore;
            model.HomeTeamScore = viewModel.HomeTeamScore;

            db.SaveChanges();

            return(Ok());
        }
Beispiel #20
0
        private SportEvent EventGetter(IEnumerable <IElement> tds)
        {
            var result = new SportEvent();

            //title
            var titleTd = tds.Skip(1).First();
            var div     = titleTd.QuerySelector(".table__match-title");

            result.Id = div.QuerySelector("span").TextContent;
            var titleEl = div.QuerySelector("a.table__match-title-text");

            if (titleEl == null)
            {
                Console.WriteLine("Title element is null");
            }
            result.TitleOrigin = titleEl?.TextContent;

            result.Win1          = GetValue(tds, 2);
            result.Draw          = GetValue(tds, 3);
            result.Win2          = GetValue(tds, 4);
            result.Win1OrDraw    = GetValue(tds, 5);
            result.Win1OrWin2    = GetValue(tds, 6);
            result.Win2OrDraw    = GetValue(tds, 7);
            result.ForaText1     = GetValue(tds, 8);
            result.ForaTeam1     = GetValue(tds, 9);
            result.ForaText2     = GetValue(tds, 10);
            result.ForaTeam2     = GetValue(tds, 11);
            result.TotalMoreText = GetValue(tds, 12);
            result.TotalLessText = GetValue(tds, 12);
            result.TotalMore     = GetValue(tds, 13);
            result.TotalLess     = GetValue(tds, 14);

            return(result);
        }
Beispiel #21
0
        public ActionResult addEvent(SportEvent toAdd)
        {
            db.events.Add(toAdd);
            db.SaveChanges();

            return(RedirectToAction("addEvent"));
        }
Beispiel #22
0
        public ActionResult changeEventState(string state, int eventId)
        {
            SportEvent current = db.events.Find(eventId);

            if (state != eventState.live && state != eventState.preview && state != eventState.finished)
            {
                TempData["badState"] = "неопознанное состояние события";
                return(RedirectToAction("Index", "Home"));
            }

            if (state == eventState.preview)
            {
                TempData["badState"] = "невозможно перевести событие в состояние ожидания";
                return(RedirectToAction("Index", "Home"));
            }

            if (state == eventState.live)
            {
                current.state = eventState.live;
                db.SaveChanges();
                TempData["goodState"] = "состояние изменено";
                return(RedirectToAction("Index", "Home"));
            }

            if (state == eventState.finished)
            {
                current.state = eventState.finished;
                updateBets(current);
                db.SaveChanges();
                TempData["goodState"] = "состояние изменено";
                return(RedirectToAction("Index", "Home"));
            }

            return(RedirectToAction("Index", "View"));
        }
Beispiel #23
0
        private float myBetCoefficient(Bet myBet, SportEvent sevent)
        {
            switch (myBet.betType)
            {
            case "П1":
                return(sevent.firstWin);

            case "П2":
                return(sevent.secondWin);

            case "Н":
                return(sevent.gameTie);

            case "НН":
                return(sevent.overallTie);

            case "Н1":
                return(sevent.tieByFirst);

            case "Н2":
                return(sevent.tieBySecond);

            case "Тотал":
                return(sevent.total);

            case "Б":
                return(sevent.b);

            case "М":
                return(sevent.m);
            }

            return(0.0f);
        }
Beispiel #24
0
        public ActionResult doBet(Bet toAdd)
        {
            try
            {
                ApplicationUser currentUser = CurrentUser();
                if (currentUser.userStatus == "baned")
                {
                    TempData["badState"] = "Вы не можете делать ставки, вы забанены";
                    return(RedirectToAction("Index", "Home"));
                }
                SportEvent current = db.events.Single(a => a.Id == toAdd.betEventId);
                if (current.state != eventState.preview && current.state != eventState.live)
                {
                    TempData["badState"] = "Невозможно сделать ставку на это событие";
                    return(RedirectToAction("Index", "Home"));
                }

                if (toAdd.amount > currentUser.userAmount)
                {
                    TempData["badState"] = "Недостаточно денег на балансе, пополните баланс";
                    return(RedirectToAction("Index", "Home"));
                }
                toAdd.userId            = currentUser.Id;
                toAdd.state             = "waiting";
                currentUser.userAmount -= toAdd.amount;
                db.bets.Add(toAdd);
                db.SaveChanges();
                TempData["goodState"] = "Ставка сделана!";
                return(RedirectToAction("Index", "Home"));
            }
            catch (ArgumentNullException e)
            {
                return(HttpNotFound());
            }
        }
        public async Task <ActionResult <SportEvent> > Create(SportEvent sportEvent)
        {
            sportEvent = repository.Add(sportEvent);
            await unitOfWork.CommitChangesAsync();

            return(CreatedAtAction(nameof(Get), new { id = sportEvent.Id }, sportEvent));
        }
Beispiel #26
0
        public async Task <int> UpsertEvent(SportEvent ev)
        {
            if (ev == null)
            {
                throw new ArgumentNullException("ev");
            }

            using var db = Connection;

            int rows = 0;

            try
            {
                rows = await db.ExecuteAsync("UpsertEvent",
                                             new
                {
                    EventId    = ev.EventId,
                    SportId    = ev.SportId,
                    EventName  = ev.EventName,
                    EventDate  = ev.EventDate,
                    Team1Price = ev.Team1Price,
                    DrawPrice  = ev.DrawPrice,
                    Team2Price = ev.Team2Price
                },
                                             commandType : CommandType.StoredProcedure);
            }
            catch { }

            return(rows);
        }
Beispiel #27
0
 public void EditEvent(SportEvent sportEvent)
 {
     UpdateEventsStatus();
     using (SqlConnection connection = new SqlConnection(_connectingString))
     {
         connection.Open();
         SqlCommand command = new SqlCommand
         {
             CommandText = "EditEvent",
             CommandType = System.Data.CommandType.StoredProcedure,
             Connection  = connection
         };
         command.Parameters.AddWithValue("@Id", sportEvent.Id);
         command.Parameters.AddWithValue("@date", sportEvent.DateTime);
         command.Parameters.AddWithValue("@status", sportEvent.Status);
         command.Parameters.AddWithValue("@kindOfSportId", sportEvent.KindOfSport.Id);
         command.Parameters.AddWithValue("@teamId1", sportEvent.FirstTeam.Id);
         command.Parameters.AddWithValue("@teamId2", sportEvent.SecondTeam.Id);
         command.Parameters.AddWithValue("@coef1", sportEvent.FirstCoeficient);
         command.Parameters.AddWithValue("@coef2", sportEvent.SecondCoeficient);
         command.Parameters.AddWithValue("@coef3", sportEvent.ThirdCoeficient);
         command.Parameters.AddWithValue("@coef4", sportEvent.FourthCoeficient);
         command.ExecuteNonQuery();
     }
 }
Beispiel #28
0
        public void UpdateSportEvent_ReflectsUpdate()
        {
            // Add sportevent to db
            SportEvent sportEvent = new SportEvent()
            {
                ID                = 13,
                EventTime         = DateTime.Now,
                EventSport        = "Mountain Biking",
                IsTentative       = false,
                Longitude         = 30.123,
                Latitude          = -80.432,
                PplAttendingCount = 2,
                MaxPeopleAllowed  = 10,
                EquipmentList     = "mountain bike, helmet"
            };

            _controller.Create(sportEvent);

            // Get added sport event to edit it
            var        result         = _controller.Edit(13) as ViewResult;
            SportEvent retrievedEvent = (SportEvent)result.ViewData.Model;

            // Check PplAttendingCount is 2
            Assert.Equal(2, retrievedEvent.PplAttendingCount);

            // Change PplAttendingCount to 4
            retrievedEvent.PplAttendingCount = 4;
            _controller.Edit(retrievedEvent);

            // Lookback up to verify change
            var result2      = _controller.Details(13) as ViewResult;
            var changedEvent = (SportEvent)result2.ViewData.Model;

            Assert.Equal(4, changedEvent.PplAttendingCount);
        }
Beispiel #29
0
        private static void Upload_InsertData(AppDatabase db, SportEventViewModel[] eventViewModels)
        {
            EventSportViewModel[] sportVms = eventViewModels.Select(x => x.Sport).DistinctBy(x => x.Id).ToArray();
            var newSportIds = new Dictionary <ulong, long>();

            foreach (EventSportViewModel sportVm in sportVms)
            {
                Sport model = Map.ToModel(sportVm);
                long  dbId  = db.Sports.Add(model).Entity.Id;
                newSportIds.Add(sportVm.Id, dbId);
            }

            EventLeagueViewModel[] leagueVms = eventViewModels.Select(x => x.League).DistinctBy(x => x.Id).ToArray();
            var newLeagueIds = new Dictionary <ulong, long>();

            foreach (EventLeagueViewModel leagueVm in leagueVms)
            {
                League model = Map.ToModel(leagueVm);
                model.SportId = newSportIds[leagueVm.SportId];
                long dbId = db.Leagues.Add(model).Entity.Id;
                newLeagueIds.Add(leagueVm.Id, dbId);
            }

            foreach (SportEventViewModel eventVm in eventViewModels)
            {
                SportEvent model = Map.ToModel(eventVm);
                model.LeagueId = newLeagueIds[eventVm.League.Id];
                model.SportId  = newSportIds[eventVm.Sport.Id];
                db.Events.Add(model);
            }
        }
Beispiel #30
0
        private SportEvent GetEvent(IEnumerable <IElement> allTds, string eventTitle, string eventId)
        {
            var sportEvent = new SportEvent()
            {
                TitleOrigin = eventTitle,
                Id          = eventId
            };

            sportEvent.Win1       = GetText(allTds, 2);
            sportEvent.Draw       = GetText(allTds, 3);
            sportEvent.Win2       = GetText(allTds, 4);
            sportEvent.Win1OrDraw = GetText(allTds, 5);
            sportEvent.Win1OrWin2 = GetText(allTds, 6);
            sportEvent.Win2OrDraw = GetText(allTds, 7);

            sportEvent.ForaText1 = GetForaText(allTds, 8);
            sportEvent.ForaTeam1 = GetText(allTds, 8);

            sportEvent.ForaText2 = GetForaText(allTds, 9);
            sportEvent.ForaTeam2 = GetText(allTds, 9);

            sportEvent.TotalLessText = GetToalText(allTds, 10);
            sportEvent.TotalLess     = GetText(allTds, 10);

            sportEvent.TotalMoreText = GetToalText(allTds, 11);
            sportEvent.TotalMore     = GetText(allTds, 11);

            return(sportEvent);
        }
Beispiel #31
0
 /// <summary>        
 /// Set SportEvent field</summary>
 /// <param name="sportEvent_">Nullable field value to be set</param>      
 public void SetSportEvent(SportEvent? sportEvent_)
 {
     SetFieldValue(58, 0, sportEvent_, Fit.SubfieldIndexMainField);
 }
Beispiel #32
0
        public void Refresh()
        {
            this.events = new List<SportEvent>();
            var webGet = new HtmlWeb();
            var footballPage = webGet.Load(@"https://www.marathonbet.co.uk/su/popular/Football/");
            var eventsInfoNodes = footballPage.DocumentNode.SelectNodes("//div[@class='block-events-head ']//a[@class='hover-underline block']");
            var teamInfo = footballPage.DocumentNode.SelectNodes("//table[@class='foot-market']");
            var eventInfo = new EventInfo();
            var coefSet = new CoefSet { BetsName = "Marafon" };
            foreach (var eventInfoSplit in eventsInfoNodes.Select(eventInfoNode => eventInfoNode.InnerText.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)))
            {
                eventInfo.TypeSport = eventInfoSplit[0];
                for (var i = 0; i < eventInfoSplit.Count(); i++)
                {
                    eventInfo.Info += eventInfoSplit[i];
                }

                foreach (var table in teamInfo)
                {
                    var body = table.ChildNodes.Where(x => x.Name == "tbody");
                    var i = 0;
                    foreach (var htmlNode in body)
                    {
                        var teamSplit = htmlNode.Attributes["data-event-name"].Value.Split(
                            new[] { " - " },
                            StringSplitOptions.RemoveEmptyEntries);

                        eventInfo.FirstTeam = teamSplit[0];
                        eventInfo.SecondTeam = teamSplit[1];

                        var eventDate = htmlNode.SelectNodes("//td[@class='date']")[i].InnerText;
                        eventInfo.Date = ParseDate(eventDate);
                        i++;
                        var trs = htmlNode.SelectNodes("//tr[@class='event-header']");
                        foreach (var coefs in trs.Select(tr => tr.SelectNodes("td/span")))
                        {
                            coefSet.FirstWin = ParseDecimal(coefs[0].InnerText);
                            coefSet.DrawnGame = ParseDecimal(coefs[1].InnerText);
                            coefSet.SecondWin = ParseDecimal(coefs[2].InnerText);
                            coefSet.FirstWinOrDrawnGame = ParseDecimal(coefs[3].InnerText);
                            coefSet.FirstWinOrSecondWin = ParseDecimal(coefs[4].InnerText);
                            coefSet.SecondWinOrDrawnGame = ParseDecimal(coefs[5].InnerText);
                            coefSet.FirstFora = ParseCoefAndGoals(coefs[6].ParentNode.InnerText);
                            coefSet.SecondFora = ParseCoefAndGoals(coefs[7].ParentNode.InnerText);
                            coefSet.Less = ParseCoefAndGoals(coefs[8].ParentNode.InnerText);
                            coefSet.Larger = ParseCoefAndGoals(coefs[9].ParentNode.InnerText);
                        }

                        var sportEvent = new SportEvent(eventInfo, coefSet);
                        this.events.Add(sportEvent);
                    }
                }
            }
        }
Beispiel #33
0
 IEventTypes certainEvent(string eventtype)
 {
     IEventTypes eventType;
     eventtype = eventtype.ToUpper();
     switch (eventtype)
     {
         case "LOCAL EVENT":
             eventType = new LocalEvent();
             break;
         case "PUBLIC EVENT":
             eventType = new PublicEvent();
             break;
         case "SPORT EVENT":
             eventType = new SportEvent();
             break;
         case "MEET EVENT":
             eventType = new MeetEvent();
             break;
         default:
             return null;
     }
     return eventType;
 }