public void Remove(CacheKey key, IReplaceableCache cache) { if (cache.AlgorithmData != null && key != null) { cache.AlgorithmData.Remove(key); } }
public override void OnActionExecuting(HttpActionContext actionContext) { ReflectedHttpActionDescriptor actionDescriptor = actionContext.ActionDescriptor as ReflectedHttpActionDescriptor; if (null == actionDescriptor) { base.OnActionExecuting(actionContext); } CacheKey key = new CacheKey(actionDescriptor.MethodInfo,actionContext.ActionArguments); object[] array = HttpRuntime.Cache.Get(key.ToString()) as object[]; if (null == array) { base.OnActionExecuting(actionContext); return; } object value = array.Any() ? array[0] : null; IHttpActionResult actionResult = value as IHttpActionResult; if (null != actionResult) { actionContext.Response = actionResult.ExecuteAsync(CancellationToken.None).Result; return; } actionContext.Response = actionDescriptor.ResultConverter.Convert(actionContext.ControllerContext, value); }
public static ObjectAnimationUsingKeyFrames GetAnimation(ImageSource source, RepeatBehavior repeatBehavior) { var key = new CacheKey(source, repeatBehavior); ObjectAnimationUsingKeyFrames animation; _animationCache.TryGetValue(key, out animation); return animation; }
public CacheKey[] Replace(IReplaceableCache cache) { CacheKey[] items; // cache does not exceed maximum count, do not replace if (cache.Count() <= cache.MaxCount()) { return null; } else { // cache count exceeds max entries, remove from the end of queue int itemCountToReplace = (int) (cache.Count() - cache.MaxCount()); items = new CacheKey[itemCountToReplace]; for (int i = itemCountToReplace - 1; i >= 0; i--) { items[i] = cache.AlgorithmData.RemoveFromTail(); } } // to do: remove cache entries has been expired return items; }
private string StartingWithInner(string value) { var cacheKey = new CacheKey(CacheName.AdHoc, CacheKeyBase + value); var result = this.cachingService[cacheKey] as string; if (result == null) { lock (StartingWithInnerSyncRoot) { result = this.cachingService[cacheKey] as string; if (result == null) { var matchingTags = this.tagTasks.GetWhereNameStartsWith(value); var resultStrings = matchingTags.Select(t => t.Name).ToArray(); result = string.Join("\n", resultStrings); this.cachingService.Add(cacheKey, result); } } } return result; }
public static MethodInfo GetFastMemoryReader(IntPtr FixedGlobalAddress) { var CacheKey = new CacheKey() { FixedGlobalAddress = FixedGlobalAddress }; if (!Cache.ContainsKey(CacheKey)) { var DllName = "FastPspMemoryUtils_Gen.dll"; var TypeName = "Memory"; var MethodName = "Get"; var AssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("FastPspMemoryUtils_Gen"), AssemblyBuilderAccess.RunAndCollect, DllName); var ModuleBuilder = AssemblyBuilder.DefineDynamicModule(AssemblyBuilder.GetName().Name, DllName, true); var TypeBuilder = ModuleBuilder.DefineType(TypeName, TypeAttributes.Sealed | TypeAttributes.Public | TypeAttributes.Class); var Method = TypeBuilder.DefineMethod(MethodName, MethodAttributes.Final | MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(void*), new[] { typeof(uint) }); Method.SetCustomAttribute(new CustomAttributeBuilder(typeof(MethodImplAttribute).GetConstructor(new Type[] { typeof(MethodImplOptions) }), new object[] { MethodImplOptions.AggressiveInlining })); Method.SetCustomAttribute(new CustomAttributeBuilder(typeof(TargetedPatchingOptOutAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { "Performance critical to inline across NGen image boundaries" })); //Method.GetILGenerator(); var AstTree = ast.Return( ast.Cast( typeof(void*), ast.Immediate(FixedGlobalAddress) + ast.Binary(ast.Argument<uint>(0), "&", ast.Immediate(FastPspMemory.FastMemoryMask)) ) ); new GeneratorIL().Reset().Init(Method, Method.GetILGenerator()).GenerateRoot(AstTree); var Type = TypeBuilder.CreateType(); Cache[CacheKey] = Type.GetMethod(MethodName); } return Cache[CacheKey]; }
public void Get(CacheKey key, IReplaceableCache cache) { if (cache.AlgorithmData != null && key != null) { cache.AlgorithmData.MoveToHead(key); } }
public async Task<IKey> ResolveKeyAsync( string kid, CancellationToken token ) { if ( _isDisposed ) throw new ObjectDisposedException( "CachingKeyResolver" ); if ( string.IsNullOrWhiteSpace( kid ) ) throw new ArgumentNullException( "kid" ); IKey result = _cache.Get( kid ); if ( result == null ) { result = await _inner.ResolveKeyAsync( kid, token ).ConfigureAwait( false ); if ( result != null ) { // Cache the resolved key using the result's Kid. // This is especially for the case when the resolved key contains information about the key version var cacheKid = string.IsNullOrWhiteSpace( result.Kid ) ? kid : result.Kid; var cachedKey = new CacheKey(result); _cache.Add( cacheKid, cachedKey ); return cachedKey; } } return result; }
public BoundExpression GetOrCreateBoundExpression(IBindingContext binder, BoundExpressionOptions options) { Require.NotNull(binder, "binder"); Require.NotNull(options, "options"); var key = new CacheKey( _dynamicExpression.ParseResult.Identifiers, !DynamicExpression.IsLanguageCaseSensitive(_dynamicExpression.Language), binder, options ); lock (_syncRoot) { BoundExpression boundExpression; if (!_cache.TryGetValue(key, out boundExpression)) { boundExpression = new BoundExpression( _dynamicExpression, key.OwnerType, key.Imports, key.IdentifierTypes, key.Options ); _cache.Add(key, boundExpression); } return boundExpression; } }
public Task Start() { timer = schedule.Schedule(async () => { var addedOrUpdated = new List<Entry>(); var results = (await dataBackplane.Query()); var removed = cache.Values.Where(x => !results.Any(r => r.Type == x.Type && r.Owner == x.Owner)).ToArray(); foreach (var entry in results) { Entry oldEntry; var key = new CacheKey(entry.Owner, entry.Type); if (!cache.TryGetValue(key, out oldEntry) || oldEntry.Data != entry.Data) { cache[key] = entry; addedOrUpdated.Add(entry); } } foreach (var change in addedOrUpdated) { await NotifyChanged(change).ConfigureAwait(false); } foreach (var entry in removed) { cache.Remove(new CacheKey(entry.Owner, entry.Type)); await NotifyRemoved(entry).ConfigureAwait(false); } }); return Task.FromResult(0); }
public void KeyHash() { CacheKey k1 = new CacheKey(string.Empty, "646846516584", "57"); Dictionary<CacheKey, object> dic = new Dictionary<CacheKey, object>(); dic.Add(k1, new object()); var found = dic[k1]; Assert.NotNull(found); }
public static void IncrementReferenceCount(ImageSource source, RepeatBehavior repeatBehavior) { var cacheKey = new CacheKey(source, repeatBehavior); int count; _referenceCount.TryGetValue(cacheKey, out count); count++; _referenceCount[cacheKey] = count; }
public void CompareHashCodesWhenNotEqualViaDifferentTypes() { var cacheKey1 = new CacheKey(this.GetType(), new RockOptions(OptimizationSetting.Release, CodeFileOptions.Create, SerializationOptions.Supported)); var cacheKey2 = new CacheKey(typeof(Guid), new RockOptions(OptimizationSetting.Release, CodeFileOptions.Create, SerializationOptions.Supported)); Assert.AreNotEqual(cacheKey1, cacheKey2); }
public bool Equals(CacheKey cacheKey) { if (cacheKey == null) return false; return cacheKey.Username.Equals(this.Username) && cacheKey.EntityToken.Equals(this.EntityToken) && cacheKey.Locale.Equals(this.Locale); }
public void KeyComposition() { Key k1 = "test"; KeyPrefix p1 = new KeyPrefix("tenant", "region"); CacheKey cc = new CacheKey(p1, k1); Assert.True(cc.Prefix.Tenant == "tenant" && cc.Prefix.Region == "region" && cc.Suffix == "test"); CacheKey newcc = cc; Assert.True(newcc == cc); }
/// <summary> /// Sets the Cache item for the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="data">The data.</param> /// <param name="cacheTime">The cache time - sliding scale in minutes.</param> public void Set(CacheKey key, object data, int cacheTime) { var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime) }; Cache.Add(new CacheItem(key.ToString(), data), policy); }
public void Affectation() { Key k1 = "ppppp"; KeyPrefix p1 = new KeyPrefix(Key.Null, "1651651645621"); CacheKey cc = new CacheKey(p1, k1); CacheKey affected = cc; Assert.True(cc == affected); var kv = new KeyValuePair<CacheKey, object>(affected, null); Assert.Equal(cc, kv.Key); }
public Image GetResizedWithCache(Image source, int width, int height, InterpolationMode mode = InterpolationMode.HighQualityBicubic) { var key = new CacheKey(source, width, height); return cachedImages.GetOrAdd(key, (k) => { var resized = new Bitmap(k.Width, k.Height); using (var g = Graphics.FromImage(resized)) { g.InterpolationMode = mode; g.DrawImage(source, 0, 0, k.Width, k.Height); } return resized; }); }
public static Type Get(String[] args, Type[] types, Func<Type> factory) { lock (_cache) { var key = new CacheKey(args, types); if (!_cache.ContainsKey(key)) { _cache.Add(key, factory()); } return _cache[key]; } }
public void Remove(CacheKey key) { if (key == null || this.dataInDict.ContainsKey(key) == false) { return; } Node<CacheSummary> node = this.dataInDict[key]; this.dataInList.Remove(node); this.dataInDict.Remove(key); }
public Func<object, object[], object> GetOrCreateFastMethodInvoker(Type declaringType, string methodName, Type[] typeParameters, Type[] argumentTypes, BindingFlags bindingFlags) { Func<object, object[], object> invoker; var key = new CacheKey(declaringType, methodName, typeParameters, argumentTypes); if (!_cache.TryGetValue (key, out invoker)) { invoker = _generator.GetFastMethodInvoker (declaringType, methodName, typeParameters, argumentTypes, bindingFlags); _cache.Add (key, invoker); } return invoker; }
public void ZeroHash() { var cache = new CachingFactory<CacheKey, CacheValue>(512, k => new CacheValue(k.Value + 1), k => k.Value, (k, v) => k.Value == v.Value); var key = new CacheKey(0); Assert.Equal(CacheKey.GetHashCode(key), 0); CacheValue value; bool found = cache.TryGetValue(key, out value); Assert.False(found); }
//check in-memory dictionary for cached value, if not found execute method and add to dictionary public override void OnInvoke(MethodInterceptionArgs args) { var key = new CacheKey(args); if (cache.ContainsKey(key)) { args.ReturnValue = cache[key]; } else { var result = args.Invoke(args.Arguments); cache.Add(key, result); args.ReturnValue = result; } }
public bool Set(CacheKey key, CacheValue value) { if (this.logger != null) { this.logger.Log("Set " + key.ToString() + ":" + value.ToString(), Category.Info, Priority.Medium); } if (this.Remove(key) == false) { return false; } return this.mediums[0].Set(key, value); }
private static Action<object[]> CreateValueProcessor(CacheKey cacheKey) { var valuesParam = Expression.Parameter(typeof(object[]), "values"); var conversions = new List<Expression>(); var valueTypes = cacheKey.ValueTypes; var valueVariable = Expression.Variable(typeof(object), "value"); for (var i = 0; i < valueTypes.Count; i++) { var type = valueTypes[i]; if (type.UnwrapNullableType().GetTypeInfo().IsEnum) { var arrayAccess = Expression.ArrayAccess(valuesParam, Expression.Constant(i)); conversions.Add(Expression.Assign(valueVariable, arrayAccess)); conversions.Add( Expression.IfThen( Expression.IsFalse( Expression.ReferenceEqual( valueVariable, Expression.Constant(DBNull.Value))), Expression.Assign( arrayAccess, Expression.Convert( Expression.Convert( Expression.Convert( valueVariable, type.UnwrapEnumType()), type), typeof(object))))); } } if (conversions.Count == 0) { return null; } return Expression.Lambda<Action<object[]>>( Expression.Block( new[] { valueVariable }, conversions), valuesParam) .Compile(); }
private bool Equals(CacheKey other) { if (!ValueTypes.SequenceEqual(other.ValueTypes)) { return false; } if (IndexMap == null) { return other.IndexMap == null; } return (other.IndexMap != null) && IndexMap.SequenceEqual(other.IndexMap); }
public Image GetImageWithCache(Rectangle r, StyleType style, StyleType? overlayStyle = null) { var key = new CacheKey { OverlayStyle = overlayStyle, Rectangle = r, Style = style }; Image img; if (cachedImages.TryGetValue(key, out img)) return img; var bmp = new Bitmap(r.Width, r.Height); using (var g = Graphics.FromImage(bmp)) { RenderToGraphics(g, r, style); if (overlayStyle != null) RenderToGraphics(g, r, overlayStyle.Value); } cachedImages[key] = bmp; return bmp; }
/// <summary> /// Interceptor /// </summary> /// <param name="invocation">Method invocation</param> public void Intercept(IInvocation invocation) { var key = new CacheKey(invocation.Request.Arguments); if (this._cache.Contais(key)) { invocation.ReturnValue = this._cache.Get(key); return; } invocation.Proceed(); this._cache.Put(key, invocation.ReturnValue); }
protected override CacheValue DoGet(CacheKey key) { if (this.cacheDictionary == null) { return null; } if (this.Exists(key) == true) { return this.cacheDictionary[key]; } else { return null; } }
private static Func<DbDataReader, object[]> CreateArrayInitializer(CacheKey cacheKey) { var dataReaderParam = Expression.Parameter(typeof(DbDataReader), "dataReader"); return Expression.Lambda<Func<DbDataReader, object[]>>( Expression.NewArrayInit( typeof(object), cacheKey.ValueTypes .Select((type, i) => CreateGetValueExpression( dataReaderParam, type, Expression.Constant(cacheKey.IndexMap?[i] ?? i)))), dataReaderParam) .Compile(); }
public bool Equals(CacheKey other) { return(other != null && GetHashCode().Equals(other.GetHashCode())); }
public bool Contains(CacheKey key) { return(pathLookup.ContainsKey(key)); }
public List <Tile> GetPath(CacheKey key) { return(pathLookup[key]); }
public bool Equals(CacheKey key) { return(start.Equals(key.start) && end.Equals(key.end)); }
private bool Equals(CacheKey other) => TypeMaterializationInfo.SequenceEqual(other.TypeMaterializationInfo);
public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag) { eTag = (TimedEntityTagHeaderValue)_eTagCache.Get(key.HashBase64); return(eTag != null); }
public bool TryRemove(CacheKey key) { return(_eTagCache.Remove(key.HashBase64) != null); }
/// <summary> /// 用户登录 /// </summary> /// <param name="loginInput"></param> /// <param name="loginPwd"></param> /// <returns></returns> /// <remarks> /// 用户可通过登录名及工号登录系统。 /// </remarks> public LoginStatusEnum UserLogin(string loginInput, string loginPwd) { #region 为减少数据库请求,用户实体保存在缓存中,可通过登录名及工号登录系统 // 使用2个缓存KEY保存指向用户ID的缓存KEY,从而获取用户实体。 string loginNameKey = CacheKey.GetKeyDefine(CacheKey.USER_LOGIN_NAME_KEY, loginInput); string loginWorkIdKey = CacheKey.GetKeyDefine(CacheKey.USER_WORKID_KEY, loginInput); // 通过登录名称获取指向用户实体的ID缓存KEY string userDomainInfoKey = CacheUtil.Get <string>(loginNameKey); if (userDomainInfoKey == null) { // 如果通过登录名称获取不到,说明可能输入的是工号,尝试通过工号获取指向用户实体的ID缓存KEY userDomainInfoKey = CacheUtil.Get <string>(loginWorkIdKey); } // 从缓存中获取用户领域模型 UserDomainModel domainModel = CacheUtil.Get <UserDomainModel>(userDomainInfoKey); #endregion #region 如果缓存中没有用户领域模型,再从数据库中重新获取用户领域模型,并缓存 if (domainModel == null) { domainModel = GetUserDomainModelFromDatabase(loginInput); if (domainModel == null) { // 数据库中不存在该用户。 return(LoginStatusEnum.NotExists); } userDomainInfoKey = CacheKey.GetKeyDefine(CacheKey.USERDOMAIN_INFO, domainModel.BasicInfo.UserId); // 保存缓存KEY。 CacheUtil.Set(userDomainInfoKey, domainModel); CacheUtil.Set(CacheKey.USER_LOGIN_NAME_KEY.GetKeyDefine(domainModel.BasicInfo.LoginName), CacheKey.GetKeyDefine(CacheKey.USER_LOGIN_NAME_KEY, domainModel.BasicInfo.LoginName)); CacheUtil.Set(CacheKey.USER_WORKID_KEY.GetKeyDefine(domainModel.BasicInfo.WorkId), CacheKey.GetKeyDefine(CacheKey.USER_WORKID_KEY, domainModel.BasicInfo.WorkId)); } #endregion #region 判断用户登录密码 if (domainModel.BasicInfo.LoginPwd != loginPwd) { // 记录用户登录次数 SessionUtil.LoginTryCount = (Convert.ToInt32(SessionUtil.LoginTryCount) + 1).ToString(); if (Convert.ToInt32(SessionUtil.LoginTryCount.Substring(7, 2)) > ConfigUtil.GetLoginTryCountLimit()) { return(LoginStatusEnum.NameOrPwdErrorAndShowValidCode); } else { return(LoginStatusEnum.NameOrPwdError); } } #endregion #region 判断用户状态 if (domainModel.BasicInfo.Status == 1) { return(LoginStatusEnum.Disabled); } #endregion #region 保存Session信息 SessionInfo sessionInfo = new SessionInfo(); sessionInfo.UserId = domainModel.BasicInfo.UserId; sessionInfo.LoginName = domainModel.BasicInfo.LoginName; sessionInfo.CnName = domainModel.BasicInfo.CnName; sessionInfo.EnName = domainModel.BasicInfo.EnName; sessionInfo.IsLogin = true; sessionInfo.RoleId = domainModel.BasicInfo.RoleId; sessionInfo.LanguageCode = IBP.Common.Consts.LANGUAGE_CN; sessionInfo.UserGroup = domainModel.InGroupList; sessionInfo.ExtAttributes = new Dictionary <string, object>(); // CTI 账号信息。 sessionInfo.ExtAttributes["CtiUserId"] = domainModel.BasicInfo.CtiUserId; sessionInfo.ExtAttributes["CtiUserPwd"] = domainModel.BasicInfo.CtiUserPwd; SessionUtil.Current = sessionInfo; SessionUtil.ResetLoginTryCount(); #endregion return(LoginStatusEnum.Success); }
/// <summary> /// Perform the second step of 2-phase load. Fully initialize the entity instance. /// After processing a JDBC result set, we "resolve" all the associations /// between the entities which were instantiated and had their state /// "hydrated" into an array /// </summary> public static void InitializeEntity(object entity, bool readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) { //TODO: Should this be an InitializeEntityEventListener??? (watch out for performance!) bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; var stopWath = new Stopwatch(); if (statsEnabled) { stopWath.Start(); } IPersistenceContext persistenceContext = session.PersistenceContext; EntityEntry entityEntry = persistenceContext.GetEntry(entity); if (entityEntry == null) { throw new AssertionFailure("possible non-threadsafe access to the session"); } IEntityPersister persister = entityEntry.Persister; object id = entityEntry.Id; object[] hydratedState = entityEntry.LoadedState; if (log.IsDebugEnabled) { log.Debug("resolving associations for " + MessageHelper.InfoString(persister, id, session.Factory)); } IType[] types = persister.PropertyTypes; for (int i = 0; i < hydratedState.Length; i++) { object value = hydratedState[i]; if (value != LazyPropertyInitializer.UnfetchedProperty && value != BackrefPropertyAccessor.Unknown) { hydratedState[i] = types[i].ResolveIdentifier(value, session, entity); } } //Must occur after resolving identifiers! if (session.IsEventSource) { preLoadEvent.Entity = entity; preLoadEvent.State = hydratedState; preLoadEvent.Id = id; preLoadEvent.Persister = persister; IPreLoadEventListener[] listeners = session.Listeners.PreLoadEventListeners; for (int i = 0; i < listeners.Length; i++) { listeners[i].OnPreLoad(preLoadEvent); } } persister.SetPropertyValues(entity, hydratedState, session.EntityMode); ISessionFactoryImplementor factory = session.Factory; if (persister.HasCache && ((session.CacheMode & CacheMode.Put) == CacheMode.Put)) { if (log.IsDebugEnabled) { log.Debug("adding entity to second-level cache: " + MessageHelper.InfoString(persister, id, session.Factory)); } object version = Versioning.GetVersion(hydratedState, persister); CacheEntry entry = new CacheEntry(hydratedState, persister, entityEntry.LoadedWithLazyPropertiesUnfetched, version, session, entity); CacheKey cacheKey = new CacheKey(id, persister.IdentifierType, persister.RootEntityName, session.EntityMode, session.Factory); bool put = persister.Cache.Put(cacheKey, persister.CacheEntryStructure.Structure(entry), session.Timestamp, version, persister.IsVersioned ? persister.VersionType.Comparator : null, UseMinimalPuts(session, entityEntry)); if (put && factory.Statistics.IsStatisticsEnabled) { factory.StatisticsImplementor.SecondLevelCachePut(persister.Cache.RegionName); } } if (readOnly || !persister.IsMutable) { //no need to take a snapshot - this is a //performance optimization, but not really //important, except for entities with huge //mutable property values persistenceContext.SetEntryStatus(entityEntry, Status.ReadOnly); } else { //take a snapshot TypeFactory.DeepCopy(hydratedState, persister.PropertyTypes, persister.PropertyUpdateability, hydratedState, session); persistenceContext.SetEntryStatus(entityEntry, Status.Loaded); } persister.AfterInitialize(entity, entityEntry.LoadedWithLazyPropertiesUnfetched, session); if (session.IsEventSource) { postLoadEvent.Entity = entity; postLoadEvent.Id = id; postLoadEvent.Persister = persister; IPostLoadEventListener[] listeners = session.Listeners.PostLoadEventListeners; for (int i = 0; i < listeners.Length; i++) { listeners[i].OnPostLoad(postLoadEvent); } } if (log.IsDebugEnabled) { log.Debug("done materializing entity " + MessageHelper.InfoString(persister, id, session.Factory)); } if (statsEnabled) { stopWath.Stop(); factory.StatisticsImplementor.LoadEntity(persister.EntityName, stopWath.Elapsed); } }
/// <summary> /// Registers a type in this scope's type cache. /// </summary> /// <param name="key">The key to be associated with the type.</param> /// <param name="type">The type to be stored in the cache.</param> public void RegisterInCache(CacheKey key, Type type) { typeCache[key] = type; }
public bool Equals(CacheKey key) => key._value == _value;
/// <summary> Add the collection to the second-level cache </summary> /// <param name="lce">The entry representing the collection to add </param> /// <param name="persister">The persister </param> /// <param name="cacheBatchingHandler">The action for handling cache batching</param> /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param> private async Task AddCollectionToCacheAsync(LoadingCollectionEntry lce, ICollectionPersister persister, Action <CachePutData> cacheBatchingHandler, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ISessionImplementor session = LoadContext.PersistenceContext.Session; ISessionFactoryImplementor factory = session.Factory; if (log.IsDebugEnabled()) { log.Debug("Caching collection: {0}", MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session)); } if (!(session.EnabledFilters.Count == 0) && persister.IsAffectedByEnabledFilters(session)) { // some filters affecting the collection are enabled on the session, so do not do the put into the cache. log.Debug("Refusing to add to cache due to enabled filters"); // todo : add the notion of enabled filters to the CacheKey to differentiate filtered collections from non-filtered; // but CacheKey is currently used for both collections and entities; would ideally need to define two separate ones; // currently this works in conjunction with the check on // DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from // cache with enabled filters). return; // EARLY EXIT!!!!! } IComparer versionComparator; object version; if (persister.IsVersioned) { versionComparator = persister.OwnerEntityPersister.VersionType.Comparator; object collectionOwner = LoadContext.PersistenceContext.GetCollectionOwner(lce.Key, persister); if (collectionOwner == null) { return; } version = LoadContext.PersistenceContext.GetEntry(collectionOwner).Version; } else { version = null; versionComparator = null; } CollectionCacheEntry entry = await(CollectionCacheEntry.CreateAsync(lce.Collection, persister, cancellationToken)).ConfigureAwait(false); CacheKey cacheKey = session.GenerateCacheKey(lce.Key, persister.KeyType, persister.Role); if (persister.GetBatchSize() > 1 && persister.Cache.IsBatchingPutSupported()) { cacheBatchingHandler( new CachePutData( cacheKey, persister.CacheEntryStructure.Structure(entry), version, versionComparator, factory.Settings.IsMinimalPutsEnabled && session.CacheMode != CacheMode.Refresh)); } else { bool put = await(persister.Cache.PutAsync(cacheKey, persister.CacheEntryStructure.Structure(entry), session.Timestamp, version, versionComparator, factory.Settings.IsMinimalPutsEnabled && session.CacheMode != CacheMode.Refresh, cancellationToken)).ConfigureAwait(false); if (put && factory.Statistics.IsStatisticsEnabled) { factory.StatisticsImplementor.SecondLevelCachePut(persister.Cache.RegionName); } } }
public void Add(DomainName name, RecordType recordType, RecordClass recordClass, DnsCacheRecordList <DnsRecordBase> records, int timeToLive) { CacheKey key = new CacheKey(name, recordType, recordClass); _cache.TryAdd(key, new CacheValue(records, timeToLive)); }
public CacheKeyInfo(CacheKey cacheKey, object param) { this.cacheKey = cacheKey; this.param = param; }
private bool TryGetCacheValue(SqlConnectionStringBuilder builder, out CachedInfo value) { CacheKey key = new CacheKey(builder); return(_cache.TryGetValue(key, out value)); }
internal RedisQueue(RedisCluster redis, CacheKey key) { _redis = redis; _key = key; }
// TODO: this method is terribly long. Shorten protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var cacheCowHeader = new CacheCowHeader(); string uri = request.RequestUri.ToString(); TraceWriter.WriteLine("{0} - Starting SendAsync", TraceLevel.Verbose, request.RequestUri.ToString()); // check if needs to be ignored if (_ignoreRequestRules(request)) { return(await base.SendAsync(request, cancellationToken).ConfigureAwait(false)); // EXIT !! _________________ } IEnumerable <string> varyHeaders; if (!VaryHeaderStore.TryGetValue(uri, out varyHeaders)) { varyHeaders = DefaultVaryHeaders; } var cacheKey = new CacheKey(uri, request.Headers.Where(x => varyHeaders.Any(y => y.Equals(x.Key, StringComparison.CurrentCultureIgnoreCase))) .SelectMany(z => z.Value) ); // get from cache and verify response HttpResponseMessage cachedResponse; ResponseValidationResult validationResultForCachedResponse = ResponseValidationResult.NotExist; TraceWriter.WriteLine("{0} - Before TryGetValue", TraceLevel.Verbose, request.RequestUri.ToString()); cachedResponse = await _cacheStore.GetValueAsync(cacheKey).ConfigureAwait(false); cacheCowHeader.DidNotExist = cachedResponse == null; TraceWriter.WriteLine("{0} - After TryGetValue: DidNotExist => {1}", TraceLevel.Verbose, request.RequestUri.ToString(), cacheCowHeader.DidNotExist); if (!cacheCowHeader.DidNotExist.Value) // so if it EXISTS in cache { TraceWriter.WriteLine("{0} - Existed in the cache. CacheControl Headers => {1}", TraceLevel.Verbose, request.RequestUri.ToString(), cachedResponse.Headers.CacheControl.ToString()); cachedResponse.RequestMessage = request; validationResultForCachedResponse = ResponseValidator(cachedResponse); } TraceWriter.WriteLine("{0} - After ResponseValidator => {1}", TraceLevel.Verbose, request.RequestUri, validationResultForCachedResponse); // PUT/PATCH/DELETE validation if (request.Method.IsPutPatchOrDelete() && validationResultForCachedResponse.IsIn( ResponseValidationResult.OK, ResponseValidationResult.MustRevalidate)) { ApplyPutPatchDeleteValidationHeaders(request, cacheCowHeader, cachedResponse); return(await base.SendAsync(request, cancellationToken).ConfigureAwait(false)); // EXIT !! _____________________________ } // here onward is only GET only. See if cache OK and if it is then return if (validationResultForCachedResponse == ResponseValidationResult.OK) { cacheCowHeader.RetrievedFromCache = true; return(cachedResponse.AddCacheCowHeader(cacheCowHeader)); // EXIT !! ____________________________ } // if stale else if (validationResultForCachedResponse == ResponseValidationResult.Stale) { cacheCowHeader.WasStale = true; var isFreshOrStaleAcceptable = IsFreshOrStaleAcceptable(cachedResponse, request); if (isFreshOrStaleAcceptable.HasValue && isFreshOrStaleAcceptable.Value) // similar to OK { // TODO: CONSUME AND RELEASE Response !!! return(cachedResponse.AddCacheCowHeader(cacheCowHeader)); // EXIT !! ____________________________ } else { validationResultForCachedResponse = ResponseValidationResult.MustRevalidate; // revalidate } } // cache validation for GET else if (validationResultForCachedResponse == ResponseValidationResult.MustRevalidate) { ApplyGetCacheValidationHeaders(request, cacheCowHeader, cachedResponse); } // _______________________________ RESPONSE only GET ___________________________________________ var serverResponse = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); // HERE IS LATE FOR APPLYING EXCEPTION POLICY !!! TraceWriter.WriteLine("{0} - After getting response", TraceLevel.Verbose, request.RequestUri.ToString()); if (request.Method != HttpMethod.Get) // only interested here if it is a GET - this line really never called - only GET gets here { return(serverResponse); } // in case of MustRevalidate with result 304 if (validationResultForCachedResponse == ResponseValidationResult.MustRevalidate && serverResponse.StatusCode == HttpStatusCode.NotModified) { TraceWriter.WriteLine("{0} - Got 304 from the server and ResponseValidationResult.MustRevalidate", TraceLevel.Verbose, request.RequestUri.ToString()); cachedResponse.RequestMessage = request; cacheCowHeader.RetrievedFromCache = true; TraceWriter.WriteLine("{0} - NotModified", TraceLevel.Verbose, request.RequestUri.ToString()); await UpdateCachedResponseAsync(cacheKey, cachedResponse, serverResponse, _cacheStore).ConfigureAwait(false); ConsumeAndDisposeResponse(serverResponse); return(cachedResponse.AddCacheCowHeader(cacheCowHeader).CopyOtherCacheCowHeaders(serverResponse)); // EXIT !! _______________ } var validationResult = ResponseValidator(serverResponse); switch (validationResult) { case ResponseValidationResult.MustRevalidate: case ResponseValidationResult.OK: TraceWriter.WriteLine("{0} - ResponseValidationResult.OK or MustRevalidate", TraceLevel.Verbose, request.RequestUri.ToString()); // prepare ResponseStoragePreparationRules(serverResponse); // re-create cacheKey with real server accept // if there is a vary header, store it if (serverResponse.Headers.Vary != null) { varyHeaders = serverResponse.Headers.Vary.Select(x => x).ToArray(); IEnumerable <string> temp; if (!VaryHeaderStore.TryGetValue(uri, out temp)) { VaryHeaderStore.AddOrUpdate(uri, varyHeaders); } } // create real cacheKey with correct Vary headers cacheKey = new CacheKey(uri, request.Headers.Where(x => varyHeaders.Any(y => y.Equals(x.Key, StringComparison.CurrentCultureIgnoreCase))) .SelectMany(z => z.Value) ); // store the cache CheckForCacheCowHeader(serverResponse); await _cacheStore.AddOrUpdateAsync(cacheKey, serverResponse).ConfigureAwait(false); TraceWriter.WriteLine("{0} - After AddOrUpdate", TraceLevel.Verbose, request.RequestUri.ToString()); break; default: TraceWriter.WriteLine("{0} - ResponseValidationResult. Other", TraceLevel.Verbose, request.RequestUri.ToString()); TraceWriter.WriteLine("{0} - Before TryRemove", TraceLevel.Verbose, request.RequestUri.ToString()); await _cacheStore.TryRemoveAsync(cacheKey); TraceWriter.WriteLine("{0} - After TryRemoveAsync", TraceLevel.Verbose, request.RequestUri.ToString()); cacheCowHeader.NotCacheable = true; break; } TraceWriter.WriteLine("{0} - Before returning response", TraceLevel.Verbose, request.RequestUri.ToString()); return(serverResponse.AddCacheCowHeader(cacheCowHeader)); }