Beispiel #1
0
        public override Config GetConfig()
        {
            bool denyToNonAdmins = !CacheProvider.GetSignInView().IsAdmin.ToBool();

            Config config = ScrudProvider.GetScrudConfig();

            config.DenyAdd    = denyToNonAdmins;
            config.DenyEdit   = denyToNonAdmins;
            config.DenyDelete = denyToNonAdmins;

            config.KeyColumn = "api_access_policy_id";

            config.TableSchema = "policy";
            config.Table       = "api_access_policy";
            config.ViewSchema  = "policy";
            config.View        = "api_access_policy";

            config.PageSize = 100;

            config.DisplayFields = GetDisplayFields();
            config.DisplayViews  = GetDisplayViews();

            config.Text             = "API Access Policy";
            config.ResourceAssembly = Assembly.GetAssembly(typeof(ApiAccessController));

            ViewData["Pocos"] = this.GetPocos();

            return(config);
        }
Beispiel #2
0
        public AppServerApiController(UCenterDatabaseContext database)
            : base(database)
        {
            this.appConfigurationCacheProvider = new CacheProvider <AppConfigurationResponse>(
                TimeSpan.FromMinutes(5),
                async(key, token) =>
            {
                var appConfiguration = await this.Database.AppConfigurations.GetSingleAsync(key, token);

                var response = new AppConfigurationResponse
                {
                    AppId         = key,
                    Configuration = appConfiguration == null ? string.Empty : appConfiguration.Configuration
                };

                return(response);
            });
            this.appCacheProvider = new CacheProvider <AppResponse>(
                TimeSpan.FromMinutes(5),
                async(key, token) =>
            {
                var app      = await this.Database.Apps.GetSingleAsync(key, token);
                var response = new AppResponse
                {
                    AppId     = key,
                    AppSecret = app == null ? string.Empty : app.AppSecret
                };

                return(response);
            });
        }
Beispiel #3
0
        public virtual async Task <T> GetOrAddAsync <T>(string key, Func <ICacheEntry, Task <T> > addItemFactory)
        {
            ValidateKey(key);

            T cacheItem;

            await _lock.WaitAsync().ConfigureAwait(false);

            try
            {
                cacheItem = await CacheProvider.GetOrCreateAsync <T>(key, async (entry) =>
                {
                    // thread safety is up to the provider
                    var result = await addItemFactory(entry);
                    EnsureEvictionCallbackDoesNotReturnTheAsyncOrLazy <T>(entry.PostEvictionCallbacks);
                    return(result);
                });
            }
            finally
            {
                _lock.Release();
            }

            return(cacheItem);
        }
Beispiel #4
0
        static Untils()
        {
            ResourceContext resContext = ResourceContext.GetForCurrentView();

            DeviceFamily = resContext.QualifierValues["DeviceFamily"];
            cache        = new CacheProvider(StorageType.SqliteStorage);
        }
        public void SlidingExpiredItemIsRemoved()
        {
            var stringKey = CacheKey.Create <string>("hello");
            var myObject1 = CacheProvider.GetOrCreate(stringKey,
                                                      () => new CacheValueOf <TestCacheObject>(new TestCacheObject("hello-1"), new StaticCachePolicy(TimeSpan.FromSeconds(1))));

            Assert.NotNull(myObject1);

            Assert.That(myObject1.AlreadyExisted, Is.False);

            Assert.That(myObject1.WasInserted, Is.True);

            Assert.NotNull(myObject1.Value);

            if (CacheIsAsync)
            {
                Thread.Sleep(500);
            }

            Assert.NotNull(CacheProvider.GetValue <TestCacheObject>(stringKey));

            Assert.NotNull(CacheProvider.Get <TestCacheObject>(stringKey));

            Thread.Sleep(TimeSpan.FromSeconds(1.2d));

            Assert.Null(CacheProvider.Get <TestCacheObject>(stringKey));
        }
