Example #1
0
        /// <summary>
        /// Stores news items in the cache
        /// </summary>
        public static void SetCachedNews(List <NewsItem> news)
        {
            NewsCacheEntity entity = GetOrCreateEntity();

            entity.News = news;
            entity.Save(); // sets the UpdatedAt value to "now" automatically
        }
Example #2
0
        /// <summary>
        /// Finds the cache entity in the database or creates and saves new one
        /// </summary>
        private static NewsCacheEntity GetOrCreateEntity()
        {
            var entity = DB.First <NewsCacheEntity>();

            if (entity == null)
            {
                entity = new NewsCacheEntity();
                entity.Save();
            }

            return(entity);
        }
Example #3
0
        /// <summary>
        /// Returns the latest news, prepared for display
        /// </summary>
        public List <NewsItem> GetLatestNews()
        {
            // === try to get news from the cache first ===

            var cachedNews = NewsCacheEntity.GetCachedNews();

            if (cachedNews != null)
            {
                return(cachedNews);
            }

            // === only then query all the news sources to build the news ===

            var news = BuildTheNews();

            NewsCacheEntity.SetCachedNews(news);

            return(news);
        }
Example #4
0
        /// <summary>
        /// Returns the cached news, or null if there's nothing cached
        /// </summary>
        public static List <NewsItem> GetCachedNews()
        {
            NewsCacheEntity entity = GetOrCreateEntity();

            // nothing cached
            if (entity.News == null || entity.News.Count == 0)
            {
                return(null);
            }

            // cached, but expired
            double age = (DateTime.UtcNow - entity.UpdatedAt).TotalMinutes;

            if (age > CacheExpiryMinutes)
            {
                return(null);
            }

            return(entity.News);
        }