Example #1
0
        // This method will return the date and time from the cache if the stored data is still valid,
        // else it will be regenerated and then returned.
        public DateTime GetCachedDateTime(string service = "CacheService")
        {
            if (service == "CacheService")
            {
                // CacheService has a very simple API.
                return(_cacheService.Get(CacheKey, () => _clock.UtcNow));
            }
            else // Using CacheManager.
            {
                // The first parameter should be a unique identifier for your cache entry.
                return(_cacheManager.Get(CacheKey, ctx =>
                {
                    // Not that here we use two kinds of cache entry invalidation but normally you use only one.

                    // We are "monitoring" the expiration of the cache entry using the Clock service,
                    // which will invalidate the cache entry when a given amount of time has passed.
                    // Use this if the cache entry should be periodically invalidated.
                    ctx.Monitor(_clock.When(TimeSpan.FromSeconds(90)));

                    // One of ISignal's method is "When", just like with IClock. This will trigger the invalidation
                    // of this cache entry when the "Trigger" method is called with the same parameter.
                    // Use this if you want to invalidate the cache entry explicitly.
                    ctx.Monitor(_signals.When(InvalidateDateTimeCacheSignal));

                    return _clock.UtcNow;
                }));
            }
        }
Example #2
0
        private ContentTypeRecord AcquireContentTypeRecord(string contentType)
        {
            var contentTypeId = _cacheManager.Get(contentType + "_Record", ctx => {
                ctx.Monitor(_signals.When(contentType + "_Record"));

                var contentTypeRecord = _contentTypeRepository.Get(x => x.Name == contentType);

                if (contentTypeRecord == null)
                {
                    //TEMP: this is not safe... ContentItem types could be created concurrently?
                    contentTypeRecord = new ContentTypeRecord {
                        Name = contentType
                    };
                    _contentTypeRepository.Create(contentTypeRecord);
                }

                return(contentTypeRecord.Id);
            });

            // There is a case when a content type record is created locally but the transaction is actually
            // cancelled. In this case we are caching an Id which is none existent, or might represent another
            // content type. Thus we need to ensure that the cache is valid, or invalidate it and retrieve it
            // another time.

            var result = _contentTypeRepository.Get(contentTypeId);

            if (result != null && result.Name.Equals(contentType, StringComparison.OrdinalIgnoreCase))
            {
                return(result);
            }

            // invalidate the cache entry and load it again
            _signals.Trigger(contentType + "_Record");
            return(AcquireContentTypeRecord(contentType));
        }
        public string GetThumbnail(string url, int width, int height)
        {
            if (url.IndexOf(_publicPath, StringComparison.InvariantCultureIgnoreCase) == -1)
            {
                return(url);
            }

            string relativePath      = url.Substring(url.IndexOf(_publicPath, StringComparison.InvariantCultureIgnoreCase) + _publicPath.Length);
            string mediaPath         = Fix(Path.GetDirectoryName(relativePath));
            string name              = Path.GetFileName(relativePath);
            string fileHash          = CreateMd5Hash(string.Concat(mediaPath, name, width, height));
            string fileExtension     = Path.GetExtension(name);
            string thumbnailFileName = fileHash + fileExtension;

            return(_cacheManager.Get(
                       "Contrib.Thumbnails." + fileHash,
                       ctx =>
            {
                ctx.Monitor(_signals.When("Contrib.Thumbnails." + fileHash + ".Changed"));
                WorkContext workContext = _wca.GetContext();
                if (_mediaService.GetMediaFiles(ThumbnailsCacheMediaPath).Any(i => i.Name == thumbnailFileName))
                {
                    return _mediaService.GetPublicUrl(Combine(ThumbnailsCacheMediaPath, thumbnailFileName));
                }
                UrlHelper urlHelper = new UrlHelper(new RequestContext(workContext.HttpContext, new RouteData()));
                return urlHelper.Action("Create", "Thumbnails", new
                {
                    area = "Contrib.Thumbnails",
                    mediaPath = mediaPath,
                    name = name,
                    width = width,
                    height = height
                });
            }));
        }
