public async Task <IActionResult> PutScore(string id, string userid, ScoreRequest request)
        {
            if (userid == "@me")
            {
                userid = UserId;
            }

            var objective = (await _scoreboard.GetByApplicationAsync(AppId)).FirstOrDefault(o => o.Id == id);

            if (objective == null)
            {
                return(NotFound(new ErrorResponse("The objective does not exist.")));
            }

            var user = await _users.GetByIdAsync(userid);

            if (user == null)
            {
                return(NotFound(new ErrorResponse("The user does not exist.")));
            }

            await _scoreboard.SetScoreAsync(id, userid, request.Value);

            return(NoContent());
        }
Beispiel #2
0
        /// <summary>
        /// 增加积分记录
        /// </summary>
        public ResultJson AddScoreRecord(ScoreRequest request)
        {
            ResultJson result = new ResultJson();
            bool       flag   = false;

            if (request.ScoreType.EqualString(Enum_ScoreType.Sport.Enum_GetString()))
            {
                if (CacheForModelScore.Instance.InsertSportScore(request.UserId))
                {
                    flag = true;
                }
            }
            else if (request.ScoreType.EqualString(Enum_ScoreType.Sleep.Enum_GetString()))
            {
                if (CacheForModelScore.Instance.InsertSleepScore(request.UserId))
                {
                    flag = true;
                }
            }
            if (flag)
            {
                result.HttpCode = 200;
                result.Message  = "用户积分增加";
            }
            else
            {
                result.HttpCode = 300;
                result.Message  = Enum_Message.DataNotSuccessMessage.Enum_GetString();
            }
            return(result);
        }
        public IActionResult Get([FromQuery] ScoreRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.TimeStamp))
                {
                    return(BadRequest("Timestamp not set in the request"));
                }
                string[] facilityIds = ParseFacilities();
                if (facilityIds.Length == 0)
                {
                    Log.Information($"GetAll returning BadRequest & facility parameter not set in request headers");
                    return(BadRequest("facility parameter not set"));
                }

                DateTime dateTimeFormatted = RoundUp(DateTime.Parse(request.TimeStamp), TimeSpan.FromMinutes(30));
                var      buildingScores    = _healthyBuildingRepository
                                             .GetHealthyBuildingScoreTask(ParseFacilities(), dateTimeFormatted).Result;

                if (buildingScores.Length == 0)
                {
                    Log.Information($"returning 404 & no data found for Facility ids");
                    return(NotFound("no data found for Facility ids"));
                }

                return(Ok(buildingScores));
            }
            catch (Exception ex)
            {
                Log.Error($"exception {ex}");
                return(StatusCode(500, new { Status = "Error", Message = "Failed in fetching recent aggregated score for healthy buildings" }));
            }
        }
Beispiel #4
0
    public static IEnumerator addScore(int score, Action <String> onDone)
    {
        Dictionary <string, string> headers = new Dictionary <string, string> ();

        headers.Add("Content-Type", "application/json");
        headers.Add("Token", AppGlobal.token);

        ScoreRequest requestData   = new ScoreRequest(score);
        String       requestString = requestData.toJson();

        var encoding = new System.Text.UTF8Encoding();
        WWW request  = new WWW(SCORE_URI, encoding.GetBytes(requestString), headers);

        yield return(request);

        if (request.error != null)
        {
            Debug.Log("request error: " + request.error);
        }
        else
        {
            Debug.Log("request error: " + request.text);
        }

        onDone.Invoke("");
    }