Beispiel #6
0
 /// <summary>
 /// Unloads the image
 /// </summary>
 /// <param name="saveToCache">should the image kept in cache</param>
 /// <returns>true if successful, false otherwise</returns>
 public bool UnloadBanner(bool saveToCache)
 {
     if (BannerLoading)
     {
         if (!SpinWait.SpinUntil(BannerIsLoading, _bannerLoadTimeout))
         {
             //banner is currently loading
             Log.Warn("Can't remove banner while it's loading");
             return(false);
         }
     }
     try
     {
         if (IsLoaded)
         {
             LoadBanner(null);
         }
         if (!saveToCache)
         {//we don't want the image in cache -> if we already cached it it should be deleted
             String cacheName = CreateCacheName(Id, BannerPath);
             if (CacheProvider != null && CacheProvider.Initialised)
             {//try to load the image from cache first
                 CacheProvider.RemoveImageFromCache(SeriesId, CachePath, cacheName);
             }
         }
     }
     catch (Exception ex)
     {
         Log.Warn("Error while unloading banner", ex);
     }
     return(true);
 }
        public void CanAddAtLeast300ItemsPerSecond()
        {
            var watch = new Stopwatch();

            TypedEntity[] itemsToAdd = new TypedEntity[500];
            for (int i = 0; i < 300; i++)
            {
                var item = HiveModelCreationHelper.MockTypedEntity(true);
                itemsToAdd[i] = item;
            }

            watch.Start();
            for (int i = 0; i < 300; i++)
            {
                CacheProvider.AddOrChangeValue(CacheKey.Create("Item " + i), itemsToAdd[i]);
            }
            watch.Stop();
            var writeElapsed = watch.Elapsed;

            watch.Reset();
            watch.Start();
            for (int i = 0; i < 300; i++)
            {
                var cacheKey = CacheKey.Create("Item " + i);
                var item     = CacheProvider.Get <TypedEntity>(cacheKey);
                Assert.That(item, Is.Not.Null);
            }
            watch.Stop();
            var readElapsed = watch.Elapsed;

            LogHelper.TraceIfEnabled <AbstractCacheProviderFixture>("Write Took (s): " + writeElapsed.TotalSeconds);
            LogHelper.TraceIfEnabled <AbstractCacheProviderFixture>("Read Took (s): " + readElapsed.TotalSeconds);
            Assert.That(writeElapsed, Is.LessThan(TimeSpan.FromSeconds(1)));
            Assert.That(readElapsed, Is.LessThan(TimeSpan.FromSeconds(1)));
        }
Beispiel #8
0
 private void BuildVm()
 {
     try
     {
         if (CacheProvider.Exist("FamRecs"))
         {
             FamRecs = (List <SelectListItem>)CacheProvider.Get("FamRecs");
         }
         else
         {
             // TODO: Modify TEXT (SelectList)
             FamRecs = _serviceFamRec.GetAll(null, null).Select(x => new SelectListItem {
                 Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id)
             }).ToList();
             FamRecs.Insert(0, new SelectListItem {
                 Text = string.Empty, Value = string.Empty
             });
             CacheProvider.Set("FamRecs", FamRecs);
         }
     }
     catch (Exception ex)
     {
         //LoggerFactory.CreateLog().Error(string.Format(CultureInfo.InvariantCulture, "Presentation Layer - InitializeVMReceta ERROR"), ex);
     }
 }
        public override async Task GetInfoAsync(GeMenuItemInput geMenuItemInput)
        {
            var itemDataModel  = geMenuItemInput.ItemDataModel;
            var moduleId       = itemDataModel.Id;
            var currentRequest = geMenuItemInput.CurrentRequest;
            var propertyName   = itemDataModel.PropertyName;

            var isPrivate = NewsItemBusinessModule.IsPrivate(propertyName);

            if (isPrivate && geMenuItemInput.IsSitemap)
            {
                return;
            }

            var menuItem = await NewsItemBusinessModule.GetMenuItemAsync(_urlProvider, itemDataModel, currentRequest, ModuleName, isPrivate);

            if (menuItem != null)
            {
                var expendoMenu = CacheProvider.ToExpando(menuItem);
                {
                    var items =
                        await
                        geMenuItemInput.DataFactory.ItemRepository.GetItemsAsync(itemDataModel.SiteId,
                                                                                 new ItemFilters { ParentId = moduleId });

                    await
                    CacheProvider.GetChildsAsync(_businessModuleFactory, geMenuItemInput.CurrentRequest, items,
                                                 expendoMenu,
                                                 geMenuItemInput.DataFactory);
                }

                ModuleManager.Add(geMenuItemInput.Master, itemDataModel.PropertyName, expendoMenu,
                                  itemDataModel.PropertyType);
            }
        }
Beispiel #10
0
        public virtual LookupItemCollection GetLookups(string collectionName)
        {
            cacheLock.EnterUpgradeableReadLock();
            try {
                Dictionary <string, LookupItemCollection> cachedItems = new Dictionary <string, LookupItemCollection>();
                if (CacheProvider.Contains(this.Name))
                {
                    cachedItems = CacheProvider.Read(this.Name) as Dictionary <string, LookupItemCollection>;
                }

                if (cachedItems.ContainsKey(collectionName))
                {
                    return(cachedItems[collectionName]);
                }
                else
                {
                    cacheLock.EnterWriteLock();
                    try {
                        LookupItemCollection result = InitializeLookups(collectionName);

                        cachedItems.Add(collectionName, result);
                        CacheProvider.Update(this.Name, cachedItems);
                        return(result);
                    } finally  {
                        cacheLock.ExitWriteLock();
                    }
                }
            } finally {
                cacheLock.ExitUpgradeableReadLock();
            }
        }
Beispiel #11
0
 private void BuildVm()
 {
     try
     {
         if (CacheProvider.Exist("Alims"))
         {
             Alims = (List <SelectListItem>)CacheProvider.Get("Alims");
         }
         else
         {
             // TODO: Modify TEXT (SelectList)
             Alims = _serviceAlim.GetAll(null, null).Select(x => new SelectListItem {
                 Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id)
             }).ToList();
             CacheProvider.Set("Alims", Alims);
         }
         if (CacheProvider.Exist("Desechos"))
         {
             Desechos = (List <SelectListItem>)CacheProvider.Get("Desechos");
         }
         else
         {
             // TODO: Modify TEXT (SelectList)
             Desechos = _serviceDesecho.GetAll(null, null).Select(x => new SelectListItem {
                 Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id)
             }).ToList();
             CacheProvider.Set("Desechos", Desechos);
         }
     }
     catch (Exception ex)
     {
         //LoggerFactory.CreateLog().Error(string.Format(CultureInfo.InvariantCulture, "Presentation Layer - InitializeVMDesCant ERROR"), ex);
     }
 }
