Exemplo n.º 1
0
        public void AddTest()
        {
            var cacheKey = new CacheKey("/api/Cars", new[] { "1234", "abcdef" });
            var store    = new SqlServerEntityTagStore();
            var value    = new TimedEntityTagHeaderValue("\"abcdef1234\"")
            {
                LastModified = DateTime.Now
            };


            // first remove them
            store.RemoveAllByRoutePattern(cacheKey.RoutePattern);

            // add
            store.AddOrUpdate(cacheKey, value);

            // get
            TimedEntityTagHeaderValue dbValue;

            store.TryGetValue(cacheKey, out dbValue);


            Assert.AreEqual(value.Tag, dbValue.Tag);
            Assert.AreEqual(value.LastModified.ToString(), dbValue.LastModified.ToString());
        }
        public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag)
        {
            eTag = null;
            using (var connection = new SqlConnection(this._connectionString))
                using (var command = new SqlCommand())
                {
                    connection.Open();
                    command.Connection  = connection;
                    command.CommandText = this.GetStoredProcedureName(StoredProcedureNames.GetCache);
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue(ColumnNames.CacheKeyHash, key.Hash);

                    using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        if (!reader.HasRows)
                        {
                            return(false);
                        }

                        reader.Read();                 // there must be only one record

                        eTag = new TimedEntityTagHeaderValue((string)reader[ColumnNames.ETag])
                        {
                            LastModified = DateTime.SpecifyKind((DateTime)reader[ColumnNames.LastModified], DateTimeKind.Utc)
                        };
                        return(true);
                    }
                }
        }
Exemplo n.º 3
0
        public void RemoveByIdTest()
        {
            var cacheKey      = new CacheKey("/api/Cars", new[] { "1234", "abcdef" });
            var documentStore = new EmbeddableDocumentStore()
            {
                RunInMemory = true
            }.Initialize();

            var store = new RavenDbEntityTagStore(documentStore);
            var value = new TimedEntityTagHeaderValue("\"abcdef1234\"")
            {
                LastModified = DateTime.Now
            };


            // first remove them
            store.RemoveAllByRoutePattern(cacheKey.RoutePattern);

            // add
            store.AddOrUpdate(cacheKey, value);

            // delete
            Assert.True(store.TryRemove(cacheKey));
            Assert.True(!store.TryRemove(cacheKey));
        }
