예제 #1
0
        public JObject GetTranslationDataForLanguage(string lang = null)
        {
            //read fallback localization json object first
            var fallbackCacheKey = CacheKey.With(GetType(), "FallbackJson");
            var result           = _memoryCache.GetOrCreateExclusive(fallbackCacheKey, cacheEntry =>
            {
                //Add cache  expiration token
                cacheEntry.AddExpirationToken(LocalizationCacheRegion.CreateChangeToken());
                return(InnerGetTranslationData(_options.FallbackLanguage));
            });

            if (lang != null && !lang.EqualsInvariant(_options.FallbackLanguage))
            {
                var cacheKey = CacheKey.With(GetType(), "RequestedLanguageJson", lang);
                result = _memoryCache.GetOrCreateExclusive(cacheKey, cacheEntry =>
                {
                    //Add cache  expiration token
                    cacheEntry.AddExpirationToken(LocalizationCacheRegion.CreateChangeToken());
                    var langJson = InnerGetTranslationData(lang);
                    // Make another instance of fallback language to avoid corruption of it in the memory cache
                    result = (JObject)result.DeepClone();
                    // Need merge default and requested localization json to resulting object
                    result.Merge(langJson, new JsonMergeSettings {
                        MergeArrayHandling = MergeArrayHandling.Merge
                    });
                    return(result);
                });
            }
            return(result);
        }
예제 #2
0
        protected virtual Dictionary <string, Category> PreloadCategories(string catalogId)
        {
            var cacheKey = CacheKey.With(GetType(), "PreloadCategories", catalogId);

            return(_memoryCache.GetOrCreateExclusive(cacheKey, (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                CategoryEntity[] entities;
                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();

                    entities = repository.GetCategoriesByIds(repository.Categories.Select(x => x.Id).ToArray());
                }
                var result = entities.Select(x => x.ToModel(AbstractTypeFactory <Category> .TryCreateInstance())).ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase);

                LoadDependencies(result.Values, result);
                ApplyInheritanceRules(result.Values.OrderBy(x => x.Level));

                // Fill outlines for categories
                _outlineService.FillOutlinesForObjects(result.Values, catalogId);

                var objectsWithSeo = new List <ISeoSupport>(result.Values);
                var outlineItems = result.Values.Where(c => c.Outlines != null).SelectMany(c => c.Outlines.SelectMany(o => o.Items));
                objectsWithSeo.AddRange(outlineItems);
                //TODO: convert to async
                _seoService.LoadSeoForObjectsAsync(objectsWithSeo.ToArray());
                return result;
            }));
        }
예제 #3
0
        public async Task <ActionResult <ContentStatistic> > GetStoreContentStatsAsync(string storeId)
        {
            var contentStorageProvider = _blobContentStorageProviderFactory.CreateProvider("");
            var cacheKey   = CacheKey.With(GetType(), "pagesCount", $"content-{storeId}");
            var pagesCount = _platformMemoryCache.GetOrCreateExclusive(cacheKey, cacheEntry =>
            {
                cacheEntry.AddExpirationToken(ContentCacheRegion.CreateChangeToken($"content-{storeId}"));
                var result = CountContentItemsRecursive(GetContentBasePath("pages", storeId), contentStorageProvider, GetContentBasePath("blogs", storeId));
                return(result);
            });
            var themesTask = contentStorageProvider.SearchAsync(GetContentBasePath("themes", storeId), null);
            var blogsTask  = contentStorageProvider.SearchAsync(GetContentBasePath("blogs", storeId), null);

            await Task.WhenAll(themesTask, blogsTask);

            var themes = themesTask.Result;
            var blogs  = blogsTask.Result;

            var retVal = new ContentStatistic
            {
                ActiveThemeName = "default",
                ThemesCount     = themes.Results.OfType <BlobFolder>().Count(),
                BlogsCount      = blogs.Results.OfType <BlobFolder>().Count(),
                PagesCount      = pagesCount
            };

            return(Ok(retVal));
        }
