public void RunRoutine(Key key, MethodInterceptionArgs args, ICache cache, Mutex mutex, Action routine) { using (mutex) //avoid mutex being lost through garbage collection (unsure if required) see: odetocode.com/blogs/scott/archive/2004/08/20/the-misunderstood-mutex.aspx { for (;;) { routine(); cache.Add(key, args.ReturnValue); Thread.Sleep(key.DurationToStore - TimeBeforeExpiryToRunRoutine); } } }
/// <summary> /// Processes a <see cref="PathRequest"/> /// </summary> /// <param name="pathRequest"></param> public void Process(PathRequest <TPath> pathRequest) { if (_pathCache == null || !_pathCache.TryGetValue(pathRequest, out var path)) { path = _algorithm.FindPath(NodeNetwork, pathRequest); _pathCache?.Add(pathRequest, path); } var succes = path != null?_algorithm.ValidatePath(NodeNetwork, pathRequest, path) : false; if (path == null) { path = _algorithm.GetDefaultPath(NodeNetwork, pathRequest); } Debug.WriteLine(succes ? $"{_algorithm.GetType()} has found a path" : $"{_algorithm.GetType()} did not find a path :("); pathRequest.FinishSolvePath(path, succes); }
/// <summary> /// Gets a cached value. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="cacheRegion">The cache region.</param> /// <param name="cacheKey">The cache key.</param> /// <param name="addFunction">The function used to provide a value if no value is cached yet.</param> /// <remarks> /// This uses the TOM.NET Session Cache if available (it typically is during rendering/publishing). /// </remarks> /// <returns>The cached value.</returns> protected T GetCachedValue <T>(string cacheRegion, string cacheKey, Func <T> addFunction) { ICache cache = Session.Cache; object cachedValue = cache?.Get(cacheRegion, cacheKey); T result; if (cachedValue == null) { result = addFunction(); cache?.Add(cacheRegion, cacheKey, result); } else { result = (T)cachedValue; } return(result); }
/// <summary> /// This method adds an instance of Produc in the cache with notification based Dependency. /// </summary> /// <param name="customer"> customer that is to be added. </param> private static void AddCustomerToCacheWithDependency(Customer customer) { string endPoint = ConfigurationManager.AppSettings["EndPoint"]; string authKey = ConfigurationManager.AppSettings["AuthKey"]; string monitoredCollection = ConfigurationManager.AppSettings["MonitoredCollection"]; string leaseCollection = ConfigurationManager.AppSettings["LeaseCollection"]; string databaseName = ConfigurationManager.AppSettings["DatabaseName"]; string providerName = ConfigurationManager.AppSettings["ProviderName"]; IDictionary <string, string> param = new Dictionary <string, string>(); param.Add("Key", customer.Id); param.Add("MonitoredCollectionName", monitoredCollection); param.Add("LeaseCollectionName", leaseCollection); CacheItem cacheItem = new CacheItem(customer); CustomDependency cosmosDbDependency = new CustomDependency(providerName, param); cacheItem.Dependency = cosmosDbDependency; // Inserting Loaded customer into cache with key: [item:1] _cache.Add(customer.Id, cacheItem); }
public virtual void Register(IWithId objectWithId) { if (string.IsNullOrEmpty(objectWithId.Id)) { return; } if (!ContainsObjectWithId(objectWithId.Id)) { _entities.Add(objectWithId); return; } var existing = Get(objectWithId.Id); if (ReferenceEquals(existing, objectWithId)) { return; } throw new NotUniqueIdException(objectWithId.Id); }
public List <SysDict> GetDictsByKey(string key) { string cachekey = PkPmCacheKeys.SysDictByKeyFmt.Fmt(key); var dictCategory = cache.Get(cachekey); if (dictCategory != null) { return(dictCategory); } else { List <SysDict> result = new List <SysDict>(); dictCategory = rep.GetByCondition(r => r.KeyValue == key && r.CategoryId == -1 && r.Status == 1); if (dictCategory != null && dictCategory.Count > 0) { result = rep.GetByConditionSort(r => r.CategoryId == dictCategory[0].Id, new SortingOptions <SysDict>(r => new { r.OrderNo })); } cache.Remove(cachekey); cache.Add(cachekey, result); return(result); } }
public void CreateEvents(IBuildConfiguration buildConfiguration, IModel model) { try { _model = model; _buildConfiguration = buildConfiguration; _allModelContainerDescriptors = model.Root.GetAllContainersAndSelf <IContainer>().ToEntityDescriptorMapList(); _sourceCriteriaTargetContainerCache = new Cache <DescriptorCriteria, IEnumerable <IContainer> >(); _applicationTransportTargetContainerCache = new Cache <DescriptorCriteria, IEnumerable <IContainer> >(); //Cache all containers where the event group builder will be created using the source criteria foreach (var eventGroupBuilder in _buildConfiguration.EventGroups) { if (_sourceCriteriaTargetContainerCache.Contains(eventGroupBuilder.SourceCriteria)) { continue; } _sourceCriteriaTargetContainerCache.Add(eventGroupBuilder.SourceCriteria, _allModelContainerDescriptors.AllSatisfiedBy(eventGroupBuilder.SourceCriteria)); } foreach (var eventGroupBuilder in _buildConfiguration.EventGroups) { createEventGroupFrom(eventGroupBuilder, buildConfiguration.Molecules); } } finally { _model = null; _allModelContainerDescriptors = null; _sourceCriteriaTargetContainerCache.Clear(); _sourceCriteriaTargetContainerCache = null; _applicationTransportTargetContainerCache.Clear(); _applicationTransportTargetContainerCache = null; _buildConfiguration = null; } }
public void ConverterCacheEnumeratorTests() { ICache cache = InstantiateCache(); IConverter conv = new ConvertDown(); for (int i = 0; i < 3; i++) { cache.Add(i, i + 1); } ICacheEnumerator cacheEnumerator = cache.GetEnumerator(); ICacheEnumerator convEnum = ConverterCollections.GetCacheEnumerator(cacheEnumerator, conv, conv, conv); Assert.IsNotNull(convEnum); Assert.IsTrue(convEnum.MoveNext()); convEnum.MoveNext(); convEnum.MoveNext(); Assert.IsFalse(convEnum.MoveNext()); convEnum.Reset(); Assert.IsTrue(convEnum.MoveNext()); object o = convEnum.Current; ICacheEntry entry = convEnum.Entry; Assert.AreEqual(o, entry); Assert.AreEqual(entry.Key, convEnum.Key); Assert.AreEqual(entry.Value, convEnum.Value); Assert.AreEqual(entry.Key, conv.Convert(cacheEnumerator.Key)); Assert.AreEqual(entry.Value, conv.Convert(cacheEnumerator.Value)); Assert.IsInstanceOf(typeof(ConverterCollections.ConverterCacheEnumerator), convEnum); ConverterCollections.ConverterCacheEnumerator cce = convEnum as ConverterCollections.ConverterCacheEnumerator; Assert.IsNotNull(cce); Assert.AreEqual(cce.ConverterKeyUp, conv); Assert.AreEqual(cce.ConverterValueUp, conv); }
/// <summary> /// Gets the compiled schematron from a given path. /// </summary> /// <param name="path">The path where to find the </param> /// <returns></returns> public CompiledXslt GetCompiledSchematron(string path) { if (path == null) { throw new ArgumentNullException("path"); } string cacheKey = path; FileInfo fileInfo; if (string.IsNullOrEmpty(this.basePath)) { string stylesheetPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path); fileInfo = new FileInfo(stylesheetPath); } else { string combinedPath = Path.Combine(this.basePath, path); fileInfo = new FileInfo(combinedPath); } CompiledXslt compiledXsltEntry = null; lock (lockObject) { if (cache.TryGetValue(cacheKey, out compiledXsltEntry)) { // pre-compiled schematron found } else { compiledXsltEntry = new CompiledXslt(fileInfo); cache.Add(cacheKey, compiledXsltEntry); } } return(compiledXsltEntry); }
/// <summary> /// This method adds file based dependency /// </summary> private static void AddFileBasedDependency() { string dependecyfile = Environment.GetEnvironmentVariable("NCHOME") + @"\Samples\dotnetcore\Dependencies\FileBasedDependency\DependencyFile\foobar.txt"; // Generate a new instance of product Product product = new Product { Id = 52, Name = "Filo Mix", Category = "Grains/Cereals", UnitPrice = 46 }; // Adding item dependent on file CacheItem cacheItem = new CacheItem(product); cacheItem.Dependency = new FileDependency(dependecyfile); _cache.Add("Product:" + product.Id, cacheItem); Console.WriteLine("\nItem 'Product:52' added to cache with file dependency. "); // To verify that the dependency is working, uncomment the following code. // Any change in the file will cause invalidation of cache item and thus the item will be removed from cache. // Following code modifies the file and then verifies the existence of item in cache. //// Modify file programmatically //ModifyDependencyFile(dependecyfile); //////... and then check for its existence //object item = _cache.Get<object>("Product:52"); //if (item == null) //{ // Console.WriteLine("Item has been removed due to file dependency."); //} //else //{ // Console.WriteLine("File based dependency did not work. Dependency file located at " + dependecyfile + " might be missing or file not changed within the given interval."); //} // Remove sample data from Cache to _cache.Remove("Product:" + product.Id); }
public async Task <IActionResult> PostAsync(string key, [FromBody] string value) { try { if (await Task.Run(() => !_cache.Contains(key))) { await Task.Run(() => _cache.Add(key, new CacheItem(value) { Tags = new Tag[] { _tag } })); return(CreatedAtAction(nameof(GetByIdAsync), key, value)); } else { return(BadRequest("Item already exists in cache")); } } catch (Exception e) { return(BadRequest($"Something went wrong. Details \n{e}")); } }
private string GetAuthTokenCachedInternal(string login, string password, string locale, int employeeId, int?clientId, bool updateToken) { var baseKey = new List <string> { "Service.Hotels:TestSupplier:AuthToken", locale, employeeId.ToString() }; if (clientId.HasValue) { baseKey.Add(clientId.ToString()); } var key = string.Join("_", baseKey); string token = string.Empty; if (updateToken || !_cache.Get <string>(key, out token)) { var period = new TimeSpan(23, 0, 0); token = GetAuthTokenInternal(login, password, locale); _cache.Add <string>(key, token, period); } return(token); }
private IEditInSimulationPresenter setupEditPresenter(IEntity entity) { var entityType = entity.GetType(); var showPresenter = _cacheShowPresenter[entityType]; if (showPresenter == null) { //create a new one and add it to the cache showPresenter = _showPresenterFactory.PresenterFor(entity); if (showPresenter == null) { return(null); } showPresenter.InitializeWith(CommandCollector); _cacheShowPresenter.Add(entityType, showPresenter); } _view.SetEditView(showPresenter.BaseView); showPresenter.Simulation = _simulation; showPresenter.Edit(entity); return(showPresenter); }
protected override void DoStart() { // first, cache all (static) molecules used in model (besides DRUG) foreach (var flatModel in _flatModelRepo.All()) { var modelName = flatModel.Id; var molecules = (from mcm in _flatModelContainerMoleculeRepo.All() where mcm.Model.Equals(modelName) where mcm.IsPresent where !mcm.Molecule.Equals(CoreConstants.Molecule.Drug) select mcm.Molecule).Distinct().ToList(); _moleculesForModel.Add(modelName, molecules); } // second, cache MCM-info by {Model, Container, Molecule} foreach (var flatMCM in _flatModelContainerMoleculeRepo.All()) { var key = new ModelContainerMoleculeKey(flatMCM.Model, flatMCM.Id, flatMCM.Molecule); _mcmProperties.Add(key, flatMCM); } }
private ICustomParametersPresenter presenterFor(ITreeNode node) { if (!_parameterPresenterCache.Contains(node)) { var hasParameters = allVisibleParametersIn(node).Any(); var presenter = _parametersPresenterMapper.MapFrom(node); if (presenter != null && (hasParameters || presenter.ForcesDisplay)) { presenter.InitializeWith(CommandCollector); presenter.StatusChanged += OnStatusChanged; presenter.Description = descriptionFor(node); } else { presenter = _noItemInSelectionPresenter; presenter.Description = NoSelectionCaption; } _parameterPresenterCache.Add(node, presenter); } return(_parameterPresenterCache[node]); }
/// <summary> /// 获取sql /// </summary> /// <param name="className"></param> /// <param name="propertyInfos"></param> /// <param name="sqlType">SQL 类型 1 insert 2 delete 3 update 4 select</param> /// <returns></returns> public string GetSQL <T>(T t, string tableName, string className, PropertyInfo[] propertyInfos, int sqlType, out List <MySqlParameter> parameters) where T : class { string result = null; parameters = new List <MySqlParameter>(); //去缓存查找一次是否存在该类名称的缓存的SQL List <SqlInfo> sqlInfoList = _cache.Query <List <SqlInfo> >(new CacheFilter() { Key = className + "_ORM" }); //如果缓存中没有 if (sqlInfoList == null || sqlInfoList.Count == 0) { sqlInfoList = InitSqlInfos <T>(t, tableName, className, propertyInfos); _cache.Add(new CacheModel() { Key = className + "_ORM", Data = sqlInfoList }); } SqlInfo sqlInfo = sqlInfoList.FirstOrDefault(x => x.Type == sqlType); if (sqlInfo != null) { result = sqlInfo.SqlString; parameters = sqlInfo.Parameters; } return(result); }
private async void ConsumePacket(Packet packet, CancellationToken ct) { try { cache.IncrementTotal(); //receive only portuguese data Task <Country> packetCountry = reverseGeocoding.GetCountry(packet.Latitude, packet.Longitude); if (await packetCountry == Country.Portugal) { List <Packet> vehiclePackets = cache.Add(packet.VehicleId, packet); if (vehiclePackets != null) { await service.Post(packet.VehicleId, vehiclePackets); } } } catch (Exception) { Console.WriteLine("Something went wrong"); } }
protected override IFormula CreateFormulaCloneFor(IFormula srcFormula) { // constant formulas are always cloned if (srcFormula.IsConstant()) { return(CloneFormula(srcFormula)); } // Check if target formula cache already contains the formula // to be cloned. This can happen if we are cloning // any substructure within the same building block // In this case, all formulas are already present in the // formula cache of this building block if (_formulaCache.Contains(srcFormula.Id)) { return(srcFormula); } // Check if the formula was already cloned. Return the cloned // formula if so. if (_clonedFormulasByOriginalFormulaId.Contains(srcFormula.Id)) { return(_clonedFormulasByOriginalFormulaId[srcFormula.Id]); } // Formula is neither present in the passed formula cahce nor // was already cloned. So create a new clone and insert it // in both target formula cache and the cache of all cloned formulas var clonedFormula = CloneFormula(srcFormula); _formulaCache.Add(clonedFormula); _clonedFormulasByOriginalFormulaId.Add(srcFormula.Id, clonedFormula); return(clonedFormula); }
private static async Task <IDocument> GetCachedDocument(Url urlObj, ICache <string, IDocument> cache) { IDocument document; if (cache == null) { document = await getPageAsync(urlObj); } else { if (cache.Contains(urlObj.Href)) { document = cache.Get(urlObj.Href); } else { document = await getPageAsync(urlObj); cache.Add(urlObj.Href, document); } } return(document); }
public async Task <Result> Handle(TRequest src) { var cacheData = src as ICacheble; if (cacheData != null) { (string key, string val) = cacheData.CacheKeyVal(); if (cache.Get <string>(key) == val) { return(Result.Ok(cache.Get <string>(key))); } else { var result = await request.Handle(src); if (result.IsSuccess) { cache.Add(key, val); } return(result); } } return(await request.Handle(src)); }
public Role GetRoleByCode(string Code) { var cacheKey = PkPmCacheKeys.GetRoleByRoleCode.Fmt(Code); var role = cacheRole.Get(cacheKey); if (role != null) { return(role); } var roles = roleRep.GetByCondition(r => r.Code == Code); if (roles.Count == 0) { return(new Role() { Id = -1, Name = "不存在" }); } else { cacheRole.Add(cacheKey, roles[0]); return(roles[0]); } }
public Member Caching(ref Member entity, bool update = false) { _cache.Add(entity.User.Id, ref entity); return(entity); }
/// <summary>申请任务分片</summary> /// <param name="server">申请任务的服务端</param> /// <param name="ip">申请任务的IP</param> /// <param name="pid">申请任务的服务端进程ID</param> /// <param name="count">要申请的任务个数</param> /// <param name="cache">用于设置全局锁的缓存对象</param> /// <returns></returns> public IList <JobTask> Acquire(String server, String ip, Int32 pid, Int32 count, ICache cache) { var list = new List <JobTask>(); if (!Enable) { return(list); } var step = Step; if (step <= 0) { step = 30; } //// 全局锁,确保单个作业只有一个线程在分配作业 //using var ck = cache.AcquireLock($"Job:{ID}", 5_000); using var ts = Meta.CreateTrans(); var start = Start; for (var i = 0; i < count; i++) { if (!TrySplit(start, step, out var end)) { break; } // 创建新的分片 var ti = new JobTask { AppID = AppID, JobID = ID, Start = start, End = end, BatchSize = BatchSize, }; ti.Server = server; ti.ProcessID = Interlocked.Increment(ref _idxBatch); ti.Client = $"{ip}@{pid}"; ti.Status = JobStatus.就绪; ti.CreateTime = DateTime.Now; ti.UpdateTime = DateTime.Now; //// 如果有模板,则进行计算替换 //if (!Data.IsNullOrEmpty()) ti.Data = TemplateHelper.Build(Data, ti.Start, ti.End); // 重复切片判断 var key = $"Job:{ID}:{start:yyyyMMddHHmmss}"; if (!cache.Add(key, ti, 30)) { var ti2 = cache.Get <JobTask>(key); XTrace.WriteLine("[{0}]重复切片:{1}", key, ti2?.ToJson()); using var span = DefaultTracer.Instance?.NewSpan($"antjob:AcquireDuplicate", ti2); } else { ti.Insert(); list.Add(ti); } // 更新任务 Start = end; start = end; } if (list.Count > 0) { // 任务需要ID,不能批量插入优化 //list.Insert(null); UpdateTime = DateTime.Now; Save(); ts.Commit(); } return(list); }
/// <summary> /// 添加一个缓存值 /// </summary> /// <param name="key">键</param> /// <param name="value">内容</param> /// <param name="expiry">时间</param> public bool Add(string key, object value, TimeSpan expiry) { return(_ICache.Add(key, value, expiry)); }
/// <summary> /// Query all the data from the database. /// </summary> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table.</param> /// <param name="fields">The list of fields to be queried.</param> /// <param name="orderBy">The order definition of the fields to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlTableHints"/> class.</param> /// <param name="cacheKey"> /// The key to the cache. If the cache key is present in the cache, then the item from the cache will be returned instead. Setting this /// to null would force to query from the database. /// </param> /// <param name="cacheItemExpiration">The expiration in minutes of the cache item.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="cache">The cache object to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>An enumerable list of data entity object.</returns> internal static async Task <IEnumerable <dynamic> > QueryAllAsyncInternalBase(this IDbConnection connection, string tableName, IEnumerable <Field> fields = null, IEnumerable <OrderField> orderBy = null, string hints = null, string cacheKey = null, int cacheItemExpiration = Constant.DefaultCacheItemExpirationInMinutes, int?commandTimeout = null, IDbTransaction transaction = null, ICache cache = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { // Get Cache if (cacheKey != null) { var item = cache?.Get(cacheKey, false); if (item != null) { return((IEnumerable <dynamic>)item.Value); } } // Check the fields if (fields?.Any() != true) { fields = DbFieldCache.Get(connection, tableName)?.Select(f => f.AsField()); } // Variables var commandType = CommandType.Text; var request = new QueryAllRequest(tableName, connection, fields, orderBy, hints, statementBuilder); var commandText = CommandTextCache.GetQueryAllText(request); var param = (object)null; // Before Execution if (trace != null) { var cancellableTraceLog = new CancellableTraceLog(commandText, param, null); trace.BeforeQueryAll(cancellableTraceLog); if (cancellableTraceLog.IsCancelled) { if (cancellableTraceLog.IsThrowException) { throw new CancelledExecutionException(commandText); } return(null); } commandText = (cancellableTraceLog.Statement ?? commandText); param = (cancellableTraceLog.Parameter ?? param); } // Before Execution Time var beforeExecutionTime = DateTime.UtcNow; // Actual Execution var result = await ExecuteQueryAsyncInternal(connection : connection, commandText : commandText, param : param, commandType : commandType, commandTimeout : commandTimeout, transaction : transaction, tableName : tableName, skipCommandArrayParametersCheck : true); // After Execution if (trace != null) { trace.AfterQueryAll(new TraceLog(commandText, param, result, DateTime.UtcNow.Subtract(beforeExecutionTime))); } // Set Cache if (cacheKey != null) { cache?.Add(cacheKey, result, cacheItemExpiration); } // Result return(result); }
/// <summary> /// Query all the data from the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="orderBy">The order definition of the fields to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlTableHints"/> class.</param> /// <param name="cacheKey"> /// The key to the cache. If the cache key is present in the cache, then the item from the cache will be returned instead. Setting this /// to null would force to query from the database. /// </param> /// <param name="cacheItemExpiration">The expiration in minutes of the cache item.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="cache">The cache object to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>An enumerable list of data entity object.</returns> internal static Task <IEnumerable <TEntity> > QueryAllAsyncInternalBase <TEntity>(this IDbConnection connection, IEnumerable <OrderField> orderBy = null, string hints = null, string cacheKey = null, int cacheItemExpiration = Constant.DefaultCacheItemExpirationInMinutes, int?commandTimeout = null, IDbTransaction transaction = null, ICache cache = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { // Get Cache if (cacheKey != null) { var item = cache?.Get(cacheKey, false); if (item != null) { return(Task.FromResult((IEnumerable <TEntity>)item.Value)); } } // Variables var commandType = CommandType.Text; var request = new QueryAllRequest(typeof(TEntity), connection, FieldCache.Get <TEntity>(), orderBy, hints, statementBuilder); var commandText = CommandTextCache.GetQueryAllText(request); var param = (object)null; // Database pre-touch for field definitions DbFieldCache.Get(connection, ClassMappedNameCache.Get <TEntity>()); // Before Execution if (trace != null) { var cancellableTraceLog = new CancellableTraceLog(commandText, param, null); trace.BeforeQueryAll(cancellableTraceLog); if (cancellableTraceLog.IsCancelled) { if (cancellableTraceLog.IsThrowException) { throw new CancelledExecutionException(commandText); } return(Task.FromResult <IEnumerable <TEntity> >(null)); } commandText = (cancellableTraceLog.Statement ?? commandText); param = (cancellableTraceLog.Parameter ?? param); } // Before Execution Time var beforeExecutionTime = DateTime.UtcNow; // Actual Execution var result = ExecuteQueryAsyncInternal <TEntity>(connection: connection, commandText: commandText, param: param, commandType: commandType, commandTimeout: commandTimeout, transaction: transaction, basedOnFields: false, skipCommandArrayParametersCheck: true); // After Execution if (trace != null) { trace.AfterQueryAll(new TraceLog(commandText, param, result, DateTime.UtcNow.Subtract(beforeExecutionTime))); } // Set Cache if (cacheKey != null /* && result.Result?.Any() == true */) { cache?.Add(cacheKey, result, cacheItemExpiration); } // Result return(result); }
public virtual void Add(CovariateValues covariateValues) => _covariateValuesCache.Add(covariateValues);
/// <remarks> /// Consider alternatives to instantiating instances /// of the specified types using Activator.CreateInstance. /// </remarks> public override void OnInvoke(MethodInterceptionArgs args) { Ensure.That<ArgumentNullException>(args.IsNotNull(), "args"); _cache = (ICache) Activator.CreateInstance(_cacheType); _keyCreationStrategy = (IFriendlyNameCreationStrategy) Activator.CreateInstance(_keyCreationStrategyType); if (_recalculationStrategyType.IsNotNull()) { _recalculationStrategy = (ICacheItemRecalculationStrategy) Activator.CreateInstance(_recalculationStrategyType, _durationToRecalculate); } var friendlyName = _keyCreationStrategy.GenerateFriendlyName(args); var key = _durationToStore == default(TimeSpan) //infer from the variables set, the key type to create? ? new Key(DefaultCacheDuration, DefaultCacheExpirationType, friendlyName) : new Key(_durationToStore, _storageStyle, _expirationType, friendlyName); object cacheItem; if ((cacheItem = _cache[key.ToString()]).IsNotNull()) { args.ReturnValue = cacheItem; } else { args.Proceed(); _cache.Add(key, args.ReturnValue); if (_recalculationStrategy.IsNotNull()) AsyncCacheItemRecalculator.EnsureIsStarted(key, _recalculationStrategy, args, _cache); } }
/// <inheritdoc /> public void Add(string key, object cachingData, object cacheTimer, bool isNoSlidingExpiration = true, bool useSitecoreCache = true, bool globalCache = false, bool removeOnPublish = true, string siteName = "", string databaseName = "", System.Web.Caching.CacheDependency cacheDep = null, System.Web.Caching.CacheItemPriority priority = System.Web.Caching.CacheItemPriority.Normal, System.Web.Caching.CacheItemRemovedCallback callback = null) { // make sure we have data if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (cachingData == null) { throw new ArgumentNullException(nameof(cachingData)); } if (!removeOnPublish) { key = KeyAgent.AddKeepAfterPublish(key); } // setup defaults for caching types TimeSpan slidingCache = System.Web.Caching.Cache.NoSlidingExpiration; DateTime absoluteCache = System.Web.Caching.Cache.NoAbsoluteExpiration; // set the cache type if (isNoSlidingExpiration) { // make sure it's right if (cacheTimer is DateTime) { absoluteCache = (DateTime)cacheTimer; } else { // we have an issue fix up var timeSpanCheck = (TimeSpan)cacheTimer; absoluteCache = DateTime.Now.Add(timeSpanCheck); } } else { // make sure it's right if (cacheTimer is TimeSpan) { slidingCache = (TimeSpan)cacheTimer; } else { // we have an issue fix up var dateCheck = (DateTime)cacheTimer; slidingCache = dateCheck.Subtract(DateTime.Now); } } // what type of cache are we using if (useSitecoreCache) { ICache cache = SitecoreCacheManager.GetCache(globalCache, siteName, databaseName); if (cache.ContainsKey(key)) { cache.Remove(key); } cache.Add(key, cachingData, slidingCache, absoluteCache); } else { var cacheStartKey = KeyAgent.GetBaseKey(globalCache, siteName, databaseName) + key; System.Web.HttpRuntime.Cache.Add(cacheStartKey, cachingData, cacheDep, absoluteCache, slidingCache, priority, callback); } }
ScriptBatch GetNextBatchCached(ISet<int> indexes, ICache cache) { var remainingIndexes = new HashSet<int>(); var scripts = new Script[indexes.Count]; int sidx = 0; foreach (int index in indexes) { string key = index.ToString() + uid; var script = cache[key] as Script; if (script == null) { remainingIndexes.Add(index); } else { scripts[sidx++] = script; } } if (remainingIndexes.Count != 0) { if (remainingIndexes.Count == 1) { int index = remainingIndexes.First(); var script = ScriptProvider[index]; scripts[sidx++] = script; string key = index.ToString() + uid; cache.Add(key, script); } else { var indexEnum = remainingIndexes.GetEnumerator(); foreach (var script in ScriptProvider.GetScripts(remainingIndexes)) { indexEnum.MoveNext(); int index = indexEnum.Current; scripts[sidx++] = script; string key = index.ToString() + uid; cache.Add(key, script); } } } return new ScriptBatch(scripts, Strategy as ILearningErrorReport); }
protected void Cache(ISession session, object sessionId, ICache cache) { cache.Add(sessionId, session); }
LearningScriptBatch GetNextBatchCached(ISet<int> indexes, ICache cache) { // TODO: Grouping. var scripts = new List<LearningScript>(indexes.Count); foreach (int index in indexes) { string key = index.ToString() + uid; var script = cache[key] as LearningScript; if (script == null) { script = ScriptProvider[index]; cache.Add(key, script); } scripts.Add(script); } return new LearningScriptBatch(scripts, Strategy as ILearningErrorReport); }
public void AddColumn(ColumnProperties columnToAdd) { _columnCache.Add(columnToAdd, addColumn(columnToAdd)); }
public ResponseHandlerResult HandleResponse(HttpRequestBase httpRequest, HttpResponseBase httpResponse, IResponse suggestedResponse, ICache cache, string cacheKey) { httpRequest.ThrowIfNull("request"); httpResponse.ThrowIfNull("httpResponse"); suggestedResponse.ThrowIfNull("suggestedResponse"); if (!suggestedResponse.CachePolicy.HasPolicy || cache == null || cacheKey == null) { return ResponseHandlerResult.ResponseNotHandled(); } CacheItem cacheItem = cache.Get(cacheKey); string responseETag = suggestedResponse.CachePolicy.ETag; #region If-Match precondition header IfMatchHeader[] ifMatchHeaders = IfMatchHeader.ParseMany(httpRequest.Headers["If-Match"]).ToArray(); // Only consider If-Match headers if response status code is 2xx or 412 if (ifMatchHeaders.Any() && ((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412)) { // Return 412 if no If-Match header matches the response ETag // Return 412 if an "If-Match: *" header is present and the response has no ETag if (ifMatchHeaders.All(arg => arg.EntityTag.Value != responseETag) || (responseETag == null && ifMatchHeaders.Any(arg => arg.EntityTag.Value == "*"))) { return WriteResponse(httpResponse, Response.PreconditionFailed()); } } #endregion #region If-None-Match precondition header IfNoneMatchHeader[] ifNoneMatchHeaders = IfNoneMatchHeader.ParseMany(httpRequest.Headers["If-None-Match"]).ToArray(); if (ifNoneMatchHeaders.Any()) { // Return 304 if an If-None-Match header matches the response ETag and the request method was GET or HEAD // Return 304 if an "If-None-Match: *" header is present, the response has an ETag and the request method was GET or HEAD // Return 412 if an "If-None-Match: *" header is present, the response has an ETag and the request method was not GET or HEAD if (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == responseETag) || (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == "*") && responseETag != null)) { if (String.Equals(httpRequest.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) || String.Equals(httpRequest.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase)) { if (cacheItem != null) { cacheItem.Response.CachePolicy.Apply(httpResponse.Cache); } else { suggestedResponse.CachePolicy.Apply(httpResponse.Cache); } return WriteResponse(httpResponse, Response.NotModified()); } return WriteResponse(httpResponse, Response.PreconditionFailed()); } } #endregion #region If-Modified-Since precondition header IfModifiedSinceHeader ifModifiedSinceHeader = IfModifiedSinceHeader.Parse(httpRequest.Headers["If-Modified-Since"]); bool validIfModifiedSinceHttpDate = ifModifiedSinceHeader != null && ifModifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime; // Only consider an If-Modified-Since header if response status code is 200 and the HTTP-date is valid if (suggestedResponse.StatusCode.ParsedStatusCode == HttpStatusCode.OK && validIfModifiedSinceHttpDate) { // Return 304 if the response was cached before the HTTP-date if (cacheItem != null && cacheItem.CachedUtcTimestamp < ifModifiedSinceHeader.HttpDate) { return WriteResponse(httpResponse, Response.NotModified()); } } #endregion #region If-Unmodified-Since precondition header IfUnmodifiedSinceHeader ifUnmodifiedSinceHeader = IfUnmodifiedSinceHeader.Parse(httpRequest.Headers["If-Unmodified-Since"]); bool validIfUnmodifiedSinceHttpDate = ifUnmodifiedSinceHeader != null && ifUnmodifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime; // Only consider an If-Unmodified-Since header if response status code is 2xx or 412 and the HTTP-date is valid if (((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412) && validIfUnmodifiedSinceHttpDate) { // Return 412 if the previous response was removed from the cache or was cached again at a later time if (cacheItem == null || cacheItem.CachedUtcTimestamp >= ifUnmodifiedSinceHeader.HttpDate) { return WriteResponse(httpResponse, Response.PreconditionFailed()); } } #endregion #region No server caching // Do not cache the response when the response sends a non-cacheable status code, or when an Authorization header is present if (!_cacheableStatusCodes.Contains(suggestedResponse.StatusCode) || httpRequest.Headers["Authorization"] != null) { return WriteResponse(httpResponse, suggestedResponse); } CacheControlHeader cacheControlHeader = CacheControlHeader.Parse(httpRequest.Headers["Cache-Control"]); // Do not cache the response if a "Cache-Control: no-cache" or "Cache-Control: no-store" header is present if (cacheControlHeader != null && (cacheControlHeader.NoCache || cacheControlHeader.NoStore)) { return WriteResponse(httpResponse, suggestedResponse); } IEnumerable<PragmaHeader> pragmaHeader = PragmaHeader.ParseMany(httpRequest.Headers["Pragma"]); // Do not cache the response if a "Pragma: no-cache" header is present if (pragmaHeader.Any(arg => String.Equals(arg.Name, "no-cache", StringComparison.OrdinalIgnoreCase))) { return WriteResponse(httpResponse, suggestedResponse); } #endregion // Return 504 if the response has not been cached but the client is requesting to receive only a cached response if (cacheItem == null && cacheControlHeader != null && cacheControlHeader.OnlyIfCached) { return WriteResponse(httpResponse, Response.GatewayTimeout()); } if (cacheItem != null) { // Write the cached response if no Cache-Control header is present // Write the cached response if a "Cache-Control: max-age" header is validated // Write the cached response if a "Cache-Control: max-stale" header is validated // Write the cached response if a "Cache-Control: min-fresh" header is validated if (cacheControlHeader == null || _systemClock.UtcDateTime - cacheItem.CachedUtcTimestamp <= cacheControlHeader.MaxAge || cacheControlHeader.OnlyIfCached || cacheItem.ExpiresUtcTimestamp == null || _systemClock.UtcDateTime - cacheItem.ExpiresUtcTimestamp.Value <= cacheControlHeader.MaxStale || cacheItem.ExpiresUtcTimestamp.Value - _systemClock.UtcDateTime < cacheControlHeader.MinFresh) { return WriteResponseInCache(httpResponse, cacheItem); } } bool cacheOnServer = suggestedResponse.CachePolicy.AllowsServerCaching; var cacheResponse = new CacheResponse(suggestedResponse); if (cacheOnServer) { DateTime expirationUtcTimestamp = suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp != null ? suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp.Value : _systemClock.UtcDateTime + suggestedResponse.CachePolicy.ServerCacheMaxAge.Value; cache.Add(cacheKey, cacheResponse, expirationUtcTimestamp); } return WriteResponse(httpResponse, cacheResponse); }
public override void DoAction(ICache cache, IServiceDto serviceDto) { cache.Add(serviceDto); }
public static void Run() { var done = false; while (!done) { switch (GetUserChoice()) { case 1: { IEnumerable <string> customerIds; var stopWatch = new Stopwatch(); if (useCache) { stopWatch.Start(); customerIds = cache.DataTypeManager.GetList <string>( "Customer:CustomerID:All", new ReadThruOptions { Mode = ReadMode.ReadThru }); stopWatch.Stop(); } else { stopWatch.Start(); customerIds = CustomerRepository.GetCustomerIDs(); stopWatch.Stop(); } var ms = stopWatch.ElapsedMilliseconds; Console.WriteLine($"Total operation time: {ms} ms"); if (customerIds.Count() == 0) { Console.WriteLine("No customers in database"); } else { PrintCustomerIDs(customerIds); } } break; case 2: { var customerID = GetCustomerID(); var stopWatch = new Stopwatch(); if (!string.IsNullOrWhiteSpace(customerID)) { Customer customer; if (useCache) { stopWatch.Start(); customer = cache.Get <Customer>( $"Customer:CustomerID:{customerID}", new ReadThruOptions( ReadMode.ReadThru)); stopWatch.Stop(); } else { stopWatch.Start(); customer = CustomerRepository.GetCustomer(customerID); stopWatch.Stop(); } var ms = stopWatch.ElapsedMilliseconds; Console.WriteLine($"Total operation time: {ms} ms"); PrintCustomerDetails(customer); } } break; case 3: { var customerID = GetCustomerID(); if (!string.IsNullOrWhiteSpace(customerID)) { if (useCache) { cache.Remove( $"Customer:CustomerID:{customerID}", null, null, new WriteThruOptions( WriteMode.WriteThru)); } else { CustomerRepository.DeleteCustomer(customerID); } } } break; case 4: { var customer = CustomerSeed.SeedCustomers() .Generate(); Console.WriteLine("New customer:\n"); PrintCustomerDetails(customer); if (useCache) { cache.Add( $"Customer:CustomerID:{customer.CustomerID}", new CacheItem(customer) { Dependency = GetCustomerSqlDependency( customer.CustomerID), ResyncOptions = new ResyncOptions(true) }, new WriteThruOptions { Mode = WriteMode.WriteThru }); } else { CustomerRepository.SaveCustomer(customer); } } break; case 5: { var customerID = GetCustomerID(); Customer oldCustomer = null; if (!string.IsNullOrWhiteSpace(customerID)) { if (useCache) { oldCustomer = cache.Get <Customer>( $"Customer:CustomerID:{customerID}", new ReadThruOptions { Mode = ReadMode.ReadThru }); } else { oldCustomer = CustomerRepository.GetCustomer(customerID); } } if (oldCustomer == null) { Console.WriteLine( $"No customer with ID {customerID} exists " + $"in database"); } else { var newCustomer = CustomerSeed.SeedCustomers() .Generate(); newCustomer.CustomerID = customerID; Console.WriteLine("Updated customer:\n"); PrintCustomerDetails(newCustomer); if (useCache) { cache.Insert( $"Customer:CustomerID:{customerID}", new CacheItem(newCustomer) { Dependency = GetCustomerSqlDependency( customerID), ResyncOptions = new ResyncOptions(true) }, new WriteThruOptions { Mode = WriteMode.WriteThru }); } else { CustomerRepository.UpdateCustomer(newCustomer); } } } break; case 6: { var country = GetCustomerCountry(); if (!string.IsNullOrWhiteSpace(country)) { IEnumerable <string> customerIds; var stopWatch = new Stopwatch(); if (useCache) { stopWatch.Start(); customerIds = cache.DataTypeManager.GetList <string>( $"Customer:Country:{country}", new ReadThruOptions { Mode = ReadMode.ReadThru }); stopWatch.Stop(); } else { stopWatch.Start(); customerIds = CustomerRepository.GetCustomerIDsByCountry( country); stopWatch.Stop(); } var ms = stopWatch.ElapsedMilliseconds; Console.WriteLine($"Total operation time: {ms} ms"); if (customerIds.Count() == 0) { Console.WriteLine( $"No customers in database with country " + $" {country}"); } else { PrintCustomerIDs(customerIds); } } } break; case 7: { done = true; } break; } } }
public void Add(T item) { _cache.Add(item); }
// Cache private void GetFeatureMatrixCache(FeatureIndexSet indexes, List<Vector<double>[]> vectors, ICache cache) { //var sl = new SpinLock(); //Parallel.ForEach(indexes, (index) => //{ // string key = index.ToString() + uid; // var cv = cache[key] as Vector<double>[]; // if (cv == null) // { // cv = GetFeatureVectorsOf(RetrieveFeatureSet(index)); // cache.Add(key, cv); // } // bool taken = false; // try // { // sl.Enter(ref taken); // vectors.Add(cv); // } // finally // { // if (taken) sl.Exit(); // } //}); foreach (int index in indexes) { string key = index.ToString() + uid; var cv = cache[key] as Vector<double>[]; if (cv != null) { vectors.Add(cv); } else { cv = GetFeatureVectorsOf(RetrieveFeatureSet(index)); cache.Add(key, cv); vectors.Add(cv); } } }