public string GetAvatar(IUser user) { if (user == null) { return(string.Empty); // { throw new ArgumentNullException("user"); } } var orchardUser = user as User; if (orchardUser == null) { throw new ArgumentNullException("orchardUser"); } var memoryCacheKey = $"{AvatarCacheKeyPrefix}-{orchardUser.UserName}"; if (!_memoryCache.TryGetValue(memoryCacheKey, out string avatar)) { //cachedDate = (await _localClock.LocalNowAsync).DateTime; var usermetadata = orchardUser.As <UserMetadata>(); if (usermetadata != null) { var resolvedAssetPath = _mediaFileStore.MapPathToPublicUrl(usermetadata.Avatar); avatar = resolvedAssetPath; _memoryCache.Set(memoryCacheKey, avatar, _signal.GetToken(memoryCacheKey)); } } return(avatar); }
public async Task <List <SysModuleViewModel> > GetSysModuleViewModels(string roleId) { try { var c = HttpContext.Current; return(await _memoryCache.GetOrCreateAsync(roleId, async entity => { entity.ExpirationTokens.Add(_signal.GetToken(roleId)); var list = await _repository.Query().Where(a => a.IsDelete == false && a.ModuleType == 0).ProjectTo <SysModuleViewModel>(AutoMapperConfiguration.MapperConfiguration).OrderByDescending(a => a.CreateTime).ToListAsync(); var rolePurviewlist = await _roleModulesRepository.ListAsync(a => a.RoleId == roleId); List <SysModuleViewModel> tem = new List <SysModuleViewModel>(); foreach (var module in list) { if (module.ParentId != "0") { var p = rolePurviewlist.FirstOrDefault(a => a.ControllerName == module.ControllerName); if ((module.PurviewSum & p?.PurviewSum) == module.PurviewSum) { tem.Add(module); if (tem.All(a => a.Id != module.ParentId)) { tem.Add(list.FirstOrDefault(a => a.Id == module.ParentId)); } } } } return tem.OrderBy(a => a.Sort).ToList(); })); } catch (Exception ex) { } return(await Task.FromResult(new List <SysModuleViewModel>())); }
private async Task <ICollection <IWorkflowBlueprint> > GetWorkflowBlueprints(CancellationToken cancellationToken) { return(await _memoryCache.GetOrCreateAsync(CacheKey, async entry => { entry.Monitor(_signal.GetToken(CacheKey)); return await _workflowRegistry.ListAsync(cancellationToken).ToList(); })); }
public Task <List <Role> > GetRolesAsync() { return(_memoryCache.GetOrCreateAsync(Key, async entry => { var roles = await _roleRepository.GetAllListAsync(); entry.ExpirationTokens.Add(_signal.GetToken(Key)); return roles; })); }
/// <summary> /// 信号过期 /// </summary> /// <param name="provider"></param> /// <returns></returns> public static DateTime MemcacheSignal(IServiceProvider provider) { IMemoryCache _cache = provider.GetService <IMemoryCache>(); ISignal _signal = provider.GetService <ISignal>(); return(_cache.GetOrCreate("GetOrCreateTest", (entry) => { entry.ExpirationTokens.Add(_signal.GetToken("GetOrCreateTest")); return DateTime.Now; })); }
/// <summary> /// implementing operate on rows (instead of row) to allow loading of external (file based) templates first /// </summary> /// <param name="rows"></param> /// <returns></returns> public override IEnumerable <IRow> Operate(IEnumerable <IRow> rows) { if (!Run) { yield break; } var key = string.Join(':', Context.Process.Id, Context.Entity.Alias, Context.Field.Alias, Context.Operation.Method, Context.Operation.Index); if (!_memoryCache.TryGetValue(key, out CachedRazorTransform transform)) { transform = new CachedRazorTransform(); var fileBasedTemplate = Context.Process.Templates.FirstOrDefault(t => t.Name == Context.Operation.Template); if (fileBasedTemplate != null) { Context.Operation.Template = fileBasedTemplate.Content; } var input = MultipleInput(); var matches = Context.Entity.GetFieldMatches(Context.Operation.Template); transform.Input = input.Union(matches).ToArray(); var engine = new RazorEngine(); try { transform.Template = engine.Compile(Context.Operation.Template, builder => { builder.AddUsing("System"); }); // any changes to content item will invalidate cache _memoryCache.Set(key, transform, _signal.GetToken(Common.GetCacheKey(Context.Process.Id))); } catch (RazorEngineCompilationException ex) { foreach (var error in ex.Errors) { var line = error.Location.GetLineSpan(); Context.Error($"C# error on line {line.StartLinePosition.Line}, column {line.StartLinePosition.Character}."); Context.Error(error.GetMessage()); } Context.Error(ex.Message.Replace("{", "{{").Replace("}", "}}")); Utility.CodeToError(Context, Context.Operation.Template); yield break; } } foreach (var row in rows) { var output = transform.Template.Run(row.ToFriendlyExpandoObject(transform.Input)); row[Context.Field] = _convert(output); yield return(row); } }
public async Task <IEnumerable <IRole> > GetRolesAsync() { // 同一租户环境下角色数据进行缓存 return(await _memoryCache.GetOrCreateAsync(Key, async (entry) => { var roles = await Task.FromResult(_dbContext.Set <Role>().Select(e => (IRole)e).ToArray().AsEnumerable()); entry.ExpirationTokens.Add(_signal.GetToken(Key)); return roles; })); }
public async Task <int> GetFeatureHashAsync() { int serial; if (_memoryCache.TryGetValue(FeatureHashCacheKey, out serial)) { return(serial); } // Calculate a hash of all enabled features' name serial = (await _featureManager.GetEnabledFeaturesAsync()) .OrderBy(x => x.Name) .Aggregate(0, (a, f) => a * 7 + f.Name.GetHashCode()); var options = new MemoryCacheEntryOptions() .AddExpirationToken(_signal.GetToken(FeatureManager.FeatureManagerCacheKey)); _memoryCache.Set(FeatureHashCacheKey, serial, options); return(serial); }
public async Task <int> GetFeatureHashAsync() { int serial; if (_memoryCache.TryGetValue(FeatureHashCacheKey, out serial)) { return(serial); } var enabledFeatures = await _featureManager.GetEnabledFeaturesAsync(); serial = enabledFeatures .OrderBy(x => x.Id) .Aggregate(0, (a, f) => a * 7 + f.Id.GetHashCode()); var options = new MemoryCacheEntryOptions() .AddExpirationToken(_signal.GetToken(FeaturesProvider.FeatureProviderCacheKey)); _memoryCache.Set(FeatureHashCacheKey, serial, options); return(serial); }
private async Task <ICollection <WorkflowDefinitionVersion> > ReadCacheAsync(CancellationToken cancellationToken) { return(await cache.GetOrCreateAsync( CacheKey, async entry => { var workflowDefinitions = await LoadWorkflowDefinitionsAsync(cancellationToken); entry.SlidingExpiration = TimeSpan.FromHours(1); entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(4); entry.Monitor(signal.GetToken(CacheKey)); return workflowDefinitions; })); }
/// <summary> /// implementing operate on rows (instead of row) to allow loading of external (file based) templates first /// </summary> /// <param name="rows"></param> /// <returns></returns> public override IEnumerable <IRow> Operate(IEnumerable <IRow> rows) { if (!Run) { yield break; } var key = string.Join(':', Context.Process.Id, Context.Entity.Alias, Context.Field.Alias, Context.Operation.Method, Context.Operation.Index); if (!_memoryCache.TryGetValue(key, out CachedFluidTransform transform)) { transform = new CachedFluidTransform(); var fileBasedTemplate = Context.Process.Templates.FirstOrDefault(t => t.Name == Context.Operation.Template); if (fileBasedTemplate != null) { Context.Operation.Template = fileBasedTemplate.Content; } var input = MultipleInput(); var matches = Context.Entity.GetFieldMatches(Context.Operation.Template); transform.Input = input.Union(matches).ToArray(); if (FluidTemplate.TryParse(Context.Operation.Template, out transform.Template)) { // any changes to content item will invalidate cache _memoryCache.Set(key, transform, _signal.GetToken(Common.GetCacheKey(Context.Process.Id))); } else { Context.Error("Failed to parse fluid template."); Utility.CodeToError(Context, Context.Operation.Template); yield break; } } var context = new TemplateContext(); foreach (var row in rows) { foreach (var field in transform.Input) { context.SetValue(field.Alias, row[field]); } row[Context.Field] = _convert(transform.Template.Render(context)); yield return(row); } }
public async Task <RolesDocument> GetRolesAsync() { return(await _memoryCache.GetOrCreateAsync(Key, async (entry) => { _roles = await _session.QueryAsync <RolesDocument>().FirstOrDefault(); if (_roles == null) { _roles = new RolesDocument(); UpdateRoles(); } entry.ExpirationTokens.Add(_signal.GetToken(Key)); return _roles; })); }
public Task <RolesDocument> GetRolesAsync() { return(_memoryCache.GetOrCreateAsync(Key, async(entry) => { var roles = await _session.Query <RolesDocument>().FirstOrDefaultAsync(); if (roles == null) { roles = new RolesDocument(); _session.Save(roles); } entry.ExpirationTokens.Add(_signal.GetToken(Key)); return roles; })); }
public Task <IEnumerable <LayerMetadata> > GetLayerWidgetsAsync(Expression <Func <ContentItemIndex, bool> > predicate) { return(_memoryCache.GetOrCreateAsync("Orchard.Layers:Layers" + predicate.ToString(), async entry => { entry.AddExpirationToken(_signal.GetToken(LayerMetadataHandler.LayerChangeToken)); var allWidgets = await _session .Query <ContentItem, LayerMetadataIndex>() .With(predicate) .ListAsync(); return (IEnumerable <LayerMetadata>)allWidgets .Select(x => x.As <LayerMetadata>()) .Where(x => x != null) .OrderBy(x => x.Position) .ToList(); })); }
public Task <int> GetTypesHashAsync() { // The serial number is stored in local cache in order to prevent // loading the record if it's not necessary int serial; if (!_memoryCache.TryGetValue(TypeHashCacheKey, out serial)) { serial = _memoryCache.Set( TypeHashCacheKey, GetContentDefinitionRecord().Serial, _signal.GetToken(TypeHashCacheKey) ); } return(Task.FromResult(serial)); }
/// <summary> /// Returns the document from the cache or creates a new one. The result should not be updated. /// </summary> private async Task <RolesDocument> GetRolesAsync() { if (!_memoryCache.TryGetValue <RolesDocument>(Key, out var document)) { var changeToken = _signal.GetToken(Key); document = await _sessionHelper.GetForCachingAsync <RolesDocument>(); foreach (var role in document.Roles) { role.IsReadonly = true; } _memoryCache.Set(Key, document, changeToken); } return(document); }
public Task <int> GetTypesHashAsync() { // The serial number is store in local cache in order to prevent // loading the record if it's not necessary int serial; if (!_memoryCache.TryGetValue(TypeHashCacheKey, out serial)) { var options = new MemoryCacheEntryOptions() .AddExpirationToken(_signal.GetToken(TypeHashCacheKey)); serial = GetContentDefinitionRecord().Serial; _memoryCache.Set(TypeHashCacheKey, serial, options); } return(Task.FromResult(serial)); }
public virtual Task <Deployment> GetLatestProductionDeploymentAsync() { return(_cache.GetOrAddAsync(DeploymentCacheKeys.LatestDeployment, async entry => { ThrowIfReadNotConfigured(); entry.AddExpirationToken(_signal.GetToken(DeploymentCacheKeys.LatestDeployment)); var latestDeployment = await GetLatestProductionDeploymentAsync_Impl(); // Reset waiting for deployment, if another new production deployment has arrived _deploymentStatus.MaybeResetWaitingForDeployment(latestDeployment?.Id); entry.SetAbsoluteExpiration(DateTime.UtcNow + TimeSpan.FromSeconds( _deploymentStatus.IsWaitingForDeployment() ? _deploymentOptions.HighPriorityCacheInSeconds : _deploymentOptions.CacheInSeconds )); return latestDeployment; })); }
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { // Should only run on the front-end for a full view if ((context.Result is ViewResult || context.Result is PageResult) && !AdminAttribute.IsApplied(context.HttpContext)) { // Even if the Admin attribute is not applied we might be using the admin theme, for instance in Login views. // In this case don't render Layers. var selectedTheme = (await _themeManager.GetThemeAsync())?.Id; var adminTheme = await _adminThemeService.GetAdminThemeNameAsync(); if (selectedTheme == adminTheme) { await next.Invoke(); return; } var widgets = await _memoryCache.GetOrCreateAsync("OrchardCore.Layers.LayerFilter:AllWidgets", entry => { entry.AddExpirationToken(_signal.GetToken(LayerMetadataHandler.LayerChangeToken)); return(_layerService.GetLayerWidgetsAsync(x => x.Published)); }); var layers = (await _layerService.GetLayersAsync()).Layers.ToDictionary(x => x.Name); dynamic layout = await _layoutAccessor.GetLayoutAsync(); var updater = _modelUpdaterAccessor.ModelUpdater; var engine = _scriptingManager.GetScriptingEngine("js"); var scope = engine.CreateScope(_scriptingManager.GlobalMethodProviders.SelectMany(x => x.GetMethods()), _serviceProvider, null, null); var layersCache = new Dictionary <string, bool>(); foreach (var widget in widgets) { var layer = layers[widget.Layer]; if (layer == null) { continue; } bool display; if (!layersCache.TryGetValue(layer.Name, out display)) { if (String.IsNullOrEmpty(layer.Rule)) { display = false; } else { display = Convert.ToBoolean(engine.Evaluate(scope, layer.Rule)); } layersCache[layer.Rule] = display; } if (!display) { continue; } var widgetContent = await _contentItemDisplayManager.BuildDisplayAsync(widget.ContentItem, updater); widgetContent.Classes.Add("widget"); widgetContent.Classes.Add("widget-" + widget.ContentItem.ContentType.HtmlClassify()); var wrapper = new WidgetWrapper { Widget = widget.ContentItem, Content = widgetContent }; wrapper.Metadata.Alternates.Add("Widget_Wrapper__" + widget.ContentItem.ContentType); wrapper.Metadata.Alternates.Add("Widget_Wrapper__Zone__" + widget.Zone); var contentZone = layout.Zones[widget.Zone]; contentZone.Add(wrapper); } } await next.Invoke(); }
/// <summary> /// implementing operate on rows (instead of row) to allow loading of external (file based) scripts to load first /// </summary> /// <param name="rows"></param> /// <returns></returns> public override IEnumerable <IRow> Operate(IEnumerable <IRow> rows) { if (!Run) { yield break; } var key = string.Join(':', Context.Process.Id, Context.Entity.Alias, Context.Field.Alias, Context.Operation.Method, Context.Operation.Index); if (!_memoryCache.TryGetValue(key, out CachedJintTransform transform)) { transform = new CachedJintTransform(); var scriptBuilder = new StringBuilder(); var scriptReader = new ScriptReader(Context, _reader); // to support shorthand script (e.g. t="js(scriptName)") if (Context.Operation.Scripts.Count == 0) { var script = Context.Process.Scripts.FirstOrDefault(s => s.Name == Context.Operation.Script); if (script != null) { Context.Operation.Script = scriptReader.Read(script); } } var tester = new ScriptTester(Context); if (tester.Passes(Context.Operation.Script)) { // automatic parameter binding if (!Context.Operation.Parameters.Any()) { var parameters = _parameterMatcher.Match(Context.Operation.Script, Context.GetAllEntityFields()); foreach (var parameter in parameters) { Context.Operation.Parameters.Add(new Parameter { Field = parameter, Entity = Context.Entity.Alias }); } } } else { Run = false; } // for js, always add the input parameter transform.Input = MultipleInput().Union(new[] { Context.Field }).Distinct().ToArray(); if (Context.Process.Scripts.Any(s => s.Global && (s.Language == "js" || s.Language == Constants.DefaultSetting && s.File != null && s.File.EndsWith(".js", StringComparison.OrdinalIgnoreCase)))) { // load any global scripts foreach (var sc in Context.Process.Scripts.Where(s => s.Global && (s.Language == "js" || s.Language == Constants.DefaultSetting && s.File != null && s.File.EndsWith(".js", StringComparison.OrdinalIgnoreCase)))) { var content = scriptReader.Read(Context.Process.Scripts.First(s => s.Name == sc.Name)); if (tester.Passes(content)) { scriptBuilder.AppendLine(content); } else { Run = false; } } } // load any specified scripts if (Context.Operation.Scripts.Any()) { foreach (var sc in Context.Operation.Scripts) { var content = scriptReader.Read(Context.Process.Scripts.First(s => s.Name == sc.Name)); if (tester.Passes(content)) { scriptBuilder.AppendLine(content); } else { Run = false; } } } if (scriptBuilder.Length > 0) { scriptBuilder.AppendLine(Context.Operation.Script); } else { scriptBuilder.Append(Context.Operation.Script); } try { transform.Program = new JavaScriptParser(scriptBuilder.ToString(), new ParserOptions() { Tolerant = true }).ParseProgram(); } catch (ParserException ex) { Context.Error(ex.Message); Utility.CodeToError(Context, scriptBuilder.ToString()); Run = false; } // any changes to content item will invalidate cache _memoryCache.Set(key, transform, _signal.GetToken(Common.GetCacheKey(Context.Process.Id))); } if (!Run) { yield break; } foreach (var row in rows) { foreach (var field in transform.Input) { _jint.SetValue(field.Alias, row[field]); } if (TryFirst) { try { TryFirst = false; var obj = _jint.Execute(transform.Program).GetCompletionValue().ToObject(); var value = obj == null ? null : Context.Field.Convert(obj); if (value == null && !_errors.ContainsKey(0)) { Context.Error($"Jint transform in {Context.Field.Alias} returns null!"); _errors[0] = $"Jint transform in {Context.Field.Alias} returns null!"; } else { row[Context.Field] = value; } } catch (Jint.Runtime.JavaScriptException jse) { if (!_errors.ContainsKey(jse.LineNumber)) { Context.Error("Script: " + Context.Operation.Script.Replace("{", "{{").Replace("}", "}}")); Context.Error(jse, "Error Message: " + jse.Message); Context.Error("Variables:"); foreach (var field in transform.Input) { Context.Error($"{field.Alias}:{row[field]}"); } _errors[jse.LineNumber] = jse.Message; } } } else { row[Context.Field] = Context.Field.Convert(_jint.Execute(transform.Program).GetCompletionValue().ToObject()); } yield return(row); } }
public async Task <string> ReadCache() { DateTimeOffset localTime; if (!_memoryCache.TryGetValue(CacheKey, out localTime)) { localTime = _memoryCache.Set(CacheKey, await _localClock.LocalNowAsync, _signal.GetToken(SignalKey)); } return(localTime.ToString()); }
// This change token is generated based on the cache key using the ISignal service. It is used to invalidate // the memory cache. private IChangeToken GetMemoryCacheChangeToken() => _signal.GetToken(MemoryCacheKey);