Beispiel #12
0
        public static void CleanUpCache()
        {
            string filePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "JianShuCahce.db");

            new FileInfo(filePath).Delete();
            cache = new CacheProvider(StorageType.SqliteStorage);
        }
Beispiel #13
0
        public virtual async Task <FulfillmentSchedule> GetStoreScheduleAsync(GetStoreScheduleParam param)
        {
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(param.Scope)), nameof(param));
            }
            if (param.FulfillmentLocationId == null)
            {
                throw new ArgumentException(GetMessageOfNull(nameof(param.FulfillmentLocationId)), nameof(param));
            }

            var cacheKey = new CacheKey(CacheConfigurationCategoryNames.StoreSchedule)
            {
                Scope = param.Scope
            };

            cacheKey.AppendKeyParts(param.FulfillmentLocationId.ToString());

            var request = new GetScheduleRequest
            {
                ScopeId = param.Scope,
                FulfillmentLocationId = param.FulfillmentLocationId,
                ScheduleType          = ScheduleType.OpeningHours
            };

            return(await CacheProvider.GetOrAddAsync(cacheKey, () => OvertureClient.SendAsync(request)).ConfigureAwait(false));
        }
        public ICacheProvider Create(CacheProvider cacheProviderType, ServerSettings serverSettings)
        {
            var cacheProvider = Instances[cacheProviderType]();

            cacheProvider.SetupConfiguration(serverSettings);
            return(cacheProvider);
        }
Beispiel #15
0
        public virtual async Task <Overture.ServiceModel.Customers.Stores.Store> GetStoreByNumberAsync(GetStoreByNumberParam param)
        {
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(param.Scope)), nameof(param));
            }
            if (string.IsNullOrWhiteSpace(param.StoreNumber))
            {
                throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(param.StoreNumber)), nameof(param));
            }

            var cacheKey = new CacheKey(CacheConfigurationCategoryNames.Store)
            {
                Scope = param.Scope
            };

            cacheKey.AppendKeyParts(GETSTOREBYNUMBER_CACHE_KEYPART, param.StoreNumber);

            var request = new GetStoreByNumberRequest()
            {
                ScopeId          = param.Scope,
                Number           = param.StoreNumber,
                IncludeAddresses = param.IncludeAddresses,
                IncludeSchedules = param.IncludeSchedules
            };

            return(await CacheProvider.GetOrAddAsync(cacheKey, () => OvertureClient.SendAsync(request)).ConfigureAwait(false));
        }
Beispiel #16
0
        public virtual async Task <Overture.ServiceModel.Customers.Stores.Store> GetStoreAsync(GetStoreParam param)
        {
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException(nameof(param.Scope));
            }
            if (param.Id == default)
            {
                throw new ArgumentException(nameof(param.Id));
            }

            var cacheKey = new CacheKey(CacheConfigurationCategoryNames.Store)
            {
                Scope = param.Scope
            };

            cacheKey.AppendKeyParts(GETSTOREBYID_CACHE_KEYPART, param.Id);

            var request = new GetStoreRequest()
            {
                ScopeId                = param.Scope,
                Id                     = param.Id,
                IncludeAddresses       = param.IncludeAddresses,
                IncludeSchedules       = param.IncludeSchedules,
                IncludeOperatingStatus = param.IncludeOperatingStatus
            };

            return(await CacheProvider.GetOrAddAsync(cacheKey, () => OvertureClient.SendAsync(request)).ConfigureAwait(false));
        }