Exemplo n.º 4
0
        public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag)
        {
            eTag = null;

            if (key == null)
            {
                return(false);
            }

            var operationResult = _memcachedClient.Get <string>(key.HashBase64);

            if (operationResult == null)
            {
                return(false);
            }

            var value = operationResult;

            if (!TimedEntityTagHeaderValue.TryParse(value, out eTag))
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 5
0
        protected virtual void CheckExpiry(HttpRequestMessage request)
        {
            // not interested if not GET
            if (request.Method != HttpMethod.Get)
            {
                return;
            }

            var cacheExpiry = CacheRefreshPolicyProvider(request, _configuration);

            if (cacheExpiry == TimeSpan.MaxValue)
            {
                return; // infinity
            }
            var cacheKey = GenerateCacheKey(request);
            TimedEntityTagHeaderValue value = null;

            if (!_entityTagStore.TryGetValue(cacheKey, out value))
            {
                return;
            }

            if (value.LastModified.Add(cacheExpiry) < DateTimeOffset.Now)
            {
                _entityTagStore.TryRemove(cacheKey);
            }
        }
Exemplo n.º 6
0
        public void AddTest()
        {
            var cacheKey      = new CacheKey("/api/Cars", new[] { "1234", "abcdef" });
            var documentStore = new EmbeddableDocumentStore()
            {
                RunInMemory = true
            }.Initialize();

            new RavenDocumentsByEntityName().Execute(documentStore);

            var store = new RavenDbEntityTagStore(documentStore);
            var value = new TimedEntityTagHeaderValue("\"abcdef1234\"")
            {
                LastModified = DateTime.Now
            };


            // first remove them
            store.RemoveAllByRoutePattern(cacheKey.RoutePattern);

            // add
            store.AddOrUpdate(cacheKey, value);

            // get
            TimedEntityTagHeaderValue dbValue;

            store.TryGetValue(cacheKey, out dbValue);


            Assert.AreEqual(value.Tag, dbValue.Tag);
            Assert.AreEqual(value.LastModified.ToString(), dbValue.LastModified.ToString());
        }
Exemplo n.º 7
0
        internal Func <HttpRequestMessage, Task <HttpResponseMessage> > PutIfUnmodifiedSince()
        {
            return((request) =>
            {
                if (request.Method != HttpMethod.Put)
                {
                    return null;
                }

                DateTimeOffset?ifUnmodifiedSince = request.Headers.IfUnmodifiedSince;
                if (ifUnmodifiedSince == null)
                {
                    return null;
                }

                DateTimeOffset modifiedInQuestion = ifUnmodifiedSince.Value;

                var entityTagKey = GenerateCacheKey(request);
                TimedEntityTagHeaderValue actualEtag = null;

                bool isModified = true;
                if (_entityTagStore.TryGetValue(entityTagKey, out actualEtag))
                {
                    isModified = actualEtag.LastModified > modifiedInQuestion;
                }

                return isModified ? request.CreateResponse(HttpStatusCode.PreconditionFailed)
                .ToTask()
                                        : null;
            });
        }
Exemplo n.º 8
0
        internal Func <HttpRequestMessage, Task <HttpResponseMessage> > PutIfMatch()
        {
            return((request) =>
            {
                if (request.Method != HttpMethod.Put)
                {
                    return null;
                }

                ICollection <EntityTagHeaderValue> matchTags = request.Headers.IfMatch;
                if (matchTags == null || matchTags.Count == 0)
                {
                    return null;
                }

                var entityTagKey = GenerateCacheKey(request);
                TimedEntityTagHeaderValue actualEtag = null;

                bool matchFound = false;
                if (_entityTagStore.TryGetValue(entityTagKey, out actualEtag))
                {
                    if (matchTags.Any(etag => etag.Tag == actualEtag.Tag))
                    {
                        matchFound = true;
                    }
                }

                return matchFound ? null
                                        : request.CreateResponse(HttpStatusCode.PreconditionFailed)
                .ToTask();
            });
        }
Exemplo n.º 9
0
        // TODO: !!! routePattern implementation needs to be changed to Cas

        public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag)
        {
            // add item
            _memcachedClient.ExecuteStore(StoreMode.Set, key.HashBase64, eTag.ToString());

            // add route pattern if not there
            string keyForRoutePattern  = GetKeyForRoutePattern(key.RoutePattern);
            string keyForResourceUri   = GetKeyForResourceUri(key.ResourceUri);
            var    routePatternEntries = GetRoutePatternEntries(key.RoutePattern);
            var    resourceUriEntries  = GetResourceUriEntries(key.ResourceUri);


            if (!routePatternEntries.Contains(key.HashBase64))
            {
                var bytes = new List <byte>();
                foreach (var routePatternEntry in routePatternEntries)
                {
                    bytes.AddRange(new LengthedPrefixedString(routePatternEntry).ToByteArray());
                }
                bytes.AddRange(new LengthedPrefixedString(key.HashBase64).ToByteArray());
                _memcachedClient.ExecuteStore(StoreMode.Set, keyForRoutePattern, bytes.ToArray());
            }

            if (!resourceUriEntries.Contains(key.HashBase64))
            {
                var bytes = new List <byte>();
                foreach (var routePatternEntry in resourceUriEntries)
                {
                    bytes.AddRange(new LengthedPrefixedString(routePatternEntry).ToByteArray());
                }
                bytes.AddRange(new LengthedPrefixedString(key.HashBase64).ToByteArray());
                _memcachedClient.ExecuteStore(StoreMode.Set, keyForResourceUri, bytes.ToArray());
            }
        }
Exemplo n.º 10
0
        public async Task GivenPublishedProviderWhenRequestQueriedShouldReturnCurrentVersionAsTimedEtagHeaderValue()
        {
            string providerId                 = NewRandomString();
            string fundingPeriodId            = NewRandomString();
            string fundingStreamId            = NewRandomString();
            int    version                    = NewRandomNumber();
            string publishedProviderversionId = $"publishedprovider-{providerId}-{fundingPeriodId}-{fundingStreamId}-{version}";

            _routeValueDictionary.Add(nameof(publishedProviderversionId), publishedProviderversionId);

            PublishedProvider publishedProvider = new PublishedProvider()
            {
                Current = new PublishedProviderVersion()
                {
                    Version = NewRandomNumber()
                }
            };

            _publishedFundingRepository.GetPublishedProvider(fundingStreamId, fundingPeriodId, providerId)
            .Returns(publishedProvider);

            TimedEntityTagHeaderValue result = await WhenTheRequestIsQueried();

            result.ETag.Tag
            .Should()
            .Be($"\"{publishedProvider.Current.Version.ToString()}\"");
        }
