示例#1
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));
        }
示例#2
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));
        }
示例#3
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;
                }
            }
        }