Beispiel #1
0
        private string GenerateEmailDetails(AMFUserLogin playerInfo, PlayerSeason playerSeasonInfo)
        {
            string retVal = "\n" + "\n" + "First Name: " + playerInfo.FirstName + "\n" + "Last Name: " + playerInfo.LastName + "\n" + "Email Address: " + playerInfo.Email + "\n" +
                            "USA Hockey Number: " + playerInfo.USAHockeyNum + "\n" + "DOB: " + playerInfo.DOB + "\n" + "Address: " + playerInfo.Address1 + " " + playerInfo.Address2 + "\n" +
                            "City: " + playerInfo.City + "\n" + "State: " + playerInfo.State + "\n" + "Zip Code: " + playerInfo.ZipCode + "\n" + "Primary Phone: " + playerInfo.Phone1 + "\n" +
                            "Secondary Phone: " + playerInfo.Phone2 + "\n" + "Emergency Contacts: " + playerInfo.Emergency1 + ", " + playerInfo.Emergency2 + "\n" + "Years Experience: " + playerInfo.YearsExp + "\n" +
                            "Experience Level: " + playerInfo.Level + "\n" + "\n" + "Programs requested: " + "\n";

            for (int i = 0; i < playerSeasonInfo.Programs.Count; i++)
            {
                retVal = retVal + playerSeasonInfo.Programs[i].Name + "  ";
            }

            retVal = retVal + "/n" + "/n" + "Payment Details listed below: " + "/n";
            for (int x = 0; x < playerSeasonInfo.Payments.Count; x++)
            {
                retVal = retVal + "Payment Method: " + playerSeasonInfo.Payments[x].PaymentMethod + ", ";
                if (playerSeasonInfo.Payments[x].PaymentMethod.Equals("Check"))
                {
                    retVal = retVal + "Check Number: " + playerSeasonInfo.Payments[x].AdditionalDetails + ", ";
                }
                retVal = retVal + "Payment Amount: " + playerSeasonInfo.Payments[x].Amount + ", ";
                retVal = retVal + "Payment Promised On: " + playerSeasonInfo.Payments[x].DateSubmitted + " ";
            }
            return(retVal);
        }
Beispiel #2
0
        public ActionResult ConfirmPromise(long paymentId, long playerSeasonId)
        {
            if (this.CurrentPrincipal == null || this.CurrentPrincipal.IsAuthenticated == false)
            {
                return(this.RedirectToAction("Signin", "User"));
            }
            else
            {
                Payment targetPayment = this.ServiceManager.PaymentService.ConfirmPromise(this.CurrentPrincipal.User.Id, playerSeasonId, paymentId);

                if (targetPayment != null)
                {
                    //ADD CODE HERE FOR SENDING EMAIL TO PLAYER AND KERRI ABOUT PAYMENT
                    EmailService       sendPlayerEmail  = new EmailService();
                    EmailConfiguration emailConfig      = new EmailConfiguration();
                    AMFUserLogin       playerDemoInfo   = this.ServiceManager.UserService.GetByEmail(this.CurrentPrincipal.User.Email);
                    PlayerSeason       playerSeasonInfo = this.ServiceManager.SeasonService.GetPlayerSeasonById(playerSeasonId);

                    sendPlayerEmail.SendThankYouForPaymentEmail(this.CurrentPrincipal.User.Email, emailConfig, playerDemoInfo, playerSeasonInfo);

                    return(this.RedirectToAction("Season"));
                }
                else
                {
                    ConfirmPaymentModel retVal = new ConfirmPaymentModel();

                    PlayerSeason playerSeason = this.ServiceManager.SeasonService.GetPlayerSeasonById(playerSeasonId);
                    retVal.PaymentDetails = playerSeason.Payments.FirstOrDefault(p => p.Id == paymentId);
                    retVal.PlayerInfo     = this.CurrentPrincipal.User;
                    return(this.View("Confirm", retVal));
                }
            }
        }
Beispiel #3
0
 public ActionResult Edit([Bind(Include = "PlayerSeasonId,SeasonString,GamedMatches,Goals,Assists,PlayerId,TeamSeasonId")] PlayerSeason playerSeason)
 {
     try
     {
         if (ModelState.IsValid)
         {
             PlayerSeason find = db.PlayerSeasons.Find(playerSeason.PlayerSeasonId);
             find.Assists         = playerSeason.Assists;
             find.GamedMatches    = playerSeason.GamedMatches;
             find.Goals           = playerSeason.Goals;
             db.Entry(find).State = EntityState.Modified;
             db.SaveChanges();
             return(RedirectToAction("Index"));
         }
         Player player = new Player();
         player.Name         = (string)TempData["Name"];
         player.Surname      = (string)TempData["Surname"];
         playerSeason.Player = player;
         return(View(playerSeason));
     }
     catch (Exception e)
     {
         ViewBag.Error = e.Message;
         return(View("Error"));
     }
 }
Beispiel #4
0
        public PlayerSeasonPaymentModel Get(long id)
        {
            PlayerSeasonPaymentModel retVal = new PlayerSeasonPaymentModel();

            PlayerSeason playerSeason = this.Services.SeasonService.GetPlayerSeasonById(id);

            if (playerSeason != null)
            {
                retVal.PlayerSeasonId = playerSeason.Id;
                retVal.TotalCost      = playerSeason.CalculateAmountDue();
                retVal.Payments       = new List <DisplaySeasonPayment>();

                if (playerSeason.Payments != null)
                {
                    foreach (Payment seasonPayment in playerSeason.Payments)
                    {
                        retVal.Payments.Add(new DisplaySeasonPayment(seasonPayment));
                    }
                }
            }
            else
            {
                retVal.PlayerSeasonId = 0;
                retVal.TotalCost      = 0;
                retVal.Payments       = new List <DisplaySeasonPayment>();
            }

            return(retVal);
        }
        public ActionResult <PlayerSeason> makePlayerSeason([FromBody] PlayerSeasonInput seasonInput)
        {
            LeagueManager LM           = new LeagueManager();
            PlayerSeason  playerSeason = LM.makePlayerSeason(seasonInput.SeasonId, seasonInput.PlayerId);


            return(playerSeason);
        }
