public async Task <(bool IsValid, PostcodeLocation PostcodeLocation)> IsPostcodeValid(string postcode)
    {
        var key = CacheKeys.PostcodeKey(postcode);

        if (_cache.TryGetValue(key, out PostcodeLocation postcodeLocation))
        {
            _logger.LogInformation("Cache hit - found postcode {postcode}", postcodeLocation.Postcode);
        }
        else
        {
            var location = await _locationApiClient.GetGeoLocationDataAsync(postcode);

            if (location is not null)
            {
                postcodeLocation = new PostcodeLocation
                {
                    Postcode  = location.Postcode,
                    Latitude  = location.Latitude,
                    Longitude = location.Longitude
                };

                if (_cacheExpiryInSeconds > 0)
                {
                    _cache.Set(key, postcodeLocation, CacheUtilities.DefaultMemoryCacheEntryOptions(
                                   _dateTimeService,
                                   _logger,
                                   _cacheExpiryInSeconds,
                                   _cacheExpiryInSeconds
                                   ));
                }
            }
        }

        return(postcodeLocation != null, postcodeLocation);
    }
예제 #2
0
 protected bool BeginCachedContent(string site, CacheExpires expires, params object[] key)
 {
     this._currentCacheScope = new CacheScopeImpl(this, CacheUtilities.ToIdentifier(site, key), expires);
     if (this._currentCacheScope.Begin())
     {
         return(true);
     }
     this.EndCachedContent();
     return(false);
 }
    public void EvictionLoggingCallback_Ignores_Null_Logger()
    {
        const string         key    = "TEST_KEY";
        const EvictionReason reason = EvictionReason.Removed;
        var value = new { x = "test " };

        Action act = () => CacheUtilities.EvictionLoggingCallback(key, value, reason, null);

        act
        .Should().NotThrow <ArgumentNullException>();
    }
예제 #4
0
        public void KeyMultipleKeysHaveUnitSeperatorDelimitingParts()
        {
            var id2 = CacheUtilities.ToIdentifier("foo", new object[] { "bar", "quux" });

            Assert.That(id2, Is.EqualTo("foobar\u001fquux"));

            using (new CurrentCultureScope(""))
            {
                var id3 = CacheUtilities.ToIdentifier("foo", new object[] { 45.2, null, this });
                Assert.That(id3, Is.EqualTo("foo45.2\u001f\u001fSpark.Tests.Caching.CacheUtilitiesTester"));
            }
        }
    public void Basic_DefaultMemoryCacheEntryOptions_Returns_Expected_Value2()
    {
        const int absoluteExpirationInSeconds = 90;

        var options = CacheUtilities.DefaultMemoryCacheEntryOptions(
            absoluteExpirationInSeconds);

        options.Should().NotBeNull();

        options.PostEvictionCallbacks.Count.Should().Be(0);
        options.AbsoluteExpirationRelativeToNow
        .Should()
        .NotBeNull();
    }
예제 #6
0
        public PageSiteNodeModel GetPageSiteNodeModelByKey(Guid id)
        {
            if (id == Guid.Empty)
            {
                return(null);
            }
            // Construct the cache key
            string cacheKey = CacheUtilities.BuildCacheKey(NavigationSubControl.cacheKey, id.ToString());
            var    model    = (PageSiteNodeModel)CacheUtilities.CacheManagerGlobal[cacheKey];

            if (model == null)
            {
                lock (this.nodeDataLock)
                {
                    model = (PageSiteNodeModel)CacheUtilities.CacheManagerGlobal[cacheKey];
                    if (model == null)
                    {
                        // Get the page node
                        PageManager manager = PageManager.GetManager();
                        var         node    = manager.GetPageNode(id);

                        // Get the models from the node fields
                        var relatedPage = this.GetRelatedPageModel(node, "RelatedPage");

                        var relatedImage = this.GetRelatedImageModel(node, "RelatedImage");

                        string additionalInfo = node.GetValue <Lstring>("AdditionalInfo");

                        // Build the Model
                        model = new PageSiteNodeModel(relatedPage, relatedImage,
                                                      additionalInfo);

                        // Add the model in the cache
                        CacheUtilities.CacheManagerGlobal.Add(
                            cacheKey,
                            model,
                            CacheItemPriority.Normal,
                            null,
                            // Add cache dependency for automatic invalidation
                            new DataItemCacheDependency(typeof(PageNode), id),
                            // Configure sliding time
                            new SlidingTime(TimeSpan.FromMinutes(20)));
                    }
                }
            }

            return(model);
        }
    public void DefaultMemoryCacheEntryOptions_Returns_Expected_Value()
    {
        var dateTimeService = Substitute.For <IDateTimeService>();
        var logger          = Substitute.For <ILogger <object> >();

        var options = CacheUtilities.DefaultMemoryCacheEntryOptions(
            dateTimeService,
            logger);

        options.Should().NotBeNull();

        options.PostEvictionCallbacks.Count.Should().Be(1);
        options.AbsoluteExpiration
        .Should()
        .Be(new DateTimeOffset(dateTimeService.Now.AddSeconds(CacheUtilities.DefaultCacheExpiryInSeconds)));
    }
    public void Basic_DefaultMemoryCacheEntryOptions_Returns_Expected_Value()
    {
        const int absoluteExpirationInSeconds = 90;
        var       logger = Substitute.For <ILogger <object> >();

        var options = CacheUtilities.DefaultMemoryCacheEntryOptions(
            absoluteExpirationInSeconds,
            logger);

        options.Should().NotBeNull();

        options.PostEvictionCallbacks.Count.Should().Be(1);
        options.AbsoluteExpirationRelativeToNow
        .Should()
        .NotBeNull();
    }
