Example #1
0
 public static void InvalidateAllObjects <T>(this IBlobCache This)
 {
     foreach (var key in This.GetAllKeys().Where(x => x.StartsWith(GetTypePrefixedKey("", typeof(T)))))
     {
         This.Invalidate(key);
     }
 }
        public Task Remove(string key)
        {
            var t = Task.Run(() => cache.Invalidate(key));

            t.ConfigureAwait(false);
            return(t);
        }
Example #3
0
        /// <summary>
        /// This is the non-generic analog of JsonSerializationMixin.GetAndFetchLatest[1]
        /// We shouldn't make modifications to this that alter its behavior from the generic
        /// version. By having this we can keep our two GetAndRefresh methods extremely
        /// similar and thus trust that what works in one will work in the other.
        ///
        /// 1. https://github.com/akavache/Akavache/blob/1b19bb56d/Akavache/Portable/JsonSerializationMixin.cs#L202-L236
        /// </summary>
        static IObservable <byte[]> GetAndFetchLatestBytes(
            this IBlobCache blobCache,
            string key,
            Func <IObservable <byte[]> > fetchFunc,
            Func <DateTimeOffset, bool> fetchPredicate = null,
            DateTimeOffset?absoluteExpiration          = null)
        {
            var fetch = Observable.Defer(() => blobCache.GetCreatedAt(key))
                        .Select(x => fetchPredicate == null || x == null || fetchPredicate(x.Value))
                        .Where(predicateIsTrue => predicateIsTrue)
                        .SelectMany(_ =>
            {
                return(fetchFunc()
                       .SelectMany(x => blobCache.Invalidate(key).Select(__ => x))
                       .SelectMany(x => blobCache.Insert(key, x, absoluteExpiration).Select(__ => x)));
            });

            var result = blobCache.Get(key).Select(x => Tuple.Create(x, true))
                         .Catch(Observable.Return(new Tuple <byte[], bool>(null, false)));

            return(result
                   .SelectMany(x => x.Item2
                    ? Observable.Return(x.Item1)
                    : Observable.Empty <byte[]>())
                   .Concat(fetch)
                   .Replay()
                   .RefCount());
        }
Example #4
0
        /// <summary>
        /// This method attempts to returned a cached value, while
        /// simultaneously calling a Func to return the latest value. When the
        /// latest data comes back, it replaces what was previously in the
        /// cache.
        ///
        /// This method is best suited for loading dynamic data from the
        /// Internet, while still showing the user earlier data.
        ///
        /// This method returns an IObservable that may return *two* results
        /// (first the cached data, then the latest data). Therefore, it's
        /// important for UI applications that in your Subscribe method, you
        /// write the code to merge the second result when it comes in.
        /// </summary>
        /// <param name="key">The key to store the returned result under.</param>
        /// <param name="fetchFunc"></param>
        /// <param name="fetchPredicate">An optional Func to determine whether
        /// the updated item should be fetched. If the cached version isn't found,
        /// this parameter is ignored and the item is always fetched.</param>
        /// <param name="absoluteExpiration">An optional expiration date.</param>
        /// <returns>An Observable stream containing either one or two
        /// results (possibly a cached version, then the latest version)</returns>
        public static IObservable <T> GetAndFetchLatest <T>(this IBlobCache This,
                                                            string key,
                                                            Func <IObservable <T> > fetchFunc,
                                                            Func <DateTimeOffset, bool> fetchPredicate = null,
                                                            DateTimeOffset?absoluteExpiration          = null)
        {
            bool foundItemInCache;
            var  fail = Observable.Defer(() => This.GetCreatedAt(key))
                        .Select(x => fetchPredicate != null && x != null ? fetchPredicate(x.Value) : true)
                        .Where(x => x != false)
                        .SelectMany(_ => fetchFunc())
                        .Finally(() => This.Invalidate(key))
                        .Do(x => This.InsertObject(key, x, absoluteExpiration));

            var result = This.GetObjectAsync <T>(key).Select(x => new Tuple <T, bool>(x, true))
                         .Catch(Observable.Return(new Tuple <T, bool>(default(T), false)));

            return(result.SelectMany(x =>
            {
                foundItemInCache = x.Item2;
                return x.Item2 ?
                Observable.Return(x.Item1) :
                Observable.Empty <T>();
            }).Concat(fail).Multicast(new ReplaySubject <T>()).RefCount());
        }
        /// <summary>
        /// Invalidates a single object from the cache. It is important that the Type
        /// Parameter for this method be correct, and you cannot use
        /// IBlobCache.Invalidate to perform the same task.
        /// </summary>
        /// <typeparam name="T">The type of item to invalidate.</typeparam>
        /// <param name="blobCache">The cache to invalidate.</param>
        /// <param name="key">The key to invalidate.</param>
        /// <returns>An observable that signals when the operation has completed.</returns>
        public static IObservable <Unit> InvalidateObject <T>(this IBlobCache blobCache, string key)
        {
            if (blobCache is IObjectBlobCache objCache)
            {
                return(objCache.InvalidateObject <T>(key));
            }

            return(blobCache.Invalidate(GetTypePrefixedKey(key, typeof(T))));
        }
Example #6
0
        private static async Task TestIt(IBlobCache cache)
        {
            _cnt = 0;
            Console.WriteLine(await GetOrFetchAsync(cache, DateTime.UtcNow + TimeSpan.FromMilliseconds(1000)));
            await cache.Invalidate("a");

            Console.WriteLine(await GetOrFetchAsync(cache, DateTime.UtcNow + TimeSpan.FromMilliseconds(1000)));
            Console.WriteLine("=====================");
            Console.WriteLine();
        }
        /// <summary>
        /// Invalidates a single object from the cache. It is important that the Type
        /// Parameter for this method be correct, and you cannot use
        /// IBlobCache.Invalidate to perform the same task.
        /// </summary>
        /// <param name="key">The key to invalidate.</param>
        public static IObservable <Unit> InvalidateObject <T>(this IBlobCache This, string key)
        {
            var objCache = This as IObjectBlobCache;

            if (objCache != null)
            {
                return(objCache.InvalidateObject <T>(key));
            }

            return(This.Invalidate(GetTypePrefixedKey(key, typeof(T))));
        }
