コード例 #1
0
 public static void SaveProfile(Profile profile)
 {
     lock (locker)
     {
         barrel.Add <Profile>("profile", profile, TimeSpan.FromDays(1));
     }
 }
コード例 #2
0
        public async Task <Edition> GetEditionAsync(string id, bool forceRefresh = false)
        {
            var editionFile = $"{id}.json";
            var edition     = _barrel.Get <Edition>(key: editionFile);

            if (await CachedEditionUpToDate(edition) && !forceRefresh)
            {
                return(edition);
            }

            if (_connectivity.NetworkAccess != NetworkAccess.Internet)
            {
                return(edition);
            }

            try
            {
                var editionResponse = await _httpClient.GetStringAsync(editionFile);

                edition = JsonConvert.DeserializeObject <Edition>(editionResponse);

                _barrel.Add(key: editionFile, data: edition, expireIn: TimeSpan.FromDays(999));
                return(edition);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, nameof(GetEditionsAsync));
                return(edition);
            }
        }
コード例 #3
0
        public async Task <Edition> GetEditionAsync(string id, bool forceRefresh = false)
        {
            var editionFile = $"{id}.json";
            var edition     = _barrel.Get <Edition>(key: editionFile);

            var cacheInvalid = !await CachedEditionUpToDate(edition);

            if ((cacheInvalid || forceRefresh) &&
                _connectivity.NetworkAccess == NetworkAccess.Internet)
            {
                try
                {
                    // get from the interwebs
                    var editionResponse = await _httpClient.GetStringAsync(editionFile);

                    edition = JsonConvert.DeserializeObject <Edition>(editionResponse);

                    _barrel.Add(key: editionFile, data: edition, expireIn: TimeSpan.FromDays(999));
                    //return edition;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, nameof(GetEditionsAsync));
                    //return edition;
                }
            }

            CheckEditionForSavedArticles(edition);
            return(edition);
        }
コード例 #4
0
 public static void SavePerson(Person person)
 {
     lock (_locker)
     {
         _barrel.Add <Person>("person", person, TimeSpan.FromDays(1));
     }
 }
コード例 #5
0
ファイル: PlaylistProvider.cs プロジェクト: phaufe/Chameleon
        public async Task <bool> AddOrUpdate(IPlaylist item)
        {
            var items = (await GetAll())?.ToList();

            if (items == null)
            {
                return(false);
            }

            var playlist = items?.FirstOrDefault(x => x.Id == item.Id);

            if (playlist == null)
            {
                items.Add(item);
            }
            else
            {
                var index = items.IndexOf(playlist);
                items.RemoveAt(index);
                items.Insert(index, item);
            }

            _barrel.Add("playlists", items, TimeSpan.MaxValue);
            return(true);
        }
コード例 #6
0
 public void AddToCache <T>(IBarrel barrel, string key, IEnumerable <T> data)
 {
     if (data.Any())
     {
         barrel.Add(key: key, data: data, expireIn: DefaultTimeSpan);
     }
 }
コード例 #7
0
        public void SetCache(string videoId, IEnumerable <Comment> comments)
        {
            var entity = new CommentEntity()
            {
                ContentId = videoId,
                Comments  = comments.ToArray()
            };
            var commentDbId = videoId + "_c";

            _barrel.Add(commentDbId, entity, TimeSpan.FromDays(1));
        }
コード例 #8
0
        private async Task <string> GetJsonAsync(string resource, Xamarin.Essentials.NetworkAccess networkAccess, int cacheDuration = 24)
        {
            var cleanCacheKey = resource.CleanCacheKey();

            //Try Get data from Cache
            var cachedData = _cacheBarrel.Get <string>(cleanCacheKey);

            if (cacheDuration > 0 && cachedData != null)
            {
                //If the cached data is still valid
                if (!_cacheBarrel.IsExpired(cleanCacheKey))
                {
                    return(cachedData);
                }
            }

            //Check for internet connection and return cached data if possible
            if (networkAccess != NetworkAccess.Internet)
            {
                if (cachedData != null)
                {
                    return(cachedData);
                }
                else
                {
                    throw new InternetConnectionException();
                }
            }

            //No Cache Found, or Cached data was not required, or Internet connection is also available
            //Extract response from URI
            var response = await _httpClient.GetAsync(new Uri(_httpClient.BaseAddress, resource));

            response.EnsureSuccessStatusCode();

            //Read Response
            string json = await response.Content.ReadAsStringAsync();

            //Save to Cache if required
            if (cacheDuration > 0)
            {
                try
                {
                    _cacheBarrel.Add(cleanCacheKey, json, TimeSpan.FromHours(cacheDuration));
                }
                catch { }
            }

            //Return the result
            return(json);
        }