Example #4
0
 public override Zone GetById(int id)
 {
     return(cacheManager.Get("Zones_GetById_" + id, ctx =>
     {
         ctx.Monitor(signals.When("Zones_Changed"));
         return base.GetById(id);
     }));
 }
Example #5
0
 public SEOSettingsPart GetSettings()
 {
     return(_cacheManager.Get("SslSettings",
                              ctx => {
         ctx.Monitor(_signals.When(SEOSettingsPart.CacheKey));
         return _workContextAccessor.GetContext().CurrentSite.As <SEOSettingsPart>();
     }));
 }
Example #6
0
 public Domain.MessageTemplate GetTemplate(string name)
 {
     return(cacheManager.Get("GetTemplate_ByName_" + name, ctx =>
     {
         ctx.Monitor(signals.When("Templates_Changed"));
         return Repository.Table.FirstOrDefault(x => x.Name == name);
     }));
 }
 protected virtual IDictionary <string, string> LoadCulture(string cultureCode)
 {
     return(cacheManager.Get("LocalizableString_" + cultureCode, ctx =>
     {
         ctx.Monitor(signals.When("LocalizableString_Changed"));
         return LoadTranslationsForCulture(cultureCode);
     }));
 }
 public ThemeSettingsViewModel GetSettings()
 {
     return(_cacheManager.Get("KrakeAdminSettingsCache", true, context => {
         context.Monitor(_signals.When("KrakeAdminSettingsChanged"));
         var settings = GetSettingsRecord();
         return settings.ToThemeSettingsViewModel();
     }));
 }
 public IEnumerable <ThemePickerSettingsRecord> Get()
 {
     return(_cacheManager.Get("Vandelay.ThemePicker.Settings",
                              ctx => {
         ctx.Monitor(_signals.When("Vandelay.ThemePicker.SettingsChanged"));
         return _repository.Table.ToList();
     }));
 }
        public IEnumerable <string> ListCultures()
        {
            return(_cacheManager.Get("Cultures", context => {
                context.Monitor(_signals.When("culturesChanged"));

                return _cultureRepository.Table.Select(o => o.Culture).ToList();
            }));
        }
Example #11
0
 public Task <SiteSettingsRecord> Get()
 {
     return(_cacheManager.Get("SiteSettings", ctx =>
     {
         ctx.Monitor(_signals.When("SiteSettings.Change"));
         var repository = _repository.Value;
         return repository.Table.SingleAsync();
     }));
 }
        public MemcachedClient GetClient()
        {
            // caches the ignored urls to prevent a query to the settings
            var servers = _cacheManager.Get("MemcachedSettingsPart.Servers",
                                            context => {
                context.Monitor(_signals.When(MemcachedSettingsPart.CacheKey));

                var part = _service.Value.GetSiteSettings().As <MemcachedSettingsPart>();

                // initializes the client to notify it has to be constructed again
                lock (_synLock) {
                    if (_client != null)
                    {
                        _client.Dispose();
                    }
                    _client = null;
                }

                return(part.Servers);
            }
                                            );

            if (_client == null && !String.IsNullOrEmpty(servers))
            {
                var configuration = new MemcachedClientConfiguration();
                using (var urlReader = new StringReader(servers)) {
                    string server;
                    // ignore empty lines and comments (#)
                    while (null != (server = urlReader.ReadLine()))
                    {
                        if (String.IsNullOrWhiteSpace(server) || server.Trim().StartsWith("#"))
                        {
                            continue;
                        }

                        var values = server.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        int port   = 11211;

                        if (values.Length == 2)
                        {
                            Int32.TryParse(values[1], out port);
                        }

                        if (values.Length > 0)
                        {
                            configuration.AddServer(values[0], port);
                        }
                    }

                    lock (_synLock) {
                        _client = new MemcachedClient(configuration);
                    }
                }
            }

            return(_client);
        }
 private T GetFromCache <T>(string cacheKey, Func <T> method)
 {
     return(_cacheManager.Get(cacheKey, true, ctx => {
         // invalidation signal
         ctx.Monitor(_signals.When(Constants.CacheEvictSignal));
         // cache
         return method();
     }));
 }
 public string GetCurrentThemeName()
 {
     return(_cacheManager.Get("CurrentThemeName", ctx =>
     {
         ctx.Monitor(_signals.When(CurrentThemeSignal));
         //return _BoyingServices.WorkContext.CurrentSite.As<ThemeSiteSettingsPart>().CurrentThemeName;
         return "TheThemeMachine";
     }));
 }
