Exemplo n.º 1
0
        public void GetQuestion_WhenInvoked_ShouldReturnQuestionMatchingId()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            Functions functions = new Functions();

            request = new APIGatewayProxyRequest();

            const int questionId = 1;

            request.QueryStringParameters = new Dictionary <string, string>
            {
                { "Id", questionId.ToString() }
            };

            context  = new TestLambdaContext();
            response = functions.GetQuestion(request, context);

            var question         = JsonConvert.DeserializeObject <Question>(response.Body);
            var expectedQuestion = QuestionsDb.GetQuestion(questionId);

            Assert.Equal(expectedQuestion.Id, question.Id);
            Assert.Equal(expectedQuestion.Title, question.Title);
            Assert.NotEmpty(question.Options);
            Assert.Equal(expectedQuestion.Options.Count, question.Options.Count);
            Assert.Equal(expectedQuestion.Options[ZERO].Title, question.Options[ZERO].Title);
        }
Exemplo n.º 2
0
        public void GetQuestions_WhenInvoked_ShouldReturnAllAvailableQuestions()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            Functions functions = new Functions();

            request  = new APIGatewayProxyRequest();
            context  = new TestLambdaContext();
            response = functions.GetQuestions(request, context);

            var questions         = JsonConvert.DeserializeObject <List <Question> >(response.Body);
            var expectedQuestions = QuestionsDb.GetQuestions();

            Assert.Equal(expectedQuestions.Count, questions.Count);
            Assert.True(expectedQuestions.Count > ONE);

            Assert.Equal(expectedQuestions[ZERO].Title, questions[ZERO].Title);
            Assert.Equal(expectedQuestions[ZERO].Options.Count, questions[ZERO].Options.Count);
            Assert.Equal(expectedQuestions[ZERO].Options[ZERO].Title, questions[ZERO].Options[ZERO].Title);

            Assert.Equal(expectedQuestions[ONE].Title, questions[ONE].Title);
            Assert.Equal(expectedQuestions[ONE].Options.Count, questions[ONE].Options.Count);
            Assert.Equal(expectedQuestions[ONE].Options[ONE].Title, questions[ONE].Options[ONE].Title);
        }
Exemplo n.º 3
0
        public IActionResult GetGameData([FromBody] List <QuestionModel> Questions)
        {
            var data = new List <QuestionModel>();

            //Null object can be received on initial application load
            if (Questions == null)
            {
                Questions = new List <QuestionModel>();
                try
                {
                    using (var questionDb = new QuestionsDb())
                    {
                        data = questionDb.Questions.OrderByDescending(c => c.creation_date).Take(25).ToList();
                    }
                }
                catch { }
            }
            else
            {
                //Determine last question on the DOM, order did change when object was passed from the angular controller
                var lastQuestionCreated = Questions.LastOrDefault();
                int lastCreationDate    = 0;
                if (lastQuestionCreated != null)
                {
                    lastCreationDate = lastQuestionCreated.creation_date;
                    try
                    {
                        //Get 25 more questions that are older than the last question from the array
                        using (var questionDb = new QuestionsDb())
                        {
                            data = questionDb.Questions.Where(c => c.creation_date < lastCreationDate).OrderByDescending(c => c.creation_date).Take(25).ToList();
                        }
                    }
                    catch { }
                }
            }

            try
            {
                //Get coorisponding answers to questions grabbed to be returned
                using (var answersDb = new AnswersDb())
                {
                    foreach (var question in data)
                    {
                        question.answers = answersDb.Answers.Where(c => c.question_id == question.question_id).OrderBy(c => Guid.NewGuid()).ToList();
                    }
                }
            }
            catch { }
            //Add data to Questions received from the angular controller in preparation of returning the entire list
            Questions.AddRange(data);
            return(Json(Questions));
        }
Exemplo n.º 4
0
        public StorageModel()
        {
            //Initialize fromdate and todate from db records to ensure proper start point when fetching questions from the api, this will avoid any potential to receive a duplicate record.
            using (var questionsDb = new QuestionsDb())
            {
                if (questionsDb.Questions.Count() > 0)
                {
                    FromDate = questionsDb.Questions.OrderByDescending(c => c.creation_date).First().creation_date + 1;
                    ToDate   = FromDate + 172740;
                }
            }

            /*Instatiate a BackgroundWord, and run the worker only when the process has been checked by a timer interval to ensure it is not currently running. This will avoid duplicate records
             * and ensure we only run one process at a time incrementing the fromdate and todate after each successful api pull and db update*/
            using (DataUpdateService = new BackgroundWorker())
            {
                DataUpdateService.DoWork       += FetchData;
                DataUpdateServiceTimer          = new System.Timers.Timer(new TimeSpan(0, 1, 0).TotalMilliseconds);
                DataUpdateServiceTimer.Elapsed += CheckDataUpdateProcess;
                DataUpdateServiceTimer.Start();
            }
        }