Beispiel #5
0
 public override Task <ScoreReply> GetScore(ScoreRequest request, ServerCallContext context)
 {
     this._logger.LogInformation($"This is ScoreService GetScore {request.LessonId}");
     return(Task.FromResult(new ScoreReply()
     {
         Score = 100
     }));
 }
        public static Score ToScore(this ScoreRequest request)
        {
            var score = new Score
            {
                User      = String.IsNullOrEmpty(request.User) ? "anon e mouse" : request.User,
                Submitted = DateTime.UtcNow,
                Deck      = Newtonsoft.Json.JsonConvert.SerializeObject(request.Deck),
                Lenght    = request.Lenght,
                Players   = request.Players
            };

            return(score);
        }
        /// <summary>
        /// Call the end point of a scoring experiment and return the results
        /// may throw an ApiException if parsing fails
        /// </summary>
        /// <param name="webServiceUri">scoring web service end point URI</param>
        /// <param name="apiKey">scoring web service API key</param>
        /// <param name="featureVector">feature vector</param>
        /// <param name="globalParameters">global parameters</param>
        /// <param name="singleResultInitialization">initialization method for generating response entries</param>
        /// <param name="isMultipleResults">true to return multiple results (when available), false to return only one result</param>
        /// <returns>scoring results</returns>
        private static IList <T> Score <T>(string webServiceUri, string apiKey, Dictionary <string, string> featureVector, Dictionary <string, string> globalParameters, Func <string[], T> singleResultInitialization, bool isMultipleResults = false, IEnumerable <KeyValuePair <string, string> > headers = null)
        {
            ScoreData scoreData = new ScoreData
            {
                FeatureVector    = featureVector ?? new Dictionary <string, string>(),
                GlobalParameters = globalParameters ?? new Dictionary <string, string>()
            };

            ScoreRequest scoreRequest = new ScoreRequest
            {
                Id       = Guid.NewGuid().ToString(),
                Instance = scoreData
            };



            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

                // add any custom headers
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                client.BaseAddress = FormatUri(webServiceUri, isMultipleResults);
                HttpResponseMessage response = client.PostAsJsonAsync("", scoreRequest).Result;
                if (!response.IsSuccessStatusCode)
                {
                    // format all the headers of the response
                    var headersString = new StringBuilder();
                    if (response.Headers != null)
                    {
                        foreach (var header in response.Headers)
                        {
                            headersString.AppendFormat("{0}: {1} {2}", header.Key, string.Join(",", header.Value), Environment.NewLine);
                        }
                    }
                    // once an error happens, collect the response reason + http status + headers to better handle the error
                    throw new ApplicationException(string.Format("Error getting scoring results: error code: {1} , reason reported:{0} , response headers: {2}", (int)response.StatusCode, response.ReasonPhrase ?? string.Empty, headersString.ToString()));
                }

                return(ParseResponse(response.Content.ReadAsStringAsync().Result, singleResultInitialization));
            }
        }
        public async Task <bool> IsDeviceReliable(string correlationId, double temperature)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    ScoreData scoreData = new ScoreData()
                    {
                        FeatureVector = new Dictionary <string, string>()
                        {
                            { "temperature", temperature.ToString() },
                        },
                        GlobalParameters = new Dictionary <string, string>()
                        {
                        }
                    };

                    ScoreRequest scoreRequest = new ScoreRequest()
                    {
                        Id       = correlationId,
                        Instance = scoreData
                    };

                    string apiKey   = CloudConfigurationManager.GetSetting("AzureMLApiKey");
                    string endpoint = CloudConfigurationManager.GetSetting("AzureMLEndpoint");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

                    client.BaseAddress = new Uri(endpoint);
                    HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();

                        var array = JArray.Parse(result);

                        return(array.Last.Value <int>() == 0);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("There was an error with AzureML: {0}", ex);
            }

            return(_defaultReliability == FailAction.Reliable);
        }
