/// <summary> /// Gets a subset of search results to search in based on the current criteria /// </summary> /// <param name="criteriaSet"></param> /// <returns>Search subset</returns> protected virtual SearchSubset GetSearchSubset(SearchCriteriaSet criteriaSet) { ICacheable finalEntry = null; int hashSum = criteriaSet.DescriptionFilter.GetHashCode(); int i, n = criteriaSet.Count; for (i = 0; i < n; i++) { ISearchCriteria criteria = criteriaSet[i]; //combine the current hash with the pervious hash hashSum = hashSum ^ criteria.GetHashCode(); //check if a subset is cached for this hash ICacheable entry = SearchSubsetsCache.Instance.GetEntry(hashSum); if (entry != null) { criteriaSet.StartCriteriaIndex = i; finalEntry = entry; } else { break; } } SearchSubset subset = null; if (finalEntry != null) { subset = finalEntry.GetClone() as SearchSubset; } return(subset); }
public UserManager(IRepository <User> userContext, IDataSerialization serializer, ICacheable cacheProvider) { dataSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _cache = cacheProvider ?? throw new ArgumentNullException(nameof(cacheProvider)); _userRepository = userContext ?? throw new ArgumentNullException(nameof(userContext)); _cache.SetInstance(_userRepository.GetAll().ToList()); }
public void Cleared(ICacheable obj) { if (CacheCleared != null) { CacheCleared(obj); } }
/// <summary> /// Performs a search /// </summary> /// <param name="dataSource">Traffic data accesssor</param> /// <param name="criteriaSet">Set of criteria for the search</param> /// <param name="result">The search result</param> public void Search(ITrafficDataAccessor dataSource, SearchCriteriaSet criteriaSet, ISearchResult result) { _stopSearch = false; //check the search results cache int hash = GetSearchHash(dataSource, criteriaSet); ICacheable entry = SearchResultCache.Instance.GetEntry(hash); ISearchResult cachedResult = null; if (entry != null) { cachedResult = entry.Reserve() as ISearchResult; entry.Release(); } if (cachedResult == null) { //check for a subset SearchSubset subset = GetSearchSubset(criteriaSet); if (subset == null) { FullSearch(dataSource, criteriaSet, result); } else { SubsetSearch(dataSource, criteriaSet, result, subset); } //cache the search SearchResultCache.Instance.Add(hash, new CacheEntry(result)); } else { result.AddRange(cachedResult); } }
public void Getted(ICacheable obj) { if (CacheGetted != null) { CacheGetted(obj); } }
private void TryCache(ICacheable cacheable) { if (cacheable == null) { return; } var cacheModels = kernel.GetAssignableHandlers(typeof(IVisitCacheable)); foreach (var cache in cacheModels) { IVisitCacheable visitor = null; try { visitor = cache.Resolve(CreationContext.Empty) as IVisitCacheable; if (visitor == null) { throw new DittoConfigurationException("Problem with resolution of {0}", cache.ComponentModel.Implementation); } cacheable.Accept(visitor); } finally { if (visitor != null) { kernel.ReleaseComponent(visitor); } } } }
public HomeController( ICPFileService cpFileService, IDiagnoseService diagnoseService, IDiagService diagService, IHospitalPracticeService hospitalPracticeService, IPatientService patientService, IUsedDrugService usedDrugService, ILogger <HomeController> logger, MedicDataLocalization medicDataLocalization, ICacheable medicCache, IMedicLoggerService medicLoggerService, IFormattableFactory formattableFactory) : base(medicDataLocalization) { CPFileService = cpFileService ?? throw new ArgumentNullException(nameof(cpFileService)); DiagnoseService = diagnoseService ?? throw new ArgumentNullException(nameof(diagnoseService)); DiagService = diagService ?? throw new ArgumentNullException(nameof(diagService)); HospitalPracticeService = hospitalPracticeService ?? throw new ArgumentNullException(nameof(hospitalPracticeService)); PatientService = patientService ?? throw new ArgumentNullException(nameof(patientService)); UsedDrugService = usedDrugService ?? throw new ArgumentNullException(nameof(usedDrugService)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); MedicCache = medicCache ?? throw new ArgumentNullException(nameof(medicCache)); MedicLoggerService = medicLoggerService ?? throw new ArgumentNullException(nameof(medicLoggerService)); FormattableFactory = formattableFactory ?? throw new ArgumentNullException(nameof(formattableFactory)); }
protected override async Task <IResource> GetResourceAsync(ResourcePath path) { ICacheable cacheable = null; if (m_Resources.TryGetValue(path.Path, out cacheable)) { return((IResource)(cacheable)); } else { LogService.Logger.Log(LogService.LogType.LT_DEBUG, "ResService Cache Missed"); IResource newRes = null; IResourceCreator creator = GetCreator(path.GetExt()); if (creator == null) { newRes = new UnityResource <UnityEngine.Object>(); } else { newRes = creator.Create(); } if (newRes != null) { await newRes.LoadAsync(path); newRes = (IResource)(m_Resources.GetOrAdd(path.Path, newRes)); } return(newRes); } }
/// <summary> /// Acquires a mesh for given resolution. /// </summary> /// <param name="resolution"></param> /// <returns></returns> public TriangleSoup2f AcquireFilled(float resolution) { // We first check the cache. if (filledCache != null) { ICacheable cacheable = filledCache.FindAndTouch(resolution); if (cacheable != null) { GlyphShapeCache data = cacheable as GlyphShapeCache; return(data.Data); } } // Otherwise not found, we create it. TriangleSoup2f soup = new TriangleSoup2f(); outline.Tesselate(resolution, soup); if (filledCache != null) { // We ignore if already there. filledCache.Add(resolution, new GlyphShapeCache(soup)); } return(soup); }
public OrderManager(IRepository <Order> data, IDataSerialization serializer, ICacheable cacheProvider) { _orderRepository = data ?? throw new ArgumentNullException(nameof(data)); _dataSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _cache = cacheProvider ?? throw new ArgumentNullException(nameof(cacheProvider)); _cache.SetInstance(_orderRepository.GetAll().ToList()); }
public LookupsBaseController(IPatientService patientService, IHealthRegionService healthRegionService, ICacheable medicCache, MedicDataLocalization medicDataLocalization) : base(patientService, medicCache, medicDataLocalization) { _healthRegionService = healthRegionService ?? throw new ArgumentNullException(nameof(healthRegionService)); }
public ICacheable CreateCache(string key, ICacheable content) { var cacheItem = new CachedItem <ICacheable>(content); RemoveOldCache(key); _cachedItems.Add(key, cacheItem); return(cacheItem.Content); }
public static void RemoveFromCache(ICacheable entity) { if (entity == null) { return; } RemoveFromEntityCache(entity); }
public void Add(ICacheable obj) { if (_collection.ContainsKey(obj.Id)) { TrelloConfiguration.Log.Info($"Discovered second instance of {obj.GetType().Name} with ID {obj.Id}"); } _collection[obj.Id] = obj; }
public AppliancesDistribution(IRepository <Product> productContext, IDataSerialization serializer, ICacheable cacheProvider, IConverterService converterProvider, IUnitOfWork unitOfWork) { _productRepository = productContext ?? throw new ArgumentNullException(nameof(productContext)); _dataSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _cache = cacheProvider ?? throw new ArgumentNullException(nameof(cacheProvider)); converterProvider.GetExchengesRateAsync(new CancellationToken()); _cache.SetInstance(_productRepository.GetAll().ToList()); _unitOfWork = unitOfWork; }
protected virtual void OnDataLengthChanged(ICacheable obj) { DataLengthChangedDelegate handler = this.DataLengthChanged; if (handler != null) { handler(obj); } }
protected void Validate(ICacheable asset) { String key = asset.CacheKey; if (String.IsNullOrWhiteSpace(key)) { throw new CacheException($"Asset key can not be empty"); } }
void IGlobalCache.AddCacheable(ICacheable item) { var weakReference = new CustomWeakReference(item); //AssertTrackingDependencies(weakReference); lock (_syncRoot) { _refreshableSet.Add(weakReference); } }
private static Type GetRealType(this ICacheable entity) { var entityType = entity.GetType(); if (entityType.BaseType != null && entityType.Namespace == "System.Data.Entity.DynamicProxies") { entityType = entityType.BaseType; } return(entityType); }
/// <summary> /// Commits a response to the memory cache /// </summary> /// <param name="reqHeaderId"></param> /// <param name="data"></param> private void BufferSaveResponse(int reqHeaderId, byte[] data) { ICacheable entry = RequestDataCache.Instance.GetEntry(_objectId ^ reqHeaderId); if (entry != null) { RequestResponseBytes reqData = entry.Reserve() as RequestResponseBytes; reqData.RawResponse = data; entry.Release(); } }
private static void AddCache(ICacheable obj) { try { CacheService.Set(obj); } catch (Exception ex) { LogProxy.Error(ex, false); } }
/// <summary> /// Checks if a object has been cached past the defined caching time or if internally the object has been marked as expired /// </summary> /// <param name="value">Object to check for expiry</param> /// <returns>True if the object has expired</returns> protected bool CheckIsExpired(ICacheable value) { bool isExpired = false; TimeSpan timeToExpire; if (_cacheExpiryTimes.TryGetValue(value.GetType(), out timeToExpire)) { isExpired = value.TimeCachedUtc.HasValue && value.TimeCachedUtc.Value.Add(timeToExpire) < DateTime.UtcNow; } return(isExpired || value.HasExpired); }
public bool Add(T key, ICacheable cacheable) { lock (syncRoot) { if (cacheable == null) { throw new ArgumentNullException("cacheable"); } CachableData dummy; if (sorted.TryGetValue(key, out dummy)) { return(false); } // Cacheable was cached, must throw exception if already cached. cacheable.Cached(); // Create data. CachableData data = new CachableData(); data.Data = cacheable; data.Score = initialScore; data.EvalData = new object[evaluators.Length]; for (int i = 0; i < evaluators.Length; i++) { data.EvalData[i] = evaluators[i].Data; } // Add touched event. data.Data.OnTouch += new Action <ICacheable>(delegate(ICacheable unused) { lock (syncRoot) { // Perform the touch. for (int j = 0; j < evaluators.Length; j++) { data.Score = evaluators[j].Touch(data.EvalData[j], data.Score); } // Touching certainly ensures at least 0.0f value. data.Score = Math.MathHelper.Max(0.0f, data.Score); data.Score = Math.MathHelper.Min(maxScore, data.Score); } }); // Resource is created in touched state, no need to re-touch. This // method may throw if key already exists, but we already prechecked for uniquness. sorted.Add(key, data); return(true); } }
public ICacheable FindAndTouch(T key) { lock (syncRoot) { ICacheable c = this.Find(key); if (c != null) { c.Touch(); } return(c); } }
/// <summary> /// Retrieves the request bytes from disk or from the memory cache /// </summary> /// <param name="requestHeaderId"></param> /// <returns></returns> public byte[] LoadRequestData(int requestHeaderId) { byte[] result = new byte[0]; try { lock (_lockData) //critical section begins { TVRequestInfo reqInfo; if (_requestInfos.TryGetValue(requestHeaderId, out reqInfo) && reqInfo.RequestLength > 0) { //check if the request is already in the buffer ICacheable entry = RequestDataCache.Instance.GetEntry(_objectId ^ requestHeaderId); RequestResponseBytes reqData = null; if (entry != null) { reqData = entry.Reserve() as RequestResponseBytes; entry.Release(); } if (reqData != null && reqData.RawRequest != null) { result = reqData.RawRequest; } else { //load request from disk int length = reqInfo.RequestLength; long startPosition = reqInfo.RequestStartPosition; result = DataRead(startPosition, length); //save request to buffer if is not null if (result.Length != 0) { BufferSaveRequest(requestHeaderId, result); } } if (reqInfo.IsEncrypted && result != null && result.Length > 0) { //decrypt the request result = Encryptor.Decrypt(result); } } } //critical section ends } catch (Exception ex) { SdkSettings.Instance.Logger.Log(TraceLevel.Error, "Cannot load request data for request id: {0} . Stack trace: {1}", requestHeaderId, ex.ToString()); } return(result); }
/// <summary> /// Fügt ein neues Objekt in den Cache ein /// </summary> /// <param name="Cacheable">If set to true, the object will be ignored if it already exists</param> /// <param name="ignoreIfExists">If set to true, existing objects will be ignored</param> public void AddObject(ICacheable Cacheable, bool ignoreIfExists = true) { lock (_lockObj) { if (enableCaching) { if (Cacheable == null) { throw new BaseException(10001, "Das Cache-Object darf nicht null sein"); } else { // If we have a TypedWeakReference here, we need to store it by the type of its target if (Cacheable.GetType().BaseType == typeof(TypedWeakReference)) { var wr = (Cacheable as TypedWeakReference); var _key = new CacheKeyItem(wr.TargetType, PrepareKey(Cacheable.Key)); if (wr.IsAlive && !cache.ContainsKey(_key)) { cache.Add(_key, Cacheable); } // If it not not alive, override the object else if (!wr.IsAlive) { cache[_key] = Cacheable; } else { if (!ignoreIfExists) { throw new BaseException(10003, String.Format("Ein Cache-Objekt mit dem gleichen Schlüssel ist bereits vorhanden. (Key: {0})", Cacheable.Key.ToString())); } } } else { if (!cache.ContainsKey(new CacheKeyItem(Cacheable.GetType(), PrepareKey(Cacheable.Key)))) { cache.Add(new CacheKeyItem(Cacheable.GetType(), PrepareKey(Cacheable.Key)), Cacheable); } else { if (!ignoreIfExists) { throw new BaseException(10003, String.Format("Ein Cache-Objekt mit dem gleichen Schlüssel ist bereits vorhanden. (Key: {0})", Cacheable.Key.ToString())); } } } } } } }
/// <summary> /// Fügt ein neues Objekt in den Cache ein /// </summary> /// <param name="Cacheable">If set to true, the object will be ignored if it already exists</param> /// <param name="ignoreIfExists">If set to true, existing objects will be ignored</param> public void AddObject(ICacheable Cacheable, bool ignoreIfExists = true) { lock (_lockObj) { if (enableCaching) { if (Cacheable == null) { throw new CoreException("S-0000002", "9c2917a6-41a7-4dc6-876c-43e6336a610f", ExceptionType.Unexpected); } else { // If we have a TypedWeakReference here, we need to store it by the type of its target if (Cacheable.GetType().BaseType == typeof(TypedWeakReference)) { var wr = (Cacheable as TypedWeakReference); var _key = new CacheKeyItem(wr.TargetType, PrepareKey(Cacheable.Key)); if (wr.IsAlive && !cache.ContainsKey(_key)) { cache.Add(_key, Cacheable); } // If it not not alive, override the object else if (!wr.IsAlive) { cache[_key] = Cacheable; } else { if (!ignoreIfExists) { throw new CoreException("S-0000005", "17771eac-511e-4d83-bd95-288417867990", ExceptionType.Unexpected, () => Cacheable.Key.ToString()); } } } else { if (!cache.ContainsKey(new CacheKeyItem(Cacheable.GetType(), PrepareKey(Cacheable.Key)))) { cache.Add(new CacheKeyItem(Cacheable.GetType(), PrepareKey(Cacheable.Key)), Cacheable); } else { if (!ignoreIfExists) { throw new CoreException("S-0000005", "8ba4d284-62f7-4c53-8c95-2c9efe5ff3fd", ExceptionType.Unexpected, () => Cacheable.Key.ToString()); } } } } } } }
public MyCacheObject(ICacheable obj, DateTime overdueTime) { this.Obj = obj; if (obj is IFixCache && ((IFixCache)obj).IsFixCache) { this.OverdueTime = DateTime.MaxValue; } else { this.OverdueTime = overdueTime; } }
private async Task <TResponse> GetFromMemoryCache(ICacheable cacheable, RequestHandlerDelegate <TResponse> next) { bool isExist = _cache.TryGetValue(cacheable.CacheSettings.Key, out TResponse response); if (isExist) { return(response); } response = await next(); _cache.Set(cacheable.CacheSettings.Key, response, cacheable.CacheSettings.Value); return(response); }
private static void RemoveFromEntityCache(ICacheable entity) { var type = entity.GetRealType(); if (EntityCache.ContainsKey(type)) { if (EntityCache[type].ContainsKey(entity.Id)) { var ce = EntityCache[type][entity.Id]; ce.Workspace.Dispose(); EntityCache[type].Remove(ce.Cacheable.Id); } } }