Exemplo n.º 11
0
        public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag)
        {
            TimedEntityTagHeaderValue test;

            if (!TryGetValue(key, out test))
            {
                var cacheKey = new PersistentCacheKey
                {
                    Hash         = key.Hash,
                    RoutePattern = key.RoutePattern,
                    ETag         = eTag.Tag,
                    LastModified = eTag.LastModified,
                    ResourceUri  = key.ResourceUri
                };

                using (var connection = new MongoEntiryStoreConnection(this.connectionString))
                {
                    connection.DocumentStore.Save(cacheKey);
                }
            }
            else
            {
                using (var connection = new MongoEntiryStoreConnection(this.connectionString))
                {
                    var cacheKey = connection.DocumentStore.AsQueryable().FirstOrDefault(x => x.Hash == key.Hash);
                    if (cacheKey != null)
                    {
                        cacheKey.ETag         = eTag.Tag;
                        cacheKey.LastModified = eTag.LastModified;
                        connection.DocumentStore.Save(cacheKey);
                    }
                }
            }
        }
 public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag)
 {
     _cache.Put(key.HashBase64, eTag.ToString(), new[]
     {
         new DataCacheTag(key.ResourceUri),
         new DataCacheTag(key.RoutePattern),
     }, _regionName);
 }
Exemplo n.º 13
0
        public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag)
        {
            eTag = null;
            string value = _database.StringGet(key.HashBase64);

            if (value != null)
            {
                return(TimedEntityTagHeaderValue.TryParse(value, out eTag));
            }
            return(false);
        }
Exemplo n.º 14
0
 public static void ApplyTimedETag(this HttpResponse response, TimedEntityTagHeaderValue timedETag)
 {
     if (timedETag.LastModified.HasValue)
     {
         response.Headers[HttpHeaderNames.LastModified] = timedETag.LastModified.Value.ToUniversalTime().ToString("r");
     }
     else if (timedETag.ETag != null)
     {
         response.Headers[HttpHeaderNames.ETag] = timedETag.ETag.ToString();
     }
 }
