Exemplo n.º 1
0
    public bool RecycleBinSmells()
    {
        IAppPolicyCache cache    = _cache.RuntimeCache;
        var             cacheKey = CacheKeys.MediaRecycleBinCacheKey;

        // always cache either true or false
        return(cache.GetCacheItem(cacheKey, () => CountChildren(RecycleBinId) > 0));
    }
Exemplo n.º 2
0
 private IReadOnlyDictionary <string, string> GetIconDictionary() => _cache.GetCacheItem(
     $"{typeof(IconService).FullName}.{nameof(GetIconDictionary)}",
     () => GetAllIconsFiles()
     .Select(GetIcon)
     .Where(i => i != null)
     .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
     .ToDictionary(g => g.Key, g => g.First().SvgString, StringComparer.OrdinalIgnoreCase)
     );
Exemplo n.º 3
0
 public List <DtgeManifest> GetAllCachedManifests(bool purgeCache = false)
 {
     if (purgeCache)
     {
         _cache.ClearByKey("skttlDtgeTreeManifests");
     }
     return(_cache.GetCacheItem <List <DtgeManifest> >("skttlDtgeTreeManifests", () => GetAllManifests(), new TimeSpan(1, 0, 0)));
 }
 public List <Schema> GetIcons()
 {
     // GetCacheItem will automatically insert the object
     // into cache if it doesn't exist.
     return(_runtimeCache.GetCacheItem(Settings.CacheKey, () =>
     {
         using (var scope = _scopeProvider.CreateScope(autoComplete: true))
         {
             var database = scope.Database;
             var results = scope.Database.Fetch <Schema>("SELECT * FROM U8SK_ContentNodeIcons");
             scope.Complete();
             return results;
         }
     }));
 }
Exemplo n.º 5
0
    // gets this macro content from the cache
    // ensuring that it is appropriate to use the cache
    private MacroContent?GetMacroContentFromCache(MacroModel model)
    {
        if (!_umbracoContextAccessor.TryGetUmbracoContext(out IUmbracoContext? umbracoContext))
        {
            return(null);
        }

        // only if cache is enabled
        if (umbracoContext.InPreviewMode || model.CacheDuration <= 0)
        {
            return(null);
        }

        IAppPolicyCache cache        = _appCaches.RuntimeCache;
        MacroContent?   macroContent =
            cache.GetCacheItem <MacroContent>(CacheKeys.MacroContentCacheKey + model.CacheIdentifier);

        if (macroContent == null)
        {
            return(null);
        }

        _logger.LogDebug("Macro content loaded from cache '{MacroCacheId}'", model.CacheIdentifier);

        // ensure that the source has not changed
        // note: does not handle dependencies, and never has
        FileInfo?macroSource = GetMacroFile(model);  // null if macro is not file-based

        if (macroSource != null)
        {
            if (macroSource.Exists == false)
            {
                _logger.LogDebug("Macro source does not exist anymore, ignore cache.");
                return(null);
            }

            if (macroContent.Date < macroSource.LastWriteTime)
            {
                _logger.LogDebug("Macro source has changed, ignore cache.");
                return(null);
            }
        }

        return(macroContent);
    }
