public MemoryFlow(IMemoryCache memoryCache, ILogger <MemoryFlow>?logger = default, IOptions <FlowOptions>?options = default) { _activitySource = ActivitySourceContainer.Instance; Instance = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache)); _logger = logger ?? new NullLogger <MemoryFlow>(); if (options is null) { _logger.LogNoOptionsProvided(nameof(MemoryFlow)); Options = new FlowOptions(); } else { Options = options.Value; } if (Options.DataLoggingLevel is DataLogLevel.Disabled) { _logger = new NullLogger <MemoryFlow>(); } _executor = new Executor(_logger, Options.SuppressCacheExceptions, Options.DataLoggingLevel); _prefix = CacheKeyHelper.GetFullCacheKeyPrefix(Options.CacheKeyPrefix, Options.CacheKeyDelimiter); _logSensitive = Options.DataLoggingLevel is DataLogLevel.Sensitive; }
public void By_Double_ShouldBeCacheKeyString() { const double number = 5.5; var key = _cacheKeyBuilder.By(number).ToString(); key.Should().Be(CacheKeyHelper.Format(number.ToString(CultureInfo.InvariantCulture))); }
public void Execute(RemoveTranslation.Command command) { using (var db = new LanguageEntities()) { var resource = db.LocalizationResources.Include(r => r.Translations).FirstOrDefault(r => r.ResourceKey == command.Key); if (resource == null) { return; } if (!resource.IsModified.HasValue || !resource.IsModified.Value) { throw new InvalidOperationException($"Cannot delete translation for unmodified resource `{command.Key}`"); } var t = resource.Translations.FirstOrDefault(_ => _.Language == command.Language.Name); if (t != null) { db.LocalizationResourceTranslations.Remove(t); db.SaveChanges(); } } ConfigurationContext.Current.CacheManager.Remove(CacheKeyHelper.BuildKey(command.Key)); }
public override void Given() { _logger = Substitute.For <ILogger <HomeController> >(); _homeController = new HomeController(_logger); var httpContext = new ClaimsIdentityBuilder <HomeController>(_homeController) .Add(CustomClaimTypes.UserId, Guid.NewGuid().ToString()) .Build() .HttpContext; HttpContextAccessor.HttpContext.Returns(httpContext); CacheKey = CacheKeyHelper.GetCacheKey(HttpContextAccessor.HttpContext.User.GetUserId(), CacheConstants.UserSessionActivityCacheKey); var routeData = new RouteData(); routeData.Values.Add("controller", "Home"); routeData.Values.Add("action", nameof(HomeController.Index)); var controllerActionDescriptor = new ControllerActionDescriptor { ControllerName = "Home", ActionName = nameof(HomeController.Index) }; var actionContext = new ActionContext(HttpContextAccessor.HttpContext, routeData, controllerActionDescriptor); _actionExecutingContext = new ActionExecutingContext(actionContext, new List <IFilterMetadata>(), new Dictionary <string, object>(), _homeController); }
/// <summary> /// It doesn't cache user profiles /// </summary> /// <param name="uow"></param> /// <param name="userDto"></param> protected void CacheUserDto(IdentityUow uow, UserDto userDto) { if (userDto == null) { return; } uow.Cache.SetCachedItemAsync(CacheKeyHelper.GetCacheKey <UserDto>(userDto.Key), userDto); uow.Cache.SetCachedItemAsync(CacheKeyHelper.GetCacheKey <UserDto>(userDto.Username), userDto); uow.Cache.SetCachedItemAsync(CacheKeyHelper.GetCacheKey <UserDto>(userDto.Email), userDto); uow.Cache.SetCachedItemAsync( CacheKeyHelper.GetCacheKey <UserDto>(userDto.Mobile.LocalNumberWithAreaCode), userDto); uow.Cache.SetCachedItemAsync( CacheKeyHelper.GetCacheKey <UserDto>(userDto.Mobile.LocalNumberWithAreaCodeInDigits), userDto); var userUpdatedEvent = new UserUpdatedEvent { UpdatedUser = userDto }; var userProfile = GetUserProfile(userDto.Key, _userProfileConfig.UserProfileOriginator); if (!string.IsNullOrWhiteSpace(userProfile?.Body)) { var basicMemberInfo = Serializer.Deserialize <BasicMemberInfo>(userProfile.Body); userUpdatedEvent.Roles = basicMemberInfo.Roles; } DispatchEvent(userUpdatedEvent); }
public void Execute(Command command) { if (string.IsNullOrEmpty(command.Key)) { throw new ArgumentNullException(nameof(command.Key)); } using (var db = new LanguageEntities()) { var existingResource = db.LocalizationResources.FirstOrDefault(r => r.ResourceKey == command.Key); if (existingResource == null) { return; } if (existingResource.FromCode) { throw new InvalidOperationException($"Cannot delete resource `{command.Key}` that is synced with code"); } db.LocalizationResources.Remove(existingResource); db.SaveChanges(); } ConfigurationContext.Current.CacheManager.Remove(CacheKeyHelper.BuildKey(command.Key)); }
public string Execute(GetTranslation.Query query) { if (!ConfigurationContext.Current.EnableLocalization()) { return(query.Key); } var key = query.Key; var language = query.Language; var cacheKey = CacheKeyHelper.BuildKey(key); var localizationResource = ConfigurationContext.Current.CacheManager.Get(cacheKey) as LocalizationResource; if (localizationResource != null) { return(GetTranslationFromAvailableList(localizationResource.Translations, language, query.UseFallback)?.Value); } var resource = GetResourceFromDb(key); LocalizationResourceTranslation localization = null; if (resource == null) { resource = LocalizationResource.CreateNonExisting(key); } else { localization = GetTranslationFromAvailableList(resource.Translations, language, query.UseFallback); } ConfigurationContext.Current.CacheManager.Insert(cacheKey, resource); return(localization?.Value); }
public override void Given() { _resultsAndCertificationConfiguration = new ResultsAndCertificationConfiguration { DfeSignInSettings = new DfeSignInSettings { Timeout = 2 } }; _timeoutController = new TimeoutController(_resultsAndCertificationConfiguration, CacheService); var httpContext = new ClaimsIdentityBuilder <TimeoutController>(_timeoutController) .Add(CustomClaimTypes.UserId, Guid.NewGuid().ToString()) .Build() .HttpContext; HttpContextAccessor.HttpContext.Returns(httpContext); CacheKey = CacheKeyHelper.GetCacheKey(HttpContextAccessor.HttpContext.User.GetUserId(), CacheConstants.UserSessionActivityCacheKey); var routeData = new RouteData(); routeData.Values.Add("controller", "Timeout"); routeData.Values.Add("action", nameof(TimeoutController.GetActiveDurationAsync)); var controllerActionDescriptor = new ControllerActionDescriptor { ControllerName = "Timeout", ActionName = nameof(TimeoutController.GetActiveDurationAsync) }; var actionContext = new ActionContext(HttpContextAccessor.HttpContext, routeData, controllerActionDescriptor); _actionExecutingContext = new ActionExecutingContext(actionContext, new List <IFilterMetadata>(), new Dictionary <string, object>(), _timeoutController); }
public UserDto GetUser(Guid userKey, string userProfileOriginator) { UserDto userDto = null; Execute(uow => { var cacheKey = CacheKeyHelper.GetCacheKey <UserDto>(userKey); userDto = uow.Cache.GetCachedItem <UserDto>(cacheKey); if (userDto != null) { userDto.UserProfile = GetUserProfile(uow, userDto.Key, userProfileOriginator); return; } var user = uow.Store.FirstOrDefault <User>(x => x.Key == userKey); if (user == null) { return; } userDto = MappingService.Map <UserDto>(user); userDto.UserProfile = GetUserProfile(uow, userDto.Key, userProfileOriginator); CacheUserDto(uow, userDto); }); return(userDto); }
public void By_String_ShouldBeCacheKeyString() { const string text = "test"; var key = _cacheKeyBuilder.By(text).ToString(); key.Should().Be(CacheKeyHelper.Format(text)); }
public void TestKeyExtract_ExistingKey() { var key = CacheKeyHelper.GenerateKey("MyProject.MyResources", "en", true); var name = CacheKeyHelper.GetContainerName(key); Assert.Equal("MyProject.MyResources", name); }
private string GetTranslation(string key, CultureInfo language) { var cacheKey = CacheKeyHelper.BuildKey(key); var localizationResource = ConfigurationContext.Current.CacheManager.Get(cacheKey) as LocalizationResource; if (localizationResource != null) { // if value for the cache key is null - this is non-existing resource (no hit) return(localizationResource.Translations?.FirstOrDefault(t => t.Language == language.Name)?.Value); } var resource = GetResourceFromDb(key); LocalizationResourceTranslation localization = null; if (resource == null) { // create empty null resource - to indicate non-existing one resource = LocalizationResource.CreateNonExisting(key); } else { localization = resource.Translations.FirstOrDefault(t => t.Language == language.Name); } ConfigurationContext.Current.CacheManager.Insert(cacheKey, resource); return(localization?.Value); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { try { if (context.Controller.GetType() != typeof(HomeController) && context.Controller.GetType() != typeof(TimeoutController) && !string.IsNullOrWhiteSpace(context.HttpContext.User.GetUserId())) { var cacheKey = CacheKeyHelper.GetCacheKey(context.HttpContext.User.GetUserId(), CacheConstants.UserSessionActivityCacheKey); await _cacheService.SetAsync(cacheKey, DateTime.UtcNow); } if (context.HttpContext.User.Identity.IsAuthenticated && !context.HttpContext.User.HasAccessToService() && IsAccessDenied(context)) { var routeValues = new RouteValueDictionary { { "controller", Constants.ErrorController }, { "action", nameof(ErrorController.ServiceAccessDenied) } }; context.Result = new RedirectToRouteResult(routeValues); await context.Result.ExecuteResultAsync(context); } else { await next(); } } catch (Exception exception) { _logger.LogError(exception, exception.Message); } }
public DistributedFlow(IDistributedCache distributedCache, ILogger <DistributedFlow>?logger = default, IOptions <FlowOptions>?options = default, ISerializer?serializer = default) { Instance = distributedCache ?? throw new ArgumentNullException(nameof(distributedCache)); _activitySource = ActivitySourceContainer.Instance; _logger = logger ?? new NullLogger <DistributedFlow>(); _serializer = serializer ?? new TextJsonSerializer(); if (options is null) { _logger.LogNoOptionsProvided(nameof(DistributedFlow)); Options = new FlowOptions(); } else { Options = options.Value; } if (Options.DataLoggingLevel is DataLogLevel.Disabled) { _logger = new NullLogger <DistributedFlow>(); } _executor = new Executor(_logger, Options.SuppressCacheExceptions, Options.DataLoggingLevel); _prefix = CacheKeyHelper.GetFullCacheKeyPrefix(Options.CacheKeyPrefix, Options.CacheKeyDelimiter); _logSensitive = Options.DataLoggingLevel is DataLogLevel.Sensitive; }
public void By_DateTime_ShouldBeCacheKeyString() { var dateTime = default(DateTime); var key = _cacheKeyBuilder.By(dateTime).ToString(); key.Should().Be(CacheKeyHelper.Format(dateTime.Ticks)); }
/// <summary> /// Handles the command. Actual instance of the command being executed is passed-in as argument /// </summary> /// <param name="command">Actual command instance being executed</param> /// <exception cref="InvalidOperationException">Cannot delete translation for not modified resource (key: `{command.Key}`</exception> public void Execute(RemoveTranslation.Command command) { var repository = new ResourceRepository(_configurationContext); var resource = repository.GetByKey(command.Key); if (resource == null) { return; } if (!resource.IsModified.HasValue || !resource.IsModified.Value) { throw new InvalidOperationException( $"Cannot delete translation for not modified resource (key: `{command.Key}`"); } var t = resource.Translations.FirstOrDefault(_ => _.Language == command.Language.Name); if (t != null) { repository.DeleteTranslation(resource, t); } _configurationContext.CacheManager.Remove(CacheKeyHelper.BuildKey(command.Key)); }
protected virtual string GetTranslation(Query query) { var key = query.Key; var language = query.Language; var cacheKey = CacheKeyHelper.BuildKey(key); var localizationResource = ConfigurationContext.Current.CacheManager.Get(cacheKey) as LocalizationResource; if (localizationResource != null) { return(GetTranslationFromAvailableList(localizationResource.Translations, language, query.UseFallback)?.Value); } var resource = GetResourceFromDb(key); LocalizationResourceTranslation localization = null; // create empty null resource - to indicate non-existing one if (resource == null) { resource = LocalizationResource.CreateNonExisting(key); } else { localization = GetTranslationFromAvailableList(resource.Translations, language, query.UseFallback); } ConfigurationContext.Current.CacheManager.Insert(cacheKey, resource); return(localization?.Value); }
public void Intercept(IInvocation invocation) { var cacheAttribute = invocation.MethodInvocationTarget.GetCustomAttribute <CacheAttribute>(); cacheAttribute = cacheAttribute ?? new StackTrace().GetFrames() .Select(x => x.GetMethod().GetCustomAttribute <CacheAttribute>()) .FirstOrDefault(x => x != null); if (IsReadFromCache(invocation, cacheAttribute)) { var key = CacheKeyHelper.GenerateKey( invocation.MethodInvocationTarget, invocation.Arguments, cacheAttribute.Template); var cacheValue = GetCache(key, cacheAttribute.Db); if (cacheValue.HasValue) { invocation.ReturnValue = JsonConvert.DeserializeObject(cacheValue, invocation.Method.ReturnType); } else { invocation.Proceed(); } } else { invocation.Proceed(); } }
public bool TryGetValue <T>(string key, out T value) { var fullKey = CacheKeyHelper.GetFullKey(_prefix, key); using var activity = _activitySource.CreateStartedActivity(nameof(TryGetValue), BuildTags(CacheEvents.Miss, fullKey)); bool isCached; (isCached, value) = _executor.TryExecute(() => { var result = Instance.TryGetValue(fullKey, out T obj); return(result, obj); }); if (!isCached) { _logger.LogMissed(BuildTarget(nameof(TryGetValue)), fullKey, _logSensitive); return(false); } _logger.LogHit(BuildTarget(nameof(TryGetValue)), fullKey, value !, _logSensitive); activity.SetEvent(CacheEvents.Hit); return(true); }
public void By_Integer_ShouldBeCacheKeyString() { const int number = 5; var key = _cacheKeyBuilder.By(number).ToString(); key.Should().Be(CacheKeyHelper.Format(number)); }
public void By_Guid_ShouldBeCacheKeyString() { var guid = Guid.NewGuid(); var key = _cacheKeyBuilder.By(guid).ToString(); key.Should().Be(CacheKeyHelper.Format(guid)); }
public override void Setup() { HttpContextAccessor = Substitute.For <IHttpContextAccessor>(); ResultLoader = Substitute.For <IResultLoader>(); CacheService = Substitute.For <ICacheService>(); Logger = Substitute.For <ILogger <ResultController> >(); Controller = new ResultController(ResultLoader, CacheService, Logger); AoUkprn = 1234567890; ViewModel = new ManageCoreResultViewModel { ProfileId = 1, ResultId = 11, SelectedGradeCode = "PCG1" }; var httpContext = new ClaimsIdentityBuilder <ResultController>(Controller) .Add(CustomClaimTypes.Ukprn, AoUkprn.ToString()) .Add(CustomClaimTypes.UserId, Guid.NewGuid().ToString()) .Build() .HttpContext; HttpContextAccessor.HttpContext.Returns(httpContext); CacheKey = CacheKeyHelper.GetCacheKey(httpContext.User.GetUserId(), CacheConstants.ResultCacheKey); MockResult = new ChangeResultResponse(); }
public void Return_Valid_CacheKey(string origin, string destination) { string expected = $"traintimes_{origin.RemoveWhiteSpace()}-{destination.RemoveWhiteSpace()}"; string actual = CacheKeyHelper.GetTrainTimesCacheKey(origin, destination); Assert.Equal(expected, actual); }
public async Task SignOut() { await _cacheService.RemoveAsync <DateTime>(CacheKeyHelper.GetCacheKey(User.GetUserId(), CacheConstants.UserSessionActivityCacheKey)); await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); }
public void By_CacheableObject_ShouldBeCacheKeyString() { const int number = 5; const string text = "test"; var obj = new CacheableObject(number, text); var key = _cacheKeyBuilder.By(obj).ToString(); key.Should().Be(CacheKeyHelper.Format(number) + CacheKeyHelper.Format(text)); }
public void Return_Valid_CacheKey() { string account = "51671327713"; string expected = $"account_{account}"; string actual = CacheKeyHelper.GetAccountCacheKey(account); Assert.Equal(expected, actual); }
public void Remove(string key) { var fullKey = CacheKeyHelper.GetFullKey(_prefix, key); using var activity = _activitySource.CreateStartedActivity(nameof(Remove), BuildTags(CacheEvents.Remove, fullKey)); _executor.TryExecute(() => Instance.Remove(fullKey)); _logger.LogRemoved(BuildTarget(nameof(Remove)), key, _logSensitive); }
public void Execute(ClearCache.Command command) { var manager = ConfigurationContext.Current.CacheManager; foreach (var key in ConfigurationContext.Current.BaseCacheManager.KnownResourceKeys.Keys) { var cachedKey = CacheKeyHelper.BuildKey(key); manager.Remove(cachedKey); } }
/// <summary> Populate cache. </summary> // ReSharper disable once MemberCanBeMadeStatic.Local private void PopulateCache() { new ClearCache.Command().Execute(); var allResources = new GetAllResources.Query().Execute(); foreach (var resource in allResources) { var key = CacheKeyHelper.BuildKey(resource.ResourceKey); ConfigurationContext.Current.CacheManager.Insert(key, resource); } }
public async Task ActivityTimeout() { var userId = User.GetUserId(); TempData.Set(Constants.UserSessionActivityId, userId); await _cacheService.RemoveAsync <DateTime>(CacheKeyHelper.GetCacheKey(userId, CacheConstants.UserSessionActivityCacheKey)); await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); }