Exemplo n.º 1
0
        public IObservable <IEnumerable <GitHubRepository> > LoadNextRepositories()
        {
            return(_blob.GetObject <IEnumerable <GitHubRepository> >(nameof(GitHubRepository))
                   .Select(x =>
            {
                var page = x.Any() ? x.Count() / 50 : 0;
                page++;
                return _apiService.GetRepositories(_language, page)
                .Select(response =>
                {
                    var copy = new List <GitHubRepository>(x);
                    if (copy.Count + response.Count() < KeyValues.MaxRepositories)
                    {
                        copy.AddRange(response);
                    }
                    else
                    {
                        var rest = KeyValues.MaxRepositories - copy.Count;
                        var complete = new List <GitHubRepository>(response.Take(rest));
                        copy.AddRange(complete);
                        response = new List <GitHubRepository>(complete);
                    }

                    _blob.InsertObject(nameof(GitHubRepository), copy, DateTimeOffset.UtcNow.AddDays(1));
                    return response;
                }).Wait();
            }));
        }
Exemplo n.º 2
0
        public async Task <bool> Store(IStorableObject o, string key)
        {
            await cache.InsertObject(key, JsonConvert.SerializeObject(o, o.GetType(), settings));

            Debug.WriteLine("Storing in the cache: {0} ", o);
            return(true);
        }
Exemplo n.º 3
0
        public IObservable <Unit> InsertAll(IList <Session> sessions)
        {
            return(blob.GetOrCreateObject <IList <Session> >(KEY_SESSIONS, () => new List <Session>())
                   .Select(source =>
            {
                var checkedSessions = sessions.Where(session => session.IsChecked).ToDictionary(session => session.id);
                var merged = sessions.Union(source);

                return merged.Select(session =>
                {
                    session.IsChecked = checkedSessions.ContainsKey(session.id);
                    return session;
                });
            })
                   .SelectMany(merged =>
            {
                return Observable.Merge(
                    merged.ToObservable()
                    .Select(session => session.category)
                    .ToList().Distinct()
                    .SelectMany(categoryDao.InsertAll),
                    merged.ToObservable()
                    .Select(session => session.place)
                    .ToList().Distinct()
                    .SelectMany(placeDao.InsertAll),
                    blob.InsertObject(KEY_SESSIONS, merged)
                    );
            }));
        }