Beispiel #17
0
        public override ValueTask <MemberUpdatedEventArgs> HandleDispatchAsync(IGatewayApiClient shard, GuildMemberUpdateJsonModel model)
        {
            CachedMember oldMember = null;
            IMember      newMember = null;

            if (CacheProvider.TryGetMembers(model.GuildId, out var memberCache))
            {
                if (memberCache.TryGetValue(model.User.Value.Id, out var member))
                {
                    newMember = member;
                    var oldUser = member.SharedUser.Clone() as CachedSharedUser;
                    oldMember            = member.Clone() as CachedMember;
                    oldMember.SharedUser = oldUser;
                    newMember.Update(model);
                }
                else if (CacheProvider.TryGetUsers(out var userCache))
                {
                    newMember = Dispatcher.GetOrAddMemberTransient(userCache, memberCache, model.GuildId, model);
                }
            }

            var e = new MemberUpdatedEventArgs(oldMember, newMember);

            return(new(e));
        }
        public async Task LoadLoggedClient()
        {
            // check kung may session na ung logged client.
            // pag wala, i-load natin then saka idisplay ung nav head details

            if (CacheProvider.IsSet(CacheKey.LoggedClient))
            {
                client = CacheProvider.Get <Client> (CacheKey.LoggedClient);
                return;
            }

            ClientSession cliSession = SessionFactory.ReadSession <ClientSession>(SessionKeys.LoggedClient);

            // may client session na, so kunin nalang natin ung info nya.
            if (cliSession != null && cliSession.IsSet)
            {
                client = await cliService.GetClientByUsername(cliSession.Username);
            }

            // i-load muna ung client session from account session
            ClientSessionLoader cliLoader = new ClientSessionLoader(cliService);
            bool isLoaded = await cliLoader.LoadClientSession();

            if (isLoaded)
            {
                client = cliLoader.LoadedClient;
                CacheProvider.Set(CacheKey.LoggedClient, client);
            }
        }
        public HttpResponseMessage GetValidateCode(string sid)
        {
            string code = RandomStringGenerator.CreateRandomNumeric(5);
            var    resp = new HttpResponseMessage();

            try
            {
                if (string.IsNullOrEmpty(sid) || sid.Length < 32)
                {
                    resp.StatusCode = HttpStatusCode.BadRequest;
                }
                else
                {
                    CacheProvider.Set("vcode." + sid, code, TimeSpan.FromMinutes(10));
                    byte[] buffer = ValidateCodeGenerator.CreateImage(code);
                    resp.Content = new ByteArrayContent(buffer);
                    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                }
            }
            catch
            {
                resp.StatusCode = HttpStatusCode.InternalServerError;
            }

            return(resp);
        }
        public override ICacheProviderV30 GetProvider()
        {
            var prov = new CacheProvider();

            prov.Init(MockHost(), "");
            return(prov);
        }
Beispiel #21
0
        public override ValueTask <ThreadCreatedEventArgs> HandleDispatchAsync(IGatewayApiClient shard, ChannelJsonModel model)
        {
            IThreadChannel thread;

            if (CacheProvider.TryGetChannels(model.GuildId.Value, out var channelCache))
            {
                thread = channelCache.AddOrUpdate(model.Id,
                                                  (_, tuple) =>
                {
                    var(client, model) = tuple;
                    return(new CachedThreadChannel(client, model));
                },
                                                  (_, tuple, oldThread) =>
                {
                    var(_, model) = tuple;
                    oldThread.Update(model);
                    return(oldThread);
                }, (Client, model)) as IThreadChannel;
            }
            else
            {
                thread = new TransientThreadChannel(Client, model);
            }

            var e = new ThreadCreatedEventArgs(thread);

            return(new(e));
        }
Beispiel #22
0
 /// <summary>
 /// Unloads the image
 /// </summary>
 /// <param name="saveToCache">should the image kept in cache</param>
 /// <returns>true if successful, false otherwise</returns>
 public bool UnloadThumb(bool saveToCache)
 {
     if (ThumbLoading)
     {//banner is currently loading
         Log.Warn("Can't remove banner while it's loading");
         return(false);
     }
     try
     {
         if (IsThumbLoaded)
         {
             LoadThumb(null);
         }
         if (!saveToCache && ThumbPath != null && !ThumbPath.Equals(""))
         {//we don't want the image in cache -> if we already cached it it should be deleted
             String cacheName = CreateCacheName(ThumbPath, true);
             if (CacheProvider != null && CacheProvider.Initialised)
             {//try to load the image from cache first
                 CacheProvider.RemoveImageFromCache(SeriesId, cacheName);
             }
         }
     }
     catch (Exception ex)
     {
         Log.Warn("Error while unloading banner", ex);
     }
     return(true);
 }
        /// <summary>
        /// Performs a request to the TVDB API and returns the resultant object.
        /// </summary>
        /// <typeparam name="T">Type of the object to return.</typeparam>
        /// <param name="url">API sub-URL to use for the request.</param>
        /// <param name="cacheKey">Key to use for cache storage of this request.</param>
        /// <param name="ignoreCurrentCache">Ignores existing cache entries for this request.</param>
        /// <param name="ignorePersistentCache">Does not add this request to the persistent cache.</param>
        /// <returns>Object returned for the API request.</returns>
        public T PerformApiRequestAndDeserialize <T>(string url, string cacheKey, bool ignoreCurrentCache = false, bool ignorePersistentCache = false)
        {
            Debug.WriteLine("-> TvdbApiRequest::PerformApiRequestAndDeserialize url=\"" + url + "\" cacheKey=\"" + cacheKey +
                            "\" ignoreCurrentCache=\"" + ignoreCurrentCache + "\" ignorePersistentCache=\"" + ignorePersistentCache + "\" Called");
            try
            {
                // Retreive previous api request from the cache
                if (CacheProvider.ContainsKey(cacheKey))
                {
                    return((T)CacheProvider[cacheKey]);
                }

                // Perform api request and deserialize
                var stream       = PerformApiRequest(url);
                var ser          = new XmlSerializer(typeof(T));
                var deserialized = (T)ser.Deserialize(stream);

                // Add to cache if cache is enabled
                if (CacheProvider.CacheType != TvdbCacheType.None)
                {
                    CacheProvider.Add(cacheKey, deserialized, ignorePersistentCache);
                }

                return(deserialized);
            }
            catch (Exception e)
            {
                Debug.WriteLine("!> TvdbApiRequest::PerformApiRequestAndDeserialize threw an exception: " + e);
                return(default(T)); // request probably failed so return null for safe abort
            }
        }
 public SaveAddSiteCommand(IDataFactory dataFactory, UserService userService, CacheProvider cacheProvider, ModuleManager moduleManager)
 {
     _dataFactory   = dataFactory;
     _userService   = userService;
     _cacheProvider = cacheProvider;
     _moduleManager = moduleManager;
 }