Example #8
0
        private void OnRequestFailed(PreparedTrackingRequest request, IRestResponse response)
        {
            if (response.ResponseStatus != ResponseStatus.Completed || response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ThreadPool.RegisterWaitForSingleObject(new ManualResetEvent(false), (completed, state) =>
                {
                    RequestQueue.OnNext(request); //Re-queue the item for sending
                }, null, RetryInterval, true);
            }

            Debug.WriteLine("Analytics Request Failed");
            Debug.Indent();
            Debug.WriteLine("{0} {1} {2}", response.ResponseStatus, (int)response.StatusCode, response.StatusCode);
            Debug.WriteLine("{0}", response.Request.Parameters.Select(x => x.Name + "=" + x.Value).Aggregate((x, y) => x + "&" + y));
            if (!response.Content.IsNullOrEmpty())
            {
                Debug.WriteLine("{0}", response.Content);
            }
            Debug.Unindent();
            KeyStore.Invalidate(string.Format("PreparedTrackingRequest_{0}", request.RequestID.ToString()));
        }
Example #9
0
        public Task Logout() => Task.Run(async() =>
        {
            var keys = await _blobCache.GetAllKeys();
            foreach (var driveKey in keys.Where(x => x.StartsWith("google-drive", StringComparison.OrdinalIgnoreCase)))
            {
                await _blobCache.Invalidate(driveKey);
            }

            _driveService = null;
            _isAuthorized.OnNext(false);
            return(Task.CompletedTask);
        });
Example #10
0
        public static IObservable <Unit> Invalidate(this IBlobCache This, IEnumerable <string> keys)
        {
            var bulkCache = This as IBulkBlobCache;

            if (bulkCache != null)
            {
                return(bulkCache.Invalidate(keys));
            }

            return(keys.ToObservable()
                   .SelectMany(x => This.Invalidate(x))
                   .TakeLast(1));
        }
Example #11
0
        /// <summary>
        /// Invalidates a single object from the cache. It is important that the Type
        /// Parameter for this method be correct, and you cannot use
        /// IBlobCache.Invalidate to perform the same task.
        /// </summary>
        /// <typeparam name="T">The type of item to invalidate.</typeparam>
        /// <param name="blobCache">The cache to invalidate.</param>
        /// <param name="key">The key to invalidate.</param>
        /// <returns>An observable that signals when the operation has completed.</returns>
        public static IObservable <Unit> InvalidateObject <T>(this IBlobCache blobCache, string key)
        {
            if (blobCache is null)
            {
                throw new ArgumentNullException(nameof(blobCache));
            }

            if (blobCache is IObjectBlobCache objCache)
            {
                return(objCache.InvalidateObject <T>(key));
            }

            return(blobCache.Invalidate(GetTypePrefixedKey(key, typeof(T))));
        }
Example #12
0
        public async Task <bool> Delete <T>(T item) where T : BaseModel, new()
        {
            var collection = (await GetAll <T>()).ToList();

            var element = collection.FirstOrDefault(x => x.Id == item.Id);

            if (element != null)
            {
                collection.Remove(element);
                await localBlobCache.Invalidate(typeof(T).Name);

                InsertAll(collection);
            }

            return(false);
        }
        // deletes and then inserts an object in the cache
        public static async Task UpdateUserCache <T>(String key, T obj)
        {
            if (key == null || obj == null)
            {
                return;
            }

            try
            {
                await userCache.Invalidate(key).FirstAsync().ToTask().ContinueWith(async(unit) =>
                {
                    await userCache.InsertObject(key, obj)
                    .FirstAsync().ToTask().ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw new Exception($"Exception on UpdateUserCache: { ex.Message }");
                //Debug.WriteLine("*** " + e.Message);
            }
        }
Example #14
0
 public async Task RemoveFileRecordAsync(string path)
 {
     await Cache.Invalidate(path);
 }
 public IObservable <Unit> Invalidate(string key)
 {
     return(_inner.Invalidate(key));
 }
 public async Task DeleteAsync <T>(string key)
 {
     var identity = $"google-drive-{_id}-{key}";
     await _blobCache.Invalidate(identity);
 }
Example #17
0
 public IObservable <Unit> ClearCache() =>
 _blob.Invalidate(nameof(GitHubRepository)).Select(x =>
 {
     _blob.InsertObject(nameof(GitHubRepository), new List <GitHubRepository>());
     return(x);
 });
Example #18
0
 public void InvalidateCache(string key)
 {
     Cache.Invalidate(key);
 }
 public void Remove(string key)
 {
     _internalCache.Invalidate(key);
 }
 public void Remove(string key)
 {
     blobCache.Invalidate(key).Wait();
 }
Example #21
0
 public static void InvalidateObject <T>(this IBlobCache This, string key)
 {
     This.Invalidate(GetTypePrefixedKey(key, typeof(T)));
 }
Example #22
0
 public IObservable <Unit> InvalidateAvatar(IAvatarContainer apiAccount)
 {
     return(String.IsNullOrWhiteSpace(apiAccount?.Login)
         ? Observable.Return(Unit.Default)
         : cache.Invalidate(apiAccount.Login));
 }
Example #23
0
 public static void DeleteUserData(string key)
 {
     UserData.Invalidate(key);
 }