Exemplo n.º 4
0
        /// <summary>
        /// This method attempts to returned a cached value, and fetch one from
        /// the web. Optionally, it can continue to query to see if an update is required.
        ///
        /// If the cached value exists, it is returned. Then the predicate is queried to see
        /// if the remote value should be refreshed.
        ///
        /// If there is no cached value, then the value is fetched.
        ///
        /// Once the above is done, as the retrySequence comes in, the predicate will
        /// be called to see if a refresh is needed. If so, the data will be re-fetched.
        ///
        /// In all cases any remotely fetched data is cached.
        ///
        /// This also means that await'ing this method is a Bad Idea(tm), always
        /// use Subscribe. 1-infinity values can be returned depending on the arguments.
        /// </summary>
        /// <param name="key">The key to store the returned result under.</param>
        /// <param name="fetchFunc">A sequence that will return the new values of the data</param>
        /// <param name="fetchPredicate">A Func to determine whether
        /// the updated item should be fetched. Only called once a cached version exists.</param>
        /// <param name="retrySequence">Sequence that will trigger a predicate call followed by
        /// a fetch call if the predicate indicates so.</param>
        /// <param name="This">The blob cache against which we operate</param>
        /// <returns>An Observable stream containing one or more
        /// results (possibly a cached version, then the latest version(s))</returns>
        public static IObservable <T> GetAndFetchLatest <T>(this IBlobCache This,
                                                            string key,
                                                            Func <IObservable <T> > fetchFunc,
                                                            Func <DateTimeOffset, IObservable <bool> > fetchPredicate,
                                                            IObservable <Unit> retrySequence  = null,
                                                            DateTimeOffset?absoluteExpiration = null
                                                            )
        {
            if (fetchPredicate == null)
            {
                throw new ArgumentException("fetchPredicate");
            }
            if (fetchFunc == null)
            {
                throw new ArgumentException("fetchFunc");
            }

            // We are going to get the cache value if we can. And then we will run updates after that.
            // If we have nothing cached, then we will run the fetch directly. Otherwise we will run the
            // fetch sequence.

            var getOldKey = This.GetObjectCreatedAt <T>(key);

            var refetchIfNeeded = getOldKey
                                  .Where(dt => dt != null && dt.HasValue && dt.Value != null)
                                  .SelectMany(dt => fetchPredicate(dt.Value))
                                  .Where(doit => doit == true)
                                  .Select(_ => default(Unit));

            var fetchRequired = getOldKey
                                .Where(dt => dt == null || !dt.HasValue || dt.Value == null)
                                .Select(_ => default(Unit));

            // Next, get the item...

            var fetchFromCache = Observable.Defer(() => This.GetObject <T>(key))
                                 .Catch <T, KeyNotFoundException>(_ => Observable.Empty <T>());

            var fetchFromRemote = fetchRequired.Concat(refetchIfNeeded)
                                  .SelectMany(_ => fetchFunc())
                                  .SelectMany(x => This.InsertObject <T>(key, x, absoluteExpiration).Select(_ => x));

            var items = fetchFromCache.Concat(fetchFromRemote);

            // Once we have these, we also have to kick off a second set of fetches for our retry sequence.
            if (retrySequence == null)
            {
                return(items);
            }

            var getAfter = retrySequence
                           .SelectMany(_ => This.GetObjectCreatedAt <T>(key))
                           .SelectMany(dt => fetchPredicate(dt.Value))
                           .Where(doit => doit == true)
                           .SelectMany(_ => fetchFunc())
                           .SelectMany(x => This.InsertObject <T>(key, x, absoluteExpiration).Select(_ => x));

            return(items.Concat(getAfter));
        }
Exemplo n.º 5
0
 public async Task SaveAsync <T>(string key, T value, TimeSpan?expiration = null) where T : class
 {
     if (expiration != null && expiration.HasValue)
     {
         await localBlobCache.InsertObject(key, value, expiration.Value);
     }
     else
     {
         await localBlobCache.InsertObject(key, value);
     }
 }
Exemplo n.º 6
0
        public async Task Logout()
        {
            try
            {
                //await _accountApiService.Logout();
            }
            catch (Exception) { }
            AccessToken = string.Empty;
            await _secureBlobCache.Invalidate(AccessTokenKey);

            await _localMachineCache.InsertObject(IsNewUserKey, true);

            IsNewUser = true;
        }
Exemplo n.º 7
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.
        ///
        /// This also means that await'ing this method is a Bad Idea(tm), always
        /// use Subscribe.
        /// </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>
        /// <param name="shouldInvalidateOnError">If this is true, the cache will
        /// be cleared when an exception occurs in fetchFunc</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 shouldInvalidateOnError = false)
        {
            var fetch = Observable.Defer(() => This.GetObjectCreatedAt <T>(key))
                        .Select(x => fetchPredicate == null || x == null || fetchPredicate(x.Value))
                        .Where(x => x != false)
                        .SelectMany(_ =>
            {
                var fetchObs = fetchFunc().Catch <T, Exception>(ex =>
                {
                    var shouldInvalidate = shouldInvalidateOnError ?
                                           This.InvalidateObject <T>(key) :
                                           Observable.Return(Unit.Default);
                    return(shouldInvalidate.SelectMany(__ => Observable.Throw <T>(ex)));
                });

                return(fetchObs
                       .SelectMany(x => This.InvalidateObject <T>(key).Select(__ => x))
                       .SelectMany(x => This.InsertObject <T>(key, x, absoluteExpiration).Select(__ => x)));
            });

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

            return(result.SelectMany(x =>
            {
                return x.Item2 ?
                Observable.Return(x.Item1) :
                Observable.Empty <T>();
            }).Concat(fetch).Multicast(new ReplaySubject <T>()).RefCount());
        }
