Ejemplo n.º 1
0
        public async Task <QbQuestionResponse> UpdateAsync(int id, QbQuestion qbQuestion)
        {
            QbQuestion oldQuestion = await _qbQuestionRepository.FindByIdAsync(id);

            if (oldQuestion == null)
            {
                return(new QbQuestionResponse("Question not found."));
            }

            oldQuestion.Level      = qbQuestion.Level;
            oldQuestion.Tournament = qbQuestion.Tournament;
            oldQuestion.Year       = qbQuestion.Year;
            oldQuestion.Power      = qbQuestion.Power;
            oldQuestion.Body       = qbQuestion.Body;
            oldQuestion.Answer     = qbQuestion.Answer;
            oldQuestion.Notes      = qbQuestion.Notes;

            try
            {
                _qbQuestionRepository.Update(oldQuestion);
                await _unitOfWork.CompleteAsync();

                return(new QbQuestionResponse(oldQuestion));
            }
            catch (Exception ex)
            {
                return(new QbQuestionResponse($"An error occurred when updating the question: {ex.Message}"));
            }
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> GetRandomAsync(string level = null)
        {
            int?levelInt = null;

            if (!String.IsNullOrEmpty(level))
            {
                Enum.TryParse(level, true, out ETournamentLevel levelEnum);
                // 0 is default enum value, which is returned if TryParse fails
                if (levelEnum != 0)
                {
                    levelInt = (int?)levelEnum;
                }
                else
                {
                    return(BadRequest());
                }
            }

            QbQuestion question = await _qbQuestionService.GetRandomAsync(levelInt);

            if (question == null)
            {
                return(NotFound());
            }

            QbQuestionResource resource = _mapper.Map <QbQuestion, QbQuestionResource>(question);

            return(Ok(resource));
        }
Ejemplo n.º 3
0
        /// <summary>Parses the raw text of the questions to obtain relevant information</summary>
        /// <returns>JSON representation of the questions in an array</returns>
        public override string Parse()
        {
            CleanText();

            const string questionSeparator      = @"\s{5,}[0-9]+\. ";
            const string powerSeparator         = @"\(\*\)";
            const string firstQuestionSeparator = @"1\. ";
            const string answerSeparator        = "ANSWER: ";
            const string notesPattern           = @"\[(.|\n|\r)*\]";

            List <string> tossups = Regex.Split(base.text, questionSeparator).ToList();

            if (tossups[0] == "")
            {
                tossups.RemoveAt(0);
            }
            tossups[0] = Regex.Replace(tossups[0], firstQuestionSeparator, String.Empty);

            // foreach loop does not allow assignment of individual elements
            for (int i = 0; i < tossups.Count; i++)
            {
                tossups[i] = tossups[i].Replace("\n", String.Empty);
                tossups[i] = tossups[i].Replace("\r", String.Empty);
                tossups[i] = tossups[i].Replace("\r\n", String.Empty);
            }

            List <QbQuestion> questions = new List <QbQuestion>();

            foreach (string tossup in tossups)
            {
                string[] tossupParts     = Regex.Split(tossup, powerSeparator);
                string   power           = tossupParts[0].Trim();
                string   bodyAnswerNotes = tossupParts[1];
                string   body            = Regex.Split(bodyAnswerNotes, answerSeparator)[0].Trim();
                string   answerNotes     = Regex.Split(bodyAnswerNotes, answerSeparator)[1];
                string   answer          = Regex.Split(answerNotes, notesPattern)[0].Trim();
                string   notes           = Regex.Match(answerNotes, notesPattern).ToString().Trim();

                if (!string.IsNullOrEmpty(notes))
                {
                    notes = notes.Split('[')[1].Split(']')[0];
                }

                QbQuestion question = new QbQuestion
                {
                    Level      = base.level,
                    Tournament = base.tournament,
                    Year       = base.year,
                    Power      = power,
                    Body       = body,
                    Answer     = answer,
                    Notes      = notes
                };

                questions.Add(question);
            }
            return(SerializeQuestionsToJson(questions));
        }
 public bool Remove(QbQuestion qbQuestion)
 {
     try
     {
         _context.QbQuestions.Remove(qbQuestion);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 5
0
        public async Task <IActionResult> GetAsync(int id)
        {
            QbQuestion question = await _qbQuestionService.GetAsync(id);

            if (question == null)
            {
                return(NotFound());
            }

            QbQuestionResource resource = _mapper.Map <QbQuestion, QbQuestionResource>(question);

            return(Ok(resource));
        }
Ejemplo n.º 6
0
        // TODO
        // public async Task AddToGame(string gameId)
        // {
        //     await Groups.AddToGroupAsync(Context.ConnectionId, gameId);
        // }

        // public async Task RemoveFromGroup(string gameId)
        // {
        //     await Groups.RemoveFromGroupAsync(Context.ConnectionId, gameId);
        // }

        public async Task SendQuestion(string gameId)
        {
            // TODO: Pre-fetch questions
            QbQuestionsClient client = new QbQuestionsClient();
            var response             = await client.GetRandomQuestionAsync();

            var json = await response.Content.ReadAsStringAsync();

            QbQuestion question = JsonConvert.DeserializeObject <QbQuestion>(json);
            await Clients.All.SendAsync("ReceiveQuestion", question);

            // TODO
            //await Clients.Group(gameId).SendAsync("ReceiveQuestion", question);
        }
        public async Task GetAsyncSuccessTest()
        {
            // Arrange
            IQbQuestionService qbQuestionService = Substitute.For <IQbQuestionService>();
            QbQuestion         question          = new QbQuestion();

            qbQuestionService.GetAsync(Arg.Any <int>()).Returns(question);
            QbQuestionsController controller = new QbQuestionsController(qbQuestionService, mapper);

            // Act
            IActionResult result = await controller.GetAsync(1);

            // Assert
            result.Should().BeOfType <OkObjectResult>();
        }
        public async Task GetRandomAsyncFailureTest()
        {
            // Arrange
            IQbQuestionService qbQuestionService = Substitute.For <IQbQuestionService>();
            QbQuestion         question          = null;

            qbQuestionService.GetRandomAsync(Arg.Any <int?>()).Returns(question);
            QbQuestionsController controller = new QbQuestionsController(qbQuestionService, mapper);

            // Act
            IActionResult result = await controller.GetRandomAsync(null);

            // Assert
            result.Should().BeOfType <NotFoundResult>();
        }
Ejemplo n.º 9
0
        public async Task <QbQuestionResponse> SaveAsync(QbQuestion qbQuestion)
        {
            try
            {
                await _qbQuestionRepository.AddAsync(qbQuestion);

                await _unitOfWork.CompleteAsync();

                return(new QbQuestionResponse(qbQuestion));
            }
            catch (Exception ex)
            {
                return(new QbQuestionResponse($"An error occurred when saving the question: {ex.Message}"));
            }
        }
Ejemplo n.º 10
0
        // TODO: Abstract more functionalities into the base class
        /// <summary>Parses the raw text of the questions to obtain relevant information</summary>
        /// <returns>JSON representation of the questions in an array</returns>
        public override string Parse()
        {
            CleanText();

            const string questionSeparator = @"\([0-9]+\) ";
            const string powerSeparator    = @"\(\*\)";
            const string answerSeparator   = "ANSWER: ";
            const string notesPattern      = @"\((.|\n|\r)*\)";

            List <string> tossups = Regex.Split(base.text, questionSeparator).ToList();

            if (tossups[0] == "\r\n\r\n")
            {
                tossups.RemoveAt(0);
            }

            List <QbQuestion> questions = new List <QbQuestion>();

            foreach (string tossup in tossups)
            {
                string[] tossupParts     = Regex.Split(tossup, powerSeparator);
                string   power           = tossupParts[0].Trim();
                string   bodyAnswerNotes = tossupParts[1];
                string   body            = Regex.Split(bodyAnswerNotes, answerSeparator)[0].Trim();
                string   answerNotes     = Regex.Split(bodyAnswerNotes, answerSeparator)[1];
                string   answer          = Regex.Split(answerNotes, notesPattern)[0].Trim();
                string   notes           = Regex.Match(answerNotes, notesPattern).ToString().Trim();

                if (!string.IsNullOrEmpty(notes))
                {
                    notes = notes.Split('(')[1].Split(')')[0];
                }

                QbQuestion question = new QbQuestion
                {
                    Level      = base.level,
                    Tournament = base.tournament,
                    Year       = base.year,
                    Power      = power,
                    Body       = body,
                    Answer     = answer,
                    Notes      = notes
                };

                questions.Add(question);
            }
            return(SerializeQuestionsToJson(questions));
        }
        public void UpdateAsyncSuccessTest()
        {
            // Arrange
            IQbQuestionRepository repository = Substitute.For <IQbQuestionRepository>();
            IUnitOfWork           unitOfWork = Substitute.For <IUnitOfWork>();
            QbQuestion            question   = new QbQuestion();

            repository.FindByIdAsync(Arg.Any <int>()).Returns(question);
            repository.Update(Arg.Any <QbQuestion>()).Returns(true);
            unitOfWork.CompleteAsync().Returns(Task.CompletedTask);
            QbQuestionService service = new QbQuestionService(repository, unitOfWork);

            // Act
            Task <QbQuestionResponse> result = service.UpdateAsync(1, question);

            // Assert
            result.Result.Success.Should().Be(true);
        }
        public async Task DeleteAsyncSuccessTest()
        {
            // Arrange
            QbQuestion         question          = new QbQuestion();
            QbQuestionResponse response          = new QbQuestionResponse(question);
            IQbQuestionService qbQuestionService = Substitute.For <IQbQuestionService>();

            qbQuestionService.DeleteAsync(Arg.Any <int>()).Returns(response);
            QbQuestionResource resource = new QbQuestionResource();

            mapper.Map <QbQuestion, QbQuestionResource>(Arg.Any <QbQuestion>()).Returns(resource);
            QbQuestionsController controller = new QbQuestionsController(qbQuestionService, mapper);

            // Act
            IActionResult result = await controller.DeleteAsync(1);

            // Assert
            result.Should().BeOfType <OkObjectResult>();
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> PutAsync(int id, [FromBody] SaveQbQuestionResource resource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorMessages()));
            }

            QbQuestion         question = _mapper.Map <SaveQbQuestionResource, QbQuestion>(resource);
            QbQuestionResponse result   = await _qbQuestionService.UpdateAsync(id, question);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }

            QbQuestionResource questionResource = _mapper.Map <QbQuestion, QbQuestionResource>(result.QbQuestion);

            return(Ok(questionResource));
        }
        public void SaveAsyncFailureOnAddTest()
        {
            // Arrange
            IQbQuestionRepository repository = Substitute.For <IQbQuestionRepository>();
            IUnitOfWork           unitOfWork = Substitute.For <IUnitOfWork>();

            repository.AddAsync(Arg.Any <QbQuestion>()).Throws(new Exception("Exception occurred on AddAsync"));
            QbQuestionService service  = new QbQuestionService(repository, unitOfWork);
            QbQuestion        question = new QbQuestion();

            // Act
            Task <QbQuestionResponse> result = service.SaveAsync(question);

            // Assert
            string errorMessage = "An error occurred when saving the question: Exception occurred on AddAsync";

            result.Result.Success.Should().Be(false);
            result.Result.Message.Should().Be(errorMessage);
        }
        public void DeleteAsyncFailureOnFindTest()
        {
            // Arrange
            IQbQuestionRepository repository = Substitute.For <IQbQuestionRepository>();
            IUnitOfWork           unitOfWork = Substitute.For <IUnitOfWork>();
            QbQuestion            question   = null;

            repository.FindByIdAsync(Arg.Any <int>()).Returns(question);
            QbQuestionService service = new QbQuestionService(repository, unitOfWork);

            // Act
            Task <QbQuestionResponse> result = service.DeleteAsync(1);

            // Assert
            string errorMessage = "Question not found.";

            result.Result.Success.Should().Be(false);
            result.Result.Message.Should().Be(errorMessage);
        }
        public async Task UpdateAsyncFailureTest()
        {
            // Arrange
            SaveQbQuestionResource resource = new SaveQbQuestionResource();
            QbQuestion             question = new QbQuestion();

            mapper.Map <SaveQbQuestionResource, QbQuestion>(Arg.Any <SaveQbQuestionResource>()).Returns(question);
            IQbQuestionService qbQuestionService = Substitute.For <IQbQuestionService>();
            QbQuestionResponse response          = new QbQuestionResponse(string.Empty);

            qbQuestionService.UpdateAsync(Arg.Any <int>(), Arg.Any <QbQuestion>()).Returns(response);
            QbQuestionsController controller = new QbQuestionsController(qbQuestionService, mapper);

            // Act
            IActionResult result = await controller.PutAsync(1, resource);

            // Assert
            result.Should().BeOfType <BadRequestObjectResult>();
        }
        public void DeleteAsyncFailureOnRemoveTest()
        {
            // Arrange
            IQbQuestionRepository repository = Substitute.For <IQbQuestionRepository>();
            IUnitOfWork           unitOfWork = Substitute.For <IUnitOfWork>();
            QbQuestion            question   = new QbQuestion();

            repository.FindByIdAsync(Arg.Any <int>()).Returns(question);
            repository.Remove(Arg.Any <QbQuestion>()).Throws(new Exception("Exception occurred on Remove"));
            QbQuestionService service = new QbQuestionService(repository, unitOfWork);

            // Act
            Task <QbQuestionResponse> result = service.DeleteAsync(1);

            // Assert
            string errorMessage = "An error occurred when deleting the question: Exception occurred on Remove";

            result.Result.Success.Should().Be(false);
            result.Result.Message.Should().Be(errorMessage);
        }
Ejemplo n.º 18
0
        public async Task <QbQuestionResponse> DeleteAsync(int id)
        {
            QbQuestion oldQuestion = await _qbQuestionRepository.FindByIdAsync(id);

            if (oldQuestion == null)
            {
                return(new QbQuestionResponse("Question not found."));
            }

            try
            {
                _qbQuestionRepository.Remove(oldQuestion);
                await _unitOfWork.CompleteAsync();

                return(new QbQuestionResponse(oldQuestion));
            }
            catch (Exception ex)
            {
                return(new QbQuestionResponse($"An error occurred when deleting the question: {ex.Message}"));
            }
        }
Ejemplo n.º 19
0
 private QbQuestionResponse(bool success, string message, QbQuestion qbQuestion)
 {
     Success    = success;
     Message    = message;
     QbQuestion = qbQuestion;
 }
Ejemplo n.º 20
0
 public async Task AddAsync(QbQuestion qbQuestion)
 {
     await _context.QbQuestions.AddAsync(qbQuestion);
 }
Ejemplo n.º 21
0
 public QbQuestionResponse(QbQuestion qbQuestion) : this(true, string.Empty, qbQuestion)
 {
 }