Exemplo n.º 1
0
        public async Task <bool> SyncShowData()
        {
            // we get the highest id in our db to calculate a starting point
            var highestShowId = await ShowRepository.GetHighestShowId();

            var    done       = false;
            double pageNumber = (double)(highestShowId) / 250;
            // note, the documentation of the TVMaze Api tells us to floor highestShowId) / 250
            // but this will give us the last page number we requested, what we want is the next page number to request so we use ceiling
            int pageNum = highestShowId < 1 ? 0 : (int)(Math.Ceiling(pageNumber));

            while (!done)
            {
                var request = new HttpRequestMessage(HttpMethod.Get, "http://api.tvmaze.com/shows?page=" + pageNum);
                request.Headers.Add("Accept", "application/json");

                var response = await HttpClient.SendAsync(request);

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

                    var shows = JsonConvert.DeserializeObject <IEnumerable <Show> >(json);
                    await ShowRepository.AddShows(shows);
                }
                else
                {
                    done = true;
                }
                pageNum++;
            }
            var affectedRows = await DatabaseRepository.SaveChanges();

            return(affectedRows > 0);
        }