Example #15
0
        public override IList <MetaTag> GetRecords()
        {
            return(cacheManager.Get("MetaTags_GetMetaTags", ctx =>
            {
                ctx.Monitor(signals.When("MetaTags_Changed"));

                return base.GetRecords();
            }));
        }
Example #16
0
        public IEnumerable <string> SiteCultureNames()
        {
            return(_cacheManager.Get("ListCultures", ctx =>
            {
                ctx.Monitor(_signals.When("culturesChanged"));

                return _lazyCultureManager.Value.ListCultures();
            }));
        }
Example #17
0
        public IEnumerable <ElementDescriptor> DescribeElements(DescribeElementsContext context)
        {
            var contentType = context.Content != null ? context.Content.ContentItem.ContentType : default(string);
            var cacheKey    = String.Format("LayoutElementTypes-{0}-{1}", contentType ?? "AnyType", context.CacheVaryParam);

            return(_cacheManager.Get(cacheKey, acquireContext => {
                var harvesterContext = new HarvestElementsContext {
                    Content = context.Content
                };
                var query =
                    from harvester in _elementHarvesters.Value
                    from elementDescriptor in harvester.HarvestElements(harvesterContext)
                    orderby elementDescriptor.DisplayText.Text
                    select elementDescriptor;

                acquireContext.Monitor(_signals.When(Signals.ElementDescriptors));
                return query.ToArray();
            }));
        }
Example #18
0
 public IEnumerable <CacheRouteConfig> GetRouteConfigs()
 {
     return(_cacheManager.Get(RouteConfigsCacheKey,
                              ctx => {
         ctx.Monitor(_signals.When(RouteConfigsCacheKey));
         return _repository.Fetch(c => true).Select(c => new CacheRouteConfig {
             RouteKey = c.RouteKey, Duration = c.Duration, GraceTime = c.GraceTime
         }).ToReadOnlyCollection();
     }));
 }
Example #19
0
 private CheckoutPolicySettingsPart GetSettings()
 {
     return(_cacheManager.Get(CheckoutPolicySettingsPart.CacheKey,
                              ctx => {
         ctx.Monitor(_signals.When(CheckoutPolicySettingsPart.CacheKey));
         var settingsPart = _workContextAccessor.GetContext()
                            .CurrentSite.As <CheckoutPolicySettingsPart>();
         return settingsPart;
     }));
 }
Example #20
0
        public IContent GetCachedSetting(string settingName)
        {
            var advancedSettings = _cacheManager.Get(SettingsCacheKey(settingName), true, context => {
                context.Monitor(_signals.When(SettingsCacheKey(settingName)));
                var settings = _contentManager.Query <AdvancedSettingsPart, AdvancedSettingsPartRecord>().Where(x => x.Name.Equals(settingName, StringComparison.InvariantCultureIgnoreCase)).Slice(0, 1).SingleOrDefault();
                return(settings?.ContentItem);
            });

            return(advancedSettings);
        }
Example #21
0
 public BraintreeSettings GetSettings()
 {
     return(_cacheManager.Get(BraintreeSiteSettingsPart.CacheKey,
                              ctx => {
         ctx.Monitor(_signals.When(BraintreeSiteSettingsPart.CacheKey));
         var settingsPart = _orchardServices.WorkContext
                            .CurrentSite.As <BraintreeSiteSettingsPart>();
         return new BraintreeSettings(settingsPart);
     }));
 }