Exemplo n.º 5
0
        public IActionResult GetRandomGameData()
        {
            var data = new List <QuestionModel>();

            try
            {
                //Get 10 random questions from DB
                using (var questionDb = new QuestionsDb())
                {
                    data = questionDb.Questions.OrderByDescending(c => Guid.NewGuid()).Take(10).ToList();
                }
                // Get coorisponding answers to questions grabbed to be returned
                using (var answersDb = new AnswersDb())
                {
                    foreach (var question in data)
                    {
                        question.answers = answersDb.Answers.Where(c => c.question_id == question.question_id).OrderBy(c => Guid.NewGuid()).ToList();
                    }
                }
            }
            catch { }
            return(Json(data));
        }
Exemplo n.º 6
0
        private async void FetchData(object sender, DoWorkEventArgs e)
        {
            try
            {
                //HttpClientHandler is needed to configure the HttpClient to utlize GZip
                HttpClientHandler handler = new HttpClientHandler()
                {
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                };
                using (HttpClient client = new HttpClient(handler))
                {
                    //Get response from API
                    using (HttpResponseMessage response = await client.GetAsync("https://api.stackexchange.com/2.2/questions?filter=!6h_6LPB9mi4f3VS50f9bHUwlhXNhd(idEXcx.qsqzpIjX9&order=desc&sort=activity&site=stackoverflow&pagesize=100&fromdate=" + FromDate + "&todate=" + ToDate))
                    {
                        using (HttpContent content = response.Content)
                        {
                            //Read content as a string, easiest for parsing the json string into an explicit model
                            var result = await content.ReadAsStringAsync();

                            DataModel            jsonObj   = JsonConvert.DeserializeObject <DataModel>(result);
                            List <QuestionModel> Questions = JsonConvert.DeserializeObject <List <QuestionModel> >(jsonObj.items.ToString());
                            //initialize db, prepare for update
                            using (var questionsDb = new QuestionsDb())
                            {
                                //If less than 100 records received throttle back the timer that controls the interval between api calls
                                if (Questions.Count < 100)
                                {
                                    DataUpdateServiceTimer.Interval = new TimeSpan(0, runFlag, 0).TotalMilliseconds;
                                    DataUpdateServiceTimer.Elapsed += CheckDataUpdateProcess;
                                    DataUpdateServiceTimer.Start();
                                    runFlag = 30;
                                }
                                //No need to take action if there are not any questions
                                if (Questions.Count > 0)
                                {
                                    var duplicates = questionsDb.Questions.Except(Questions);
                                    //Duplicate Found
                                    if (duplicates.Any())
                                    {
                                        foreach (var question in duplicates)
                                        {
                                            Questions.Remove(question);
                                        }
                                    }
                                    //Only interested in questions that have 2 answers or more and one of them have been accepted
                                    await questionsDb.AddRangeAsync(Questions.Where(c => c.answer_count >= 2 && c.accepted_answer_id > 0));

                                    var dbSaveResult = await questionsDb.SaveChangesAsync();

                                    //No need to increment the flag variable if the data fetched was not successfully updated to the db
                                    if (dbSaveResult >= 1)
                                    {
                                        /*Increment these flag parameters for use in the next api call, this will make sure we don't accidentally call for
                                         * the same data and attempt to add a duplicate record into the db*/
                                        FromDate = questionsDb.Questions.OrderByDescending(c => c.creation_date).First().creation_date + 1;
                                        ToDate   = FromDate + 172740;
                                    }
                                }
                            }
                            using (var answersDb = new AnswersDb())
                            {
                                /*Iterate over each question and parse json string into a answer model and save to db, again only interested in
                                 * questions with more than 2 answers where one has been accepted*/
                                foreach (QuestionModel question in Questions.Where(c => c.answer_count >= 2 && c.accepted_answer_id > 0))
                                {
                                    await answersDb.Answers.AddRangeAsync(question.answers);
                                }
                                await answersDb.SaveChangesAsync();
                            }
                            //Clear variable and release resources to GC
                            if (Questions != null)
                            {
                                Questions.Clear();
                            }
                        }
                    }
                }
            } catch (Microsoft.EntityFrameworkCore.DbUpdateException error)
            {
                using (var questionsDb = new QuestionsDb())
                {
                    FromDate = questionsDb.Questions.OrderByDescending(c => c.creation_date).First().creation_date + 100;
                    ToDate   = FromDate + 172740;
                }
            }
        }