예제 #4
0
        protected virtual Task <IDictionary <string, Catalog> > PreloadCatalogs()
        {
            var cacheKey = CacheKey.With(GetType(), "AllCatalogs");

            return(_platformMemoryCache.GetOrCreateExclusive(cacheKey, async(cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                CatalogEntity[] entities;
                using (var repository = _repositoryFactory())
                {
                    //Optimize performance and CPU usage
                    repository.DisableChangesTracking();

                    var ids = await repository.Catalogs.Select(x => x.Id).ToArrayAsync();
                    entities = await repository.GetCatalogsByIdsAsync(ids);
                }

                var result = entities.Select(x => x.ToModel(AbstractTypeFactory <Catalog> .TryCreateInstance()))
                             .ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase)
                             .WithDefaultValue(null);

                LoadDependencies(result.Values, result);
                return result;
            }));
        }
예제 #5
0
        public string GetFileVersionHash(string physicalPath)
        {
            if (physicalPath == null)
            {
                throw new ArgumentNullException(nameof(physicalPath));
            }
            string result = null;

            if (File.Exists(physicalPath))
            {
                var cacheKey = CacheKey.With(GetType(), "GetVersion", physicalPath);
                result = _platformMemoryCache.GetOrCreateExclusive(cacheKey, cacheEntry =>
                {
                    cacheEntry.AddExpirationToken(_fileSystemWatcher.CreateFileChangeToken(GetRelativePath(physicalPath)));
                    using (var stream = File.OpenRead(physicalPath))
                    {
                        using (var hashAlgorithm = CryptoConfig.AllowOnlyFipsAlgorithms ? (SHA256) new SHA256CryptoServiceProvider() : new SHA256Managed())
                        {
                            return($"{WebEncoders.Base64UrlEncode(hashAlgorithm.ComputeHash(stream))}");
                        }
                    }
                });
            }
            return(result);
        }
예제 #6
0
        public async Task <ActionResult <ContentStatistic> > GetStoreContentStats(string storeId)
        {
            var contentStorageProvider = _blobContentStorageProviderFactory.CreateProvider("");
            var cacheKey   = CacheKey.With(GetType(), "pagesCount", $"content-{storeId}");
            var pagesCount = _platformMemoryCache.GetOrCreateExclusive(cacheKey, cacheEntry =>
            {
                cacheEntry.AddExpirationToken(ContentCacheRegion.CreateChangeToken($"content-{storeId}"));
                var result = CountContentItemsRecursive(GetContentBasePath("pages", storeId), contentStorageProvider, _blogsFolderName);
                return(result);
            });

            var storeTask  = _storeService.GetByIdAsync(storeId, StoreResponseGroup.DynamicProperties.ToString());
            var themesTask = contentStorageProvider.SearchAsync(GetContentBasePath("themes", storeId), null);
            var blogsTask  = contentStorageProvider.SearchAsync(GetContentBasePath(_blogsFolderName, storeId), null);

            await Task.WhenAll(themesTask, blogsTask, storeTask);

            var store  = storeTask.Result;
            var themes = themesTask.Result;
            var blogs  = blogsTask.Result;

            var retVal = new ContentStatistic
            {
                ActiveThemeName = store.DynamicProperties.FirstOrDefault(x => x.Name == "DefaultThemeName")?.Values?.FirstOrDefault()?.Value.ToString() ?? "default",
                ThemesCount     = themes.Results.OfType <BlobFolder>().Count(),
                BlogsCount      = blogs.Results.OfType <BlobFolder>().Count(),
                PagesCount      = pagesCount
            };

            return(Ok(retVal));
        }
        public virtual IList <PlatformEventInfo> GetAllEvents()
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetAllEvents));

            return(_platformMemoryCache.GetOrCreateExclusive(cacheKey, (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(AllEventsCacheRegion.CreateChangeToken());
                return DiscoverAllDomainEvents();
            }));
        }
예제 #8
0
        private Notification[] GetTransientNotifications()
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetTransientNotifications));

            return(_platformMemoryCache.GetOrCreateExclusive(cacheKey, (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(NotificationTypesCacheRegion.CreateChangeToken());
                return AbstractTypeFactory <Notification> .AllTypeInfos.Select(x =>
                {
                    return AbstractTypeFactory <Notification> .TryCreateInstance(x.Type.Name);
                }).ToArray();
            }));
        }