Exemplo n.º 6
0
    /// <summary>
    ///     Calculate start nodes, combining groups' and user's, and excluding what's in the bin
    /// </summary>
    public static int[]? CalculateContentStartNodeIds(this IUser user, IEntityService entityService, AppCaches appCaches)
    {
        var             cacheKey     = CacheKeys.UserAllContentStartNodesPrefix + user.Id;
        IAppPolicyCache runtimeCache = appCaches.IsolatedCaches.GetOrCreate <IUser>();
        var             result       = runtimeCache.GetCacheItem(
            cacheKey,
            () =>
        {
            // This returns a nullable array even though we're checking if items have value and there cannot be null
            // We use Cast<int> to recast into non-nullable array
            var gsn = user.Groups.Where(x => x.StartContentId is not null).Select(x => x.StartContentId).Distinct()
                      .Cast <int>().ToArray();
            var usn = user.StartContentIds;
            if (usn is not null)
            {
                var vals = CombineStartNodes(UmbracoObjectTypes.Document, gsn, usn, entityService);
                return(vals);
            }

            return(null);
        },
Exemplo n.º 7
0
        /// <summary>
        ///  Get the GUIDs for all items in a folder
        /// </summary>
        /// <remarks>
        ///  This is disk intensive, (checking the .config files all the time)
        ///  so we cache it, and if we are using the flat folder stucture, then
        ///  we only do it once, so its quicker.
        /// </remarks>
        private IList <Guid> GetFolderKeys(string folder, bool flat)
        {
            // We only need to load all the keys once per handler (if all items are in a folder that key will be used).
            var folderKey = folder.GetHashCode();

            var cacheKey = $"keycache_{this.Alias}_{folderKey}";

            return(runtimeCache.GetCacheItem(cacheKey, () =>
            {
                var keys = new List <Guid>();
                var files = syncFileService.GetFiles(folder, "*.config");
                foreach (var file in files)
                {
                    var node = XElement.Load(file);
                    var key = node.GetKey();
                    if (!keys.Contains(key))
                    {
                        keys.Add(key);
                    }
                }

                return keys;
            }, null));
        }
Exemplo n.º 8
0
        /// <summary>
        ///  Get the GUIDs for all items in a folder
        /// </summary>
        /// <remarks>
        ///  This is disk intensive, (checking the .config files all the time)
        ///  so we cache it, and if we are using the flat folder stucture, then
        ///  we only do it once, so its quicker.
        /// </remarks>
        private IList <Guid> GetFolderKeys(string folder, bool flat)
        {
            // if it's flat, then we only need to load all the keys once per handler
            var folderKey = flat == true ? 1 : folder.GetHashCode();

            var cacheKey = $"uSyncKeyList_{folderKey}_{this.Alias}";

            return(runtimeCache.GetCacheItem(cacheKey, () =>
            {
                var keys = new List <Guid>();
                var files = syncFileService.GetFiles(folder, "*.config");
                foreach (var file in files)
                {
                    var node = XElement.Load(file);
                    var key = node.GetKey();
                    if (!keys.Contains(key))
                    {
                        keys.Add(key);
                    }
                }

                return keys;
            }, null));
        }
        /// <summary>
        /// This is used to configure the file sources with the main file sources shipped with Umbraco and also including supplemental/plugin based
        /// localization files. The supplemental files will be loaded in and merged in after the primary files.
        /// The supplemental files must be named with the 4 letter culture name with a hyphen such as : en-AU.xml
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="fileSourceFolder"></param>
        /// <param name="supplementFileSources"></param>
        public LocalizedTextServiceFileSources(
            ILogger logger,
            AppCaches appCaches,
            DirectoryInfo fileSourceFolder,
            IEnumerable <LocalizedTextServiceSupplementaryFileSource> supplementFileSources)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (appCaches == null)
            {
                throw new ArgumentNullException("cache");
            }
            if (fileSourceFolder == null)
            {
                throw new ArgumentNullException("fileSourceFolder");
            }

            _logger = logger;
            _cache  = appCaches.RuntimeCache;

            //Create the lazy source for the _xmlSources
            _xmlSources = new Lazy <Dictionary <CultureInfo, Lazy <XDocument> > >(() =>
            {
                var result = new Dictionary <CultureInfo, Lazy <XDocument> >();

                if (_fileSourceFolder == null)
                {
                    return(result);
                }

                foreach (var fileInfo in _fileSourceFolder.GetFiles("*.xml"))
                {
                    var localCopy = fileInfo;
                    var filename  = Path.GetFileNameWithoutExtension(localCopy.FullName).Replace("_", "-");

                    // TODO: Fix this nonsense... would have to wait until v8 to store the language files with their correct
                    // names instead of storing them as 2 letters but actually having a 4 letter culture. So now, we
                    // need to check if the file is 2 letters, then open it to try to find it's 4 letter culture, then use that
                    // if it's successful. We're going to assume (though it seems assuming in the legacy logic is never a great idea)
                    // that any 4 letter file is named with the actual culture that it is!
                    CultureInfo culture = null;
                    if (filename.Length == 2)
                    {
                        //we need to open the file to see if we can read it's 'real' culture, we'll use XmlReader since we don't
                        //want to load in the entire doc into mem just to read a single value
                        using (var fs = fileInfo.OpenRead())
                            using (var reader = XmlReader.Create(fs))
                            {
                                if (reader.IsStartElement())
                                {
                                    if (reader.Name == "language")
                                    {
                                        if (reader.MoveToAttribute("culture"))
                                        {
                                            var cultureVal = reader.Value;
                                            try
                                            {
                                                culture = CultureInfo.GetCultureInfo(cultureVal);
                                                //add to the tracked dictionary
                                                _twoLetterCultureConverter[filename] = culture;
                                            }
                                            catch (CultureNotFoundException)
                                            {
                                                Current.Logger.Warn <LocalizedTextServiceFileSources>("The culture {CultureValue} found in the file {CultureFile} is not a valid culture", cultureVal, fileInfo.FullName);
                                                //If the culture in the file is invalid, we'll just hope the file name is a valid culture below, otherwise
                                                // an exception will be thrown.
                                            }
                                        }
                                    }
                                }
                            }
                    }
                    if (culture == null)
                    {
                        culture = CultureInfo.GetCultureInfo(filename);
                    }

                    //get the lazy value from cache
                    result[culture] = new Lazy <XDocument>(() => _cache.GetCacheItem <XDocument>(
                                                               string.Format("{0}-{1}", typeof(LocalizedTextServiceFileSources).Name, culture.Name), () =>
                    {
                        XDocument xdoc;

                        //load in primary
                        using (var fs = localCopy.OpenRead())
                        {
                            xdoc = XDocument.Load(fs);
                        }

                        //load in supplementary
                        MergeSupplementaryFiles(culture, xdoc);

                        return(xdoc);
                    }, isSliding: true, timeout: TimeSpan.FromMinutes(10), dependentFiles: new[] { localCopy.FullName }));
                }
                return(result);
            });

            if (fileSourceFolder.Exists == false)
            {
                Current.Logger.Warn <LocalizedTextServiceFileSources>("The folder does not exist: {FileSourceFolder}, therefore no sources will be discovered", fileSourceFolder.FullName);
            }
            else
            {
                _fileSourceFolder      = fileSourceFolder;
                _supplementFileSources = supplementFileSources;
            }
        }
Exemplo n.º 10
0
 public IEnumerable <IPublishedContent> GetCachedResult(string cacheKey, Func <IEnumerable <IPublishedContent> > function)
 {
     return(_runtimeCache.GetCacheItem <IEnumerable <IPublishedContent> >(cacheKey, () => function.Invoke()));
 }
Exemplo n.º 11
0
 public T GetCacheItem <T>(string key, Func <T> getCacheItem)
 {
     return(_cacheEnabled ? _cache.GetCacheItem(key, getCacheItem, TimeSpan.FromSeconds(_cacheDuration)) : getCacheItem.Invoke());
 }
Exemplo n.º 12
0
 private object GetPreValuesCollectionByDataTypeId(int dataTypeId)
 {
     return(_runtimeCache.GetCacheItem(
                string.Concat("Bento.Core.Services.EmbeddedContentService.GetPreValuesCollectionByDataTypeId_", dataTypeId),
                () => _dataTypeService.GetDataType(dataTypeId).Configuration));
 }