Exemplo n.º 8
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());
        }
Exemplo n.º 9
0
        public static IObservable <T> CacheApiResult <T>(
            this IObservable <T> source,
            string cacheKey,
            IBlobCache blobCache,
            IFullLogger?logger   = null,
            IScheduler?scheduler = null,
            bool forceUpdate     = false,
            TimeSpan expiration  = default)
        {
            expiration = expiration == TimeSpan.Zero ? Constants.DefaultCacheExpirationTimeOut : expiration;

            if (forceUpdate)
            {
                // TODO: [rlittlesii: July 30, 2020] Add retry and cached
                return(source.SelectMany(async value =>
                {
                    await blobCache.InsertObject(cacheKey, value, expiration);

                    logger?.Debug($"CACHE: Writing {{Value}} to cache with key: {{CacheKey}}", value, cacheKey);

                    return value;
                }));
            }

            blobCache
            .GetObject <T>(cacheKey)
            .Subscribe(obj => logger?.Debug("Found: {@Object}", obj));

            // TODO: [rlittlesii: July 30, 2020] Add retry and cached
            return(blobCache
                   .GetOrFetchObject(
                       cacheKey,
                       () => source.Timeout(Constants.DefaultRequestTimeout), DateTimeOffset.Now.Add(expiration)));
        }
Exemplo n.º 10
0
        private async void InsertObjects()
        {
            var postService = RestService.For <IHttpCallsJsonPlaceHolder>("http:\\jsonplaceholder.com");

            var posts = await postService.GetPosts();

            localData.InsertObject("Posts", posts);
        }
