Пример #1
0
        public void AsyncRetrieveCacheKeyGetsGenerated()
        {
            var    repo      = new TestRepository();
            var    generator = new CacheKeyGenerator();
            string key;

            generator.TryBuildCacheKey(() => repo.RetrievePersonsAsync(), out key);

            Assert.AreEqual("RetrievePersonsAsync", key);
        }
Пример #2
0
        public void RegularRetrieveWithArgumentsGetsGenerated()
        {
            var    repo      = new TestRepository();
            var    generator = new CacheKeyGenerator();
            string key;

            generator.TryBuildCacheKey(() => repo.RetrievePerson(1), out key);

            Assert.AreEqual("RetrievePerson#1", key);
        }
Пример #3
0
        private async Task <Dictionary <string, Order> > PlaceOrderAndTryExecute(Order order)
        {
            string key = CacheKeyGenerator.ToStoreKey(ref order);

            order.DeletionReferenceKey = key;

            await _orderCacheService.Cache(key, order);

            return(await TryExecute(order));
        }
Пример #4
0
 private void RemoveClaimsCache()
 {
     try
     {
         ClaimsCache.Remove(CacheKeyGenerator.GetClaimsKey(Identity));
     }
     catch (Exception ex)
     {
         Logger.Technical.From <AppPrincipalFactory>().Exception(ex).Log();
     }
 }
Пример #5
0
        /// <summary>
        /// Creates a real memory cache.
        /// </summary>
        /// <param name="cachePolicy">When no policy is provided an empty only will be used.</param>
        /// <returns>MemoryCacheService</returns>
        public MemoryCacheService CreateMemoryCacheService(ICachePolicy cachePolicy = null)
        {
            if (cachePolicy == null)
            {
                cachePolicy = new StubCachePolicy();
            }

            var cacheKeyGenerator = new CacheKeyGenerator();

            return(new MemoryCacheService(cachePolicy, cacheKeyGenerator));
        }
Пример #6
0
 // must be refactored => Take this based on a strategy based on the .Net code.
 private List <ClaimDto> GetClaimsFromCache(ClaimsIdentity identity)
 {
     try
     {
         var secureClaims = ClaimsCache.Get <List <ClaimDto> >(CacheKeyGenerator.GetClaimsKey(identity));
         return(secureClaims ?? new List <ClaimDto>());
     }
     catch (Exception)
     {
         return(new List <ClaimDto>());
     }
 }
Пример #7
0
        private void SaveClaimsToCache(IEnumerable <Claim> claims)
        {
            var dto = claims.Select(c => new ClaimDto(c.Type, c.Value)).ToList();

            try
            {
                ClaimsCache.Put(CacheKeyGenerator.GetClaimsKey(Identity), dto);
            }
            catch (Exception ex)
            {
                Logger.Technical.From <AppPrincipalFactory>().Exception(ex).Log();
            }
        }
        public static void UseAwsKeyManagementServiceSerializerWithCache(this IReceiveEndpointConfigurator configurator,
                                                                         string kmsKeyId, IAmazonKeyManagementService amazonKeyManagementService, IDistributedCache distributedCache)
        {
            var amazonKeyManagementServiceWrapper = new AmazonKeyManagementServiceWrapper(amazonKeyManagementService);

            var emptyEncryptionContextBuilder = new EmptyEncryptionContextBuilder();

            var cacheKeyGenerator = new CacheKeyGenerator();

            var cacheValueConverter = new CacheValueConverter();

            configurator.UseAwsKeyManagementServiceSerializerWithCache(amazonKeyManagementServiceWrapper,
                                                                       emptyEncryptionContextBuilder,
                                                                       kmsKeyId, distributedCache, cacheKeyGenerator, cacheValueConverter);
        }
Пример #9
0
        public void ShouldGenerateCacheKeyForKeydId()
        {
            var keyId = Guid.NewGuid().ToString();

            var encryptionContext = new Dictionary <string, string>()
            {
                { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() },
                { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() },
            };

            var sut = new CacheKeyGenerator();
            var key = sut.Generate(new DataKeyIdentifier(keyId, encryptionContext));

            key.ShouldBe(string.Join("", keyId, encryptionContext.Keys.ElementAt(0), encryptionContext.Values.ElementAt(0), encryptionContext.Keys.ElementAt(1), encryptionContext.Values.ElementAt(1)));
        }
