public void SaveNewGameAndExistingTeamsTest()
        {
            // setup
            Game saved = null;
            string homeTeam = "TestTeam1", awayTeam = "TestTeam2";
            long homeId = -1, awayId = -1, gameId = -1;
            using (var repository = new TeamRepository())
            {
                homeId = repository.Add(new Team() { Name = homeTeam });
                awayId = repository.Add(new Team() { Name = awayTeam });
            }
            Game game = new Game()
            {
                Start = new DateTime(2014, 1, 1),
                HomeTeamId = homeId,
                AwayTeamId = awayId,
                TweetsRetrieved = RetrievalStatus.NONE
            };

            // execute
            using (var repository = new GameRepository())
            {
                gameId = repository.Save(game).Id;
                saved = (from g in repository.DataSet.Include("HomeTeam").Include("AwayTeam")
                         where g.Id == gameId
                         select g).FirstOrDefault();
            }

            // validate
            Assert.IsNotNull(saved);
            Assert.IsNotNull(saved.HomeTeam);
            Assert.IsNotNull(saved.AwayTeam);
            Assert.AreEqual(homeTeam, saved.HomeTeam.Name);
            Assert.AreEqual(awayTeam, saved.AwayTeam.Name);
        }
        public Game GameFromArray(string[] line)
        {
            // set up a new game
            Game game = new Game();
            // set up the teams
            using (var repository = new TeamRepository())
            {
                var teams = (repository.GetAll().Where(t => t.Name == line[iHome])).ToList();
                if (teams.Count > 0)
                {
                    game.HomeTeamId = teams[0].Id;
                }
                else
                {
                    var home = new Team() { Name = line[iHome] };
                    home.Id = repository.Add(home);
                    game.HomeTeamId = home.Id;
                }
                teams = (repository.GetAll().Where(t => t.Name == line[iAway])).ToList();
                if (teams.Count > 0)
                {
                    game.AwayTeamId = teams[0].Id;
                }
                else
                {
                    var away = new Team() { Name = line[iAway] };
                    away.Id = repository.Add(away);
                    game.AwayTeamId = away.Id;
                }
            }

            // get the start time
            DateTime start = DateTime.Parse(line[iDate]);
            TimeSpan time = TimeSpan.Parse(line[iTime]);

            game.Start = start + time;

            // get the score
            string score = line[iScore];
            var scores = Regex.Matches(score, @"\d");
            game.HomeGoals = Int32.Parse(scores[0].Value);
            game.AwayGoals = Int32.Parse(scores[1].Value);

            // set the status of the tweet mining
            game.TweetsRetrieved = RetrievalStatus.NONE;

            return game;
        }