Exemplo n.º 15
0
 public static void ApplyTimedETag(this HttpResponseMessage response, TimedEntityTagHeaderValue timedETag)
 {
     if (timedETag.LastModified.HasValue)
     {
         response.Content.Headers.LastModified = timedETag.LastModified.Value;
     }
     else if (timedETag.ETag != null)
     {
         response.Headers.ETag = timedETag.ETag;
     }
 }
        public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag)
        {
            var cacheObject = _cache.Get(key.HashBase64, _regionName) as string;

            if (!TimedEntityTagHeaderValue.TryParse(cacheObject, out eTag))
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 17
0
        public static void ToStringAndTryParseTest(string tag, bool isWeak)
        {
            var headerValue = new TimedEntityTagHeaderValue(tag, isWeak);
            var s           = headerValue.ToString();
            TimedEntityTagHeaderValue headerValue2 = null;

            Assert.IsTrue(TimedEntityTagHeaderValue.TryParse(s, out headerValue2));
            Assert.AreEqual(headerValue.Tag, headerValue2.Tag);
            Assert.AreEqual(headerValue.LastModified.ToString(), headerValue2.LastModified.ToString());
            Assert.AreEqual(headerValue.IsWeak, headerValue2.IsWeak);
            Assert.AreEqual(headerValue.ToString(), headerValue2.ToString());
        }
        public void ExtractsHeaderValueOffViewModelLastModifiedProperty()
        {
            FundingStructure metadataContents = NewFundingStructure();

            TimedEntityTagHeaderValue headerValue = WhenTheHeaderValueIsExtracted(metadataContents);

            headerValue
            ?.ETag
            ?.Tag
            .Should()
            .Be($"\"{metadataContents.LastModified.ToETagString()}\"");
        }
        public void AddGetTest()
        {
            using (var store = new InMemoryEntityTagStore())
            {
                var cacheKey = new CacheKey(Url, new[] { "Accept" });

                var headerValue = new TimedEntityTagHeaderValue("\"abcdefghijkl\"");
                store.AddOrUpdate(cacheKey, headerValue);
                TimedEntityTagHeaderValue storedHeader;
                Assert.True(store.TryGetValue(cacheKey, out storedHeader));
                Assert.AreEqual(headerValue.ToString(), storedHeader.ToString());
            }
        }
Exemplo n.º 20
0
        public void CheckStorage()
        {
            var cacheKey = GetCacheKey();
            var original = GetETag();

            _memcachedEntityTagStore.AddOrUpdate(cacheKey, original);

            TimedEntityTagHeaderValue etag = null;

            Assert.IsTrue(_memcachedEntityTagStore.TryGetValue(cacheKey, out etag), "retrieving failed!!");

            Assert.AreEqual(original.Tag, etag.Tag);
        }
 public void AddRemoveTest()
 {
     using (var store = new InMemoryEntityTagStore())
     {
         var cacheKey    = new CacheKey(Url, new[] { "Accept" });
         var headerValue = new TimedEntityTagHeaderValue("\"abcdefghijkl\"");
         store.AddOrUpdate(cacheKey, headerValue);
         store.TryRemove(cacheKey);
         TimedEntityTagHeaderValue storedHeader;
         Assert.False(store.TryGetValue(cacheKey, out storedHeader));
         Assert.IsNull(storedHeader);
     }
 }
Exemplo n.º 22
0
        public void RemoveByRoutePatternTest()
        {
            var cacheKey = GetCacheKey();
            var original = GetETag();

            _memcachedEntityTagStore.AddOrUpdate(cacheKey, original);


            var removeAllByRoutePattern    = _memcachedEntityTagStore.RemoveAllByRoutePattern(cacheKey.RoutePattern);
            TimedEntityTagHeaderValue etag = null;

            Assert.IsFalse(_memcachedEntityTagStore.TryGetValue(cacheKey, out etag), "retrieving failed!!");

            Assert.IsNull(etag);
        }
        public void ExtractsHeaderValueOfViewModelFromFundingStructurePublishedProviderVersionProperty()
        {
            PublishedProviderFundingStructure fundingStructure = new PublishedProviderFundingStructure()
            {
                PublishedProviderVersion = new RandomNumberBetween(1, int.MaxValue)
            };

            TimedEntityTagHeaderValue headerValue = WhenTheHeaderValueIsExtracted(fundingStructure);

            headerValue
            ?.ETag
            ?.Tag
            .Should()
            .Be($"\"{fundingStructure.PublishedProviderVersion.ToString()}\"");
        }
Exemplo n.º 24
0
 public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag)
 {
     using (var connection = new SqlConnection(this._connectionString))
         using (var command = new SqlCommand())
         {
             connection.Open();
             command.Connection  = connection;
             command.CommandText = this.GetStoredProcedureName(StoredProcedureNames.AddUpdateCache);
             command.CommandType = CommandType.StoredProcedure;
             command.Parameters.AddWithValue(ColumnNames.CacheKeyHash, key.Hash);
             command.Parameters.AddWithValue(ColumnNames.RoutePattern, key.RoutePattern);
             command.Parameters.AddWithValue(ColumnNames.ResourceUri, key.ResourceUri);
             command.Parameters.AddWithValue(ColumnNames.ETag, eTag.Tag);
             command.Parameters.AddWithValue(ColumnNames.LastModified, eTag.LastModified.ToUniversalTime());
             command.ExecuteNonQuery();
         }
 }
Exemplo n.º 25
0
        public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag)
        {
            eTag = null;
            var persistentCacheKey = TryGetPersistentCacheKey(key.HashBase64);

            if (persistentCacheKey != null)
            {
                eTag = new TimedEntityTagHeaderValue(persistentCacheKey.ETag)
                {
                    LastModified = persistentCacheKey.LastModified
                };

                return(true);
            }

            return(false);
        }