コード例 #9
0
        public static T GetOrCreate <T>(this IBarrel barrel, string key, T defaultValue, TimeSpan timeSpan = default)
        {
            if (string.IsNullOrWhiteSpace(key) || !barrel.Exists(key))
            {
                if (timeSpan == default)
                {
                    timeSpan = TimeSpan.MaxValue;
                }
                barrel.Add(key, defaultValue, timeSpan);
                return(defaultValue);
            }

            return(barrel.Get <T>(key));
        }
コード例 #10
0
        public async Task <Edition> GetEditionAsync(string id, bool forceRefresh = false)
        {
            //_logger.Log(LogLevel.Information, $"Getting Edition {id}");
            var editionFile = $"{id}.json";
            var edition     = _barrel.Get <Edition>(key: editionFile);

            var cacheInvalid = !await CachedEditionUpToDate(edition);

            if ((cacheInvalid || forceRefresh) &&
                _connectivity.NetworkAccess == NetworkAccess.Internet)
            {
                try
                {
                    //_logger.Log(LogLevel.Information, $"  Getting {id} from the web");
                    // get from the interwebs
                    var editionResponse = await _httpClient.GetStringAsync(editionFile);

                    edition = JsonConvert.DeserializeObject <Edition>(editionResponse);

                    _barrel.Add(key: editionFile, data: edition, expireIn: TimeSpan.FromDays(999));
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, nameof(GetEditionsAsync));
                    _analytics.TrackError(ex, new Dictionary <string, string> {
                        { Constants.Analytics.Properties.FileName, editionFile }
                    });
                }
            }

            if (edition != null) // smelly??!?!
            {
                CheckEditionForSavedArticles(edition);
            }

            return(edition);
        }
コード例 #11
0
        public override User GetUser(string userPid)
        {
            User user = null;

            if (!_barrel.IsExpired(userPid))
            {
                user = _barrel.Get <User>(userPid);
            }
            else
            {
                user = base.GetUser(userPid);
                _barrel.Add(userPid, user, TimeSpan.FromDays(_expiryLengthDays));
            }

            return(user);
        }
コード例 #12
0
        /// <summary>
        /// WebAPIから県別のデータを取得する.
        /// </summary>
        /// <returns></returns>
        public async Task <IEnumerable <Prefecture> > GetPrefectures()
        {
            try
            {
                //キャッシュが存在して,有効期間内の場合はキャッシュから
                if (!_barrel.IsExpired(key: CachePrefecturesKey))
                {
                    await Task.Yield();

                    return(_barrel.Get <IEnumerable <Prefecture> >(key: CachePrefecturesKey));
                }

                //インターネットに接続してれば取得
                if (Connectivity.NetworkAccess == NetworkAccess.Internet)
                {
                    //WebAPIからデータ取得
                    var prefecturesData = await _httpClient.GetFromJsonAsync <IEnumerable <Prefecture> >("prefectures");

                    //キャッシュを更新.キャッシュの有効期限を設定
                    _barrel.Add(key: CachePrefecturesKey, data: prefecturesData, expireIn: TimeSpan.FromMinutes(10));

                    return(prefecturesData);
                }

                //インターネットにも接続してないし,キャッシュも有効期限切れだった場合
                //それでも有効期限切れのキャッシュデータを返すか.
                if (_barrel.Exists(key: CachePrefecturesKey))
                {
                    //とりあえず返すことにした.
                    return(_barrel.Get <IEnumerable <Prefecture> >(key: CachePrefecturesKey));
                }

                return(new List <Prefecture>());
            }
            catch
            {
                throw;
            }
        }