예제 #9
0
        public void KeyConcatinationShouldSimplyStringConcatWithZeroOrOneParts()
        {
            var id0 = CacheUtilities.ToIdentifier("foo", new object[] { });

            Assert.That(id0, Is.EqualTo("foo"));

            var id1a = CacheUtilities.ToIdentifier("foo", new object[] { "bar" });

            Assert.That(id1a, Is.EqualTo("foobar"));

            using (new CurrentCultureScope(""))
            {
                var id1b = CacheUtilities.ToIdentifier("foo", new object[] { 45.2 });
                Assert.That(id1b, Is.EqualTo("foo45.2"));
            }
        }
        private static DataBundle GetDataBundle(string compressedSequencePath, string cachePrefix)
        {
            Console.Write("- loading global cache and reference sequence... ");
            var sequence = new CompressedSequence();

            var bundle = new DataBundle
            {
                Sequence       = sequence,
                SequenceReader = new CompressedSequenceReader(FileUtilities.GetReadStream(compressedSequencePath), sequence),
                Cache          = CacheUtilities.LoadCache(cachePrefix)
            };

            Console.WriteLine("finished.");

            return(bundle.Cache == null ? null : bundle);
        }
    public void EvictionLoggingCallback_Calls_Logger()
    {
        const string         key    = "TEST_KEY";
        const EvictionReason reason = EvictionReason.Removed;
        var value  = new { x = "test " };
        var logger = Substitute.For <ILogger <object> >();

        CacheUtilities.EvictionLoggingCallback(key, value, reason, logger);

        logger.ReceivedCalls()
        .Select(call => call.GetArguments())
        .Should()
        .Contain(args => args[0] is LogLevel && (LogLevel)args[0] == LogLevel.Information);

        logger.ReceivedCalls()
        .Select(call => call.GetArguments())
        .Should()
        .Contain(args => args[2] != null && args[2].ToString() == $"Entry {key} was evicted from the cache. Reason: {reason}.");
    }
예제 #12
0
        private static DataBundle GetDataBundle(string compressedSequencePath, string cachePrefix)
        {
            Console.Write("- loading global cache and reference sequence... ");
            var sequence = new CompressedSequence();

            var bundle = new DataBundle
            {
                Sequence       = sequence,
                SequenceReader = new CompressedSequenceReader(FileUtilities.GetReadStream(compressedSequencePath), sequence),
                Cache          = CacheUtilities.LoadCache(cachePrefix),
                SiftReader     = CacheUtilities.GetPredictionReader(CacheConstants.SiftPath(cachePrefix)),
                PolyPhenReader = CacheUtilities.GetPredictionReader(CacheConstants.PolyPhenPath(cachePrefix))
            };

            bundle.TranscriptForest = CacheUtilities.GetIntervalForest(bundle.Cache.Transcripts, bundle.Sequence.Renamer.NumRefSeqs);

            Console.WriteLine("finished.");

            return(bundle.Cache == null ? null : bundle);
        }
        public ConferenceModel GetConferenceModelById(Guid id, string provider)
        {
            if (id == Guid.Empty)
            {
                return(null);
            }
            // Construct the cache key
            string cacheKey = CacheUtilities.BuildCacheKey(ConferenceSubControl.cacheKey, id.ToString());
            var    model    = (ConferenceModel)CacheUtilities.CacheManagerGlobal[cacheKey];

            if (model == null)
            {
                lock (this.nodeDataLock)
                {
                    model = (ConferenceModel)CacheUtilities.CacheManagerGlobal[cacheKey];
                    if (model == null)
                    {
                        // Get the conference item
                        DynamicModuleManager manager = DynamicModuleManager.GetManager(provider);
                        Type latestHotTopicsType     = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Conferences.Conference");

                        DynamicContent conference = manager.GetDataItem(latestHotTopicsType, id);
                        // Build the Model
                        model = this.PopulateModel(conference);

                        // Add the model in the cache
                        CacheUtilities.CacheManagerGlobal.Add(
                            cacheKey,
                            model,
                            CacheItemPriority.Normal,
                            null,
                            // Add cache dependency for automatic invalidation
                            new DataItemCacheDependency(typeof(DynamicContent), id),
                            // Configure sliding time
                            new SlidingTime(TimeSpan.FromMinutes(20)));
                    }
                }
            }

            return(model);
        }
예제 #14
0
        private DataBundle GetDataBundle(string genomeAssembly, TranscriptDataSource ds)
        {
            var compressedSequencePath = GetCompressedSequencePath(_referenceDir, genomeAssembly);
            var cachePrefix            = GetCachePrefix(_cacheRoot, genomeAssembly, ds, _newVepVersion);

            var sequence = new CompressedSequence();

            var bundle = new DataBundle
            {
                Sequence       = sequence,
                SequenceReader = new CompressedSequenceReader(FileUtilities.GetReadStream(compressedSequencePath), sequence),
                Cache          = CacheUtilities.LoadCache(cachePrefix),
                SiftReader     = CacheUtilities.GetPredictionReader(CacheConstants.SiftPath(cachePrefix)),
                PolyPhenReader = CacheUtilities.GetPredictionReader(CacheConstants.PolyPhenPath(cachePrefix))
            };

            if (bundle.Cache == null)
            {
                return(null);
            }

            bundle.TranscriptForest = CacheUtilities.GetIntervalForest(bundle.Cache.Transcripts, bundle.Sequence.Renamer.NumRefSeqs);
            return(bundle);
        }