Beispiel #9
0
        public void SendPicture(byte[] data)
        {
            if (!tcpClient.Connected)
            {
                tcpClient.Connect("localhost", 52200);
            }

            var     stream  = tcpClient.GetStream();
            Request request = new EmptyRequest();

            switch (response.Type)
            {
            case Response.MessageType.Start:
                request = new ImageRequest(data);
                break;

            case Response.MessageType.Control:
                request = new ImageRequest(data);
                break;

            case Response.MessageType.Result:
                request = new ScoreRequest(score);
                break;

            case Response.MessageType.Finish:
                SceneManager.LoadScene(0);
                SeriesNumber++;
                break;

            case Response.MessageType.End:
                Application.Quit();
                break;

            default:
                break;
            }

            var reqBytes = reqSerializer.Serialize(request);

            stream.Write(reqBytes, 0, reqBytes.Length);
            var receiveBytes = new byte[9];

            stream.Read(receiveBytes, 0, receiveBytes.Length);
            response = respSerializer.Deserialize(receiveBytes);
            Debug.Log(string.Format("{0:0.000} {1:0.000}", response.DeltaAngle, response.DeltaVelocity));
        }
        public async Task<bool> IsDeviceReliable(string correlationId, double temperature)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    ScoreData scoreData = new ScoreData()
                    {
                        FeatureVector = new Dictionary<string, string>()
                    {
                        {"temperature", temperature.ToString()},
                    },
                        GlobalParameters = new Dictionary<string, string>() { }

                    };

                    ScoreRequest scoreRequest = new ScoreRequest()
                    {
                        Id = correlationId,
                        Instance = scoreData
                    };

                    string apiKey = CloudConfigurationManager.GetSetting("AzureMLApiKey");
                    string endpoint = CloudConfigurationManager.GetSetting("AzureMLEndpoint");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

                    client.BaseAddress = new Uri(endpoint);
                    HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();
                        
                        var array = JArray.Parse(result);

                        return array.Last.Value<int>() == 0;
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("There was an error with AzureML: {0}", ex);
            }

            return _defaultReliability == FailAction.Reliable;
        }
    private ScoreResponse OnUpdateScoreboard(ScoreRequest request, ICommandCallerInfo callerInfo)
    {
        List <ScoreEntry> points = request.points;

        for (int i = 0; i < 5; i++)
        {
            if (i < points.Count)
            {
                scoreCanvasUI.transform.Find("Position" + i).GetComponentInChildren <Text>().text = points[i].name + ": " + points[i].value;
            }
            else
            {
                scoreCanvasUI.transform.Find("Position" + i).GetComponentInChildren <Text>().text = "";
            }
        }
        return(new ScoreResponse());
    }
    static async Task InvokeRequestResponseService()
    {
        using (var client = new HttpClient())
        {
            ScoreData scoreData = new ScoreData()
            {
                FeatureVector = new Dictionary <string, string>()
                {
                    { "vtCOPBRWheelSpeed", "0" },
                    { "vtCOPBRMassFlow", "0" },
                    { "vtCOPBRRotorDrivePressure", "0" },
                    { "vtCOPBRRotorSpeed", "0" },
                    { "vtCOPBRFuelConsumption", "0" },
                    { "vtCOPBRRotorEfficiency", "0" },
                },
                GlobalParameters =
                    new Dictionary <string, string>()
                {
                }
            };

            ScoreRequest scoreRequest = new ScoreRequest()
            {
                Id       = "score00001",
                Instance = scoreData
            };

            const string apiKey = "0feHeToqtjZZFTH+2rF17V7C1qo7RVaIs+kT7AkqqI0711KiHBhI8tyFWFT2T4SO1AtSMjZPecBHrmFPCjdOYA==";     // Replace this with the API key for the web service
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

            client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/fc2a1659df5d4f5fb16c9fd6aaebf458/services/c54e29675c0b444083ef6bc655be78f5/score");
            HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();

                Console.WriteLine("Result: {0}", result);
            }
            else
            {
                Console.WriteLine("Failed with status code: {0}", response.StatusCode);
            }
        }
    }
