public void CacheMethod_Member_NestedProperty() { var cache = CreateCache(); //we expect this to fail because caching of nested properties is not supported CacheStrategy cacheStrategy = cache.Method(r => r.NestedProperty.Property1); }
/// <summary> /// Updates a caching strategy to use the specified sliding expiration expiration callback /// </summary> public static CacheStrategy <TResult> ExpireAfter <TResult>(this CacheStrategy <TResult> source, Func <TResult, TimeSpan> expireAfterCallback) { Func <object, CacheExpiration> callback = obj => new CacheExpiration(expireAfterCallback((TResult)obj)); source.ExpirationCallback = callback; return(source); }
public async Task Method_ExpireAfter(Cache <Example> cache) { TimeSpan wait = TimeSpan.FromSeconds(1); CacheStrategy <double> strategy = cache.Method(c => c.CalculateSomeWork()) .ExpireAfter(wait); DateTime firstCacheDate = default(DateTime); strategy.Get(); for (int i = 1; i < 10; i++) { CachedValue <double> result = strategy.Get(); Assert.AreEqual(0L, result.Version, "These calls should be cached"); await Task.Delay(TimeSpan.FromSeconds(wait.TotalSeconds / 5.0)); firstCacheDate = result.CachedDate; } await Task.Delay(wait); CachedValue <double> expiredResult = strategy.Get(); Assert.AreNotEqual(firstCacheDate, expiredResult.CachedDate, "This call should have expired after waiting for {0}", wait); }
public void ErrorHandling_NoErrorHandling() { CacheStrategy <int> cacheStrategy = CreateCache().Method(c => c.ThrowsExceptionImmediately()) .IfRetrievalFailsUsePreviousValue(); cacheStrategy.GetValue(); }
public void Method_Get_Invalidation(Cache <Example> cache) { bool isInvalid = false; Func <CachedValue <double>, CacheValidationResult> validate = existing => { if (isInvalid) { return(CacheValidationResult.Invalid); } else { return(CacheValidationResult.Unknown); } }; CacheStrategy <double> strategy = cache.Method(c => c.CalculateSomeWork()) .Validate(validate); CachedValue <double> result0 = strategy.Get(); Assert.AreEqual(0L, result0.Version); isInvalid = true; CachedValue <double> result1 = strategy.Get(); CachedValue <double> result2 = strategy.Get(); Assert.AreEqual(1L, result1.Version); Assert.AreEqual(2L, result2.Version); }
public async Task Method_ExpireAfter_Callback(Cache <Example> cache) { TimeSpan wait1 = TimeSpan.FromSeconds(1.25); TimeSpan wait2 = TimeSpan.FromSeconds(0.75); Func <double, TimeSpan> waitCallback = d => d < 1.0 ? wait1 : wait2; CacheStrategy <double> strategy = cache.Method(c => c.CalculateSomeWork()) .ExpireAfter(waitCallback); DateTime firstCacheDate = default(DateTime); strategy.Get(); for (int i = 1; i < 10; i++) { CachedValue <double> result = strategy.Get(); Assert.AreEqual(0L, result.Version, "These calls should be cached"); var wait = waitCallback(result.Value); await Task.Delay(TimeSpan.FromSeconds(wait.TotalSeconds / 5.0)); firstCacheDate = result.CachedDate; } await Task.Delay(wait1 + wait2); CachedValue <double> expiredResult = strategy.Get(); Assert.AreNotEqual(firstCacheDate, expiredResult.CachedDate, "This call should have expired after waiting"); }
public Cache(CacheMedium medium, CacheStrategy strategy, CacheFlags flags) { m_Strategy = strategy; m_Medium = medium; m_Flags = flags; }
public List <ImagesDpiDetail> GetImagesDpiConfig() { return(CacheStrategy.Get <List <ImagesDpiDetail> >(CacheKeys.ImagesDpiConfigCacheKey, () => { string menuXmlPath = WebHelper.GetMapPath(WebSettingsManager.Value.ImagesDpiConfigXmlPath); return XmlDeserialize <ImagesDpiGroup>(menuXmlPath).ImagesDpiDetails; }, 360)); }
public LazyMetadataValue(IPlugin owningPlugin, CacheStrategy cacheStrategy, Func <object> lazyValue) : base(owningPlugin) { Debug.Assert(lazyValue != null, "lazyValue cannot be null"); this.internalValue = new WeakReference(null); this.lazyValue = lazyValue; this.cacheStrategy = cacheStrategy; }
public void CacheFailureOnSet_Unhandled() { ICache <CacheMe> cache = CreateUnhandledCache(CacheOperation.Set); CacheStrategy <double> cacheStrategy = cache.Method(m => m.DoWork()); ICachedValue <double> result = cacheStrategy.Get(); }
// Convenience constructors // public Cache() { m_Strategy = CacheStrategy.Balanced; m_Medium = CacheMedium.Memory; m_Flags = 0; m_nextExpire = DateTime.UtcNow + m_expiresTime; m_Strategy = CacheStrategy.Aggressive; }
public CacheEntry( string key, object value, CacheStrategy strategy ) { this.key = key; data = new WeakReference( value ); if( strategy == CacheStrategy.Permanent ) { dataStrongRef = value; } }
public CacheEntry(string key, object value, CacheStrategy strategy) { this.key = key; data = new WeakReference(value); if (strategy == CacheStrategy.Permanent) { dataStrongRef = value; } }
public void CacheMethod_Method_GetValue() { var cache = CreateCache(); CacheStrategy <double> strat = cache.Method(r => r.Method()); double result = strat.GetValue(); Assert.AreNotEqual(0, result); }
public UserModel Login(string UserName, string PassWord) { var result = DA.GetModel(UserName, PassWord); if (result != null) { CacheStrategy.AddObject(result.Id, result); } return(result); }
/// <summary> /// Returns a memoized version of a referentially transparent function. The memoized version of the /// function keeps a cache of the mapping from arguments to results and, when calls with the same /// arguments are repeated often, has higher performance at the expense of higher memory use. /// Overload for delegates with no arguments. /// </summary> /// <typeparam name="TResult">Function result type.</typeparam> /// <param name="func">The function to memoize.</param> /// <param name="strategies">Strategies to apply. By default limitless strategy will be used.</param> /// <param name="cache">Dictionary to use for caching. If not specified the standard Dictionary will be used which /// is not thread safe.</param> /// <returns>Delegate the able to cache.</returns> public static Func <TResult> Memoize <TResult>( Func <TResult> func, CacheStrategy <int, TResult> strategies = null, IDictionary <int, TResult> cache = null) { var func2 = new Func <int, TResult>(arg => func()); var memoized = Memoize(func2, strategies, cache); return(() => memoized(0)); }
/// <summary> /// Returns a memoized version of a referentially transparent function. The memoized version of the /// function keeps a cache of the mapping from arguments to results and, when calls with the same /// arguments are repeated often, has higher performance at the expense of higher memory use. /// Overload for delegates with 3 arguments. /// </summary> /// <typeparam name="T1">Type component for key.</typeparam> /// <typeparam name="T2">Type component for key.</typeparam> /// <typeparam name="T3">Type component for key.</typeparam> /// <typeparam name="TResult">Function result type.</typeparam> /// <param name="func">The function to memoize.</param> /// <param name="strategies">Strategies to apply. By default limitless strategy will be used.</param> /// <param name="cache">Dictionary to use for caching. If not specified the standard Dictionary will be used which /// is not thread safe.</param> /// <returns>Delegate the able to cache.</returns> public static Func <T1, T2, T3, TResult> Memoize <T1, T2, T3, TResult>( Func <T1, T2, T3, TResult> func, CacheStrategy <Tuple <T1, T2, T3>, TResult> strategies = null, IDictionary <Tuple <T1, T2, T3>, TResult> cache = null) { var func2 = new Func <Tuple <T1, T2, T3>, TResult>(arg => func(arg.Item1, arg.Item2, arg.Item3)); var memoized = Memoize(func2, strategies, cache); return((arg1, arg2, arg3) => memoized(new Tuple <T1, T2, T3>(arg1, arg2, arg3))); }
public void Method_Get_MultipleSameVersion(Cache <Example> cache) { CacheStrategy <double> cacheStrategy = cache.Method(c => c.CalculateSomeWork()); for (int i = 0; i < 10; i++) { CachedValue <double> result = cacheStrategy.Get(); Assert.AreEqual(0L, result.Version, "All subsequent calls should retrieve the existing version"); } }
public void CacheMethod_Method_GetValue() { var cache = CreateCache(); CacheStrategy <double> strat = cache.Method(t => t.CalculateSomeWork()); double result = strat.GetValue(); Assert.AreNotEqual(0, result); }
public void CacheFailureOnSet_Handled() { ICache <CacheMe> cache = CreateHandledCache(CacheOperation.Set); CacheStrategy <double> cacheStrategy = cache.Method(m => m.DoWork()); ICachedValue <double> result1 = cacheStrategy.Get(); ICachedValue <double> result2 = cacheStrategy.Get(); Assert.AreNotEqual(result1.Value, result2.Value); }
public void CacheMethod_Method_FieldParameter() { var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("DownloadTextAsync") .WithParameters(TestField); CacheStrategy cacheStrategy = cache.Method(t => t.DownloadTextAsync(t.TestField)); Assert.AreEqual(expected.Key, cacheStrategy.Key); }
public void CacheMethod_Method_SetCache() { var cache = CreateCache(); double val = 100d; CacheStrategy <double> strat = cache.Method(t => t.CalculateSomeWork()); strat.SetValue(100d); Assert.AreEqual(val, strat.GetValue()); }
private void DoTestCacheMethod_KeyAndRegion_ArgumentParameter(string url) { var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("DownloadTextAsync") .WithParameters(url); CacheStrategy cacheStrategy = cache.Method(t => t.DownloadTextAsync(url)); Assert.AreEqual(expected.Key, cacheStrategy.Key); }
public void ErrorHandling_UsePreviousValueOrDefault() { int defaultValue = -1111; CacheStrategy <int> cacheStrategy = CreateCache().Method(c => c.ThrowsExceptionImmediately()) .IfRetrievalFailsUsePreviousValueOrDefault(defaultValue); int value = cacheStrategy.GetValue(); Assert.AreEqual(defaultValue, value, "The retrieval error handler should have kicked in and returned the default value"); }
public void ErrorHandling_UsePreviousValue() { CacheStrategy <int> cacheStrategy = CreateCache().Method(c => c.RandomValueThatThrowsExceptionOnSecondTry()) .IfRetrievalFailsUsePreviousValue(); int previousValue = cacheStrategy.GetValue(); int newValue = cacheStrategy.GetValue(); Assert.AreEqual(previousValue, newValue, "The retrieval error handler should have kicked in"); }
private void DoTestCacheMethod_KeyAndRegion_ArgumentParameter(string argument) { var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("MethodAsync") .WithParameters(argument); CacheStrategy cacheStrategy = cache.Method(r => r.MethodAsync(argument)); Assert.AreEqual(expected.Key, cacheStrategy.Key); }
public void CacheMethod_Method_StaticPropertyParameter() { var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("MethodAsync") .WithParameters(MethodTestsArguments.StaticProperty); CacheStrategy cacheStrategy = cache.Method(r => r.MethodAsync(MethodTestsArguments.StaticProperty)); Assert.AreEqual(expected.Key, cacheStrategy.Key); }
public void CacheMethod_Method_MethodParameter() { var args = new MethodTestsArguments(); var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("MethodAsync") .WithParameters(args.Method()); CacheStrategy cacheStrategy = cache.Method(t => t.MethodAsync(args.Method())); Assert.AreEqual(expected.Key, cacheStrategy.Key); }
public void CacheMethod_Method_IgnoreParameter() { var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("DownloadTextAsync") .WithRegion("MethodTests"); CacheStrategy cacheStrategy = cache.Method(t => t.DownloadTextAsync(Parameter.DoNotCache <string>())); Assert.AreEqual(expected.Key, cacheStrategy.Key); Assert.AreEqual(expected.Region, cacheStrategy.Region); }
public void CacheMethod_Member_Property() { var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("Property") .WithRegion(nameof(MethodTestsRepository)); CacheStrategy cacheStrategy = cache.Method(r => r.Property); Assert.AreEqual(expected.Key, cacheStrategy.Key); Assert.AreEqual(expected.Region, cacheStrategy.Region); }
public void CacheMethod_Member() { var cache = CreateCache(); CacheStrategyIncomplete expected = cache.WithKey("TestProperty") .WithRegion("MethodTests"); CacheStrategy cacheStrategy = cache.Method(t => t.TestProperty); Assert.AreEqual(expected.Key, cacheStrategy.Key); Assert.AreEqual(expected.Region, cacheStrategy.Region); }
/// <summary> /// Update the current ObjectMap instance with the table name obtained from /// the Gentle TableNameAttribute. /// Also determines whether table name is dynamic or fixed. /// </summary> internal void SetTableName( Type type ) { // determine if table name is dynamic or fixed isDynamicTable = type.GetInterface( "ITableName", false ) != null; // get fixed name if present object[] attrs = type.GetCustomAttributes( typeof(TableNameAttribute), true ); if( attrs != null && attrs.Length == 1 ) { TableNameAttribute attr = (TableNameAttribute) attrs[ 0 ]; TableName = attr.Name; cacheStrategy = attr.CacheStrategy; schemaName = attr.Schema; } else { Check.Verify( isDynamicTable, Error.DeveloperError, "The type {0} must either have a TableName attribute or implement ITableName.", type ); } }
/// <summary> /// The constructor for the TableName attribute. /// </summary> /// <param name="name">The name of the database table used to store instances of this class.</param> /// <param name="strategy">The cache stratgey to use for instances of this type. <see /// cref="CacheStrategy"/> for a list of available options.</param> public TableNameAttribute( string name, CacheStrategy strategy ) { this.name = name; cacheStrategy = strategy; }
/// <summary> /// Insert an object into the cache using the specified cache strategy (lifetime management). /// </summary> /// <param name="key">The cache key used to reference the item.</param> /// <param name="value">The object to be inserted into the cache.</param> /// <param name="strategy">The strategy to apply for the inserted item (use Temporary for objects /// that are collectible and Permanent for objects you wish to keep forever).</param> public void Insert( string key, object value, CacheStrategy strategy ) { Check.VerifyNotNull( key, Error.NullParameter, "key" ); items[ key ] = new CacheEntry( key, value, strategy ); }
/// <summary> /// Indexer for adding a cache item using the specified strategy. /// </summary> public object this[ string key, CacheStrategy strategy ] { set { Insert( key, value, strategy ); } }
/// <summary> /// Insert an entry into the cache using the specified <see cref="CacheStrategy"/>. /// </summary> /// <param name="key">The key used to find the entry again.</param> /// <param name="value">The item to cache.</param> /// <param name="strategy">The cache strategy to use for lifetime management. Possible /// values are Never, Temporary or Permanent.</param> public static void Insert( string key, object value, CacheStrategy strategy ) { Check.VerifyNotNull( key, Error.NullParameter, "key" ); Check.VerifyNotNull( value, Error.NullParameter, "value" ); Check.LogDebug( LogCategories.Cache, "Cache (add) using key: " + key ); CacheContentType contentType = key.StartsWith( "Query|" ) ? CacheContentType.Query : CacheContentType.Entity; // determine which cache to use CacheStore cacheStore = GetCacheStore( contentType ); // access cache cacheStore.Lock.AcquireWriterLock( rwLockTimeOut ); try { cacheStore.Insert( key, value, strategy ); } finally { cacheStore.Lock.ReleaseWriterLock(); } }