Exemplo n.º 1
0
        public IActionResult Index()
        {
            // Adding an expiration token allows us to trigger expiration,
            // to ensure that expiration itself is still working.
            var relative = _cache.GetOrAdd(CACHED_ITEM_RELATIVE_KEY, (entry) => {
                // expire immediately
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(1);

                return(new CachedItem
                {
                    Created = DateTime.Now,
                });
            });

            var absolute = _cache.GetOrAdd(CACHED_ITEM_ABSOLUTE_KEY, (entry) => {
                // expire immediately
                entry.AbsoluteExpiration = DateTime.UtcNow + TimeSpan.FromSeconds(1);

                return(new CachedItem
                {
                    Created = DateTime.Now,
                });
            });

            return(View("Index", new CachedItemsResult
            {
                Relative = relative,
                Absolute = absolute,
            }));
        }
Exemplo n.º 2
0
        public SiteMapModule(IAppCache appCache)
        {
            cache = appCache;
            cache.GetOrAdd("sitemap1.xml", () => getSiteMap("https://localhost:10623/sitemap1.xml"));
            cache.GetOrAdd("sitemap2.xml", () => getSiteMap("https://localhost:10623/sitemap2.xml"));
            cache.GetOrAdd("sitemap3.xml", () => getSiteMap("https://localhost:10623/sitemap3.xml"));
            cache.GetOrAdd("sitemap.xml", () => getSiteMapIndex("https://localhost:10623/sitemap.xml"));
            var list = new List <string>();

            list.AddRange(new [] { "sitemap1.xml", "sitemap2.xml", "sitemap3.xml", "sitemap.xml" });
            foreach (var item in list)
            {
                Get($"/{item}", async(req, resp) =>
                {
                    if (item.Equals("sitemap.xml"))
                    {
                        var ms           = await cache.Get <Extensions.SiteMapIndex.SiteMapIndex>("sitemap.xml").Parse();
                        resp.ContentType = "application/xml";
                        resp.StatusCode  = 200;
                        await ms.CopyToAsync(resp.Body);
                        return;
                    }

                    var smap         = cache.Get <SiteMap>(item);
                    var ms2          = await smap.Parse();
                    resp.ContentType = "application/xml";
                    resp.StatusCode  = 200;
                    await ms2.CopyToAsync(resp.Body);
                    return;
                });
            }
        }
Exemplo n.º 3
0
 public static T AddGetItem(string keyName, T value)
 {
     LogHandler.Info($"Cache - Adding {keyName}");
     return(cache.GetOrAdd(keyName,
                           () => value,
                           DateTimeOffset.Now.AddMinutes(5)));
 }
Exemplo n.º 4
0
        private IpAddress GetIpAddress(IpAddress ipAddress)
        {
            var ipAddressCacheKey = $"LoggingService-IPAddresses-{ipAddress.Address}";

            return(_appCache.GetOrAdd(ipAddressCacheKey,
                                      () => _logRepository.GetWithAddIpAddress(ipAddress),
                                      new TimeSpan(0, 10, 0)));
        }
        public IActionResult GetAllUsers()
        {
            Func <ICollection <UserViewModel> > usersGetter = () => _manager.GetAllUsers();

            var usersCached = _cache.GetOrAdd("UsersController.GetUsers", usersGetter, _cacheExpiry);

            return(Ok(usersCached));
        }
Exemplo n.º 6
0
        public Profile GetExample()
        {
            Profile ExampleFactory() => _raiderIo.GetExample();

            var profile = _cache.GetOrAdd("exampleProfile", ExampleFactory);

            return(profile);
        }
Exemplo n.º 7
0
        public IActionResult GetAllProjects()
        {
            Func <ICollection <ProjectViewModel> > projectsGetter = () => _manager.GetAllProjects();

            var projectsCached = _cache.GetOrAdd("ProjectsController.GetProjects", projectsGetter, _cacheExpiry);

            return(Ok(projectsCached));
        }
        public static async Task <ProxyProcessResult> RunPostProcessors(FHIRResponse response, HttpRequest req, ILogger log, ClaimsPrincipal principal, string res, string id, string hist, string vid)
        {
            ProxyProcessResult rslt = new ProxyProcessResult();

            //Default to server response
            rslt.Response = response;
            //Get Configured PostProcessors
            string pps = System.Environment.GetEnvironmentVariable("POST_PROCESSOR_TYPES");

            if (string.IsNullOrEmpty(pps))
            {
                return(rslt);
            }
            string[] types = pps.Split(",");
            foreach (string cls in types)
            {
                try
                {
                    string         ic = cls;
                    DateTimeOffset os = DateTimeOffset.Now;
                    if (cls.Contains(":"))
                    {
                        string[] x = cls.Split(":");
                        ic = x[0];
                        int exp = DEF_EXP_MINS;
                        int.TryParse(x[1], out exp);
                        os = os.AddMinutes(exp);
                    }
                    else
                    {
                        os = os.AddMinutes(DEF_EXP_MINS);
                    }
                    IProxyPostProcess ip = (IProxyPostProcess)cache.GetOrAdd(cls, () => GetInstance(ic), os);
                    log.LogInformation($"ProxyProcessManager is running {cls} post-process...");
                    rslt = await ip.Process(rslt.Response, req, log, principal, res, id, hist, vid);

                    if (!rslt.Continue)
                    {
                        return(rslt);
                    }
                }
                catch (InvalidCastException ece)
                {
                    log.LogWarning($"{cls} does not seem to implement IProxyPostProcess and will not be executed:{ece.Message}");
                }
                catch (Exception e)
                {
                    log.LogError(e, $"Error trying to instanciate/execute post-process {cls}: {e.Message}");
                    FHIRResponse fhirresp = new FHIRResponse();
                    fhirresp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                    fhirresp.Content    = Utils.genOOErrResponse("internalerror", $"Error trying to instanciate/execute post-process {cls}: {e.Message}");
                    return(new ProxyProcessResult(false, "internalerror", "", fhirresp));
                }
            }
            return(rslt);
        }