Beispiel #13
0
        /// <summary>
        /// 添加 成绩
        /// </summary>
        /// <param name="requestModel"></param>
        /// <returns></returns>
        public Result <long> Add(ScoreRequest requestModel)
        {
            if (requestModel == null)
            {
                return(Result.Error <long>(MsgParameterError));
            }

            var newScore = new Score()
            {
                Id        = IdHelper.Instance.LongId,
                UserId    = requestModel.UserId,
                ScoreData = requestModel.ScoreData,
            };

            var result = DbSession.ScoreRepository.Add(newScore);

            return(result ?  Result.Success(newScore.Id) : Result.Error <long>(MsgAddError));
        }
        public async Task <IHttpActionResult> ScoreAsync(int id, ScoreRequest request)
        {
            DAL.Models.Match match = await UnitOfWork.GetMatchRepository().SelectByIdAsync(id)
                                     ?? throw new ActionCannotBeExecutedException(ExceptionMessages.MatchNotFound);

            if (!match.Players.Any(p => p.Id != request.AuthorId))
            {
                throw new ActionCannotBeExecutedException(ExceptionMessages.PlayerNotFound + $" In match by Id : {id} UserId : {request.AuthorId}");
            }

            IPlayerRepository playerRepo = UnitOfWork.GetPlayerRepository();

            DAL.Models.Player author = await playerRepo.SelectByIdAsync(request.AuthorId)
                                       ?? throw new ActionCannotBeExecutedException(ExceptionMessages.PlayerNotFound);

            DAL.Models.Player assistant = null;

            if (request.AssistantId.HasValue)
            {
                if (!match.Players.Any(p => p.Id != request.AssistantId.Value))
                {
                    throw new ActionCannotBeExecutedException(ExceptionMessages.PlayerNotFound + $" In match by Id : {id} UserId : {request.AuthorId}");
                }
                assistant = await playerRepo.SelectByIdAsync(request.AssistantId.Value)
                            ?? throw new ActionCannotBeExecutedException(ExceptionMessages.PlayerNotFound);

                if (assistant.TeamId != author.TeamId)
                {
                    throw new ActionCannotBeExecutedException(ExceptionMessages.TeamsMustBeSame);
                }
            }

            match.Goals.Add(new DAL.Models.Goal
            {
                Author    = author,
                Assistant = assistant,
                GoalDt    = DateTimeOffset.Now,
                Team      = author.Team
            });
            await UnitOfWork.SaveChangesAsync();

            return(Ok());
        }
Beispiel #15
0
        public ScoreResponse Save(ScoreRequest request)
        {
            bool newRecord    = false;
            var  lastMaxScore = GetMaxScore();

            if (request.TotalScore > lastMaxScore.TotalScore && lastMaxScore.TotalScore > 0)
            {
                newRecord = true;
            }

            var score = new Score(request.GameDate, request.TotalScore, newRecord);

            if (score.Valid)
            {
                scoreRepository.Save(score);
            }

            return((ScoreResponse)score);
        }