Example #22
0
 public IEnumerable <RouteConfiguration> GetRouteConfigurations()
 {
     return(_cacheManager.Get("GetRouteConfigurations",
                              ctx => {
         ctx.Monitor(_signals.When("GetRouteConfigurations"));
         return _repository.Fetch(c => true).Select(c => new RouteConfiguration {
             RouteKey = c.RouteKey, Duration = c.Duration
         }).ToReadOnlyCollection();
     }));
 }
        public IEnumerable <Status> FetchTweetsForPart(TwitterPart part)
        {
            var cacheKey = CacheKeyPrefix + part.Id;

            return(_cacheManager.Get(cacheKey, ctx => {
                ctx.Monitor(_signals.When(WellKnownSignals.TwitterPartChanged));
                ctx.Monitor(_clock.When(TimeSpan.FromMinutes(part.CacheMinutes)));
                return FetchTweets(part).ToList();
            }));
        }
        public IList <CultureEntry> ListCultures()
        {
            return(_cacheManager.Get("ListCulturesWithId", true, context => {
                context.Monitor(_signals.When("culturesChanged"));

                return _cultureRecord.Table
                .Select(x => new CultureEntry {
                    Id = x.Id, Culture = x.Culture
                }).ToList();
            }));
        }
Example #25
0
        public IQueryable <CreativeSize> GetCreativeSizes()
        {
            var retVal = _cacheManager.Get(GetType(), context =>
            {
                context.Monitor(_clock.When(TimeSpan.FromMinutes(10))); // cache for 10 mins
                context.Monitor(_signals.When(UpdateSignal));           // wait for update signal
                return(_creativeSizeRepositoryAsync.Queryable().Where(x => x.IsActive == true).ToList());
            });

            return(retVal.ToAsyncEnumerable());
        }
        //GET /sitemap.xml
        public ActionResult Index()
        {
            var doc = _cacheManager.Get <string, XDocument>("sitemap.xml", ctx => {
                ctx.Monitor(_clock.When(TimeSpan.FromHours(1.0)));
                ctx.Monitor(_signals.When("Digic.Sitemap.XmlRefresh"));

                return(_sitemapService.GetSitemap());
            });

            return(new XmlResult(doc));
        }
Example #27
0
        private List <OrchardAuthenticationClientData> GetClientData()
        {
            return(_cacheManager.Get(Constants.CacheKey.ProviderCacheKey, context => {
                _signals.When(Constants.CacheKey.ProviderCacheKey);

                return _openAuthAuthenticationClients
                .Select(client => _orchardOpenAuthClientProvider.GetClientData(client.ProviderName))
                .Where(x => x != null)
                .ToList();
            }));
        }
        public virtual IEnumerable <Permission> GetPermissionsForRole(int roleId)
        {
            return(cacheManager.Get("Roles_GetPermissionsForRole_" + roleId, ctx =>
            {
                ctx.Monitor(signals.When("Roles_Changed"));

                var permissionIds = rolePermissionRepository.Table.Where(x => x.RoleId == roleId).Select(x => x.PermissionId).ToList();

                if (permissionIds.Count == 0)
                {
                    return Enumerable.Empty <Permission>();
                }

                var predicate = PredicateBuilder.False <Permission>();

                predicate = permissionIds.Aggregate(predicate, (current, seed) => current.Or(x => x.Id == seed));

                return permissionRepository.Table.AsExpandable().Where(predicate).ToList();
            }));
        }
 private CultureDictionary LoadCulture(string culture)
 {
     return(_cacheManager.Get(culture, ctx =>
     {
         ctx.Monitor(_signals.When("culturesChanged"));
         return new CultureDictionary
         {
             CultureName = culture,
             Translations = LoadTranslationsForCulture(culture, ctx)
         };
     }));
 }
 public GoogleCheckoutSettingsPart GetSettings()
 {
     return(_cacheManager.Get(
                "GoogleCheckoutSettings",
                ctx => {
         ctx.Monitor(_signals.When("GoogleCheckout.Changed"));
         var workContext = _wca.GetContext();
         return (GoogleCheckoutSettingsPart)workContext
         .CurrentSite
         .ContentItem
         .Get(typeof(GoogleCheckoutSettingsPart));
     }));
 }