Exemplo n.º 11
0
        public IObservable <CacheIndex> Save(IBlobCache cache,
                                             DateTimeOffset?absoluteExpiration = null)
        {
            Guard.ArgumentNotNull(cache, nameof(cache));

            return(cache.InsertObject(IndexKey, this, absoluteExpiration)
                   .Select(x => this));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Inserts a item into the cache.
        /// </summary>
        /// <param name="blobCache">The blob cache to insert the item into.</param>
        /// <param name="key">The key to associate with the entry.</param>
        /// <param name="value">The data for the entry.</param>
        /// <param name="expiration">A timespan that will be added to the current DateTime.</param>
        /// <typeparam name="T">The type of item to insert.</typeparam>
        /// <returns>A observable which will signal when the item is added.</returns>
        public static IObservable <Unit> InsertObject <T>(this IBlobCache blobCache, string key, T value, TimeSpan expiration)
        {
            if (blobCache is null)
            {
                throw new ArgumentNullException(nameof(blobCache));
            }

            return(blobCache.InsertObject(key, value, blobCache.Scheduler.Now + expiration));
        }
Exemplo n.º 13
0
        partial void BtnStoreData_TouchUpInside(UIButton sender)
        {
            _encryptionProvider.SetPassword(txtPassword.Text);

            _encryptedBlobCache
            .InsertObject("key", kStoreMe)
            .Do(_ => InvokeOnMainThread(() => lblResult.Text = "Data Stored"))
            .Subscribe();
        }
Exemplo n.º 14
0
 public IObservable<Unit> InsertAll(ICollection<Place> places)
 {
     return blob.GetOrCreateObject<IList<Place>>(KEY_PLACES, () => new List<Place>())
         .Select(source => 
             {
                 return places.Union(source);
             })
         .SelectMany(merged => blob.InsertObject(KEY_PLACES, merged));
 }        
        /// <summary>
        /// Save all the data we pull off the internet in the cache for later user.
        /// </summary>
        /// <param name="file"></param>
        /// <param name="serverModifiedType"></param>
        /// <param name="filedata"></param>
        /// <param name="cache"></param>
        /// <returns></returns>
        public static IObservable <Unit> SaveFileInCache(this IFile file, string serverModifiedType, byte[] filedata, IBlobCache cache)
        {
            var timeToDelete = DateTime.Now + Settings.CacheFilesTime;

            var insertDate = cache.InsertObject(file.FileDateKey(), serverModifiedType, timeToDelete);
            var insertData = cache.Insert(file.FileDataKey(), filedata, timeToDelete);

            return(Observable.Concat(insertDate, insertData).Skip(1));
        }
Exemplo n.º 16
0
 public IObservable <Unit> InsertAll(IList <Category> categories)
 {
     return(blob.GetOrCreateObject <IList <Category> >(KEY_CATEGORIES, () => new List <Category>())
            .Select(source =>
     {
         return categories.Union(source);
     })
            .SelectMany(merged => blob.InsertObject(KEY_CATEGORIES, merged)));
 }
Exemplo n.º 17
0
 public IObservable<CacheIndex> AddAndSave(IBlobCache cache, string indexKey, CacheItem item,
     DateTimeOffset? absoluteExpiration = null)
 {
     var k = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", IndexKey, item.Key);
     if (!Keys.Contains(k))
         Keys.Add(k);
     UpdatedAt = DateTimeOffset.UtcNow;
     return cache.InsertObject(IndexKey, this, absoluteExpiration)
         .Select(x => this);
 }
Exemplo n.º 18
0
        public async Task <bool> Create <T>(T entity) where T : EntityBase, new()
        {
            try
            {
                // Aquí se haría la llamada con await a la API Rest con _remoteDatabase para CREAR el elemento en el servidor

                // Si ha ido bien se hace lo mismo en caché
                await _cache.InsertObject <T>(
                    typeof(T).Name + "_" + entity.id.ToString(),
                    entity,
                    DateTimeOffset.Now.AddHours(1));
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 19
0
 public IObservable<CacheIndex> Clear(IBlobCache cache, string indexKey, DateTimeOffset? absoluteExpiration = null)
 {
     OldKeys = Keys.ToList();
     Keys.Clear();
     UpdatedAt = DateTimeOffset.UtcNow;
     return cache
         .InvalidateObject<CacheIndex>(indexKey)
         .SelectMany(_ => cache.InsertObject(indexKey, this, absoluteExpiration))
         .Select(_ => this);
 }
Exemplo n.º 20
0
 public IObservable <CacheIndex> Clear(IBlobCache cache, string indexKey, DateTimeOffset?absoluteExpiration = null)
 {
     OldKeys = Keys.ToList();
     Keys.Clear();
     UpdatedAt = DateTimeOffset.UtcNow;
     return(cache
            .InvalidateObject <CacheIndex>(indexKey)
            .SelectMany(_ => cache.InsertObject(indexKey, this, absoluteExpiration))
            .Select(_ => this));
 }
Exemplo n.º 21
0
        public IObservable <T> Save <T>(IBlobCache cache, string key, DateTimeOffset?absoluteExpiration = null)
            where T : CacheItem
        {
            var k = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", key, Key);

            return(cache
                   .InvalidateObject <T>(k)
                   .Select(_ => cache.InsertObject(k, this, absoluteExpiration))
                   .Select(_ => this as T));
        }
Exemplo n.º 22
0
        public async Task <List <IPage> > FetchPages(string id)
        {
            Cache = BlobCache.LocalMachine;
            List <IPage> getPagesTask = await GetPagesAsync(id);

            await Cache.InsertObject("pages", getPagesTask, DateTimeOffset.Now.AddHours(2));

            List <IPage> pages = await Cache.GetObject <List <IPage> >("pages");

            return(pages);
        }
Exemplo n.º 23
0
        public static IObservable <T?> GetAndFetchLatest <T>(
            this IBlobCache blobCache,
            string key,
            Func <IObservable <T> > fetchFunc,
            Func <DateTimeOffset, bool>?fetchPredicate = null,
            DateTimeOffset?absoluteExpiration          = null,
            bool shouldInvalidateOnError            = false,
            Func <T, bool>?cacheValidationPredicate = null)
        {
            if (blobCache is null)
            {
                throw new ArgumentNullException(nameof(blobCache));
            }

#pragma warning disable CS8604 // Possible null reference argument.
            var fetch = Observable.Defer(() => blobCache.GetObjectCreatedAt <T>(key))
                        .Select(x => fetchPredicate is null || x is null || fetchPredicate(x.Value))
                        .Where(x => x)
                        .SelectMany(_ =>
            {
                var fetchObs = fetchFunc().Catch <T, Exception>(ex =>
                {
                    var shouldInvalidate = shouldInvalidateOnError ?
                                           blobCache.InvalidateObject <T>(key) :
                                           Observable.Return(Unit.Default);
                    return(shouldInvalidate.SelectMany(__ => Observable.Throw <T>(ex)));
                });

                return(fetchObs
                       .SelectMany(x =>
                                   cacheValidationPredicate is not null && !cacheValidationPredicate(x)
                                ? Observable.Return(default(T))
                                : blobCache.InvalidateObject <T>(key).Select(__ => x))
                       .SelectMany(x =>
                                   cacheValidationPredicate is not null && !cacheValidationPredicate(x)
                                ? Observable.Return(default(T))
                                : blobCache.InsertObject(key, x, absoluteExpiration).Select(__ => x)));
            });

            if (fetch is null)
            {
                return(Observable.Throw <T>(new Exception("Could not find a valid way to fetch the value")));
            }

            var result = blobCache.GetObject <T>(key).Select(x => (x, true))
                         .Catch(Observable.Return((default(T), false)));

#pragma warning restore CS8604 // Possible null reference argument.

            return(result.SelectMany(x => x.Item2 ? Observable.Return(x.Item1) : Observable.Empty <T>())
                   .Concat(fetch)
                   .Multicast(new ReplaySubject <T?>())
                   .RefCount());
        }
Exemplo n.º 24
0
 /// <summary>
 /// Attempt to return an object from the cache. If the item doesn't
 /// exist or returns an error, call a Func to return the latest
 /// version of an object and insert the result in the cache.
 ///
 /// For most Internet applications, this method is the best method to
 /// call to fetch static data (i.e. images) from the network.
 /// </summary>
 /// <param name="key">The key to associate with the object.</param>
 /// <param name="fetchFunc">A Func which will asynchronously return
 /// the latest value for the object should the cache not contain the
 /// key.
 ///
 /// Observable.Start is the most straightforward way (though not the
 /// most efficient!) to implement this Func.</param>
 /// <param name="absoluteExpiration">An optional expiration date.</param>
 /// <returns>A Future result representing the deserialized object from
 /// the cache.</returns>
 public static IObservable <T> GetOrFetchObject <T>(this IBlobCache This, string key, Func <IObservable <T> > fetchFunc, DateTimeOffset?absoluteExpiration = null)
 {
     return(This.GetObjectAsync <T>(key).Catch <T, Exception>(_ =>
     {
         object dontcare;
         return ((IObservable <T>)inflightFetchRequests.GetOrAdd(key, __ => (object)fetchFunc()))
         .Do(x => This.InsertObject(key, x, absoluteExpiration))
         .Finally(() => inflightFetchRequests.TryRemove(key, out dontcare))
         .Multicast(new AsyncSubject <T>()).RefCount();
     }));
 }
        public Task Set <T>(string key, T value, TimeSpan?expireTimeSpan)
        {
            var t = Task.Run(async() =>
            {
                DateTimeOffset?offset = expireTimeSpan.HasValue ? DateTimeOffset.UtcNow.Add(expireTimeSpan.Value) : (DateTimeOffset?)null;
                await cache.InsertObject(key, value, offset);
            });

            t.ConfigureAwait(false);
            return(t);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Inserts the specified key/value pairs into the blob.
        /// </summary>
        /// <typeparam name="T">The type of item to insert.</typeparam>
        /// <param name="blobCache">The blob cache to insert the values to.</param>
        /// <param name="keyValuePairs">The key/value to insert.</param>
        /// <param name="absoluteExpiration">An optional expiration date.</param>
        /// <returns>A observable which signals when complete.</returns>
        public static IObservable <Unit> InsertObjects <T>(this IBlobCache blobCache, IDictionary <string, T> keyValuePairs, DateTimeOffset?absoluteExpiration = null)
        {
            if (blobCache is IObjectBulkBlobCache bulkCache)
            {
                return(bulkCache.InsertObjects(keyValuePairs, absoluteExpiration));
            }

            return(keyValuePairs.ToObservable()
                   .SelectMany(x => blobCache.InsertObject(x.Key, x.Value, absoluteExpiration))
                   .TakeLast(1));
        }
Exemplo n.º 27
0
        public async Task <bool> PickupPackage(Package package)
        {
            if (await _blobCache.ContainsKey(package.Barcode))
            {
                return(false);
            }

            await _blobCache.InsertObject(package.Barcode, package);

            return(true);
        }
Exemplo n.º 28
0
        //These methods are the ones we call from courseViewModel and ChapterViewModel
        public async Task <List <ChapterLevel> > FetchChapterLevels(string id)
        {
            Cache = BlobCache.LocalMachine;
            List <Chapter> getChaptersTask = await GetChaptersAsync(id);

            List <ChapterLevel> chapterLevels = FetchSortedLevels(getChaptersTask);
            await Cache.InsertObject("chapters", chapterLevels, DateTimeOffset.Now.AddHours(2));

            List <ChapterLevel> chapters = await Cache.GetObject <List <ChapterLevel> >("chapters");

            return(chapters);
        }
Exemplo n.º 29
0
        public async Task SaveAsync <T>(string key, T value, TimeSpan?expiration = null) where T : class
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new InvalidOperationException($"{nameof(key)} cannot be null or white space.");
            }

            if (value == null)
            {
                throw new InvalidOperationException($"{nameof(value)} cannot be null.");
            }

            if (expiration != null && expiration.HasValue)
            {
                await localBlobCache.InsertObject(key, value, expiration.Value);
            }
            else
            {
                await localBlobCache.InsertObject(key, value);
            }
        }
Exemplo n.º 30
0
        public async Task <bool> SetUser(UserDto user)
        {
            try
            {
                await _blobCache.InsertObject($"current_user", user).ToTask();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 31
0
        public IObservable <CacheIndex> AddAndSave(IBlobCache cache, string indexKey, CacheItem item,
                                                   DateTimeOffset?absoluteExpiration = null)
        {
            var k = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", IndexKey, item.Key);

            if (!Keys.Contains(k))
            {
                Keys.Add(k);
            }
            UpdatedAt = DateTimeOffset.UtcNow;
            return(cache.InsertObject(IndexKey, this, absoluteExpiration)
                   .Select(x => this));
        }
Exemplo n.º 32
0
        public override void SetOrCreate <T>(T value, [CallerMemberName] string key = null)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            AddToInternalCache(key, value);

            // Fire and forget, we retrieve the value from the in-memory cache from now on
            _blobCache.InsertObject($"{_cacheKey}:{key}", value).Wait();

            _model.RaisePropertyChanged(key);
        }
Exemplo n.º 33
0
 public static IObservable<CacheIndex> AddAndSaveToIndex(IBlobCache cache, string indexKey, CacheItem item,
     DateTimeOffset? absoluteExpiration = null)
 {
     return cache.GetOrCreateObject(indexKey, () => Create(indexKey))
         .Do(index =>
         {
             var k = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", index.IndexKey, item.Key);
             if (!index.Keys.Contains(k))
                 index.Keys.Add(k);
             index.UpdatedAt = DateTimeOffset.UtcNow;
         })
         .SelectMany(index => cache.InsertObject(index.IndexKey, index, absoluteExpiration)
         .Select(x => index));
 }
Exemplo n.º 34
0
        public FeedsViewModel(IBlobCache cache = null)
        {
            Cache = cache ?? Locator.Current.GetService<IBlobCache>();

            Cache.GetOrCreateObject(BlobCacheKeys.Blogs, () => new ReactiveList<BlogViewModel>())
                .Subscribe(blogs => { Blogs = blogs; });

            RefreshAll = ReactiveCommand.CreateAsyncTask(x =>
            {
                foreach (var blog in Blogs)
                {
                    blog.Refresh.InvokeCommand(null);
                }

                return Task.FromResult(Unit.Default);
            });

            RefreshAll.ThrownExceptions.Subscribe(thrownException => { this.Log().Error(thrownException); });

            _isLoading = RefreshAll.IsExecuting.ToProperty(this, x => x.IsLoading);

            PersistData =
                ReactiveCommand.CreateAsyncTask(async x => { await Cache.InsertObject(BlobCacheKeys.Blogs, Blogs); });

            PersistData.ThrownExceptions.Subscribe(thrownException => { this.Log().Error(thrownException); });

            // behaviours

            // when a blog is added or removed, wait for 5 seconds of inactivity before persisting the data as the user may be doing bulk [add|remove] operations.
            this.WhenAnyValue(viewModel => viewModel.Blogs)
                .Throttle(TimeSpan.FromSeconds(5), RxApp.MainThreadScheduler)
                .InvokeCommand(this, viewModel => viewModel.PersistData);

            // When an user adds a new blog to the feed, automatically fetch/cache the contents of the blog.
            // When a blog becomes the selected blog, fetch/cache the contents of the blog.
            this.WhenAnyObservable(viewModel => viewModel.Blogs.ItemsAdded)
                .Merge(this.WhenAnyValue(viewModel => viewModel.SelectedBlog).Where(blogVm => blogVm != null))
                .Subscribe(x => x.Refresh.InvokeCommand(null));

            // post-condition checks
            Condition.Ensures(Cache).IsNotNull();
            Condition.Ensures(RefreshAll).IsNotNull();
            Condition.Ensures(PersistData).IsNotNull();
        }
Exemplo n.º 35
0
		public async Task WriteToStorage(IBlobCache storage)
		{
			await storage.InsertObject("ApiKey", ApiKey);
			await storage.InsertObject("AuthUser", AuthUser);
			await storage.InsertObject("AuthPass", AuthPass);
			await storage.InsertObject("Endpoint", Endpoint);
			await storage.InsertObject("PbxFolder", PbxFolder);
			await storage.InsertObject("SyncStarred", SyncStarred);
			await storage.InsertObject("MinimizeToTray", MinimizeToTray);
			await storage.InsertObject("StartWithWindows", StartWithWindows);
			await storage.InsertObject("ReformatXml", ReformatXml);
			await storage.InsertObject("XmlFile", XmlFile);
			await storage.InsertObject("DownloadOnStartup", DownloadOnStartup);
			await storage.InsertObject("PatchTableScripts", PatchTableScripts);
			await storage.InsertObject("DownloadOrientation", DownloadOrientation);
			await storage.InsertObject("DownloadOrientationFallback", DownloadOrientationFallback);
			await storage.InsertObject("DownloadLighting", DownloadLighting);
			await storage.InsertObject("DownloadLightingFallback", DownloadLightingFallback);
			await storage.InsertObject("IsFirstRun", false);
			IsFirstRun = false;
		}
Exemplo n.º 36
0
 public IObservable<CacheIndex> Save(IBlobCache cache,
     DateTimeOffset? absoluteExpiration = null)
 {
     return cache.InsertObject(IndexKey, this, absoluteExpiration)
         .Select(x => this);
 }
Exemplo n.º 37
0
		public async Task WriteInternalToStorage(IBlobCache storage) {
			await storage.InsertObject("WindowPosition", WindowPosition);
		}
Exemplo n.º 38
0
 private static async Task Vacuum(IBlobCache x) {
     await x.Vacuum();
     await x.InsertObject(vacuumKey, DateTime.UtcNow);
 }