Пример #1
0
        /// <summary>
        /// AddAgentAsync
        /// </summary>
        /// <param name="agent"></param>
        /// <returns></returns>
        public async Task <AgentModel> AddAgentAsync(AgentModel agent)
        {
            try
            {
                using (var db = new CosmosUtil <AgentModel>("agents"))
                {
                    var theAgent = await db.GetItemAsync(agent.Id.ToString(), agent.Id.ToString());

                    if (theAgent != null) // Agent already exists
                    {
                        return(theAgent);
                    }

                    // Otherwise, add a new agent
                    agent.UpdatedOn = DateTime.UtcNow.ToString();

                    //Create or replace the Scores document
                    await db.UpsertItemAsync(agent);

                    return(agent);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #2
0
        public async Task <bool> PostAsync([FromBody] IEnumerable <IGame> games)
        {
            const string partitionKey = "/id";

            try
            {
                using (var db = new CosmosUtil <IGame>("games", partitionKey: partitionKey))
                {
                    // Update the create/update date
                    foreach (var game in games)
                    {
                        game.UpdatedOn = DateTime.UtcNow.ToString();
                    }

                    //Create or replace the Games documents
                    var response = await db.UpsertArrayAsync(games.ToList());

                    return(response.SuccessfulDocuments == games.Count());
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.PostAsync));
                Console.WriteLine(e);
                throw;
            }
        }
        public async Task <IEnumerable <ResultsModel> > CalculateGameResultsAsync([FromQuery] string id)
        {
            const string partitionKey = "/gameId";

            try
            {
                using (var db = new CosmosUtil <Scouter.Data.EventModelDTO>("events", partitionKey: partitionKey))
                {
                    //Check if the item is already exist, and then replace it
                    var eventData = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{id}'");

                    if (eventData.Count() == 0)
                    {
                        return(null);
                    }

                    // Return the game results
                    return(ScoresProcessor.ProcessResults(eventData));
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.CalculateGameResultsAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #4
0
        public async Task <IEnumerable <ScouterApi.Models.EventModel> > GetGameEventsAsync([FromQuery] string id)
        {
            const string partitionKey = "/gameId";

            try
            {
                using (var db = new CosmosUtil <Scouter.Data.EventModelDTO>("events", partitionKey: partitionKey))
                {
                    //Check if the item is already exist, and then replace it
                    var eventData = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{id}'");

                    //var eventData = await db.GetItemsAsync(
                    //    $"SELECT * FROM c WHERE c.gameId = '{id}' and c.isMaster = false");
                    var gameEvents = _mapper.Map <Scouter.Data.EventModelDTO[], IEnumerable <ScouterApi.Models.EventModel> >(eventData.ToArray());
                    return(gameEvents);
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.GetGameStatsAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #5
0
        public async Task <ScouterApi.Models.EventModel> GetEventsByAccountAsync([FromQuery] string id, [FromQuery] string account)
        {
            const string partitionKey = "/gameId";

            try
            {
                using (var db = new CosmosUtil <Scouter.Data.EventModelDTO>("events", partitionKey: partitionKey))
                {
                    //Check if the item is already exist, and then replace it
                    var events = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{id}' and c.account = '{account}'");

                    if (events.Count() > 0)
                    {
                        var data      = events.Last <Scouter.Data.EventModelDTO>();
                        var apiScores = _mapper.Map <ScouterApi.Models.EventModel>(data);
                        return(apiScores);
                    }
                    return(null);
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.GetEventsByAccountAsync));
                Console.WriteLine(e);
                throw;
            }
        }
        public async Task <IEnumerable <StandingModel> > GetStandingTableAsync([FromQuery] int numOfGames)
        {
            const string        partitionKey = "/gameId";
            var                 standings    = new List <StandingModel>();
            IEnumerable <IGame> lastGames    = null;

            try
            {
                using (var db = new CosmosUtil <IGame>("games", partitionKey: "/id"))
                {
                    // Return all games
                    var allGames = await db.GetItemsAsync("SELECT * FROM c");

                    // Take only the last numOfGames
                    lastGames = (numOfGames > 0) ? allGames.TakeLast(numOfGames) : allGames;
                }

                using (var db = new CosmosUtil <ResultsModel>("results", partitionKey: partitionKey))
                {
                    //Check if the item is already exist, and then replace it
                    var allResults = await db.GetItemsAsync($"SELECT * FROM c");

                    // Obtain the results for only the last # of games
                    List <ResultsModel> lastResults = (from result in allResults
                                                       let gameResult = lastGames.Where(g => g.Id.ToString() == result.GameId).FirstOrDefault()
                                                                        where gameResult != null
                                                                        select result).ToList();

                    // Generate the current standing based on the last # of game results
                    foreach (var result in lastResults)
                    {
                        var standing = standings.Where(s => s.AgentId == result.AgentId).FirstOrDefault();
                        if (standing != null)
                        {
                            standing.Score += result.Score;
                        }
                        else
                        {
                            standings.Add(new StandingModel
                            {
                                Id          = Guid.NewGuid(),
                                UpdatedOn   = DateTime.UtcNow.ToString(),
                                AgentId     = result.AgentId,
                                DisplayName = result.DisplayName,
                                Score       = result.Score
                            });
                        }
                    }

                    return(standings.OrderByDescending(s => s.Score));
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.GetStandingTableAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #7
0
        public async Task <bool> SaveConsensusPostAsync(ScouterApi.Models.EventModel scoreEvent)
        {
            const string partitionKey = "/gameId";

            // Update the new events's date
            scoreEvent.UpdatedOn = DateTime.UtcNow.ToString();

            try
            {
                // Map API data object to Data
                var scoreDTO = _mapper.Map <Scouter.Data.EventModelDTO>(scoreEvent);

                using (var db = new CosmosUtil <Scouter.Data.EventModelDTO>("consensus", partitionKey: partitionKey))
                {
                    //Check if the item is already exist, and then replace it
                    var oldScores = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{scoreEvent.GameId}' and c.account = '{scoreEvent.Account}'");

                    if (oldScores.Count() > 0)
                    {
                        // delete any old items except the last one
                        for (var i = 0; i < oldScores.Count() - 1; i++)
                        {
                            await db.DeleteItemAsync(oldScores.ToArray()[i].Id.ToString(), oldScores.ToArray()[i].GameId.ToString());
                        }

                        //Update precision for the event's time
                        foreach (var item in scoreEvent.Events)
                        {
                            item.EventTime = Decimal.Round(item.EventTime, 2);
                        }

                        //Replace the Scores document
                        await db.ReplaceItemAsync(scoreDTO, oldScores.Last().Id.ToString(), partitionKey : scoreEvent.GameId.ToString());
                    }
                    else
                    {
                        // Create a new one
                        await db.AddItemAsync(scoreDTO, partitionKey : scoreEvent.GameId.ToString());
                    }

                    return(true);
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.SaveConsensusPostAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #8
0
 /// <summary>
 /// GetAgent
 /// </summary>
 /// <param name="agentId"></param>
 /// <returns></returns>
 public async Task <AgentModel> GetAgent(Guid agentId)
 {
     try
     {
         using (var db = new CosmosUtil <AgentModel>("agents"))
         {
             return(await db.GetItemAsync(
                        agentId.ToString(),
                        agentId.ToString()));
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
Пример #9
0
        public async Task <IEnumerable <IGame> > GetAsync()
        {
            const string partitionKey = "/id";

            try
            {
                using (var db = new CosmosUtil <IGame>("games", partitionKey: partitionKey))
                {
                    // Return all games
                    return(await db.GetItemsAsync("SELECT * FROM c"));
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.GetAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #10
0
        public async Task <bool> SaveGoldCirclePostAsync([FromBody] GoldCircleModel goldCircle)
        {
            const string partitionKey = "/gameId";

            try
            {
                using (var db = new CosmosUtil <GoldCircleModel>("GoldCircle", partitionKey: partitionKey))
                {
                    // Update the new events's date
                    goldCircle.UpdatedOn = DateTime.UtcNow.ToString();

                    //Check if the item is already exist, and then replace it
                    var oldGoldenCircle = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{goldCircle.GameId}'");

                    if (oldGoldenCircle.Count() > 0)
                    {
                        // delete any old items except the last one
                        for (var i = 0; i < oldGoldenCircle.Count() - 1; i++)
                        {
                            await db.DeleteItemAsync(oldGoldenCircle.ToArray()[i].Id.ToString(), oldGoldenCircle.ToArray()[i].GameId.ToString());
                        }

                        //Replace the Gold Circle document
                        await db.ReplaceItemAsync(goldCircle, oldGoldenCircle.Last().Id.ToString(), partitionKey : goldCircle.GameId.ToString());
                    }
                    else
                    {
                        // Create a new one
                        await db.AddItemAsync(goldCircle, partitionKey : goldCircle.GameId.ToString());
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.SaveGoldCirclePostAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #11
0
        public async Task <GoldCircleModel> GetGoldenCircleAsync([FromQuery] string id)
        {
            const string partitionKey = "/gameId";

            try
            {
                using (var db = new CosmosUtil <GoldCircleModel>("GoldCircle", partitionKey: partitionKey))
                {
                    // Return the Gold Circle for the specific game
                    var goldCircle = await db.GetItemsAsync($"SELECT * FROM c WHERE c.gameId = '{id}'");

                    return(goldCircle.FirstOrDefault());
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.GetGoldenCircleAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #12
0
        public async Task <bool> IsMasterAsync([FromQuery] string id)
        {
            const string partitionKey = "/id";

            try
            {
                using (var db = new CosmosUtil <BaseModel>("masters", partitionKey: partitionKey))
                {
                    //Return TRUE if at least one record exists for the given Id
                    var masterRecord = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.id = '{id}'");

                    return(masterRecord != null && masterRecord.Count() > 0);
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.IsMasterAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #13
0
        public async Task <IEnumerable <ScouterApi.Models.ConsensusModel> > GetGameStatsAsync([FromBody] GoldCircleModel goldCircle)
        {
            if (!goldCircle.AgentIds.Any())
            {
                return(null);
            }

            const string partitionKey = "/gameId";

            try
            {
                using (var db = new CosmosUtil <Scouter.Data.EventModelDTO>("events", partitionKey: partitionKey))
                {
                    //Check if the item is already exist, and then replace it
                    var eventData = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{goldCircle.GameId}'");

                    if (eventData.Count() == 0)
                    {
                        return(null);
                    }

                    // Filter event data to include only the keys from the selected agents
                    var filteredData = (from key in goldCircle.AgentIds
                                        let data = eventData.Where(d => d.Account == key).FirstOrDefault()
                                                   where data != null
                                                   select data).ToList();
                    var scoreStats = ScoresProcessor.ProcessScores(filteredData);
                    return(scoreStats);
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.GetGameStatsAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #14
0
        public async Task <IEnumerable <ResultsModel> > GetGameResultsAsync([FromQuery] string id)
        {
            const string partitionKey = "/gameId";

            try
            {
                using (var db = new CosmosUtil <ResultsModel>("results", partitionKey: partitionKey))
                {
                    //Check if the item is already exist, and then replace it
                    var results = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{id}'");

                    // Return the game results
                    return(results.OrderByDescending(r => r.Score));
                }
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.GetGameResultsAsync));
                Console.WriteLine(e);
                throw;
            }
        }
Пример #15
0
        public async Task <bool> PostAsync([FromBody] ScouterApi.Models.EventModel scoreEvent)
        {
            const string partitionKey = "/gameId";

            // Update the new events's date
            scoreEvent.UpdatedOn = DateTime.UtcNow.ToString();

            try
            {
                // Map API data object to Data
                var scoreDTO = _mapper.Map <Scouter.Data.EventModelDTO>(scoreEvent);

                IEnumerable <Scouter.Data.EventModelDTO> gameScores = null;

                using (var db = new CosmosUtil <Scouter.Data.EventModelDTO>("events", partitionKey: partitionKey))
                {
                    // Get all game scores
                    gameScores = await db.GetItemsAsync(
                        $"SELECT * FROM c WHERE c.gameId = '{scoreEvent.GameId}'");

                    //Check if the item is already exist, and then replace it
                    var oldScores = gameScores.Where(s => s.Account == scoreEvent.Account).ToList();
                    //var oldScores = await db.GetItemsAsync(
                    //    $"SELECT * FROM c WHERE c.gameId = '{scoreEvent.GameId}' and c.account = '{scoreEvent.Account}'");
                    if (oldScores.Count() > 0)
                    {
                        // delete any old items except the last one
                        for (var i = 0; i < oldScores.Count() - 1; i++)
                        {
                            await db.DeleteItemAsync(oldScores.ToArray()[i].Id.ToString(), oldScores.ToArray()[i].GameId.ToString());
                        }

                        //Update precision for the event's time
                        foreach (var item in scoreEvent.Events)
                        {
                            item.EventTime = Decimal.Round(item.EventTime, 2);
                        }

                        //Replace the Scores document
                        await db.ReplaceItemAsync(scoreDTO, oldScores.Last().Id.ToString(), partitionKey : scoreEvent.GameId.ToString());
                    }
                    else
                    {
                        // Create a new one
                        await db.AddItemAsync(scoreDTO, partitionKey : scoreEvent.GameId.ToString());
                    }
                }

                if (scoreDTO.IsMaster)
                {
                    // Calculate the game results and save it in the Database
                    var gameResults = ScoresProcessor.ProcessResults(gameScores).ToList();
                    if (gameResults == null)
                    {
                        return(false);
                    }

                    // Save to the database
                    using (var db = new CosmosUtil <ResultsModel>("results", partitionKey: partitionKey))
                    {
                        // Get all game scores
                        var results = await db.GetItemsAsync(
                            $"SELECT * FROM c WHERE c.gameId = '{scoreEvent.GameId}'");

                        if (results.Count() > 0)
                        {
                            // Replace any old items with the new ones
                            foreach (var item in results)
                            {
                                //Delete old document
                                await db.DeleteItemAsync(item.Id.ToString(), partitionKey : scoreEvent.GameId.ToString());
                            }
                        }

                        // Create or update the results
                        await db.UpsertArrayAsync(gameResults, partitionKey : scoreEvent.GameId.ToString());
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                LogUtil.LogError(this._logger, e.Message, nameof(this.PostAsync));
                Console.WriteLine(e);
                throw;
            }
        }