Пример #3
0
        public void GetTeamPostsTest()
        {
            //arrange
            var userModel = new UserModel()
            {
                Name        = "Pepa Hnátek",
                LastLogged  = DateTime.Today,
                MailAddress = "*****@*****.**"
            };
            var userRepository = new UserRepository(dbContextFactory, mapper);

            userModel = userRepository.Add(userModel);

            var teamModel = new TeamModel
            {
                Description = "Tym resici ics",
                Name        = "Borci"
            };
            var teamRepository = new TeamRepository(dbContextFactory, mapper);

            teamModel = teamRepository.Add(teamModel);

            teamRepository.AddUserToTeam(teamModel.Id, userModel.Id);

            var postModel = new PostModel
            {
                Title       = "Hlava",
                Author      = userModel,
                Text        = "Ztratil jsem hlavu!",
                TimeCreated = DateTime.Now,
                Team        = teamModel
            };
            var postModel2 = new PostModel
            {
                Title       = "Vyvoj",
                Author      = userModel,
                Text        = "Už nám i zaèínají procházet testy!",
                TimeCreated = DateTime.Now,
                Team        = teamModel
            };
            var postRepository = new PostRepository(dbContextFactory, mapper);

            postModel  = postRepository.Add(postModel);
            postModel2 = postRepository.Add(postModel2);
            //act
            teamModel = teamRepository.GetById(teamModel.Id);
            var titles = new List <string>();

            foreach (var post in teamModel.Posts)
            {
                titles.Add(post.Title);
            }
            //assert
            Assert.Contains("Hlava", titles);
            Assert.Contains("Vyvoj", titles);
            Assert.DoesNotContain("balmsofinsadd", titles);
            Assert.Equal(2, teamModel.Posts.Count);

            teamRepository.Remove(teamModel.Id); //should remove also the posts
            userRepository.Remove(userModel.Id);
            Assert.Null(postRepository.getById(postModel.Id));
        }
        private bool ServerUpdatesToLocalDb()
        {
            Key  key          = GetUser().BitcoinPrivateKey;
            long since        = _connection.LastUpdated.Ticks;
            var  txsToUpdate  = _txRepo.GetTxsNeedServerUpdate();
            var  txSignatures = _txRepo.GetTxsSignaturesNeedServerUpdate();

            GetUpdatesResultData serverResponse = _server.GetUpdates(key, since, txsToUpdate.Where(x => x.Teammate.Team.IsInNormalState), txSignatures);

            if (null == serverResponse)
            {
                // todo: log record
                return(false);
            }

            txsToUpdate.ForEach(x =>
            {
                x.NeedUpdateServer = false;
                _txRepo.Update(x);
            });
            txSignatures.ForEach(x =>
            {
                x.NeedUpdateServer = false;
                _txRepo.Update(x);
            });

            serverResponse.Teams.ForEach(team =>
            {
                var existingTeam = _teamRepo.Get(team.Id);
                if (existingTeam == null)
                {
                    team.PayToAddressOkAge             = 14;
                    team.AutoApprovalMyGoodAddress     = 3;
                    team.AutoApprovalMyNewAddress      = 7;
                    team.AutoApprovalCosignGoodAddress = 3;
                    team.AutoApprovalCosignNewAddress  = 7;
                    existingTeam = _teamRepo.Add(team);
                }
                else
                {
                    // Can change Name
                    if (existingTeam.Name != team.Name)
                    {
                        existingTeam.Name = team.Name;
                        _teamRepo.Update(existingTeam);
                    }
                }
            });

            serverResponse.Teammates.ForEach(teammate =>
            {
                var existingTeammate = _teammateRepo.Get(teammate.Id);

                bool okToInsertOrUpdate = true;
                if (existingTeammate != null)
                {
                    if (existingTeammate.PublicKey != null && teammate.PublicKey != existingTeammate.PublicKey ||
                        teammate.FBName != existingTeammate.FBName ||
                        teammate.TeamId != existingTeammate.TeamId)
                    {
                        okToInsertOrUpdate = false; // we don't allow to change basic info
                    }
                }
                if (okToInsertOrUpdate)
                {
                    _teammateRepo.InsertOrUpdateDetached(teammate);
                }
            });

            serverResponse.PayTos.ForEach(payTo =>
            {
                var existingPayTo = _payToRepo.Get(payTo.TeammateId, payTo.Address);
                if (existingPayTo == null)
                {
                    payTo.KnownSince = DateTime.UtcNow;
                    existingPayTo    = _payToRepo.Add(payTo);
                }
                if (existingPayTo.IsDefault)
                {
                    _payToRepo.GetForTeammate(existingPayTo.TeammateId).ForEach(x =>
                    {
                        if (x.Address != existingPayTo.Address)
                        {
                            x.IsDefault = false;
                            _payToRepo.Update(x);
                        }
                    });
                }
            });

            serverResponse.BTCAddresses.ForEach(address =>
            {
                if (address.Address != null && _addressRepo.Get(address.Address) == null)
                {
                    if (address.Status == UserAddressStatus.Previous)
                    {
                        address.Status = UserAddressStatus.ServerPrevious;
                    }
                    else if (address.Status == UserAddressStatus.Current)
                    {
                        address.Status = UserAddressStatus.ServerCurrent;
                    }
                    else if (address.Status == UserAddressStatus.Next)
                    {
                        address.Status = UserAddressStatus.ServerNext;
                    }
                    _addressRepo.Add(address);
                }
            });

            serverResponse.Cosigners.ForEach(cosigner =>
            {
                if (cosigner.AddressId != null)
                {
                    if (_addressRepo.Get(cosigner.AddressId) == null) // can't add cosigners to existing addresses
                    {
                        _cosignerRepo.Add(cosigner);
                    }
                }
            });

            // Rules for setting new current address
            // ok to set first address
            // ok to change to next address if:
            // -- no funds on existing current address
            // -- or a real Tx from current to next occurred

            serverResponse.Txs.ForEach(tx =>
            {
                var existingTx = _txRepo.Get(tx.Id);
                if (existingTx == null)
                {
                    tx.ReceivedTime         = DateTime.UtcNow;
                    tx.UpdateTime           = DateTime.UtcNow;
                    tx.Resolution           = TxClientResolution.None;
                    tx.ClientResolutionTime = null;
                    tx.NeedUpdateServer     = false;
                    _txRepo.Add(tx);
                }
                else
                {
                    existingTx.State          = tx.State;
                    existingTx.UpdateTime     = DateTime.UtcNow;
                    existingTx.ResolutionTime = tx.ResolutionTime;
                    existingTx.ProcessedTime  = tx.ProcessedTime;
                    _txRepo.Update(existingTx);
                }
            });

            foreach (var txInput in serverResponse.TxInputs)
            {
                if (_txRepo.GetInput(txInput.Id) != null)
                {
                    continue; // can't change inputs
                }

                var tx = _txRepo.Get(txInput.TxId);
                if (tx == null)
                {
                    tx = serverResponse.Txs.FirstOrDefault(x => x.Id == txInput.TxId);
                }
                if (tx == null)
                {
                    continue; // malformed TX, todo: add log record
                }
                _txRepo.AddInput(txInput);
            }

            foreach (var txOutput in serverResponse.TxOutputs)
            {
                var tx = _txRepo.Get(txOutput.TxId);
                if (tx != null)
                {
                    continue; // can't add outputs to existing txs
                }
                tx = serverResponse.Txs.FirstOrDefault(x => x.Id == txOutput.TxId);
                if (tx == null)
                {
                    continue; // malformed TX, todo: add log record
                }
                _txRepo.AddOutput(txOutput);
            }

            foreach (var txSignatureInfo in serverResponse.TxSignatures)
            {
                if (_txRepo.GetSignature(txSignatureInfo.TxInputId, txSignatureInfo.TeammateId) != null)
                {
                    continue; // can't change signatures
                }

                var txInput = _txRepo.GetInput(txSignatureInfo.TxInputId);
                if (txInput == null)
                {
                    txInput = serverResponse.TxInputs.FirstOrDefault(x => x.Id == txSignatureInfo.TxInputId);
                }
                if (txInput == null)
                {
                    continue; // malformed TX, todo: add log record
                }
                var txSignature = new TxSignature()
                {
                    TxInputId        = txSignatureInfo.TxInputId,
                    TeammateId       = txSignatureInfo.TeammateId,
                    Signature        = Convert.FromBase64String(txSignatureInfo.Signature),
                    NeedUpdateServer = false
                };
                _txRepo.AddSignature(txSignature);
            }

            _context.SaveChanges();

            // Check outputs
            foreach (var arrivingTx in serverResponse.Txs)
            {
                var  tx           = _txRepo.Get(arrivingTx.Id);
                bool isWalletMove = (tx.Kind == TxKind.MoveToNextWallet || tx.Kind == TxKind.SaveFromPrevWallet);

                // Outputs are required unless it's a wallet update
                if (!isWalletMove && tx.Outputs == null)
                {
                    ChangeTxResolution(tx, TxClientResolution.ErrorBadRequest);
                    continue;
                }

                // AmountBTC sum must match total unless it's a wallet update
                if (!isWalletMove && Math.Abs(tx.Outputs.Sum(x => x.AmountBTC) - tx.AmountBTC.Value) > 0.000001M)
                {
                    ChangeTxResolution(tx, TxClientResolution.ErrorBadRequest);
                    continue;
                }

                if (tx.Resolution == TxClientResolution.None)
                {
                    ChangeTxResolution(tx, TxClientResolution.Received);
                }
            }

            _context.SaveChanges();

            // Check addresses
            serverResponse.BTCAddresses.ForEach(address =>
            {
                var addressSaved = _addressRepo.Get(address.Address);
                if (addressSaved != null)
                {
                    if (SignHelper.GenerateStringAddress(addressSaved) != addressSaved.Address)
                    {
                        addressSaved.Status = UserAddressStatus.Invalid;
                        _addressRepo.Update(addressSaved);
                    }
                }
            });

            // process inputs

            // verify amounts if inputs are set

            _connection.LastUpdated = new DateTime(serverResponse.LastUpdated, DateTimeKind.Utc);
            _connectionRepo.Update(_connection);

            _context.SaveChanges();

            return(true);
        }