Пример #10
0
        public void ShouldGenerateCacheKeyForCiphertextBlob()
        {
            var ciphertextBlob = new byte[] { 1, 2, 3, 4 };

            var encryptionContext = new Dictionary <string, string>()
            {
                { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() },
                { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() },
            };

            var sut = new CacheKeyGenerator();
            var key = sut.Generate(new DecryptIdentifier(ciphertextBlob, encryptionContext));

            key.ShouldBe(string.Join("", Convert.ToBase64String(ciphertextBlob), encryptionContext.Keys.ElementAt(0), encryptionContext.Values.ElementAt(0), encryptionContext.Keys.ElementAt(1), encryptionContext.Values.ElementAt(1)));
        }
Пример #11
0
        public virtual async Task <NavigationNode> GetNavigationAsync(GetNavigationDocumentInput input)
        {
            var project = await _projectRepository.GetAsync(input.ProjectId);

            input.Version = GetProjectVersionPrefixIfExist(project) + input.Version;

            var navigationDocument = await GetDocumentWithDetailsDtoAsync(
                project,
                project.NavigationDocumentName,
                input.LanguageCode,
                input.Version
                );

            if (!DocsJsonSerializerHelper.TryDeserialize <NavigationNode>(navigationDocument.Content,
                                                                          out var navigationNode))
            {
                throw new UserFriendlyException(
                          $"Cannot validate navigation file '{project.NavigationDocumentName}' for the project {project.Name}.");
            }

            var leafs = navigationNode.Items.GetAllNodes(x => x.Items)
                        .Where(x => !x.Path.IsNullOrWhiteSpace())
                        .ToList();

            foreach (var leaf in leafs)
            {
                var cacheKey =
                    CacheKeyGenerator.GenerateDocumentUpdateInfoCacheKey(project, leaf.Path, input.LanguageCode,
                                                                         input.Version);
                var documentUpdateInfo = await DocumentUpdateCache.GetAsync(cacheKey);

                if (documentUpdateInfo != null)
                {
                    leaf.CreationTime              = documentUpdateInfo.CreationTime;
                    leaf.LastUpdatedTime           = documentUpdateInfo.LastUpdatedTime;
                    leaf.LastSignificantUpdateTime = documentUpdateInfo.LastSignificantUpdateTime;
                }
            }

            await NavigationTreePostProcessor.ProcessAsync(
                new NavigationTreePostProcessorContext(
                    navigationDocument,
                    navigationNode
                    )
                );

            return(navigationNode);
        }
Пример #12
0
        public async Task RemoveFromCacheAsync(Guid documentId)
        {
            var document = await _documentRepository.GetAsync(documentId);

            var project = await _projectRepository.GetAsync(document.ProjectId);

            var documentUpdateInfoCacheKey = CacheKeyGenerator.GenerateDocumentUpdateInfoCacheKey(
                project: project,
                documentName: document.Name,
                languageCode: document.LanguageCode,
                version: document.Version
                );

            await _documentUpdateCache.RemoveAsync(documentUpdateInfoCacheKey);

            await _documentRepository.DeleteAsync(document);
        }
Пример #13
0
        protected virtual async Task <DocumentWithDetailsDto> GetDocumentWithDetailsDtoAsync(
            Project project,
            string documentName,
            string languageCode,
            string version)
        {
            version = string.IsNullOrWhiteSpace(version) ? project.LatestVersionBranchName : version;

            if (HostEnvironment.IsDevelopment())
            {
                return(await GetDocumentAsync(documentName, project, languageCode, version));
            }

            var document = await _documentRepository.FindAsync(project.Id, documentName, languageCode, version);

            if (document == null)
            {
                return(await GetDocumentAsync(documentName, project, languageCode, version));
            }

            //Only the latest version (dev) of the document needs to update the cache.
            if (!project.LatestVersionBranchName.IsNullOrWhiteSpace() &&
                document.Version == project.LatestVersionBranchName &&
                document.LastCachedTime + _cacheTimeout < DateTime.Now)
            {
                return(await GetDocumentAsync(documentName, project, languageCode, version, document));
            }

            var cacheKey = CacheKeyGenerator.GenerateDocumentUpdateInfoCacheKey(
                project: project,
                documentName: document.Name,
                languageCode: document.LanguageCode,
                version: document.Version
                );

            await DocumentUpdateCache.SetAsync(cacheKey, new DocumentUpdateInfo
            {
                Name                      = document.Name,
                CreationTime              = document.CreationTime,
                LastUpdatedTime           = document.LastUpdatedTime,
                LastSignificantUpdateTime = document.LastSignificantUpdateTime
            });

            return(CreateDocumentWithDetailsDto(project, document));
        }