Beispiel #25
0
        public void SendPushNotification()
        {
            var cacheProvider = new CacheProvider(memoryCache);

            //performances
            List <PerformanceDataModel> performancesWp =
                cacheProvider.GetAndSave(
                    () => Constants.PerformancesCacheKey + "uk",
                    () => perfomanceRepository.GetPerformanceTitlesAndImages("uk"));

            //schedule
            IEnumerable <ScheduleDataModelBase> scheduleWp =
                cacheProvider.GetAndSave(
                    () => Constants.ScheduleCacheKey + "uk",
                    () => scheduleRepository.GetListPerformancesByDateRange("uk", DateTime.Now));

            //statements above need to be changed when cache preload is implemented

            IEnumerable <PushTokenDataModelPartial> pushTokensPartial = pushTokenRepository.GetAllPushTokensToSendNotifications();

            List <PushTokenDataModel> pushTokens =
                (from partialInfo in pushTokensPartial
                 join performance in performancesWp on partialInfo.PerformanceId equals performance.PerformanceId
                 join schedule in scheduleWp on performance.PerformanceId equals schedule.PerformanceId

                 where (schedule.Beginning.Day == (DateTime.Today.AddDays(partialInfo.Frequency).Day) &&
                        (schedule.PerformanceId == partialInfo.PerformanceId))

                 select new PushTokenDataModel
            {
                Token = partialInfo.Token,
                LanguageCode = partialInfo.LanguageCode,
                ImageUrl = performance.MainImageUrl,
                Title = performance.Title
            })
                .Distinct(new PushTokenDataModelComparer())  //select distinct push tokens in order not to send several notifications
                .ToList();

            List <PushNotificationDTO> reqBody = (pushTokens.Select(p =>
                                                                    new PushNotificationDTO
            {
                To = p.Token,
                Title = p.LanguageCode == "en" ? "Lviv Puppet Theater" : "Львівський театр ляльок",
                Body = p.LanguageCode == "en" ?
                       $"{p.Title} coming soon" : $"{p.Title} скоро на сцені",
                Icon = $"{p.ImageUrl}",
                Color = "#9984d4"
            })).ToList();

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers.Add("accept", "application/json");
                client.Headers.Add("accept-encoding", "gzip, deflate");
                client.Headers.Add("Content-Type", "application/json");
                client.UploadString(
                    "https://exp.host/--/api/v2/push/send",
                    JsonConvert.SerializeObject(reqBody));
            }
        }