Beispiel #16
0
        public void Should_Add_New_Score()
        {
            ScoreRequest scoreRequest = new ScoreRequest
            {
                GameDate   = DataGenerator.GameDateValid,
                TotalScore = DataGenerator.TotalScoreValid
            };

            scoreService.Save(scoreRequest);

            scoreRepositoryMock.Verify(x =>
                                       x.Save(
                                           It.Is <Score>(s =>
                                                         s.GameDate == scoreRequest.GameDate &&
                                                         s.TotalScore == scoreRequest.TotalScore &&
                                                         s.IsRecord == false
                                                         )
                                           )
                                       );
        }
        public async Task <IActionResult> Post([FromBody] ScoreRequest value)
        {
            if (ModelState.IsValid)
            {
                //fix values
                var dbvalue = value.ToScore();

                var current = _thresholdService.UpdateThreshold(dbvalue.Lenght, dbvalue.Players);

                //add and save to db
                _context.Scores.Add(dbvalue);
                await _context.SaveChangesAsync();

                SendGameToVerify(dbvalue);

                return(Ok(current));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Beispiel #18
0
        public void Should_Add_New_Score_Record()
        {
            scoreRepositoryMock.Setup(x => x.GetMaxScore()).Returns(1);

            ScoreRequest scoreRequest = new ScoreRequest
            {
                GameDate   = DataGenerator.GameDateValid,
                TotalScore = DataGenerator.TotalScoreValid
            };

            scoreService.Save(scoreRequest);

            scoreRepositoryMock.Verify(x =>
                                       x.Save(
                                           It.Is <Score>(s =>
                                                         s.GameDate == scoreRequest.GameDate &&
                                                         s.TotalScore == scoreRequest.TotalScore &&
                                                         s.IsRecord == true
                                                         )
                                           )
                                       );
        }
        public static async Task <string> ProcessScoreRequest(ScoreRequest scoreRequest, bool scoreResult = true)
        {
            Logging.LogMessage(LogLevel.Info, $"Processing Range:{scoreRequest.Range.From}-{scoreRequest.Range.To}");
            var saveRequests  = new List <Task <((string bucketName, string key), PutObjectResponse response)> >();
            var items         = (await GetItemsFromS3(scoreRequest)).ToList();
            var scoredResults = items.Where(i => i != null).Select(ScoreResult)
                                .ToList();
            var max = scoredResults.Max(r => r.Score);
            var scoredResultsWithRatings = scoredResults
                                           .Select(c =>
            {
                c.Rating = ((c.Score / max) * 100.0).GetRating().FormatRating();
                return(c);
            })
                                           .ToList();
            var itemsJson = JsonConvert.SerializeObject(scoredResultsWithRatings);

            var keyPrefix = $"{Config.ScoresOutputPrefix}output-{scoreRequest.Range.From}-{scoreRequest.Range.To}";

            saveRequests.Add(SaveToS3Object(itemsJson, Config.PublicBucketName, $"{keyPrefix}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}.json"));

            // update latest if the Score request is equivalent to the default lookup range
            if (scoreRequest.Range.From == DefaultRange.From && scoreRequest.Range.To == DefaultRange.To)
            {
                if (scoreRequest.Range.To >= 100)
                {
                    var worst100ItemsJson = JsonConvert.SerializeObject(scoredResultsWithRatings.OrderBy(c => c.Score).Take(100));
                    var nextItemsJson     = JsonConvert.SerializeObject(scoredResultsWithRatings.OrderBy(c => c.Score).Skip(100));
                    saveRequests.Add(SaveToS3Object(worst100ItemsJson, Config.PublicBucketName, $"{Config.ScoresOutputPrefix}output-0-100-latest.json"));
                    saveRequests.Add(SaveToS3Object(nextItemsJson, Config.PublicBucketName, $"{Config.ScoresOutputPrefix}output-100-{scoreRequest.Range.To}-latest.json"));
                }
                saveRequests.Add(SaveToS3Object(itemsJson, Config.PublicBucketName, $"{keyPrefix}-latest.json"));
            }

            await Task.WhenAll(saveRequests);

            Logging.LogMessage(LogLevel.Info, $"Found {items.Count} items and saved {scoredResults.Count} of them, max score was {max}");
            return(string.Join('|', saveRequests.Select(r => $"{r.Result.Item1.bucketName}/{r.Result.Item1.key}")));
        }
Beispiel #20
0
        /// <summary>
        /// 修改 成绩
        /// </summary>
        /// <param name="id"></param>
        /// <param name="requestModel"></param>
        /// <returns></returns>
        public Result Edit(long id, ScoreRequest requestModel)
        {
            if (id < 1 || requestModel == null)
            {
                return(Result.Error(MsgParameterError));
            }

            var currentScore = DbSession.ScoreRepository.Get(id);

            if (currentScore == null)
            {
                return(Result.Error("该成绩不存在!"));
            }

            currentScore.UserId    = requestModel.UserId;
            currentScore.ScoreData = requestModel.ScoreData;


            var result = DbSession.ScoreRepository.Update(currentScore);

            return(result ?  Result.Success(MsgEditSuccess) : Result.Error(MsgEditError));
        }
Beispiel #21
0
        public ActionResult <ScoreResponse> Add([FromBody] ScoreRequest request)
        {
            var response = scoreService.Save(request);

            if (!response.Notifications.Any())
            {
                try
                {
                    unitOfWork.Commit();

                    return(Created(string.Empty, response));
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, $"Houve um problema interno com o servidor. Entre em contato com o Administrador do sistema caso o problema persista. Erro interno: {ex.Message}"));
                }
            }
            else
            {
                response.Notifications = response.Notifications;
                return(BadRequest(response));
            }
        }