Exemplo n.º 9
0
        public async Task <IApiResponse> Get([FromQuery] string url)
        {
            if (url is null)
            {
                return(new ErrorResponse {
                    Error = "No url found in query."
                });
            }

            // adds http to url if not present
            url = new UriBuilder(url).Uri.ToString();

            IApiResponse result;
            async Task <IApiResponse> websiteInfoGetter() => await UrlSolverService.GetWebsiteInfo(url);

            // heroku likely won't keep the app awake above 30 minutes
            result = await Cache.GetOrAdd($"websiteInfo-{url}", websiteInfoGetter, TimeSpan.FromMinutes(30));

            if (result is null)
            {
                return(new ErrorResponse {
                    Error = "Couldn't get website info. Try again later."
                });
            }

            return(result);
        }
Exemplo n.º 10
0
        public BaseDataResponse <IEnumerable <Guid> > GetMatchingRules(TObjectToMatch objectToMatch, IEnumerable <RulesConfig> rulesConfig)
        {
            var matching = new HashSet <Guid>();

            foreach (var ruleConfig in rulesConfig)
            {
                try
                {
                    var compiledRule = _cache.GetOrAdd($"{GetType().Name}.{ruleConfig.Id}", () =>
                    {
                        return(_compiler.CompileRule <TObjectToMatch>(ruleConfig));
                    });

                    if (compiledRule(objectToMatch))
                    {
                        matching.Add(ruleConfig.Id);
                    }
                }
                catch (Exception exc)
                {
                    return(new BaseDataResponse <IEnumerable <Guid> > {
                        Code = ErrorCode.TechnicalProblem, ErrorDescription = exc.Message, Data = matching
                    });
                }
            }

            return(new BaseDataResponse <IEnumerable <Guid> > {
                Data = matching
            });
        }
Exemplo n.º 11
0
        public void GetOrAddOnCore31ReturnsTheCachedItem()
        {
            var cachedResult = sut.GetOrAdd(TestKey, () => new { SomeProperty = "SomeValue" });

            Assert.IsNotNull(cachedResult);
            Assert.AreEqual("SomeValue", cachedResult.SomeProperty);
        }
Exemplo n.º 12
0
        public static IList <AvailableFilter> GetAvailableFilters(this IAppCache cache, Func <IList <AvailableFilter> > loader)
        {
            // TODO: Should not be called like this?!
            var list = cache.GetOrAdd(AvailableFiltersKey, loader, DateTimeOffset.UtcNow.AddSeconds(CacheTimeFilter));

            return(list);
        }
Exemplo n.º 13
0
 public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory,
                              TimeSpan slidingExpiration)
 {
     return(cache.GetOrAdd(key, addItemFactory,
                           new MemoryCacheEntryOptions {
         SlidingExpiration = slidingExpiration
     }));
 }
Exemplo n.º 14
0
 public static List <RegisteredSipDto> GetOrAddRegisteredSips(this IAppCache cache, Func <List <RegisteredSipDto> > registeredSipsLoader)
 {
     using (new TimeMeasurer("GetCachedRegisteredSips from cache."))
     {
         var list = cache.GetOrAdd(RegisteredSipsKey, registeredSipsLoader, DateTimeOffset.UtcNow.AddSeconds(CacheTimeCachedRegisteredSips));
         return(list);
     }
 }
Exemplo n.º 15
0
		public Product checkCache(string productId)
		{
			Func<Product> loadedProduct = () => LoadProduct(productId);

			Product cachedResult = cache.GetOrAdd(productId, loadedProduct, DateTimeOffset.UtcNow.AddMinutes(15));

			return cachedResult;
		}
Exemplo n.º 16
0
        public async Task <Summary> GetSummaryAsync(int stationId)
        {
            var result = await _cache.GetOrAdd($"summary-{stationId}",
                                               () => GenerateSummary(stationId),
                                               TimeSpan.FromMinutes(10));

            return(result);
        }
