Пример #1
0
    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;
    }
Пример #2
0
        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));
        }
Пример #4
0
        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);
        }
Пример #5
0
        /// <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);
        }
Пример #6
0
            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));
            }
Пример #7
0
        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);
        }
Пример #8
0
        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);
        }
Пример #9
0
        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);
        }
Пример #10
0
        public void By_String_ShouldBeCacheKeyString()
        {
            const string text = "test";
            var          key  = _cacheKeyBuilder.By(text).ToString();

            key.Should().Be(CacheKeyHelper.Format(text));
        }
Пример #11
0
        public void TestKeyExtract_ExistingKey()
        {
            var key  = CacheKeyHelper.GenerateKey("MyProject.MyResources", "en", true);
            var name = CacheKeyHelper.GetContainerName(key);

            Assert.Equal("MyProject.MyResources", name);
        }
Пример #12
0
            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);
            }
Пример #13
0
        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);
            }
        }
Пример #14
0
    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;
    }
Пример #15
0
        public void By_DateTime_ShouldBeCacheKeyString()
        {
            var dateTime = default(DateTime);
            var key      = _cacheKeyBuilder.By(dateTime).ToString();

            key.Should().Be(CacheKeyHelper.Format(dateTime.Ticks));
        }
Пример #16
0
        /// <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));
        }
Пример #17
0
            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);
            }
Пример #18
0
        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();
            }
        }
Пример #19
0
    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);
    }
Пример #20
0
        public void By_Integer_ShouldBeCacheKeyString()
        {
            const int number = 5;
            var       key    = _cacheKeyBuilder.By(number).ToString();

            key.Should().Be(CacheKeyHelper.Format(number));
        }
Пример #21
0
        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();
        }
Пример #23
0
            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);
            }
Пример #24
0
        public async Task SignOut()
        {
            await _cacheService.RemoveAsync <DateTime>(CacheKeyHelper.GetCacheKey(User.GetUserId(), CacheConstants.UserSessionActivityCacheKey));

            await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);

            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
Пример #25
0
        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));
        }
Пример #26
0
            public void Return_Valid_CacheKey()
            {
                string account  = "51671327713";
                string expected = $"account_{account}";

                string actual = CacheKeyHelper.GetAccountCacheKey(account);

                Assert.Equal(expected, actual);
            }
Пример #27
0
    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);
            }
        }
Пример #29
0
        /// <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);
            }
        }
Пример #30
0
        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);
        }