Exemplo n.º 26
0
        public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag)
        {
            _eTagCache.Set(key.HashBase64, eTag, DateTimeOffset.MaxValue);

            // route pattern
            var bag = new ConcurrentBag <CacheKey>();

            bag = (ConcurrentBag <CacheKey>)_routePatternCache.AddOrGetExisting(key.RoutePattern, bag
                                                                                , DateTimeOffset.MaxValue) ?? bag;
            bag.Add(key);

            // resource
            var rbag = new ConcurrentBag <CacheKey>();

            rbag = (ConcurrentBag <CacheKey>)_resourceCache.AddOrGetExisting(key.ResourceUri, rbag
                                                                             , DateTimeOffset.MaxValue) ?? rbag;
            rbag.Add(key);
        }
        public void AddRemoveByPatternTest()
        {
            const string RoutePattern = "stuff";

            using (var store = new InMemoryEntityTagStore())
            {
                var cacheKey    = new CacheKey(Url, new[] { "Accept" }, RoutePattern);
                var cacheKey2   = new CacheKey(Url + "/chaja", new[] { "Accept" }, RoutePattern);
                var headerValue = new TimedEntityTagHeaderValue("\"abcdefghijkl\"");
                store.AddOrUpdate(cacheKey, headerValue);
                store.AddOrUpdate(cacheKey2, headerValue);
                store.RemoveAllByRoutePattern(RoutePattern);
                store.TryRemove(cacheKey);
                TimedEntityTagHeaderValue storedHeader;
                Assert.False(store.TryGetValue(cacheKey, out storedHeader));
                Assert.False(store.TryGetValue(cacheKey2, out storedHeader));
                Assert.IsNull(storedHeader);
            }
        }
Exemplo n.º 28
0
        internal Func <HttpRequestMessage, Task <HttpResponseMessage> > GetIfMatchNoneMatch()
        {
            return((request) =>
            {
                if (request.Method != HttpMethod.Get)
                {
                    return null;
                }

                ICollection <EntityTagHeaderValue> noneMatchTags = request.Headers.IfNoneMatch;
                ICollection <EntityTagHeaderValue> matchTags = request.Headers.IfMatch;

                if (matchTags.Count == 0 && noneMatchTags.Count == 0)
                {
                    return null;                                    // no etag
                }
                if (matchTags.Count > 0 && noneMatchTags.Count > 0) // both if-match and if-none-match exist
                {
                    return request.CreateResponse(HttpStatusCode.BadRequest)
                    .ToTask();
                }

                var isNoneMatch = noneMatchTags.Count > 0;
                var etags = isNoneMatch ? noneMatchTags : matchTags;

                var entityTagKey = GenerateCacheKey(request);
                // compare the Etag with the one in the cache
                // do conditional get.
                TimedEntityTagHeaderValue actualEtag = null;

                bool matchFound = false;
                if (_entityTagStore.TryGetValue(entityTagKey, out actualEtag))
                {
                    if (etags.Any(etag => etag.Tag == actualEtag.Tag))
                    {
                        matchFound = true;
                    }
                }
                return matchFound ^ isNoneMatch ? null : new NotModifiedResponse(request,
                                                                                 actualEtag.ToEntityTagHeaderValue()).ToTask();
            });
        }
Exemplo n.º 29
0
        public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag)
        {
            eTag = null;

            using (var connection = new MongoEntiryStoreConnection(this.connectionString))
            {
                var cacheKey = connection.DocumentStore.AsQueryable().FirstOrDefault(x => x.Hash == key.Hash);
                if (null == cacheKey)
                {
                    return(false);
                }

                eTag = new TimedEntityTagHeaderValue(cacheKey.ETag)
                {
                    LastModified = cacheKey.LastModified
                };

                return(true);
            }
        }
Exemplo n.º 30
0
        public bool TryGetValue(CacheKey key, out TimedEntityTagHeaderValue eTag)
        {
            eTag = null;
            using (var session = _documentStore.OpenSession())
            {
                var cacheKey = session.Query <PersistentCacheKey>()
                               .Customize(x => x.WaitForNonStaleResultsAsOfNow())
                               .FirstOrDefault(x => x.Hash == key.Hash);
                if (null == cacheKey)
                {
                    return(false);
                }

                eTag = new TimedEntityTagHeaderValue(cacheKey.ETag)
                {
                    LastModified = cacheKey.LastModified
                };
                return(true);
            }
        }