public void TestGetItemExceptionExpired()
        {
            var memcachedMock = new Mock<IMemcachedClient>();
            var enyimProvider = new EnyimMemcachedProvider<IAwesomeInterface>(memcachedMock.Object);

            var cachePolicy = new CachePolicy()
            {
                CacheDuration = 2
            };

            var proxyContext = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.ParameteredMethod("", 1));
            var hashKey = proxyContext.CreateHash();
            var exception = new Exception("Rofl exception");

            object val = new MemcachedObject<IEnumerable<string>>()
            {
                Created = DateTime.Now.AddSeconds(-11),
                IsException = true,
                Exception = exception
            };

            memcachedMock.Setup(a => a.TryGet(hashKey, out val)).Returns(true);

            var result = enyimProvider.GetItem<IEnumerable<string>>(proxyContext, cachePolicy);
            Assert.IsTrue(result.State == CachedObjectState.None);
            Assert.IsNull(result.ThrownException, "Provider did not return null in exception field");
            Assert.IsNull(result.Object, "Provider did not return null in object field");
        }
 public HTTPResponseHandler()
 {
   cachePolicy = CachePolicy.UseProtocolCachePolicy;
   allowInvalidSSLCertificates = false;
   allowFollowRedirects = true;
   maxRedirectCount = -1;
   acceptableStatusCodeRanges = new List<HTTPStatusCodeRange>();
   _error = null;
 }
Exemplo n.º 3
0
 /// <summary>
 /// Creates a CachePolicyAttribute
 /// </summary>
 /// <param name="policy">The CachePolicy value</param>
 /// <param name="cacheTimeInSeconds">The time to cache, in seconds.  Ignored for NoCache (assumed 0) and Forever (assumed Int32.MaxValue).</param>
 public CachePolicyAttribute(CachePolicy policy, int cacheTimeInSeconds)
 {
     switch (policy) {
         case AgFx.CachePolicy.NoCache:
             CacheTimeInSeconds = 0;
             break;
         case AgFx.CachePolicy.Forever:
             CacheTimeInSeconds = Int32.MaxValue;
             break;
         default:
             CacheTimeInSeconds = cacheTimeInSeconds;
             break;
     }
     CachePolicy = policy;
 }
        public void TestStoreException()
        {
            var memcachedMock = new Mock<IMemcachedClient>();
            var enyimProvider = new EnyimMemcachedProvider<IAwesomeInterface>(memcachedMock.Object);

            var cachePolicy = new CachePolicy()
            {
                CacheDuration = 10
            };

            var proxyContext = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.ParameteredMethod("", 1));
            var hashKey = proxyContext.CreateHash();

            enyimProvider.StoreException<IEnumerable<string>>(proxyContext, cachePolicy, new Exception());

            memcachedMock.Verify(a => a.Store(StoreMode.Set, hashKey, It.IsAny<MemcachedObject<IEnumerable<string>>>()), Times.Once()); //We can't test properly if it created the object correctly.
        }
Exemplo n.º 5
0
 /// <summary>
 /// Using CacheTimeout object allows us to have a variable cache time
 /// </summary>
 /// <param name="policy">The CachePolicy value</param>
 /// <param name="cacheTimeOut">The calculated time to cache.  Ignored for NoCache (assumed 0) and Forever (assumed Int32.MaxValue).</param>
 public CachePolicyAttribute(CachePolicy policy, Type cacheTimeOut)
 {
     CacheTimeOut timeOut = (CacheTimeOut)cacheTimeOut.GetConstructor(new Type[0]).Invoke(null);
     switch (policy)
     {
         case AgFx.CachePolicy.NoCache:
             CacheTimeInSeconds = 0;
             break;
         case AgFx.CachePolicy.Forever:
             CacheTimeInSeconds = Int32.MaxValue;
             break;
         default:
             CacheTimeOut = timeOut;
             break;
     }
     CachePolicy = policy;
 }
Exemplo n.º 6
0
 public QueryUserSubscriptions(string userToRetrieve, CachePolicy policy) : base(policy)
 {
     this._userToRetrieve = userToRetrieve;
 }
Exemplo n.º 7
0
 public CatalogController(IPolicyRegistry <string> myRegistry, HttpClient httpClient)
 {
     _httpClient  = httpClient;
     _cachePolicy = myRegistry.Get <CachePolicy <HttpResponseMessage> >("myLocalCachePolicy");
 }