コード例 #13
0
 public Task SavePlaylists(IList <IPlaylist> playlists)
 {
     _barrel.Add("playlists", playlists, TimeSpan.MaxValue);
     return(Task.CompletedTask);
 }
コード例 #14
0
 /// <summary>
 /// Save a json object or item temporarily for a day
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="element">Object to save</param>
 /// <param name="expireIn">Time the saved object will last</param>
 /// <param name="nameMonkey">Name with which the object will be saved</param>
 public void SaveMokey <T>(T element, string nameMonkey, TimeSpan expireIn)
 {
     file.Add <T>(nameMonkey, element, expireIn);
 }
コード例 #15
0
        public Task Set(string key, object value, TimeSpan?lifeSpan = null, CancellationToken cancellationToken = default)
        {
            _barrel.Add(key, value, lifeSpan ?? TimeSpan.MaxValue);

            return(Task.CompletedTask);
        }
コード例 #16
0
ファイル: BarrelTests.cs プロジェクト: tbaggett/monkey-cache
        public void GetStringTest()
        {
            //Saves the cache and pass it a timespan for expiration
            barrel.Add(key: url, data: json, expireIn: TimeSpan.FromDays(1));


            var cached = barrel.Get(url);

            Assert.IsNotNull(cached);
        }
コード例 #17
0
ファイル: HttpCache.cs プロジェクト: ywscr/monkey-cache
        /// <summary>
        /// Send a cached requests
        /// </summary>
        /// <param name="http">Http client ot use</param>
        /// <param name="barrel">Barrel to use for cache</param>
        /// <param name="req">request to send</param>
        /// <param name="expireIn">expire in</param>
        /// <param name="forceUpdate">If we should force the update or not</param>
        /// <param name="throttled">If throttled or not</param>
        /// <returns>The new or cached response.</returns>
        public static async Task <string> SendCachedAsync(this HttpClient http, IBarrel barrel, HttpRequestMessage req, TimeSpan expireIn, bool forceUpdate = false, bool throttled = true)
        {
            var url = req.RequestUri.ToString();

            var contents = barrel.Get <string>(url);
            var eTag     = barrel.GetETag(url);

            if (!forceUpdate && !string.IsNullOrEmpty(contents) && !barrel.IsExpired(url))
            {
                return(contents);
            }

            var etag = eTag ?? null;

            if (throttled)
            {
                await getThrottle.WaitAsync();
            }

            HttpResponseMessage r;
            string c = null;

            try {
                if (!forceUpdate && !string.IsNullOrEmpty(etag) && !string.IsNullOrEmpty(contents))
                {
                    req.Headers.IfNoneMatch.Clear();
                    req.Headers.IfNoneMatch.Add(new EntityTagHeaderValue(etag));
                }

                r = await http.SendAsync(req);

                if (r.StatusCode == HttpStatusCode.NotModified)
                {
                    if (string.IsNullOrEmpty(contents))
                    {
                        throw new IndexOutOfRangeException($"Cached value missing for HTTP request: {url}");
                    }

                    return(contents);
                }

                c = await r.Content.ReadAsStringAsync();
            } finally {
                if (throttled)
                {
                    getThrottle.Release();
                }
            }

            if (r.StatusCode == HttpStatusCode.OK)
            {
                // Cache it?
                var newEtag = r.Headers.ETag != null ? r.Headers.ETag.Tag : null;
                if (!string.IsNullOrEmpty(newEtag) && newEtag != etag)
                {
                    barrel.Add(url, c, expireIn, newEtag);
                }

                return(c);
            }
            else
            {
                throw new HttpCacheRequestException(r.StatusCode, "HTTP Cache Request Failed");
            }
        }
コード例 #18
0
 public void SaveMokey <T>(ObservableCollection <T> elementArray, string nameMonkey) where T : Entity
 {
     file.Add <ObservableCollection <T> >(nameMonkey, elementArray, TimeSpan.FromDays(1));
 }