Пример #14
0
        public void TestGenerateMethod(string url, string expected)
        {
            var          logger        = new FakeLogger();
            var          extractor     = new DomainNameExtractor(logger);
            var          serializer    = new FakeDomainSerializer();
            var          byConvention  = new ByConvention(logger, serializer);
            var          validator     = new TenantValidator(logger, serializer, byConvention);
            const string defaultTenant = "localhost";


            var locator = new TenantLocator(logger, extractor, byConvention, validator, serializer);
            var uri     = new Uri(url);
            var keyGen  = new CacheKeyGenerator(uri, locator, defaultTenant);

            string result = keyGen.Generate();

            Assert.Equal(expected, result);
        }
Пример #15
0
        public async Task <ListResultDto <VersionInfoDto> > GetVersionsAsync(string shortName)
        {
            var project = await _projectRepository.GetByShortNameAsync(shortName);

            var versions = await _versionCache.GetOrAddAsync(
                CacheKeyGenerator.GenerateProjectVersionsCacheKey(project),
                () => GetVersionsAsync(project),
                () => new DistributedCacheEntryOptions
            {
                //TODO: Configurable?
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12),
                SlidingExpiration = TimeSpan.FromMinutes(60)
            }
                );

            return(new ListResultDto <VersionInfoDto>(
                       ObjectMapper.Map <List <VersionInfo>, List <VersionInfoDto> >(versions)
                       ));
        }
Пример #16
0
        private async Task <Dictionary <string, Order> > Execute(Order order, Order oppositeOrder)
        {
            string orderKey         = CacheKeyGenerator.ToStoreKey(ref order);
            string oppositeOrderKey = CacheKeyGenerator.ToStoreKey(ref oppositeOrder);

            Dictionary <string, Order> ordersInvolved = new Dictionary <string, Order>
            {
                { orderKey, order },
                { oppositeOrderKey, oppositeOrder }
            };

            await _orderCacheService.Decache(ordersInvolved);

            decimal execPrice = GetExecutionPrice(order, oppositeOrder);

            OrderExecutionDueDiligence(execPrice, ordersInvolved);

            return(ordersInvolved);
        }
Пример #17
0
        private async Task <LanguageConfig> GetLanguageListInternalAsync(string shortName, string version)
        {
            var project = await _projectRepository.GetByShortNameAsync(shortName);

            var store = _documentSource.Create(project.DocumentStoreType);

            async Task <LanguageConfig> GetLanguagesAsync()
            {
                return(await store.GetLanguageListAsync(project, version));
            }

            return(await LanguageCache.GetOrAddAsync(
                       CacheKeyGenerator.GenerateProjectLanguageCacheKey(project),
                       GetLanguagesAsync,
                       () => new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24)
            }
                       ));
        }
        public async Task ClearCacheAsync(ClearCacheInput input)
        {
            var project = await _projectRepository.GetAsync(input.ProjectId);

            var languageCacheKey = CacheKeyGenerator.GenerateProjectLanguageCacheKey(project);
            await _languageCache.RemoveAsync(languageCacheKey, true);

            var versionCacheKey = CacheKeyGenerator.GenerateProjectVersionsCacheKey(project);
            await _versionCache.RemoveAsync(versionCacheKey, true);

            var documents = await _documentRepository.GetListByProjectId(project.Id);

            foreach (var document in documents)
            {
                var documentUpdateInfoCacheKey = CacheKeyGenerator.GenerateDocumentUpdateInfoCacheKey(project, document.Name, document.LanguageCode, document.LanguageCode);
                await _documentUpdateCache.RemoveAsync(documentUpdateInfoCacheKey);

                document.LastCachedTime = DateTime.MinValue;
                await _documentRepository.UpdateAsync(document);
            }
        }