Exemplo n.º 17
0
        public DbTimeEntity Get()
        {
            Func <DbTimeEntity> actionThatWeWantToCache = () => dbContext.GeDbTime();

            var cachedDatabaseTime = cache.GetOrAdd(cacheKey, actionThatWeWantToCache);

            return(cachedDatabaseTime);
        }
 public FroniusClearCommandHandler(
     ILogger logger,
     IAppCache cache)
 {
     _logger = logger;
     _cache  = cache;
     _cache.GetOrAdd(SolarPowerCache.CacheKey, () => new ConcurrentDictionary <long, string>());
 }
Exemplo n.º 19
0
        public JsonResult Cache()
        {
            var list = _cache.GetOrAdd("BroadcastMessage", () => new List <BroadcastMessage>());

            list.Add(new BroadcastMessage {
                Message = "hello"
            });
            return(Json(list, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 20
0
        public byte[] GetArbitraryBytes(FileSize bytes)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }

            return(cache.GetOrAdd(bytes.ToString(), () => Enumerable.Range(0, (int)bytes).Select(i => (byte)(i % 251 + 1)).ToArray()));
        }
Exemplo n.º 21
0
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory, DateTimeOffset expires, ExpirationMode mode)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            switch (mode)
            {
            case ExpirationMode.LazyExpiration:
                return(cache.GetOrAdd(key, addItemFactory, new MemoryCacheEntryOptions {
                    AbsoluteExpiration = expires
                }));

            default:
                return(cache.GetOrAdd(key, addItemFactory, new LazyCacheEntryOptions().SetAbsoluteExpiration(expires, mode)));
            }
        }
Exemplo n.º 22
0
        public IActionResult GetTicket(string ticketId)
        {
            Func <TicketViewModel> ticketGetter = () => _manager.GetTicket(ticketId);

            var cacheExpiry = new TimeSpan(0, 0, 1);

            TicketViewModel ticketVMCached = _cache.GetOrAdd(
                "TicketsController.GetTicket." + ticketId,
                ticketGetter,
                cacheExpiry);

            if (ticketVMCached == null)
            {
                return(NotFound($"Ticket with id '{ticketId}' could not be found."));
            }

            return(Ok(ticketVMCached));
        }
Exemplo n.º 23
0
        public async Task <CodecInformation> GetCodecInformationBySipAddress(string sipAddress)
        {
            var ci = await _cache.GetOrAdd(
                CacheKeys.CodecInformation(sipAddress),
                () => _ccmRepository.GetCodecInformation(sipAddress),
                DateTime.Now.AddSeconds(_reloadIntervalInSeconds));

            return(ci);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Add item to cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="addItemFactory"></param>
        /// <returns></returns>
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            return(cache.GetOrAdd(key, addItemFactory, cache.DefaultCachePolicy.BuildOptions()));
        }
Exemplo n.º 25
0
        public void CanCreateCache()
        {
            IKernel   kernel = new StandardKernel(new LazyCacheModule());
            IAppCache cache  = kernel.Get <IAppCache>();

            var cached = cache.GetOrAdd("some-key", () => new object());

            Assert.NotNull(cached);
        }
Exemplo n.º 26
0
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory,
                                     MemoryCacheEntryOptions policy)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            return(cache.GetOrAdd(key, _ => addItemFactory(), policy));
        }
Exemplo n.º 27
0
        public Dictionary <(string, string), Event> GetEvents(DateTime date)
        {
            var cacheKey = $"Events-{date:MMdd}";

            return(_cache.GetOrAdd(cacheKey, () =>
            {
                var events = Find(x => x.Date == date).ToList();

                return events.Any() ? events.ToDictionary(x => (x.StockCode, x.EventType), x => x) : null;
            }, _stockMarketStatusRepository.NextClosingDateTime()));
Exemplo n.º 28
0
        public virtual void GetOrAdd_Guid_ReturnsExpectedResult(bool withCacheEntryOptions)
        {
            var cacheEntryKey     = Fixture.Create <string>();
            var expectedResult    = Fixture.Create <Guid>();
            var cacheEntryOptions = Fixture.Create <MemoryCacheEntryOptions>();

            var actualResult = withCacheEntryOptions
                ? CachingService.GetOrAdd(cacheEntryKey, () => expectedResult, cacheEntryOptions)
                : CachingService.GetOrAdd(cacheEntryKey, () => expectedResult);

            Assert.That(actualResult, Is.EqualTo(expectedResult));
        }
Exemplo n.º 29
0
        // GET: Products
        public async Task <IActionResult> Index()
        {
            // define a func to get the products but do not Execute() it
            Func <IEnumerable <Product> > productGetter = () => _context.Product.ToList();

            // get the results from the cache based on a unique key, or
            // execute the func and cache the results
            var productsWithCaching = _cache.GetOrAdd("ProductsController.Get", productGetter);

            return(View(productsWithCaching));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Add item to cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="addItemFactory"></param>
        /// <param name="expires"></param>
        /// <returns></returns>
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory, DateTimeOffset expires)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            return(cache.GetOrAdd(key, addItemFactory, new MemoryCacheEntryOptions {
                AbsoluteExpiration = expires
            }));
        }