Beispiel #6
0
    protected void btnPreviewSubmit_OnClick(object sender, ImageClickEventArgs e)
    {
        if (Functions.IsNumeric(txtNumberBox.Text))
        {
            PlayerSeason playerSeason = new PlayerSeason(txtNameBox.Text, txtNumberBox.Text);

            //
            // Kludge to allow leading zero until this field is converted to a string everywhere
            //
            //if (number.ToString() != txtNumberBox.Text)
            //{
            //    playerSeason.PlayerNumberFormat = "{0:00}";
            //}

            Template template = DataManager.GetTemplate(lstJerseyType.SelectedValue);

            if (template != null)
            {
                bool valid = true;

                if (_displayMode == Mode.OrderScreen)
                {
                    if (Functions.IsNumeric(txtQuantity.Text) && (int.Parse(txtQuantity.Text) > 0))
                    {
                        _quantity = int.Parse(txtQuantity.Text);
                    }
                    else
                    {
                        _validationErrorMesssage = "Please enter a numeric quantity greater than zero.";
                        valid = false;
                    }
                }

                if (valid)
                {
                    //
                    // Success!
                    //
                    _productItemJersey = new ProductItemJersey(playerSeason, template);
                }
            }
            else
            {
                _validationErrorMesssage = string.Format("Unable to determine jersey template from value \"{0}\".", lstJerseyType.SelectedValue);
            }
        }
        else
        {
            _validationErrorMesssage = string.Format("The jersey number (\"{0}\") must be numeric.", txtNumberBox.Text);
        }

        //
        // Send user's event to the parent page so it can do it's magic
        //
        base.RaiseBubbleEvent(this, (EventArgs)e);
    }
Beispiel #7
0
        public static PlayerSeason AddPlayerSeason(PlayerSeason playerSeason)
        {
            using (var db = new EloDbContext())
            {
                db.PlayerSeasons.Add(playerSeason);
                db.SaveChanges();
            }

            return(playerSeason);
        }
Beispiel #8
0
        public PlayerSeason makePlayerSeason(int seasonId, int playerId)
        {
            using (var db = new PickAndStick.Models.PickerContext())
            {
                PlayerSeason playerSeason = new PlayerSeason {
                    SeasonId = seasonId, PlayerId = playerId
                };

                db.Add(playerSeason);
                db.SaveChanges();

                return(playerSeason);
            }
        }
Beispiel #9
0
        public DisplaySeasonModel GetDisplay(long id)
        {
            DisplaySeasonModel retVal         = new DisplaySeasonModel();
            PlayerSeason       playerSeason   = this.Services.SeasonService.GetPlayerSeasonBySeasonId(this.CurrentPrincipal.User.Id, id);
            IList <Program>    seasonPrograms = null;

            if (playerSeason != null)
            {
                seasonPrograms = playerSeason.Programs;
            }

            retVal.Initialize(this.Services.SeasonService.GetById(id), seasonPrograms);
            return(retVal);
        }
Beispiel #10
0
 public ActionResult DeleteConfirmed(int id)
 {
     try
     {
         PlayerSeason playerSeason = db.PlayerSeasons.Find(id);
         db.PlayerSeasons.Remove(playerSeason);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     catch (Exception e)
     {
         ViewBag.Error = e.Message;
         return(View("Error"));
     }
 }
            public async Task <Unit> Handle(CreatePlayerSeasonCommand request, CancellationToken cancellationToken)
            {
                var seasonDivision = await _context.SeasonDivision.FirstOrDefaultAsync(
                    x => x.SeasonId == request.SeasonId && x.DivisionId == request.DivisionId, cancellationToken);

                if (seasonDivision == null)
                {
                    throw new NotFoundException(nameof(SeasonDivision), request.SeasonId);
                }

                var entity = new PlayerSeason
                {
                    PlayerId         = request.PlayerId,
                    SeasonDivisionId = seasonDivision.Id,
                    TeamId           = request.TeamId,
                    JerseyNr         = request.JerseyNr,
                    Fg3a             = request.Fg3a,
                    Fg3m             = request.Fg3m,
                    Fg2a             = request.Fg2a,
                    Fg2m             = request.Fg2m,
                    Fta      = request.Fta,
                    Ftm      = request.Ftm,
                    Orb      = request.Orb,
                    Drb      = request.Drb,
                    Ast      = request.Ast,
                    Stl      = request.Stl,
                    Blk      = request.Blk,
                    Tov      = request.Tov,
                    Fouls    = request.Fouls,
                    OffFouls = request.OffFouls
                };

                _context.PlayerSeason.Add(entity);

                var success = await _context.SaveChangesAsync(cancellationToken) > 0;

                if (success)
                {
                    return(Unit.Value);
                }

                throw new Exception("Problem saving changes");
            }
Beispiel #12
0
        private PlayerSeason CreatePlayerSeason(Match match, Player player, TeamSeason teamSeason)
        {
            PlayerSeason playerSeason = new PlayerSeason();

            if (player != null && teamSeason != null)
            {
                playerSeason.TeamSeasonId = teamSeason.TeamSeasonId;
                playerSeason.TeamSeason   = teamSeason;
                playerSeason.Player       = player;
                playerSeason.PlayerId     = player.PlayerId;

                playerSeason.Matches = new List <Match>();
                playerSeason.Season  = match.Season;

                db.PlayerSeasons.Add(playerSeason);
                db.SaveChanges();
            }

            return(playerSeason);
        }
Beispiel #13
0
 // GET: PlayerSeasons/Details/5
 public ActionResult Details(int?id)
 {
     try
     {
         if (id == null)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
         }
         PlayerSeason playerSeason = db.PlayerSeasons.Find(id);
         if (playerSeason == null)
         {
             return(HttpNotFound());
         }
         return(View(playerSeason));
     }
     catch (Exception e)
     {
         ViewBag.Error = e.Message;
         return(View("Error"));
     }
 }