Пример #5
0
 public void Add(Types.DTO.TeamDTO team)
 {
     repo.Add(team);
 }
Пример #6
0
 public void Add(Team team)
 {
     TeamRepository.Add(team);
 }
        /// <summary>
        /// From the timeline data scraped identify what game it corresponds.
        /// returns null if the game is not found
        /// </summary>
        /// <param name="data">the scraped timeline data</param>
        /// <returns>the corresponding game object</returns>
        public Game GetGameFromDetailsData(string data)
        {
            Game game = new Game();
            var allJson = JsonConvert.DeserializeObject<JObject>(data);
            string homeStr = allJson["Data"]["HomeTeam"].ToString();
            JsonTeam homeTeam = JsonConvert.DeserializeObject<JsonTeam>(homeStr);

            string awayStr = allJson["Data"]["AwayTeam"].ToString();
            JsonTeam awayTeam = JsonConvert.DeserializeObject<JsonTeam>(awayStr);

            string startStr = allJson["Data"]["DateTime"].ToString();
            DateTime start = Convert.ToDateTime(startStr);
            game.Start = start;

            if (homeTeam == null || awayTeam == null ||
                homeTeam.Name == null || awayTeam.Name == null)
            {
                return null;
            }

            // set up the teams
            using (var repository = new TeamRepository())
            {
                // home team
                var teams = (repository.GetAll().Where(t => t.ShortName == homeTeam.Code)).ToList();
                if (teams.Count > 0)
                {
                    game.HomeTeamId = teams[0].Id;
                }
                else
                {
                    var home = new Team() { Name = homeTeam.Name };
                    home.Id = repository.Add(home);
                    game.HomeTeamId = home.Id;
                    game.HomeTeam = home;
                }
                // away team
                teams = (repository.GetAll().Where(t => t.ShortName == awayTeam.Code)).ToList();
                if (teams.Count > 0)
                {
                    game.AwayTeamId = teams[0].Id;
                }
                else
                {
                    var away = new Team() { Name = awayTeam.Name };
                    away.Id = repository.Add(away);
                    game.AwayTeamId = away.Id;
                }
            }

            // get the score
            game.HomeGoals = homeTeam.Score;
            game.AwayGoals = awayTeam.Score;

            // set the status of the tweet mining
            game.TweetsRetrieved = RetrievalStatus.NONE;

            return game;
        }
Пример #8
0
 public Team Add(Team collectionItem, ObjectId parentId)
 {
     return(_teamRepository.Add(collectionItem));
 }