Exemplo n.º 8
0
 /// <summary>
 /// Obtiene una instancia que permite conectar con el servico Aspen.
 /// </summary>
 /// <param name="cachePolicy">La política para el tratamiento de la información almacenada por caché.</param>
 /// <returns>Instancia de <see cref="IRouting{TFluent}"/> que permite establecer la información de conexión.</returns>
 public static IRouting <IAutonomousApp> Initialize(
     CachePolicy cachePolicy = CachePolicy.CacheIfAvailable)
 {
     return(new AutonomousApp(cachePolicy));
 }
 public static uint _URLClientCreateHTTPConnection(string method,
     string url, CachePolicy cachePolicy, float timeout)
 {
   return (uint)UnityURLClientBindingInstance.Call<int>("createHTTPConnection",
       method, url, (int)cachePolicy, timeout);
 }
Exemplo n.º 10
0
 public MethodFamilyConfigExpression(CachePolicy policy)
 {
     _policy = policy;
 }
        public void TestGetItemFromEmpty()
        {
            var memcachedMock = new Mock<IMemcachedClient>();
            var enyimProvider = new EnyimMemcachedProvider<IAwesomeInterface>(memcachedMock.Object);

            var cachePolicy = new CachePolicy()
                                  {
                                      CacheDuration = 10
                                  };

            var proxyContext = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.ParameterlessMethod());

            var hashKey = proxyContext.CreateHash();
            var result = enyimProvider.GetItem(proxyContext, cachePolicy);

            Assert.IsTrue(result.State == CachedObjectState.None, "Provider did not return an object with state none");
            Assert.IsNull(result.Object, "Provider did not return on object field");
            Assert.IsNull(result.ThrownException, "Provider did not return null in exception field");

            object val;
            memcachedMock.Verify(a => a.TryGet(hashKey, out val));
        }
 public TemplatesController(CachePolicy cachePolicy, RestClient client) : base(cachePolicy, client)
 {
 }
 public InstanceCacheAttribute(CachePolicy policy)
 {
     this.policy = policy;
 }
Exemplo n.º 14
0
 public MoodboardsController(CachePolicy cachePolicy, string apiAddress, IAuthenticator authenticator) : base(
         cachePolicy, apiAddress, authenticator)
 {
 }
Exemplo n.º 15
0
 /// <summary>
 /// Previene la creación de una instancia de la clase <see cref="AutonomousApp"/>
 /// </summary>
 /// <param name="cachePolicy">La política para el tratamiento de la información almacenada por caché.</param>
 private AutonomousApp(CachePolicy cachePolicy)
 {
     CacheStore.Policy = cachePolicy;
 }
Exemplo n.º 16
0
 public CachedQuery(CachePolicy policy)
 {
     CachingPolicy = policy;
 }
Exemplo n.º 17
0
        public async Task StoreAsync <TResult>(ProxiedMethodInvocation <T, TResult> proxiedMethodInvocation, CachePolicy cachePolicy, TResult data)
        {
            var key          = proxiedMethodInvocation.GetHashString(_hashScramble);
            var cachedObject = new MemcachedObject <TResult>()
            {
                Created = DateTime.Now,
                Object  = data
            };

            var bytes = SerializeAndZip(cachedObject);

            if (cachePolicy.MaxAge > 0)
            {
                await _memcachedCluster.Set(key, bytes, new MemcachedStorageOptions()
                {
                    ExpirationTime = TimeSpan.FromSeconds(cachePolicy.MaxAge)
                });
            }
            else
            {
                await _memcachedCluster.Set(key, bytes);
            }
        }
Exemplo n.º 18
0
        public async Task <CachedObject <TResult> > GetAsync <TResult>(ProxiedMethodInvocation <T, TResult> proxiedMethodInvocation, CachePolicy cachePolicy)
        {
            var key           = proxiedMethodInvocation.GetHashString(_hashScramble);
            var memcachedItem = await _memcachedCluster.Get(key);

            if (memcachedItem != null)
            {
                MemcachedObject <TResult> cacheItem;
                using (var zipStream = new GZipStream(memcachedItem.Data, CompressionMode.Decompress))
                {
                    using (var streamReader = new StreamReader(zipStream))
                    {
                        var textReader = new JsonTextReader(streamReader);
                        try
                        {
                            cacheItem = _serializer.Deserialize <MemcachedObject <TResult> >(textReader);
                        }
                        catch (JsonSerializationException)
                        {
                            //This exception occurs if whatever is in memcached is impossible to deserialize. It's a tricky case, but we'll have to report back that nothing is in there.
                            return(new CachedObject <TResult>(CachedObjectState.None, default(TResult)));
                        }
                    }
                }

                if (cacheItem == null)
                {
                    return(new CachedObject <TResult>(CachedObjectState.None, default(TResult)));
                }

                if (cacheItem.IsException && cacheItem.Created.AddSeconds(cachePolicy.ExceptionCacheDuration) > DateTime.Now)
                {
                    return(new CachedObject <TResult>(CachedObjectState.Exception, cacheItem.Exception));
                }
                else if (cacheItem.IsException)
                {
                    return(new CachedObject <TResult>(CachedObjectState.None, default(TResult)));
                }

                var fresh = cacheItem.Created.AddSeconds(cachePolicy.CacheDuration) > DateTime.Now;
                var state = fresh ? CachedObjectState.Fresh : CachedObjectState.Stale;

                if (cachePolicy.DiscardStale && state == CachedObjectState.Stale)
                {
                    return(new CachedObject <TResult>(CachedObjectState.None, default(TResult)));
                }

                return(new CachedObject <TResult>(state, cacheItem.Object));
            }

            return(new CachedObject <TResult>(CachedObjectState.None, default(TResult)));
        }