예제 #9
0
        public DateTimeOffset GetLastModifiedDate(string entityName)
        {
            entityName ??= string.Empty;

            var cacheKey = CacheKey.With(GetType(), nameof(GetLastModifiedDate), entityName);

            return(_memoryCache.GetOrCreateExclusive(cacheKey, options =>
            {
                options.AddExpirationToken(LastChangesCacheRegion.CreateChangeTokenForKey(entityName));

                return DateTimeOffset.UtcNow;
            }));
        }
예제 #10
0
        private Dictionary <string, AuthorizationPolicy> GetDynamicAuthorizationPoliciesFromModulesPermissions()
        {
            var cacheKey = CacheKey.With(GetType(), "GetDynamicAuthorizationPoliciesFromModulesPermissions");
            var result   = _memoryCache.GetOrCreateExclusive(cacheKey, (cacheEntry) =>
            {
                var resultLookup = new Dictionary <string, AuthorizationPolicy>();
                foreach (var permission in _permissionsProvider.GetAllPermissions())
                {
                    resultLookup[permission.Name] = new AuthorizationPolicyBuilder().AddRequirements(new PermissionAuthorizationRequirement {
                        Permission = permission
                    }).Build();
                }
                return(resultLookup);
            });

            return(result);
        }
예제 #11
0
        private Dictionary <string, AuthorizationPolicy> GetDynamicAuthorizationPoliciesFromModulesPermissions()
        {
            var cacheKey = CacheKey.With(GetType(), "GetDynamicAuthorizationPoliciesFromModulesPermissions");
            var result   = _memoryCache.GetOrCreateExclusive(cacheKey, (cacheEntry) =>
            {
                var resultLookup = new Dictionary <string, AuthorizationPolicy>();
                foreach (var permission in _permissionsProvider.GetAllPermissions())
                {
                    resultLookup[permission.Name] = new AuthorizationPolicyBuilder().AddRequirements(new PermissionAuthorizationRequirement(permission.Name))
                                                    //Use the two schema (JwtBearer and ApiKey)  authentication for permission authorization policies.
                                                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme)
                                                    .Build();
                }
                return(resultLookup);
            });

            return(result);
        }
        public Task <PropertyDictionaryItem[]> GetByIdsAsync(string[] ids)
        {
            var cacheKey = CacheKey.With(GetType(), "GetByIdsAsync", string.Join(",", ids));

            return(_platformMemoryCache.GetOrCreateExclusive(cacheKey, async(cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(DictionaryItemsCacheRegion.CreateChangeToken());
                PropertyDictionaryItem[] result;

                using (var repository = _repositoryFactory())
                {
                    //Optimize performance and CPU usage
                    repository.DisableChangesTracking();

                    result = (await repository.GetPropertyDictionaryItemsByIdsAsync(ids))
                             .Select(x => x.ToModel(AbstractTypeFactory <PropertyDictionaryItem> .TryCreateInstance()))
                             .ToArray();
                }
                return result;
            }));
        }
예제 #13
0
        protected virtual IDictionary <string, Property> PreloadAllProperties()
        {
            var cacheKey = CacheKey.With(GetType(), "PreloadAllProperties");

            return(_memoryCache.GetOrCreateExclusive(cacheKey, (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();

                    var propertyIds = repository.Properties.Select(p => p.Id).ToArray();
                    var entities = repository.GetPropertiesByIds(propertyIds);
                    var properties = entities.Select(p => p.ToModel(AbstractTypeFactory <Property> .TryCreateInstance())).ToArray();

                    LoadDependencies(properties);
                    ApplyInheritanceRules(properties);
                    var result = properties.ToDictionary(p => p.Id, StringComparer.OrdinalIgnoreCase);
                    return result;
                }
            }));
        }
 private DateTime GetSampleValueWithCache(IPlatformMemoryCache platformMemoryCache)
 {
     return(platformMemoryCache.GetOrCreateExclusive(CacheKey, x => DateTime.Now));
 }