Beispiel #14
0
        public ActionResult Create([Bind(Include = "PlayerSeasonId,SeasonString,GamedMatches,Goals,Assists,PlayerId,TeamSeasonId")] PlayerSeason playerSeason)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.PlayerSeasons.Add(playerSeason);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }

                ViewBag.PlayerId     = new SelectList(db.Players, "PlayerId", "NameSportString", playerSeason.PlayerId);
                ViewBag.TeamSeasonId = new SelectList(db.TeamSeasons, "TeamSeasonId", "NameTeam", playerSeason.TeamSeasonId);
                return(View(playerSeason));
            }
            catch (Exception e)
            {
                ViewBag.Error = e.Message;
                return(View("Error"));
            }
        }
Beispiel #15
0
        public Payment ConfirmPromise(long playerId, long playerSeasonId, long paymentId)
        {
            Payment retVal = null;

            PlayerSeason targetSeason = this.PlayerSeasonRepository.GetById(playerSeasonId);

            if (targetSeason != null && targetSeason.PlayerId == playerId)
            {
                retVal = targetSeason.Payments.FirstOrDefault(p => p.Id == paymentId);

                if (retVal != null)
                {
                    if (retVal.State == PaymentStates.Promised)
                    {
                        retVal.State = PaymentStates.Confirmed;
                        this.PlayerSeasonRepository.Save(targetSeason);
                    }
                }
            }

            return(retVal);
        }
Beispiel #16
0
        public bool CancelPromise(long playerId, long playerSeasonId, long paymentId)
        {
            bool retVal = false;

            PlayerSeason targetSeason = this.PlayerSeasonRepository.GetById(playerSeasonId);

            if (targetSeason != null && targetSeason.PlayerId == playerId)
            {
                Payment targetPayment = targetSeason.Payments.FirstOrDefault(p => p.Id == paymentId);

                if (targetPayment != null)
                {
                    if (targetPayment.State == PaymentStates.Promised)
                    {
                        targetSeason.Payments.Remove(targetPayment);
                        this.PlayerSeasonRepository.Save(targetSeason);
                        retVal = true;
                    }
                }
            }

            return(retVal);
        }
Beispiel #17
0
        public ActionResult CancelPromise(long paymentId, long playerSeasonId)
        {
            if (this.CurrentPrincipal == null || this.CurrentPrincipal.IsAuthenticated == false)
            {
                return(this.RedirectToAction("Signin", "User"));
            }
            else
            {
                if (this.ServiceManager.PaymentService.CancelPromise(this.CurrentPrincipal.User.Id, playerSeasonId, paymentId))
                {
                    return(this.RedirectToAction("Season"));
                }
                else
                {
                    ConfirmPaymentModel retVal = new ConfirmPaymentModel();

                    PlayerSeason playerSeason = this.ServiceManager.SeasonService.GetPlayerSeasonById(playerSeasonId);
                    retVal.PaymentDetails = playerSeason.Payments.FirstOrDefault(p => p.Id == paymentId);
                    retVal.PlayerInfo     = this.CurrentPrincipal.User;
                    return(this.View("Confirm", retVal));
                }
            }
        }
Beispiel #18
0
 // GET: PlayerSeasons/Edit/5
 public ActionResult Edit(int?id)
 {
     try
     {
         if (id == null)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
         }
         PlayerSeason playerSeason = db.PlayerSeasons.Find(id);
         if (playerSeason == null)
         {
             return(HttpNotFound());
         }
         ViewBag.PlayerId     = new SelectList(db.Players, "PlayerId", "NameSportString", playerSeason.PlayerId);
         ViewBag.TeamSeasonId = new SelectList(db.TeamSeasons, "TeamSeasonId", "NameTeam", playerSeason.TeamSeasonId);
         return(View(playerSeason));
     }
     catch (Exception e)
     {
         ViewBag.Error = e.Message;
         return(View("Error"));
     }
 }
Beispiel #19
0
        public Payment AddSeasonPayment(long playerId, PaymentMethods paymentMethod, decimal paymentAmount, string additionalDetails, long playerSeasonId)
        {
            Payment retVal = null;

            PlayerSeason targetSeason = this.PlayerSeasonRepository.GetById(playerSeasonId);

            if (targetSeason != null && targetSeason.PlayerId == playerId)
            {
                retVal                   = new Payment();
                retVal.Amount            = paymentAmount;
                retVal.DateSubmitted     = DateTime.Now;
                retVal.PaymentMethod     = paymentMethod;
                retVal.AdditionalDetails = additionalDetails;
                retVal.PlayerSeasonId    = targetSeason.Id;
                retVal.TransactionId     = Guid.NewGuid();

                targetSeason.Payments.Add(retVal);
                targetSeason = this.PlayerSeasonRepository.Save(targetSeason);

                retVal = targetSeason.Payments.FirstOrDefault(p => p.TransactionId == retVal.TransactionId);
            }

            return(retVal);
        }
Beispiel #20
0
        public bool UpdateSeasonPrograms(long playerId, long seasonId, IList <long> programsToUpdate)
        {
            bool retVal = false;

            // Load up the season by the first
            Season          targetSeason          = this.SeasonRepository.GetById(seasonId);
            IList <Program> foundProgramsToUpdate = new List <Program>();

            if (targetSeason != null)
            {
                bool allMatch = true;

                // first make sure all the programs are for the same season
                for (int i = 0; i < programsToUpdate.Count; i++)
                {
                    Program foundProgramToUpdate = targetSeason.Programs.FirstOrDefault(p => p.Id == programsToUpdate[i]);

                    if (foundProgramToUpdate != null)
                    {
                        foundProgramsToUpdate.Add(foundProgramToUpdate);
                    }
                    else
                    {
                        // write an error
                        allMatch = false;
                        break;
                    }
                }

                if (allMatch)
                {
                    PlayerSeason playerSeason = this.PlayerSeasonRepository.GetByPlayerIdAndSeasonId(playerId, seasonId);

                    if (playerSeason == null)
                    {
                        playerSeason          = new PlayerSeason();
                        playerSeason.PlayerId = playerId;
                        playerSeason.SeasonId = seasonId;

                        // This is a hack for now, so that the player season will save first, then add in the programs
                        // It should all work at the same time, but there is a bug with the NHibernate and REpository code that is bigger than I thought
                        // So for now just do two saves for the first pass.
                        playerSeason = this.PlayerSeasonRepository.Save(playerSeason);
                    }


                    bool isChangeRemovingPrograms = playerSeason.IsChangeRemovingPrograms(foundProgramsToUpdate);

                    if ((isChangeRemovingPrograms == false) ||
                        (isChangeRemovingPrograms == true && playerSeason.CanRemovePrograms(targetSeason) == true))
                    {
                        playerSeason.UpdateSeasonPrograms(targetSeason, foundProgramsToUpdate);
                        playerSeason = this.PlayerSeasonRepository.Save(playerSeason);

                        if (playerSeason != null)
                        {
                            retVal = true;
                        }
                    }
                }
            }

            return(retVal);
        }