Exemplo n.º 19
0
 /// <summary>
 /// Obtiene un cliente para a partir de la aplicación autónoma de pruebas, omitiendo los valores almacenados en memoria.
 /// </summary>
 /// <param name="cachePolicy">La política para el tratamiento de la información almacenada por caché.</param>
 /// <returns>Instancia de <see cref="IAutonomousApp"/> para interactuar con el servicio.</returns>
 public IAutonomousApp GetAutonomousClient(CachePolicy cachePolicy = CachePolicy.BypassCache) =>
 AutonomousApp.Initialize(cachePolicy)
 .RoutingTo(TestingEndpointProvider.Default)
 .WithIdentity(AutonomousAppIdentity.Master)
 .Authenticate()
 .GetClient();
Exemplo n.º 20
0
 public CachedQuerySearch(SearchOptions options, CachePolicy policy) : base(policy)
 {
     this._searchOptions = options;
 }
 public QueryUserCommentVotesForSubmission(int submissionID, CachePolicy policy) : base(policy)
 {
     this._submissionID = submissionID;
 }
Exemplo n.º 22
0
        public void ExpireTest()
        {
            var    cacheManager = new CacheManager();
            string key          = "AddTest" + DateTime.Now.Ticks;
            var    tags         = new[] { "a", "b" };
            var    cacheKey     = new CacheKey(key, tags);
            var    value        = "Test Value " + DateTime.Now;
            var    cachePolicy  = new CachePolicy();

            bool result = cacheManager.Add(cacheKey, value, cachePolicy);

            result.Should().BeTrue();

            // add second value with same tag
            string key2         = "AddTest2" + DateTime.Now.Ticks;
            var    tags2        = new[] { "a", "c" };
            var    cacheKey2    = new CacheKey(key2, tags2);
            var    value2       = "Test Value 2 " + DateTime.Now;
            var    cachePolicy2 = new CachePolicy();

            bool result2 = cacheManager.Add(cacheKey2, value2, cachePolicy2);

            result2.Should().BeTrue();

            // add third value with same tag
            string key3         = "AddTest3" + DateTime.Now.Ticks;
            var    tags3        = new[] { "b", "c" };
            var    cacheKey3    = new CacheKey(key3, tags3);
            var    value3       = "Test Value 3 " + DateTime.Now;
            var    cachePolicy3 = new CachePolicy();

            bool result3 = cacheManager.Add(cacheKey3, value3, cachePolicy3);

            result3.Should().BeTrue();


            var    cacheTag = new CacheTag("a");
            string tagKey   = MemoryCacheProvider.GetTagKey(cacheTag);

            tagKey.Should().NotBeNullOrEmpty();

            var cachedTag = cacheManager.Get(tagKey);

            cachedTag.Should().NotBeNull();

            // expire actually just changes the value for tag key
            cacheManager.Expire(cacheTag);

            var expiredTag = cacheManager.Get(tagKey);

            expiredTag.Should().NotBeNull();
            expiredTag.Should().NotBe(cachedTag);

            // items should have been removed
            var expiredValue = cacheManager.Get(cacheKey.Key);

            expiredValue.Should().BeNull();

            var expiredValue2 = cacheManager.Get(cacheKey2.Key);

            expiredValue2.Should().BeNull();

            var expiredValue3 = cacheManager.Get(cacheKey3.Key);

            expiredValue3.Should().NotBeNull();
        }