Beispiel #26
0
        public void SetUp(bool ignoreSingleSquareBrackets = false)
        {
            mocks = new MockRepository();

            var settingsProvider = mocks.StrictMock <ISettingsStorageProviderV30>();

            Expect.Call(settingsProvider.GetSetting("ProcessSingleLineBreaks")).Return("false").Repeat.Any();
            Expect.Call(settingsProvider.GetSetting("WikiTitle")).Return("Title").Repeat.Any();
            Expect.Call(settingsProvider.GetSetting("IgnoreSingleSquareBrackets"))
            .Return(ignoreSingleSquareBrackets ? "true" : "false")
            .Repeat.Any();

            Collectors.SettingsProvider = settingsProvider;

            var pagesProvider = mocks.StrictMock <IPagesStorageProviderV30>();

            Collectors.PagesProviderCollector = new ProviderCollector <IPagesStorageProviderV30>();
            Collectors.PagesProviderCollector.AddProvider(pagesProvider);

            Expect.Call(settingsProvider.GetSetting("DefaultPagesProvider"))
            .Return(pagesProvider.GetType().FullName)
            .Repeat.Any();

            var page1        = new PageInfo("page1", pagesProvider, DateTime.Now);
            var page1Content = new PageContent(page1, "Page 1", "User", DateTime.Now, "Comment", "Content", null, null);

            Expect.Call(pagesProvider.GetPage("page1")).Return(page1).Repeat.Any();
            Expect.Call(pagesProvider.GetContent(page1)).Return(page1Content).Repeat.Any();

            Expect.Call(pagesProvider.GetPage("page2")).Return(null).Repeat.Any();

            //Pages.Instance = new Pages();

            Host.Instance = new Host();

            Expect.Call(settingsProvider.GetSetting("CacheSize")).Return("100").Repeat.Any();
            Expect.Call(settingsProvider.GetSetting("CacheCutSize")).Return("20").Repeat.Any();

            Expect.Call(settingsProvider.GetSetting("DefaultCacheProvider"))
            .Return(typeof(CacheProvider).FullName)
            .Repeat.Any();

            // Cache needs setting to init
            mocks.Replay(settingsProvider);

            ICacheProviderV30 cacheProvider = new CacheProvider();

            cacheProvider.Init(Host.Instance, "");
            Collectors.CacheProviderCollector = new ProviderCollector <ICacheProviderV30>();
            Collectors.CacheProviderCollector.AddProvider(cacheProvider);

            mocks.Replay(pagesProvider);

            Collectors.FormatterProviderCollector = new ProviderCollector <IFormatterProviderV30>();

            //System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(new System.IO.StreamWriter(new System.IO.MemoryStream()));
            //System.Web.Hosting.SimpleWorkerRequest request = new System.Web.Hosting.SimpleWorkerRequest("Default.aspx", "?Page=MainPage", writer);
            HttpContext.Current = new HttpContext(new DummyRequest());
        }
        public async Task UtiliseCacheWithHeroData()
        {
            var cache                = new MemoryCache(new MemoryCacheOptions());
            var cacheProvider        = new CacheProvider(cache);
            var prismicCacheProvider = new PrismicCacheProvider(cacheProvider);
            var prismicService       = new PrismicGenericService(new NullLogger <PrismicGenericService>(), _fixture.HttpClient, TestCacheFactory.BuildPrismicCacheProvider(), _fixture.Configuration);
            var prismicHeroService   = new PrismicHeroService(prismicService, prismicCacheProvider);

            var timer = new Stopwatch();

            timer.Start();
            var result1 = await prismicHeroService.GetHeroes();

            timer.Stop();
            _outputHelper.WriteLine($"Time for first result: { timer.Elapsed }");

            timer.Restart();
            var result2 = await prismicHeroService.GetHeroes();

            timer.Stop();
            _outputHelper.WriteLine($"Time for second result: {timer.Elapsed}");

            var roles = await prismicHeroService.GetRoles();

            var roleCategories = await prismicHeroService.GetRoleCategories();

            var universes = await prismicHeroService.GetUniverses();

            var inGameCategories = await prismicHeroService.GetInGameCategories();

            var firstHero = result1.FirstOrDefault();

            Assert.Same(result1, result2);

            var category = firstHero?.InGameCategories?.FirstOrDefault();

            Assert.NotNull(category);
            Assert.Same(category, inGameCategories.SingleOrDefault(x => x.Id == category.Id));

            var role = firstHero?.Roles?.FirstOrDefault();

            Assert.NotNull(role);
            Assert.Same(role, roles.SingleOrDefault(x => x.Id == role.Id));

            var roleCategory = firstHero?.Roles?.FirstOrDefault()?.RoleCategory;

            Assert.NotNull(roleCategory);
            Assert.Same(roleCategory, roleCategories.SingleOrDefault(x => x.Id == roleCategory.Id));

            var universe = firstHero?.Universe;

            Assert.NotNull(universe);
            Assert.Same(universe, universes.SingleOrDefault(x => x.Id == universe.Id));

            var inGameCategory = firstHero?.InGameCategories?.FirstOrDefault();

            Assert.NotNull(inGameCategory);
            Assert.Same(inGameCategory, inGameCategories.SingleOrDefault(x => x.Id == inGameCategory.Id));
        }
        public void CahceInitTest()
        {
            CacheProvider iso = new CacheProvider(StorageType.IsolatedStorage);
            CacheProvider sql = new CacheProvider(StorageType.SqliteStorage);

            Assert.IsNotNull(iso);
            Assert.IsNotNull(sql);
        }
Beispiel #29
0
 public SaveFreeCommand(IDataFactory dataFactory, UserService userService, CacheProvider cacheProvider, ModuleManager moduleManager, FreeBusinessModule freeBusinessModule)
 {
     _dataFactory        = dataFactory;
     _userService        = userService;
     _cacheProvider      = cacheProvider;
     _moduleManager      = moduleManager;
     _freeBusinessModule = freeBusinessModule;
 }
Beispiel #30
0
 public SaveNewsCommand(IDataFactory dataFactory, UserService userService, CacheProvider cacheProvider, ModuleManager moduleManager, NewsBusinessModule newsBusinessModule)
 {
     _dataFactory        = dataFactory;
     _userService        = userService;
     _cacheProvider      = cacheProvider;
     _moduleManager      = moduleManager;
     _newsBusinessModule = newsBusinessModule;
 }
Beispiel #31
0
 public TransfertSiteCommand(IDataFactory dataFactorySource, IDataFactory dataFactoryDestination,
                             CacheProvider cacheProvider, BusinessModuleFactory businessModuleFactory)
 {
     _dataFactorySource      = dataFactorySource;
     _dataFactoryDestination = dataFactoryDestination;
     _cacheProvider          = cacheProvider;
     _businessModuleFactory  = businessModuleFactory;
 }