Пример #19
0
        private async Task <Dictionary <string, Order> > TryExecute(Order order)
        {
            Dictionary <string, Order> ordersInvolved;
            bool   oppositeSide = !order.BuyOrder;
            string cacheKey     = CacheKeyGenerator.ToLookKey(ref oppositeSide, order.AskPrice, order.Amount);

            Order oppositeOrder = await GetOrderByKey(cacheKey);

            if (oppositeOrder == null)
            {
                return new Dictionary <string, Order>
                       {
                           { order.Id, order }
                       }
            }
            ;

            ordersInvolved = await Execute(order, oppositeOrder);

            return(ordersInvolved);
        }
        public void ShouldGenerateCacheKeyForKeydId()
        {
            var _expectedKeyId            = "keyid";
            var _expectedDictionaryKey1   = "dickey1";
            var _expectedDictionaryValue1 = "valuekey1";
            var _expectedDictionaryKey2   = "dickey2";
            var _expectedDictionaryValue2 = "valuekey2";

            var key = new CacheKeyGenerator().Generate(_expectedKeyId,
                                                       new Dictionary <string, string>()
            {
                { _expectedDictionaryKey1, _expectedDictionaryValue1 },
                { _expectedDictionaryKey2, _expectedDictionaryValue2 }
            }
                                                       );

            key.ShouldBe(string.Join("",
                                     new[]
            {
                _expectedKeyId, _expectedDictionaryKey1, _expectedDictionaryValue1, _expectedDictionaryKey2,
                _expectedDictionaryValue2
            }));
        }
Пример #21
0
        private async Task <DocumentWithDetailsDto> GetDocumentAsync(string documentName, Project project, string languageCode, string version, Document oldDocument = null)
        {
            Logger.LogInformation($"Not found in the cache. Requesting {documentName} from the source...");

            var source         = _documentStoreFactory.Create(project.DocumentStoreType);
            var sourceDocument = await source.GetDocumentAsync(project, documentName, languageCode, version, oldDocument?.LastSignificantUpdateTime);

            await _documentRepository.DeleteAsync(project.Id, sourceDocument.Name, sourceDocument.LanguageCode, sourceDocument.Version);

            await _documentRepository.InsertAsync(sourceDocument, true);

            Logger.LogInformation($"Document retrieved: {documentName}");

            var cacheKey = CacheKeyGenerator.GenerateDocumentUpdateInfoCacheKey(project, sourceDocument.Name, sourceDocument.LanguageCode, sourceDocument.Version);
            await DocumentUpdateCache.SetAsync(cacheKey, new DocumentUpdateInfo
            {
                Name                      = sourceDocument.Name,
                CreationTime              = sourceDocument.CreationTime,
                LastUpdatedTime           = sourceDocument.LastUpdatedTime,
                LastSignificantUpdateTime = sourceDocument.LastSignificantUpdateTime
            });

            return(CreateDocumentWithDetailsDto(project, sourceDocument));
        }
        public void ShouldGenerateCacheKeyForCiphertextBlob()
        {
            var ciphertextBlob = new byte[] { 1, 2, 3, 4 };

            var _expectedDictionaryKey1   = "dickey1";
            var _expectedDictionaryValue1 = "valuekey1";
            var _expectedDictionaryKey2   = "dickey2";
            var _expectedDictionaryValue2 = "valuekey2";

            var key = new CacheKeyGenerator().Generate(ciphertextBlob,
                                                       new Dictionary <string, string>()
            {
                { _expectedDictionaryKey1, _expectedDictionaryValue1 },
                { _expectedDictionaryKey2, _expectedDictionaryValue2 }
            }
                                                       );

            key.ShouldBe(string.Join("",
                                     new[]
            {
                Convert.ToBase64String(ciphertextBlob), _expectedDictionaryKey1, _expectedDictionaryValue1,
                _expectedDictionaryKey2, _expectedDictionaryValue2
            }));
        }
Пример #23
0
 public static int GenerateHash <T>(T obj)
 {
     return(CacheKeyGenerator <T> .HashFunc(obj));
 }
Пример #24
0
        public static void Remove <T>(this ObjectCache cache, string key)
        {
            string cacheKey = CacheKeyGenerator.GenerateCacheKey <T>(key);

            cache.Remove(cacheKey);
        }
Пример #25
0
        public static bool IsSet <T>(this ObjectCache cache, string key)
        {
            string cacheKey = CacheKeyGenerator.GenerateCacheKey <T>(key);

            return(cache.IsSet(cacheKey));
        }
Пример #26
0
 public HaxlCache(CacheKeyGenerator generator)
 {
     _keyGenerator = generator;
     _cache        = new Dictionary <string, BlockedRequest>();
 }
Пример #27
0
 public AbstractCacheExecutor(CachePreference aPreference)
 {
     CacheSpecs = new CacheSpecImpl(aPreference);
     Cache      = Database.Current.Factory.GetCache();
     Generator  = Database.Current.Factory.GetKeyGenerator();
 }