Exemplo n.º 23
0
 /// <summary>
 /// Returns the first element of the <paramref name="query"/>; if possible from the cache,
 /// otherwise the query is materialized and the result cached before being returned.
 /// </summary>
 /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
 /// <param name="query">The query to be materialized.</param>
 /// <param name="cachePolicy">The cache policy for the query.</param>
 /// <param name="tags">The list of tags to use for cache expiration.</param>
 /// <returns>default(T) if source is empty; otherwise, the first element in source.</returns>
 public static TEntity FromCacheFirstOrDefault <TEntity>(this IQueryable <TEntity> query, CachePolicy cachePolicy = null, IEnumerable <string> tags = null)
     where TEntity : class
 {
     return(query
            .Take(1)
            .FromCache(cachePolicy, tags)
            .FirstOrDefault());
 }
Exemplo n.º 24
0
 /// <summary>
 /// 更新缓存数据
 /// </summary>
 /// <param name="cachedResponse">可被缓存的响应数据</param>
 /// <param name="context">MVC 请求上下文</param>
 /// <param name="policy">缓存策略</param>
 protected virtual void UpdateCache(ICachedResponse cachedResponse, ControllerContext context, CachePolicy policy)
 {
     policy.UpdateCache(cachedResponse);
 }
 public SearchController(CachePolicy cachePolicy, string apiAddress, IAuthenticator authenticator) : base(
         cachePolicy, apiAddress, authenticator)
 {
 }
Exemplo n.º 26
0
 /// <summary>
 /// Obtiene un cliente para a partir de la aplicación autónoma de pruebas, omitiendo los valores almacenados en memoria.
 /// </summary>
 /// <param name="cachePolicy">La política para el tratamiento de la información almacenada por caché.</param>
 /// <returns>Instancia de <see cref="IAutonomousApp"/> para interactuar con el servicio.</returns>
 private IAnonymous GetAnonymousClient(CachePolicy cachePolicy = CachePolicy.BypassCache) =>
 Anonymous.Initialize(cachePolicy)
 .RoutingTo(TestingEndpointProvider.Default)
 .GetClient();
 public SearchController(CachePolicy cachePolicy, RestClient client) : base(cachePolicy, client)
 {
 }
Exemplo n.º 28
0
 public MoodboardsController(CachePolicy cachePolicy, RestClient client) : base(cachePolicy, client)
 {
 }
Exemplo n.º 29
0
 public QueryUserRecord(string userName, CachePolicy policy)
     : this(policy)
 {
     _userToRetrieve = userName;
 }
        public void TestGetItemStale()
        {
            var memcachedMock = new Mock<IMemcachedClient>();
            var enyimProvider = new EnyimMemcachedProvider<IAwesomeInterface>(memcachedMock.Object);

            var cachePolicy = new CachePolicy()
            {
                CacheDuration = 10
            };

            var proxyContext = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.ParameteredMethod("", 1));

            var hashKey = proxyContext.CreateHash();
            var obj = new[] { "", "" };

            object val = new MemcachedObject<IEnumerable<string>>()
            {
                Created = DateTime.Now.AddSeconds(-15),
                Object = obj
            };

            memcachedMock.Setup(a => a.TryGet(hashKey, out val)).Returns(true);

            var result = enyimProvider.GetItem<IEnumerable<string>>(proxyContext, cachePolicy);
            Assert.IsTrue(result.State == CachedObjectState.Stale, "Provider did not return stale, but: " + result.State);
            Assert.AreEqual(obj, result.Object, "Provider did not return object");
            Assert.IsNull(result.ThrownException, "Provider did not return null in exception field");
        }
Exemplo n.º 31
0
 public QueryUserRecord(CachePolicy policy)
     : base(policy)
 {
     _userToRetrieve = UserName;
 }
Exemplo n.º 32
0
 public void Set(string key, object data, CachePolicy cachePolicy)
 {
     HttpRuntime.Cache.Insert(key, data);
 }
        /// <summary>
        /// Returns the first element of the <paramref name="query"/>; if possible from the cache,
        /// otherwise the query is materialized asynchronously and the result cached before being returned.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="cachePolicy">The cache policy for the query.</param>
        /// <param name="tags">The list of tags to use for cache expiration.</param>
        /// <returns>default(T) if source is empty; otherwise, the first element in source.</returns>
        public static async Task <TEntity> FromCacheFirstOrDefaultAsync <TEntity>(this IQueryable <TEntity> query, CachePolicy cachePolicy = null, IEnumerable <string> tags = null)
            where TEntity : class
        {
            var q = await query
                    .Take(1)
                    .FromCacheAsync(cachePolicy, tags)
                    .ConfigureAwait(false);

            return(q.FirstOrDefault());
        }