Beispiel #22
0
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='quizid'>
 /// </param>
 /// <param name='attemptid'>
 /// </param>
 /// <param name='scoreReq'>
 /// </param>
 public static AttemptScore CalculateAttemptScore(this IQuizAPIClient operations, string quizid, string attemptid, ScoreRequest scoreReq)
 {
     return(Task.Factory.StartNew(s => ((IQuizAPIClient)s).CalculateAttemptScoreAsync(quizid, attemptid, scoreReq), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Beispiel #23
0
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='quizid'>
 /// </param>
 /// <param name='attemptid'>
 /// </param>
 /// <param name='scoreReq'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <AttemptScore> CalculateAttemptScoreAsync(this IQuizAPIClient operations, string quizid, string attemptid, ScoreRequest scoreReq, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CalculateAttemptScoreWithHttpMessagesAsync(quizid, attemptid, scoreReq, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Beispiel #24
0
        public async Task <HttpResponseMessage> PostScore(string quizid, string attemptid, [FromBody] ScoreRequest scoreReq)
        {
            var quiz = quizRepo.FindQuiz(quizid);

            if (quiz == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            var attempt = attemptsRepo.FindAttempt(quizid, attemptid);

            if (attempt == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            if (scoreReq == null)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            // Calculate score for the given attempt and store this:
            var score = attempt.Score(scoreReq.Answers, quizRepo);

            attemptsRepo.StoreAttemptScore(quizid, attemptid, score);

            // Raise webhook when score was posted and recorded:
            await this.NotifyAllAsync("attemptscored", new { quizid = quizid, attemptid = attemptid });

            //await this._manager.NotifyAllAsync("attemptscored", new { QuizId = quizid, AttemptId = attemptid });


            return(Request.CreateResponse(HttpStatusCode.OK, score));
        }
        public ReturnScore Index(ScoreRequest request)
        {
            var frames     = request.Frames;
            var tenthFrame = request.TenthFrame;

            if (frames.Count > 9)
            {
                return new ReturnScore
                       {
                           HasErrors = true,
                           Errors    = new List <string> {
                               "Cannot have more than 9 standard frames"
                           }
                       }
            }
            ;

            var scores = new ReturnScore
            {
                Errors    = new List <string>(),
                HasErrors = false,
                Scores    = new List <int>()
            };

            for (var i = 0; i < frames.Count; i++)
            {
                var frame = frames[i];
                try
                {
                    frame.ValidateInput();

                    if (i == frames.Count - 1)
                    {
                        scores.Scores.Add(frame.ScoreFrame(tenthFrame.MarkOne, tenthFrame.MarkTwo));
                    }

                    else
                    {
                        if (!string.IsNullOrEmpty(frames[i + 1].MarkTwo))
                        {
                            scores.Scores.Add(frame.ScoreFrame(frames[i + 1].MarkOne, frames[i + 1].MarkTwo));
                        }
                        else if (i < frames.Count - 2)
                        {
                            scores.Scores.Add(frame.ScoreFrame(frames[i + 1].MarkOne, frames[i + 2].MarkOne));
                        }
                        else if (i < frames.Count - 1) // scoring 8th frame
                        {
                            scores.Scores.Add(frame.ScoreFrame(frames[i + 1].MarkOne, tenthFrame.MarkOne));
                        }
                        else // 9th frame
                        {
                            scores.Scores.Add(frame.ScoreFrame(tenthFrame.MarkOne, tenthFrame.MarkTwo));
                        }
                    }
                }

                catch (Exception ex)
                {
                    scores.HasErrors = true;
                    scores.Errors.Add(ex.Message);
                }
            }
            try
            {
                tenthFrame.ValidateTenthFrame();

                scores.Scores.Add(tenthFrame.ScoreFrame());
            }
            catch (Exception ex)
            {
                scores.HasErrors = true;
                scores.Errors.Add(ex.Message);
            }
            return(scores);
        }
    }