Beispiel #32
0
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            this.UnhandledException += AppUnhandledException;

            CacheProvider cache = new CacheProvider(StorageType.IsolatedStorage);
            GlobalValue.CurrentUserContext = cache.GetItem<UserContext>(CacheKey.UserContext);
        }
 public void TestReset()
 {
     using (var cacheProvider = new CacheProvider<string>((int)TimeSpan.FromSeconds(60).TotalMilliseconds))
     {
         const int Key = 123;
         cacheProvider.Set(Key, "aValue1");
         cacheProvider.Set(Key, "aKey2");
         Assert.IsTrue(cacheProvider.Contains(Key));
     }
 }
        public override void TestSetUp()
        {
            var serializer = new ServiceStackSerialiser();

            _frameworkContext = new FakeFrameworkContext(serializer);
            _configuration = new IndexConfiguration(GetPathForTest());
            var controller = new IndexController(_configuration, _frameworkContext);

            CacheProvider = new CacheProvider(controller, false);
        }
 private WebPageCollection(BrowserWindow broswerWindow, CacheProvider cacheProvider = null)
 {
     Browser = broswerWindow;
       Cache = cacheProvider;
       WebPages = new Dictionary<string, WebPage>( );
       if ( Cache != null )
       {
     WebPages = Cache.LoadWebPageCollectionFromCache( this.Browser );
       }
 }
 public void TestItemExpiration()
 {
     using (var cacheProvider = new CacheProvider<string>((int)TimeSpan.FromMilliseconds(200).TotalMilliseconds))
     {
         const int Key = 123;
         cacheProvider.Set(Key, "value");
         Thread.Sleep(2000);
         var value = cacheProvider.Get(Key);
         Assert.IsNull(value, "item must be expired and removed from the cache");
     }
 }
        public JsonResult MagicTrick()
        {
            CacheProvider cache = new CacheProvider();
            cache.Remove("TwitterAuthorizationToken");

            return new JsonResult()
            {
                Data = "You-know-what removed from you-know-where...",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
Beispiel #38
0
 public AniWrap(CacheProvider cache)
 {
     if (cache != null)
     {
         this.cache = cache;
     }
     else
     {
         this.cache = new MemoryCacheProvdier();
     }
 }
Beispiel #39
0
        void PrimeCache()
        {
            // get data to prime the cache
            var topProducts = new List<ICacheable>()
            {
                new Product() {  }
            };

            _cacheProvider = new AzureRedisCacheProvider("<connection string", StackExchange.Redis.CommandFlags.HighPriority);
            _cacheProvider.SetCollectionAsync("top-products", topProducts).GetAwaiter().GetResult();
        }
 public void TestGet()
 {
     using (var cacheProvider = new CacheProvider<string>((int)TimeSpan.FromSeconds(60).TotalMilliseconds))
     {
         const int Key = 123;
         const string ExpectedValue = "aValue1";
         cacheProvider.Set(Key, ExpectedValue);
         var value = cacheProvider.Get(Key);
         Assert.AreEqual(ExpectedValue, value);
     }
 }
 public static void AddCacheProvider(this IServiceCollection services, IConfiguration configuration)
 {
     CacheProvider cachePrvdr = new CacheProvider(configuration);
     services.AddInstance<CacheProvider>(cachePrvdr);
     services.AddTransient<ICacheProvider, CacheProvider > ();
 }
        private void ListenerViewChanged(ChangeView info)
        {
            switch(info.Event)
            {
                case EventType.LoginSuccess:
                    CacheProvider tempCache1 = new CacheProvider(StorageType.IsolatedStorage);
                    UserContext user = info.Context as UserContext;

                    if (tempCache1.ContainItem(CacheKey.UserContext)) tempCache1.UpdateItem(CacheKey.UserContext, user);
                    else tempCache1.AddItem(CacheKey.UserContext, user);

                    GlobalValue.CurrentUserContext = user;

                    Avatar = new Uri(GlobalValue.CurrentUserContext.Avatar, UriKind.Absolute);
                    IsLogin = true;
                    break;
                case EventType.Logout:
                    CacheProvider tempCache2 = new CacheProvider(StorageType.IsolatedStorage);

                    GlobalValue.CurrentUserContext.IsLogin = false;
                    tempCache2.UpdateItem(CacheKey.UserContext, GlobalValue.CurrentUserContext);

                    Avatar = GlobalValue.DefaultAvatar;
                    IsLogin = false;

                    WebContentProvider.CancelPendingRequests();

                    homeViewModel.Cleanup();
                    followViewModel.Cleanup();
                    friendsViewModel.Cleanup();
                    specialTopicViewModel.Cleanup();
                    likeViewModel.Cleanup();
                    userCenterViewModel.Cleanup();

                    View.FriendsView.VerticalOffset = 0;
                    View.SpecialTopicView.leftOffset = 0;
                    View.SpecialTopicView.rightOffset = 0;
                    View.SpecialTopicView.rightCanShow = false;
                    break;
                default:
                    break;
            }

            SwitchViewModel(info.ToView ,info);
        }
 public void SetUp()
 {
     mPersistentDictionaryFactory = new PersistentDictionaryFactory();
     mCacheProvider = new CacheProvider(mPersistentDictionaryFactory);
 }
 /// <summary>
 /// Return a Instance of WebPageCollection
 /// </summary>
 /// <param name="browserWindow"></param>
 /// <returns></returns>
 public static WebPageCollection GetWebPageCollection( BrowserWindow browserWindow, CacheProvider cacheProvider = null )
 {
     if ( _instance == null )
       {
     _instance = new WebPageCollection( browserWindow, cacheProvider );
       }
       return _instance;
 }
 public override ICacheProviderV30 GetProvider()
 {
     CacheProvider prov = new CacheProvider();
     prov.Init(MockHost(), "");
     return prov;
 }
Beispiel #46
0
 static Untils()
 {
     ResourceContext resContext = ResourceContext.GetForCurrentView();
     DeviceFamily = resContext.QualifierValues["DeviceFamily"];
     cache = new CacheProvider(StorageType.SqliteStorage);
 }
Beispiel #47
0
 public static void CleanUpCache()
 {
     string filePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "JianShuCahce.db");
     new FileInfo(filePath).Delete();
     cache = new CacheProvider(StorageType.SqliteStorage);
 }
Beispiel #48
0
        private static async Task<bool> WeiboShare(string url, string text)
        {
            CacheProvider cache = new CacheProvider(StorageType.IsolatedStorage);

            if (GlobalValue.CurrentWeiboUserInfo == null)
            {
                GlobalValue.CurrentWeiboUserInfo = cache.GetItem<UserInfo>(CacheKey.WeiboUser) ?? new UserInfo();
            }
            byte[] image = await new HttpClient().GetByteArrayAsync(url);

            bool shareResult = false;

            try
            {
                WeiboClient client = new WeiboClient(GlobalValue.CurrentWeiboUserInfo);
                await client.LoginAsync();
                WeiboResult result;
                if (!string.IsNullOrEmpty(url))
                {
                    result = await client.ShareImageAsync(image, text);
                }
                else
                {
                    result = await client.ShareTextAsync(text);
                }
                GlobalValue.CurrentWeiboUserInfo = client.UserInfo;

                cache.UpdateItem(CacheKey.WeiboUser, GlobalValue.CurrentWeiboUserInfo);
                shareResult = true;
            }
            catch
            {
                shareResult = false;
            }
            return shareResult;
        }
Beispiel #49
0
        public void SetUp()
        {
            mocks = new MockRepository();

            ISettingsStorageProviderV30 settingsProvider = mocks.StrictMock<ISettingsStorageProviderV30>();
            Expect.Call(settingsProvider.GetSetting("ProcessSingleLineBreaks")).Return("false").Repeat.Any();

            Collectors.SettingsProvider = settingsProvider;

            IPagesStorageProviderV30 pagesProvider = mocks.StrictMock<IPagesStorageProviderV30>();
            Collectors.PagesProviderCollector = new ProviderCollector<IPagesStorageProviderV30>();
            Collectors.PagesProviderCollector.AddProvider(pagesProvider);

            Expect.Call(settingsProvider.GetSetting("DefaultPagesProvider")).Return(pagesProvider.GetType().FullName).Repeat.Any();

            PageInfo page1 = new PageInfo("page1", pagesProvider, DateTime.Now);
            PageContent page1Content = new PageContent(page1, "Page 1", "User", DateTime.Now, "Comment", "Content", null, null);
            Expect.Call(pagesProvider.GetPage("page1")).Return(page1).Repeat.Any();
            Expect.Call(pagesProvider.GetContent(page1)).Return(page1Content).Repeat.Any();

            Expect.Call(pagesProvider.GetPage("page2")).Return(null).Repeat.Any();

            //Pages.Instance = new Pages();

            Host.Instance = new Host();

            Expect.Call(settingsProvider.GetSetting("CacheSize")).Return("100").Repeat.Any();
            Expect.Call(settingsProvider.GetSetting("CacheCutSize")).Return("20").Repeat.Any();

            Expect.Call(settingsProvider.GetSetting("DefaultCacheProvider")).Return(typeof(CacheProvider).FullName).Repeat.Any();

            // Cache needs setting to init
            mocks.Replay(settingsProvider);

            ICacheProviderV30 cacheProvider = new CacheProvider();
            cacheProvider.Init(Host.Instance, "");
            Collectors.CacheProviderCollector = new ProviderCollector<ICacheProviderV30>();
            Collectors.CacheProviderCollector.AddProvider(cacheProvider);

            mocks.Replay(pagesProvider);

            Collectors.FormatterProviderCollector = new ProviderCollector<IFormatterProviderV30>();

            //System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(new System.IO.StreamWriter(new System.IO.MemoryStream()));
            //System.Web.Hosting.SimpleWorkerRequest request = new System.Web.Hosting.SimpleWorkerRequest("Default.aspx", "?Page=MainPage", writer);
            System.Web.HttpContext.Current = new System.Web.HttpContext(new DummyRequest());
        }
Beispiel #50
0
 public AniWrap(string cache_dir)
 {
     cache = new DiskCacheProvider(cache_dir);
 }
Beispiel #51
0
 public AniWrap()
 {
     cache = new MemoryCacheProvdier();
 }
Beispiel #52
0
 public ProductService(CacheProvider<Product> provider)
 {
     _cacheProvider = provider;
 }