Exemplo n.º 34
0
 public static extern uint _URLClientCreateHTTPConnection(string method,
     string url, CachePolicy cachePolicy, float timeout);
        /// <summary>
        /// Returns the result of the <paramref name="query"/>; if possible from the cache,
        /// otherwise the query is materialized and the result cached before being returned.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="cachePolicy">The cache policy for the query.</param>
        /// <param name="tags">The list of tags to use for cache expiration.</param>
        /// <returns>
        /// The result of the query.
        /// </returns>
        public static IEnumerable <TEntity> FromCache <TEntity>(this IQueryable <TEntity> query, CachePolicy cachePolicy = null, IEnumerable <string> tags = null)
            where TEntity : class
        {
            string key      = query.GetCacheKey();
            var    cacheKey = new CacheKey(key,
                                           tags ?? Enumerable.Empty <string>());

            // allow override of CacheManager
            var manager = Locator.Current.Resolve <CacheManager>();

            var result = manager.GetOrAdd(cacheKey, k => query.AsNoTracking().ToList(), cachePolicy ?? CachePolicy.Default) as IEnumerable <TEntity>;

            return(result);
        }
Exemplo n.º 36
0
 /// <summary>
 /// Creates a cache policy with CacheTimeInSeconds set to 300
 /// </summary>
 /// <param name="policy"></param>
 public CachePolicyAttribute(CachePolicy policy)
     : this(policy, DefaultSeconds)
 {
 }
        /// <summary>
        /// Returns the result of the <paramref name="query"/>; if possible from the cache,
        /// otherwise the query is materialized asynchronously and the result cached before being returned.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="cachePolicy">The cache policy for the query.</param>
        /// <param name="tags">The list of tags to use for cache expiration.</param>
        /// <returns>
        /// The result of the query.
        /// </returns>
        public static async Task <IEnumerable <TEntity> > FromCacheAsync <TEntity>(this IQueryable <TEntity> query, CachePolicy cachePolicy = null, IEnumerable <string> tags = null)
            where TEntity : class
        {
            string key      = query.GetCacheKey();
            var    cacheKey = new CacheKey(key,
                                           tags ?? Enumerable.Empty <string>());

            // allow override of CacheManager
            var manager = Locator.Current.Resolve <CacheManager>();

            var result = await manager
                         .GetOrAddAsync(
                cacheKey,
                async k => await query.AsNoTracking().ToListAsync().ConfigureAwait(false),
                cachePolicy ?? CachePolicy.Default
                )
                         .ConfigureAwait(false) as IEnumerable <TEntity>;

            return(result);
        }
 /// <summary>
 /// Returns the first element of the <paramref name="query"/>; if possible from the cache,
 /// otherwise the query is materialized and the result cached before being returned.
 /// </summary>
 /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
 /// <param name="query">The query to be materialized.</param>
 /// <param name="cachePolicy">The cache policy for the query.</param>
 /// <param name="tags">The list of tags to use for cache expiration.</param>
 /// <returns>default(T) if source is empty; otherwise, the first element in source.</returns>
 public static TEntity FromCacheFirstOrDefault <TEntity>(this IQueryable <TEntity> query, CachePolicy cachePolicy = null, IEnumerable <string> tags = null)
     where TEntity : class
 {
     // ReSharper disable once PossibleUnintendedQueryableAsEnumerable
     return(query.Take(1).FromCache(cachePolicy, tags).FirstOrDefault());
 }
Exemplo n.º 39
0
 public QueryDefaultSubverses(CachePolicy policy) : base(policy)
 {
 }
 public HTTPResponseHandler SetCachePolicy(CachePolicy policy)
 {
   cachePolicy = policy;
   return this;
 }
Exemplo n.º 41
0
 public QueryCommentTree(int submissionID, CachePolicy policy = null) : base(policy)
 {
     _submissionID = submissionID;
 }
        public void TestStoreItem_AbsoluteExpire()
        {
            var memcachedMock = new Mock<IMemcachedClient>();
            var enyimProvider = new EnyimMemcachedProvider<IAwesomeInterface>(memcachedMock.Object);

            var cachePolicy = new CachePolicy()
            {
                CacheDuration = 10,
                MaxAge = 20
            };

            var proxyContext = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.ParameteredMethod("", 1));
            var hashKey = proxyContext.CreateHash();

            var objectToStore = new[] { "", "" }.AsEnumerable();
            enyimProvider.StoreItem(proxyContext, cachePolicy, objectToStore);

            memcachedMock.Verify(a => a.Store(StoreMode.Set, hashKey, It.IsAny<MemcachedObject<IEnumerable<string>>>(), TimeSpan.FromSeconds(20)), Times.Once());
        }
Exemplo n.º 43
0
 public QueryComment(int commentID, CachePolicy policy = null) : base(policy)
 {
     this._commentID = commentID;
 }