Beispiel #21
0
        public void MatchAddPlayerSeason(Match match, TeamSeason seasonTeam, List <string> listPlayer, List <string> listTimeLine)
        {
            if (listPlayer != null)
            {
                foreach (string homeplayer in listPlayer)
                {
                    PlayerSeason playerSeason = new PlayerSeason();
                    string       playerName   = homeplayer;
                    string       nameSport    = match.NameSport.ToString();

                    var searchPlayer = from c in db.Players
                                       where
                                       (c.Name + " " + c.Surname == playerName ||
                                        c.Name + " " + c.Surname == playerName + " ") &&
                                       c.NameSportString == nameSport
                                       select c;

                    if (searchPlayer.Count() == 0)
                    {
                        continue;
                    }

                    string seasonPSH = match.Season.ToString();
                    string teamH     = seasonTeam.NameTeam;
                    var    searchPSH = from c in db.PlayerSeasons
                                       where
                                       c.TeamSeason.NameTeam == teamH &&
                                       (c.Player.Name + " " + c.Player.Surname == playerName ||
                                        c.Player.Name + " " + c.Player.Surname == playerName + " ") &&
                                       c.Player.NameSportString == nameSport &&
                                       c.TeamSeason.SeasonString == seasonPSH
                                       select c;

                    if (searchPSH.Count() > 0)
                    {
                        playerSeason = searchPSH.First();
                    }
                    else
                    {
                        playerSeason = CreatePlayerSeason(match, searchPlayer.First(), seasonTeam);
                    }

                    playerSeason.GamedMatches++;
                    playerSeason.Matches.Add(match);

                    if (listTimeLine != null)
                    {
                        if (string.Join(",", listTimeLine).IndexOf(homeplayer) > 0)
                        {
                            foreach (string itemLine in listTimeLine)
                            {
                                string[] actTimeLine = itemLine.Split(':');
                                if (actTimeLine[2] == homeplayer)
                                {
                                    if (actTimeLine[0] == "G")
                                    {
                                        playerSeason.Goals++;
                                    }
                                    if (actTimeLine[0] == "A")
                                    {
                                        playerSeason.Assists++;
                                    }
                                }
                            }
                        }
                    }

                    db.Entry(playerSeason).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
        }
Beispiel #22
0
        public void AddPlayerSeason(string data)
        {
            data = data.Replace("\n", "&");
            data = data.Replace("\r", "");
            List <string> dataList = data.Split('&').ToList();

            foreach (string item in dataList)
            {
                PlayerSeason playerSeason = new PlayerSeason();
                string[]     list         = item.Split(',');

                if (list.Count() < 7)
                {
                    continue;
                }

                string name      = list[5] + " " + list[6];
                string nameSport = list[0];
                var    search    = from c in db.Players
                                   where
                                   c.Name + " " + c.Surname == name &&
                                   c.NameSportString == nameSport
                                   select c;

                Player player = new Player();
                if (search.Count() < 1)
                {
                    continue;
                }
                else
                {
                    player = search.First();
                }

                string nameTeamPS   = list[4];
                string seasonPS     = Enum.Format(typeof(Season), Convert.ToInt32(list[3]), "G");
                string tournamentPS = list[2];
                string countryPS    = list[1];
                var    searchPS     = from c in db.PlayerSeasons
                                      where
                                      c.Player.Name + " " + c.Player.Surname == name &&
                                      c.SeasonString == seasonPS &&
                                      c.TeamSeason.FederationSeason.TournamentString == tournamentPS &&
                                      c.Player.NameSportString == nameSport &&
                                      c.TeamSeason.Team.Name == nameTeamPS &&
                                      c.TeamSeason.FederationSeason.SportFederation.Country == countryPS
                                      select c;

                if (searchPS.Count() == 0)
                {
                    string season           = Enum.Format(typeof(Season), Convert.ToInt32(list[3]), "G");
                    string tournament       = list[2];
                    string nameTeam         = list[4];
                    string country          = list[1];
                    var    searchTeamSeason = from c in db.TeamSeasons
                                              where
                                              c.FederationSeason.SportFederation.NameSportString == nameSport &&
                                              c.FederationSeason.TournamentString == tournament &&
                                              c.SeasonString == season &&
                                              c.Team.Name == nameTeam &&
                                              c.FederationSeason.SportFederation.Country == country
                                              select c;

                    TeamSeason teamSeason = new TeamSeason();
                    if (searchTeamSeason.Count() < 1)
                    {
                    }
                    else
                    {
                        teamSeason = searchTeamSeason.First();
                    }

                    playerSeason.Assists      = Convert.ToInt32(list[9]);
                    playerSeason.GamedMatches = Convert.ToInt32(list[7]);
                    playerSeason.Goals        = Convert.ToInt32(list[8]);
                    playerSeason.Player       = player;
                    playerSeason.PlayerId     = player.PlayerId;
                    playerSeason.Season       = season.ParseEnum <Season>();
                    playerSeason.TeamSeason   = teamSeason;
                    playerSeason.TeamSeasonId = teamSeason.TeamSeasonId;

                    db.PlayerSeasons.Add(playerSeason);

                    teamSeason.PlayerSeasons.Add(playerSeason);
                    db.Entry(teamSeason).State = EntityState.Modified;

                    player.PlayerSeasons.Add(playerSeason);
                    db.Entry(player).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
        }
Beispiel #23
0
        public void Run(SoccerDataContext dbContext)
        {
            if (!this.DbCompetitionSeason.StartDate.HasValue || !this.DbCompetitionSeason.EndDate.HasValue)
            {
                // NULL DATES INDICATES NO GAMES YET.
                return;
            }

            if (this.DbCompetitionSeason == null)
            {
                this.DbCompetitionSeason = dbContext.CompetitionSeasons.Single(x => x.ApiFootballId == this.ApiFootballLeagueId);
            }

            var url     = Feeds.TeamSquadFeed.GetUrlFromTeamIdAndSeasonYears(this.ApiFootballTeamId, this.DbCompetitionSeason.StartDate.Value, this.DbCompetitionSeason.EndDate.Value);
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.TeamSquadFeed.FromJson(rawJson);

            if (feed == null || feed.Result.Count == 0)
            {
                return;
            }

            int dbCompetitionSeasonId = this.DbCompetitionSeason.CompetitionSeasonId;
            var apiPlayerIds          = feed.Result.Players.Select(x => x.PlayerId).ToList();
            var playerDict            = dbContext.Players.Where(x => apiPlayerIds.Contains(x.ApiFootballId)).ToDictionary(x => x.ApiFootballId, y => y);
            var playerSeasonDict      = dbContext.PlayerSeasons.Where(x => x.CompetitionSeasonId == dbCompetitionSeasonId && apiPlayerIds.Contains(x.Player.ApiFootballId)).ToDictionary(x => x.Player.ApiFootballId, y => y);

            bool hasUpdate  = false;
            var  apiPlayers = feed.Result.Players.ToList();

            foreach (var apiPlayer in apiPlayers)
            {
                bool         isNewPlayer    = false;
                PlayerSeason dbPlayerSeason = null;
                if (!playerDict.TryGetValue(apiPlayer.PlayerId, out Player dbPlayer))
                {
                    dbPlayerSeason = new PlayerSeason
                    {
                        CompetitionSeasonId = this.DbCompetitionSeason.CompetitionSeasonId,
                        Height       = apiPlayer.HeightInCm,
                        JerseyNumber = apiPlayer.Number,
                        Position     = apiPlayer.Position,
                        Weight       = apiPlayer.WeightInKg
                    };

                    dbPlayer = new Player
                    {
                        ApiFootballId   = apiPlayer.PlayerId,
                        BirthCity       = apiPlayer.BirthPlace,
                        BirthCountry    = apiPlayer.BirthCountry,
                        DateOfBirth     = apiPlayer.BirthDate,
                        FirstName       = apiPlayer.Firstname,
                        LastName        = apiPlayer.Lastname,
                        Nationality     = apiPlayer.Nationality,
                        PlayerName      = apiPlayer.PlayerName,
                        ApiFootballName = apiPlayer.PlayerName,
                        PlayerSeasons   = new List <PlayerSeason> {
                            dbPlayerSeason
                        }
                    };
                    playerDict.Add(apiPlayer.PlayerId, dbPlayer);
                    playerSeasonDict.Add(apiPlayer.PlayerId, dbPlayerSeason);
                    dbContext.Players.Add(dbPlayer);
                    hasUpdate   = true;
                    isNewPlayer = true;
                }

                if (!isNewPlayer)
                {
                    if ((!string.IsNullOrEmpty(apiPlayer.BirthPlace) && dbPlayer.BirthCity != apiPlayer.BirthPlace) ||
                        (!string.IsNullOrEmpty(apiPlayer.BirthCountry) && dbPlayer.BirthCountry != apiPlayer.BirthCountry) ||
                        (apiPlayer.BirthDate.HasValue && dbPlayer.DateOfBirth != apiPlayer.BirthDate) ||
                        (!string.IsNullOrEmpty(apiPlayer.Firstname) && dbPlayer.FirstName != apiPlayer.Firstname) ||
                        (!string.IsNullOrEmpty(apiPlayer.Lastname) && dbPlayer.LastName != apiPlayer.Lastname) ||
                        (!string.IsNullOrEmpty(apiPlayer.PlayerName) && dbPlayer.ApiFootballName != apiPlayer.PlayerName) ||
                        (!string.IsNullOrEmpty(apiPlayer.Nationality) && dbPlayer.Nationality != apiPlayer.Nationality))
                    {
                        // ALLOW PlayerName TO BE UPDATED AND NOT OVERWRITTEN
                        dbPlayer.ApiFootballId   = apiPlayer.PlayerId;
                        dbPlayer.BirthCity       = apiPlayer.BirthPlace;
                        dbPlayer.BirthCountry    = apiPlayer.BirthCountry;
                        dbPlayer.DateOfBirth     = apiPlayer.BirthDate;
                        dbPlayer.FirstName       = apiPlayer.Firstname;
                        dbPlayer.LastName        = apiPlayer.Lastname;
                        dbPlayer.Nationality     = apiPlayer.Nationality;
                        dbPlayer.ApiFootballName = apiPlayer.PlayerName;
                        if (string.IsNullOrEmpty(dbPlayer.PlayerName) && !string.IsNullOrEmpty(apiPlayer.PlayerName))
                        {
                            dbPlayer.PlayerName = apiPlayer.PlayerName;
                        }
                        hasUpdate = true;
                    }

                    if (!playerSeasonDict.TryGetValue(apiPlayer.PlayerId, out dbPlayerSeason))
                    {
                        dbPlayerSeason = new PlayerSeason
                        {
                            CompetitionSeasonId = this.DbCompetitionSeason.CompetitionSeasonId,
                            Height       = apiPlayer.HeightInCm,
                            JerseyNumber = apiPlayer.Number,
                            PlayerId     = dbPlayer.PlayerId,
                            Position     = apiPlayer.Position,
                            Weight       = apiPlayer.WeightInKg
                        };
                        playerSeasonDict.Add(dbPlayer.ApiFootballId, dbPlayerSeason);
                        dbContext.PlayerSeasons.Add(dbPlayerSeason);
                        hasUpdate = true;
                    }
                    else if ((apiPlayer.WeightInKg.HasValue && apiPlayer.WeightInKg != dbPlayerSeason.Weight) ||
                             (apiPlayer.HeightInCm.HasValue && apiPlayer.HeightInCm != dbPlayerSeason.Height) ||
                             (apiPlayer.Number.HasValue && apiPlayer.Number != dbPlayerSeason.JerseyNumber) ||
                             (!string.IsNullOrEmpty(apiPlayer.Position) && apiPlayer.Position != dbPlayerSeason.Position))
                    {
                        dbPlayerSeason.Weight       = apiPlayer.WeightInKg;
                        dbPlayerSeason.Height       = apiPlayer.HeightInCm;
                        dbPlayerSeason.JerseyNumber = apiPlayer.Number;
                        dbPlayerSeason.Position     = apiPlayer.Position;
                        hasUpdate = true;
                    }
                }
            }

            if (hasUpdate)
            {
                dbContext.SaveChanges();
            }
        }
 public void AddSeason(PlayerSeason playerSeason)
 {
     //some code that adds a season.  may check if already exists. whatever your business rules say to do
     Seasons.Add(playerSeason);
 }
        /// <summary>
        /// Get all the leads from the database and do stuff with them.  That doesn't sound very good does it.
        /// </summary>
        /// <param name="testLead">(Optional) A test lead to send to rather than DB leads.</param>
        /// <remarks>
        /// This should probably go in ApplicationManager with callbacks and stuff for logging.  Todo.
        /// </remarks>
        private void ProcessNewDatabaseLeads(Lead testLead)
        {
            const string genericTeamName        = "WARRIORS";
            const string defaultTemplateDesc1   = "Football";
            const string defaultTemplateDesc2   = "Baseball";
            const int    customJersyImageWidth  = 150;
            const string imagesSubdir           = "images";
            const string commonSubdir           = "common";
            const string tempSubdir             = "temp";
            const int    maxNumLeadsCommonSense = 5;
            int          sendRetries            = 0;

            //
            // Debugging mode doesn't send emails to leads, but it sends them to a test account.
            //
            bool debugging = _settings.DebuggingMode;

            Log("Processing new leads in db, debugging mode: {0}...", debugging);

            string errMsg          = string.Empty;
            string outputEmailFile = Functions.BuildFilenameFromElements(_settings.EmailSrcDir, "output-temp.htm");
            //
            // Read header row, then read the row we want.
            //
            StreamReader reader            = File.OpenText(Functions.BuildFilenameFromElements(_settings.EmailSrcDir, string.Format("lead-email-{0}.htm", _settings.EmailTemplateNo)));
            string       emailTemplateOrig = reader.ReadToEnd();

            reader.Close();


            //  The mailman object is used for sending and receiving email.
            Chilkat.MailMan mailman = new Chilkat.MailMan();

            // The MHT component can be used to convert an HTML page
            // from a URL, file, or in-memory HTML into an email
            // with embedded images and style sheets.
            Chilkat.Mht mht = new Chilkat.Mht();


            //  Any string argument automatically begins the 30-day trial.
            bool success;

            // success = mailman.UnlockComponent(Config.ChilkatUnlockCodeEmail);
            success = mailman.UnlockComponent(ChilkatRegCodes.ChilkatEmail);
            if (success != true)
            {
                Log("Component unlock failed");
                return;
            }

            // success = mht.UnlockComponent(Config.ChilkatUnlockCodeEmail);
            success = mht.UnlockComponent(ChilkatRegCodes.ChilkatMHT);
            if (success != true)
            {
                Log("Mht component unlock failed");
                return;
            }

            //  Set the SMTP server.
            mailman.SmtpHost = Config.LeadMailboxServer;

            //  Set the SMTP login/password (if required)
            mailman.SmtpUsername = Config.LeadMailboxLoginUID;
            mailman.SmtpPassword = Config.LeadMailboxLoginPW;

            //
            // Set up parameters to append to all the email links so Google Analytics can track the clicks for us.
            //
            Campaign campaign = new Campaign();

            // Todo: grab this from the db & config file
            campaign.Source  = "fundraisingweb";
            campaign.Medium  = (debugging || testLead != null) ? "testing" : "email";
            campaign.Content = _settings.EmailTemplateNo;


            List <Lead> leads;

            if (testLead == null)
            {
                Log("Getting leads from db...");
                leads = DataManager.GetNewFundraisingLeads();
            }
            else
            {
                leads = new List <Lead>();
                leads.Add(testLead);
            }

            if (leads.Count > maxNumLeadsCommonSense)
            {
                string msg = string.Format("An unusually high amount of leads were returned from the db ({0}), do you wish to send emails anyway?", leads.Count);
                if (MessageBox.Show(msg, "Sanity Check", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    // Close the program
                    btnClose_Click(null, null);
                }
            }

            foreach (Lead lead in leads)
            {
                Log("Processing lead: {0}", lead);

                if (!_doingProcessing && testLead == null)
                {
                    //
                    // We were signalled to stop processing
                    //
                    Log("User signalled to quit, exiting...");
                    return;
                }

                string emailTemplate = emailTemplateOrig;

                //Lead lead = leads[0];
                // ApplicationManager.SetFundraisingIdeasProperties(lead);

                // const int totalNumberOfTemplates = 5;

                // string templateDescShort = Functions.FirstNonemptyString(lead.TemplateDescShort, "Football");

                //
                // Otherwise, make it 1 so that we put in two different template graphics.
                //
                // int altTemplate = lead.TemplateDescShort == string.Empty ? 1 : 0;
                string customName;

                if (!Functions.IsEmptyString(lead.LastName) && lead.LastName.Length <= 13)
                {
                    customName = lead.LastName;
                }
                else if (!Functions.IsEmptyString(lead.FirstName) && lead.LastName.Length <= 13)
                {
                    customName = lead.FirstName;
                }
                else
                {
                    customName = "anyname";
                }

                customName = customName.ToUpper();

                string customNumber = string.Format("{0:yy}", DateTime.Now);

                Template template1 = lead.TemplateCurrent;
                Template template2 = lead.TemplateCurrent;

                // If we have a specific template specified, use them both.  Otherwise, use the default and another one.
                if (template1 == null)
                {
                    template1 = DataManager.GetTemplate(defaultTemplateDesc1);
                    // template2 = DataManager.GetTemplate(((template1.TemplateId + 1) % totalNumberOfTemplates + 1) + 1);
                    template2 = DataManager.GetTemplate(defaultTemplateDesc2);
                }

                //Template template1 = DataManager.GetTemplate(templateDescShort);
                //Template template2 = DataManager.GetTemplate((template1.TemplateId + altTemplate) % totalNumberOfTemplates);

                PlayerSeason example1 = new PlayerSeason(customName, customNumber);
                PlayerSeason example2 = new PlayerSeason(genericTeamName, customNumber);

                example1.TemplateCurrent = template1;
                example2.TemplateCurrent = template2;

                string example1File  = string.Format("{0}_{1:000}_{2}_{3}.jpg", template1.TemplateDescShort, template1.TemplateId, customName, customNumber);
                string example1FPath = Functions.BuildFilenameFromElements(
                    _settings.EmailSrcDir,
                    imagesSubdir,
                    tempSubdir,
                    example1File);

                string example2File  = string.Format("{0}_{1:000}_{2}_{3}.jpg", template2.TemplateDescShort, template2.TemplateId, genericTeamName, customNumber);
                string example2FPath = Functions.BuildFilenameFromElements(
                    _settings.EmailSrcDir,
                    imagesSubdir,
                    commonSubdir,
                    example2File);

                Log("Creating image: {0}", example1File);
                ApplicationManager.WritePlayerMarketingGIFFile(example1, customJersyImageWidth, example1FPath, debugging);

                Log("Creating image: {0}", example2File);
                ApplicationManager.WritePlayerMarketingGIFFile(example2, customJersyImageWidth, example2FPath, debugging);

                //
                // Personalize the email.
                //
                Dictionary <string, string> replacements = new Dictionary <string, string>();

                replacements.Add("[cust_fname]", Functions.TitleCase(Functions.FirstNonemptyString(lead.FirstName.ToLower(), lead.LastName.ToLower(), "Hi future fundraiser")));
                replacements.Add("[current_year_2digit]", customNumber);
                replacements.Add("[homepage_href]", ApplicationManager.BuildWebsiteLink(null, campaign));

                string addtlLi = string.Empty;
                if (lead.IsAthletics)
                {
                    addtlLi = string.Format("<li>Your {0} team!</li>", lead.TemplateCurrent.TemplateDescShort);
                }
                replacements.Add("[perfect_for_addtl_li]", addtlLi);

                replacements.Add("[specific_jersey_href]", ApplicationManager.BuildWebsiteLink(example1, campaign));
                replacements.Add("[alternate_jersey_href]", ApplicationManager.BuildWebsiteLink(example2, campaign));

                replacements.Add("[specific_jersey_image]", Functions.BuildUrlFromElements(imagesSubdir, tempSubdir, example1File));
                replacements.Add("[alternate_jersey_image]", Functions.BuildUrlFromElements(imagesSubdir, commonSubdir, example2File));

                replacements.Add("[homepage_href_fundraisingpage]", ApplicationManager.BuildWebsiteLink(null, campaign, Config.WebsiteFundraisingPage));
                replacements.Add("[unsubscribe_url]", string.Format("mailto:{0}?subject=unsubscribe&body=Your%20stickers%20are%20great%20but%20please%20unsubscribe%20me.", Config.LeadMailboxLoginUID));

                replacements.Add("[how_user_entered_info]", "to the \"Fundraising Ideas\" website");

                //
                // Validate the row, all these fields must be there or we're wasting our time.
                //
                foreach (KeyValuePair <string, string> replacement in replacements)
                {
                    if (!emailTemplate.Contains(replacement.Key))
                    {
                        errMsg = string.Format("Cannot find required value in output file: \"{0}\"", replacement.Key);
                        throw new ApplicationException(errMsg);

                        //
                        // Do something with the error here.
                        //
                    }
                    else
                    {
                        emailTemplate = emailTemplate.Replace(replacement.Key, replacement.Value);
                    }
                }

                MatchCollection leftovers1 = Regex.Matches(emailTemplate, "(\\[.*\\])");

                if (leftovers1.Count > 0)
                {
                    string msg = "You need to implement the following tokens:\r\n\r\n";

                    foreach (Match token in leftovers1)
                    {
                        msg = Functions.BuildStringFromElementsWithDelimiter(msg, token.Groups[0].ToString(), "\r\n");
                    }

                    MessageBox.Show(msg, "Fix These", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }

                string emailSubject = Functions.GetValueFromText(emailTemplate, "<title>(.*)</title>");


                Functions.WriteStringAsFile(emailTemplate, outputEmailFile);

                Log("Done creating email, now gonna email it.");

                //  Create a new email object
                Chilkat.Email email = new Chilkat.Email();

                // Embed the images in the email - Outlook friendly.
                mht.UseCids = true;

                // Create an email from an HTML file.
                email = mht.GetEmail(outputEmailFile);
                if (email == null)
                {
                    MessageBox.Show(mht.LastErrorText);
                    return;
                }

                email.Subject = emailSubject;
                // email.Body = "This is a test";
                email.From    = string.Format("Fan Favorite Designs <{0}>", Config.LeadMailboxLoginUID);
                email.ReplyTo = Config.LeadMailboxLoginUID;

                if (debugging)
                {
                    email.AddTo("Lead Monitor", "*****@*****.**");
                }
                else
                {
                    email.AddTo(lead.BuildFullName(), lead.EmailAddress);
                    // email.AddBcc("Lead Monitor", "*****@*****.**");
                }

                Chilkat.HtmlToText h2t = new Chilkat.HtmlToText();
                // success = h2t.UnlockComponent(Config.ChilkatUnlockCodeEmail);
                success = h2t.UnlockComponent(ChilkatRegCodes.ChilkatHTMLtoXML);
                if (success != true)
                {
                    MessageBox.Show(h2t.LastErrorText);
                    return;
                }

                //  Get the email's HTML body.
                string html;
                html = email.GetHtmlBody();

                //  Convert it to plain text:
                string plainText;
                plainText = h2t.ToText(html);

                // Add a few things so the email makes sense.
                plainText = string.Format("This email was meant to be viewed in HTML mode.  You can visit \r\nour website here to get a better look at our product.\r\n\r\n    {0}\r\n{1}", ApplicationManager.BuildWebsiteLink(null, campaign), plainText);

                //  Add a plain-text alternative to the email:
                email.AddPlainTextAlternativeBody(plainText);

                //  Call SendEmail to connect to the SMTP server and send.
                //  The connection (i.e. session) to the SMTP server remains
                //  open so that subsequent SendEmail calls may use the
                //  same connection.
                Log("Sending SMTP mail...");
                success = mailman.SendEmail(email);
                if (success != true)
                {
                    sendRetries++;

                    if (sendRetries < 5)
                    {
                        Log("Can't send email, gonna hang out for a bit, and try again.");
                        Thread.Sleep(20000);
                    }
                    else
                    {
                        throw new ApplicationException("Cannot send email - cannot continue.");
                    }
                }
                else if (!debugging && testLead == null)
                {
                    //
                    // Update the DB indicating that we sent the email so we don't do it again.
                    //
                    bool res = DataManager.AddLeadStatusLog(lead, Lead.LeadStatusCode.lscEmailSent, string.Format("lead-email-{0}.htm", _settings.EmailTemplateNo));

                    if (res)
                    {
                        Log("Updated status log - all good.");
                    }
                    else
                    {
                        Log("Yikes, can't update status log that we emailed!  Bombing out.");
                        throw new ApplicationException("Cannot update status log - cannot continue.");
                    }
                    sendRetries = 0;
                }
                else
                {
                    Log("Email success; debug mode - not updating DB");
                    sendRetries = 0;
                }

                //  Some SMTP servers do not actually send the email until
                //  the connection is closed.  In these cases, it is necessary to
                //  call CloseSmtpConnection for the mail to be  sent.
                //  Most SMTP servers send the email immediately, and it is
                //  not required to close the connection.  We'll close it here
                //  for the example:
                success = mailman.CloseSmtpConnection();
                if (success != true)
                {
                    Log("Connection to SMTP server not closed cleanly.");
                    throw new ApplicationException("Cannot disconnect from SMTP server cleanly - cannot continue.");
                }
            }

            Log("Cleaning up temp files, if any.");
            string tempDirPath = Functions.BuildFilenameFromElements(
                _settings.EmailSrcDir,
                imagesSubdir,
                tempSubdir);

            string[] tempFiles = Directory.GetFiles(tempDirPath);
            foreach (string file in tempFiles)
            {
                File.Delete(file);
            }

            // todo: add icon to exe

            // todo: buy chilkat components

            Log("Processing of db leads completed");
        }
Beispiel #26
0
        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();
            }
        }
Beispiel #27
0
 public void SendThankYouForPaymentEmail(string emailAddress, EmailConfiguration emailConfig, AMFUserLogin playerInfo, PlayerSeason playerSeasonInfo)
 {
     if (!emailConfig.IsDebugMode)
     {
         EmailManager emailManager = new EmailManager(EmailConfiguration.GetInstance());
         String       emailBody    = "Thank you for submitting your registration for a NEWHL Program. ";
         emailBody = GenerateEmailDetails(playerInfo, playerSeasonInfo);
         emailManager.SendEmail(emailConfig.FromAddress, emailAddress, "Payment Details for NEWHL Registration", emailBody);
     }
 }
        public async Task <IEnumerable <PlayerSeason> > GetPlayersAsync(string seasonId, int teamId)
        {
            var teamUrl    = string.Format(_settings.TeamUrl, teamId);
            var teamResult = await _client.GetAsync(teamUrl);

            var teamResponse = await SerializeResult <Data.TeamInfo.Result>(teamResult);

            var teamInfo = teamResponse.teams[0];
            var team     = new Team
            {
                ExternalId   = teamInfo.id,
                FullName     = teamInfo.name,
                LocationName = teamInfo.locationName,
                Name         = teamInfo.teamName,
                ShortName    = teamInfo.abbreviation
            };


            var playerList = new List <PlayerSeason>();

            var url          = string.Format(_settings.RosterUrl, teamId, seasonId);
            var rosterResult = await _client.GetAsync(url);

            if (!rosterResult.IsSuccessStatusCode)
            {
                return(null);
            }

            var response = await SerializeResult <Data.RosterInfo.Result>(rosterResult);

            foreach (var item in response.roster)
            {
                PositionType position = null;
                if (item.position.type == "Forward")
                {
                    position = ForwardType();
                }
                else if (item.position.type == "Defenseman")
                {
                    position = DefensemanType();
                }
                else if (item.position.type == "Goalie")
                {
                    position = GoalieType();
                }
                int jerseyNumber = -1;
                int.TryParse(item.jerseyNumber, out jerseyNumber);
                var player = new Player()
                {
                    FullName   = item.person.fullName,
                    ExternalId = item.person.id.ToString(),
                    ShortName  = item.person.lastName,
                    FirstName  = item.person.firstName,
                    LastName   = item.person.lastName,
                    Number     = jerseyNumber
                };
                var playerSeason = new PlayerSeason
                {
                    Player       = player,
                    PositionType = position,
                    Team         = team
                };
                playerList.Add(playerSeason);
            }
            return(playerList);
        }