Пример #1
0
        public ApplicationRegistration RegisterUpns(ApplicationRegistration registration, IEnumerable <string> upns)
        {
            if (registration == null)
            {
                throw new ArgumentException($"Cannot update null or empty {nameof(ApplicationRegistration)}.");
            }

            var utcNow   = DateTimeOffset.UtcNow;
            var existing = registration.Upns?.Select(x => x.Suffix.ToLower());
            var unique   = upns.Where(x => !string.IsNullOrWhiteSpace(x) &&
                                      !existing.Contains(x))
                           .Select(x => new DirectoryUpn
            {
                ApplicationRegistrationId = registration.Id,
                DateCreatedUtc            = utcNow,
                Suffix = x.ToLower()
            });

            using (var db = _connectionFactory.OpenDbConnection())
            {
                db.InsertAll(unique);

                _cacheClient.RemoveAll(existing.Select(x => UrnId.Create(typeof(DirectoryRegistrationLookup), x)));
                _cacheClient.Remove(UrnId.Create(typeof(ApplicationRegistration), registration.Id.ToString()));

                // Return uncached version to avoid possible race returning invalid cached data.
                var q = db.From <ApplicationRegistration>()
                        .Where(x => x.Id == registration.Id);
                return(db.LoadSelect(q).FirstOrDefault());
            }
        }
Пример #2
0
 public bool FlushDB(string key = "*")
 {
     if (!IsCachingServer)
     {
         return(false);
     }
     try
     {
         if (key.Length < 1 || key == "*")
         {
             Sut.FlushDb();
             return(true);
         }
         else
         {
             var keys = Sut.SearchKeys(key + ":*");
             if (keys.Count() > 0)
             {
                 Sut.RemoveAll(keys);
             }
             return(true);
         }
     }
     catch
     {
         return(false);
     }
 }
Пример #3
0
        public void Can_use_batch_operations()
        {
            cache.SetAll(new Dictionary <string, string>
            {
                { "Car", "Audi" },
                { "Phone", "MotoX" }
            });

            var response = cache.GetAll <string>(new List <string> {
                "Car", "Phone"
            });

            Assert.That(response["Car"], Is.EqualTo("Audi"));
            Assert.That(response["Phone"], Is.EqualTo("MotoX"));

            var singleResponse = cache.Get <string>("Phone");

            Assert.That(singleResponse, Is.EqualTo("MotoX"));

            cache.RemoveAll(new List <string> {
                "Car", "Phone"
            });

            response = cache.GetAll <string>(new List <string> {
                "Car", "Phone"
            });
            Assert.That(response["Car"], Is.EqualTo(default(string)));
            Assert.That(response["Phone"], Is.EqualTo(default(string)));
        }
        public void Publish <T>(String DocumentId, T Payload, ChangeType Type = ChangeType.CHANGE)
        {
            var interested = _subscriptions.Where(x => x.DocumentId == DocumentId && x.Document == typeof(T).FullName);

            if (Type == ChangeType.NEW)
            {
                var interestedNew = _subscriptions.Where(x => x.Document == typeof(T).FullName && x.DocumentId.IsNullOrEmpty());

                foreach (var sub in interestedNew)
                {
                    Manage <T>(sub.CacheKey, DocumentId, sub.SubscriptionId, sub.Session);
                }

                interested = interested.Concat(interestedNew);
            }
            interested = interested.Distinct(x => x.SubscriptionId);

            // Delete entries from cache (new data == old data stale)
            _cache.RemoveAll(interested.Select(x => x.CacheKey).Distinct());

            foreach (var sub in interested)
            {
                _sse.NotifySession(sub.Session,
                                   "forte.Update",
                                   new Responses.Update <T>
                {
                    Payload = Payload,
                    Type    = Type,
                    //Etag = ETag,
                    SubscriptionId = sub.SubscriptionId
                });
            }
        }
Пример #5
0
        public static void ClearCaches(this ICacheClient cacheClient, params string[] cacheKeys)
        {
            var allContentTypes = new List <string>(EndpointHost.ContentTypes.ContentTypeFormats.Values)
            {
                MimeTypes.XmlText, MimeTypes.JsonText, MimeTypes.JsvText
            };

            var allCacheKeys = new List <string>();

            foreach (var cacheKey in cacheKeys)
            {
                allCacheKeys.Add(cacheKey);
                foreach (var serializedExt in allContentTypes)
                {
                    var serializedCacheKey = GetCacheKeyForSerialized(cacheKey, serializedExt, null);
                    allCacheKeys.Add(serializedCacheKey);

                    foreach (var compressionType in CompressionTypes.AllCompressionTypes)
                    {
                        allCacheKeys.Add(GetCacheKeyForCompressed(serializedCacheKey, compressionType));
                    }
                }
            }

            cacheClient.RemoveAll(allCacheKeys);
        }
Пример #6
0
        public async Task Flush()
        {
            // Copy and empty the bag
            var updates = _updates.Values.ToList();

            _updates.Clear();


            var notifies = new Dictionary <String, IList <Responses.Update> >();


            foreach (var doc in updates)
            {
                var interested = await RetrieveInterested(doc.Document, doc.DocumentId);

                foreach (var interest in interested.Distinct(x => new { x.Session, x.SubscriptionId }))
                {
                    if (!notifies.ContainsKey(interest.Session))
                    {
                        notifies[interest.Session] = new List <Responses.Update>();
                    }

                    notifies[interest.Session].Add(new Responses.Update
                    {
                        Payload        = doc.Payload,
                        Etag           = doc.Etag,
                        Stamp          = doc.Stamp,
                        SubscriptionId = interest.SubscriptionId,
                        Type           = doc.Type
                    });
                }

                // Delete entries from cache (new data == old data stale)
                var keys = interested.Select(x => x.CacheKey).Distinct();
                if (keys.Count() != 0)
                {
                    _cache.RemoveAll(keys.ToArray());
                }
            }

            foreach (var job in notifies)
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.DebugFormat("Notifying session {0} of {1} values", job.Key, job.Value.Count);
                }
                _sse.NotifySession(job.Key, "Demo.Update", job.Value.ToArray());
            }

            await _storage.Clean();
        }
        public void Can_remove_multiple_items()
        {
            var map = 5.Times(i => new Item {
                Id = i, Name = "Name" + i
            })
                      .ToSafeDictionary(x => x.ToUrn());

            Cache.SetAll(map);

            Cache.RemoveAll(map.Keys);

            var cacheMap = Cache.GetAll <Item>(map.Keys);

            Assert.That(cacheMap.Count, Is.EqualTo(5));
            Assert.That(cacheMap.Values.All(x => x == null));
        }
        protected static void AssertCacheClientIntModelValuesAsKeysWithNullValues(
			ICacheClient cacheClient)
        {
            var allKeys = new[] { "test:intkey1", "test:intkey2", "test:intkey3" };
            var expectedValues = new[] { 1, default(int), 3 };
            cacheClient.RemoveAll(allKeys);

            cacheClient.Set(allKeys[0], expectedValues[0]);
            cacheClient.Set(allKeys[2], expectedValues[2]);

            var keyValues = cacheClient.GetAll<int>(allKeys);
            Assert.That(keyValues, Has.Count.EqualTo(expectedValues.Length));

            for (var keyIndex = 0; keyIndex < expectedValues.Length; keyIndex++)
            {
                var key = allKeys[keyIndex];
                var keyValue = keyValues[key];
                Assert.That(keyValue, Is.EqualTo(expectedValues[keyIndex]));
            }
        }
Пример #9
0
        /// <summary>
        /// Clears all the serialized and compressed caches set
        /// by the 'Resolve' method for the cacheKey provided
        /// </summary>
        /// <param name="cacheClient">The cache client.</param>
        /// <param name="cacheKeys">The cache keys.</param>
        public static void Clear(ICacheClient cacheClient, params string[] cacheKeys)
        {
            var allCacheKeys = new List <string>();

            foreach (var cacheKey in cacheKeys)
            {
                allCacheKeys.Add(cacheKey);
                foreach (var serializedExt in AllCachedContentTypes)
                {
                    var serializedCacheKey = GetSerializedCacheKey(cacheKey, serializedExt, null);
                    allCacheKeys.Add(serializedCacheKey);

                    foreach (var compressionType in CompressionTypes.AllCompressionTypes)
                    {
                        allCacheKeys.Add(GetCompressedCacheKey(serializedCacheKey, compressionType));
                    }
                }
            }

            cacheClient.RemoveAll(allCacheKeys);
        }
        protected static void AssertCacheClientIntModelValuesAsKeysWithNullValues(
            ICacheClient cacheClient)
        {
            var allKeys        = new[] { "test:intkey1", "test:intkey2", "test:intkey3" };
            var expectedValues = new[] { 1, default(int), 3 };

            cacheClient.RemoveAll(allKeys);

            cacheClient.Set(allKeys[0], expectedValues[0]);
            cacheClient.Set(allKeys[2], expectedValues[2]);

            var keyValues = cacheClient.GetAll <int>(allKeys);

            Assert.That(keyValues, Has.Count.EqualTo(expectedValues.Length));

            for (var keyIndex = 0; keyIndex < expectedValues.Length; keyIndex++)
            {
                var key      = allKeys[keyIndex];
                var keyValue = keyValues[key];
                Assert.That(keyValue, Is.EqualTo(expectedValues[keyIndex]));
            }
        }
        public void RemoveAll(IEnumerable <string> keys)
        {
            CheckNotDisposedOrThrow();

            if (keys == null)
            {
                throw new ArgumentNullException(nameof(keys));
            }

            PerKeyCacheClientRuleAggregator aggregator
                = new PerKeyCacheClientRuleAggregator();

            try
            {
                //The naive approach would be to find the cache client for each key
                // then issue a Remove() call for that key and value,
                // but that won't use any optimisation a cache client might have for bulk operations.
                //Issuing a RemoveAll() for each client with the given set of values, doesn't work either,
                // since that would bypass any routing.
                //So, we need to see first which key by which client can be resolved,
                // and then issue a RemoveAll() on each client using only the subset of keys
                // it can resolve

                aggregator.CollectAll(keys, FindRule);

                foreach (KeyValuePair <Guid, IList <string> > keysForClient in aggregator.KeysForCacheClient)
                {
                    ICacheClient client = aggregator
                                          .CacheClients[keysForClient.Key];

                    client.RemoveAll(keysForClient.Value);
                }
            }
            finally
            {
                aggregator.Clear();
            }
        }
Пример #12
0
        public void RemoveCacheByPrefix(string keyPrefix)
        {
            var keys = RedisClient.SearchKeys(keyPrefix + "*");

            RedisClient.RemoveAll(keys);
        }
        public void RemoveByPattern(string pattern)
        {
            var keys = _database.SearchKeys(pattern);

            _database.RemoveAll(keys);
        }
Пример #14
0
 public void RemoveAll(IEnumerable <string> keys)
 {
     cache.RemoveAll(keys.Select(x => prefix + x));
 }
Пример #15
0
        public static void ClearCaches(this ICacheClient cache, params string[] cacheKeys)
        {
            var allCacheKeys = GetAllContentCacheKeys(cacheKeys);

            cache.RemoveAll(allCacheKeys);
        }
Пример #16
0
 public void RemoveAll(IEnumerable <string> keys)
 {
     _clientExt.RemoveAll(keys);
 }
Пример #17
0
        public async Task Flush()
        {
            // Copy and empty the bag
            var updates = _updates.Values.ToList();
            _updates.Clear();

            var notifies = new Dictionary<string, IList<Responses.Update>>();

            foreach (var doc in updates.GroupBy(x => x.Document))
            {
                var interested = await _storage.Retreive(x => x.Document == doc.Key).ConfigureAwait(false);
                var indirect = interested.Where(x => x.DocumentId == "");
                foreach (var indv in doc)
                {
                    var all = interested.Where(x => x.DocumentId == indv.DocumentId).ToList();

                    // Don't foreach over all the indirect because indirect contains all the open list subscriptions
                    // and the doc we are looking at might already be subscribed to which would be weeded out by the Union above
                    foreach (var paged in indirect)
                    {
                        if (all.Any(x => x.Session == paged.Session && x.SubscriptionId == paged.SubscriptionId)) continue;
                        // Deserialize the original query that generated the list of data
                        // Run the dto through the query to test if the conditions are satisfied
                        // If so, add a new subscription and notify client of new element on list

                        // Todo: using a bit of reflection to call open generic IChange.Satisfied can replace once IChange is implemented more like FluentValidation than a generic interface see PUL-5

                        var queryType = Type.GetType(paged.SerializedQueryType);
                        var query = JsonConvert.DeserializeObject(paged.SerializedQuery, queryType);

                        var pagedType = queryType.GetInterfaces().Single(x => x.IsInterface && x.GetInterfaces().Contains(typeof(IPaged)));

                        var changeType = typeof(IChange<,>).MakeGenericType(indv.Payload.GetType(), pagedType);
                        var satisfiedChange = changeType.GetMethod("Satisfied", BindingFlags.Public | BindingFlags.Instance);

                        var change = _container.TryGetInstance(changeType);
                        if (query == null || change == null || !(bool)satisfiedChange.Invoke(change, new[] { indv.Payload, query })) continue;


                        var subscription = new Subscription
                        {
                            SerializedQuery = paged.SerializedQuery,
                            SubscriptionId = paged.SubscriptionId,
                            Document = indv.Document,
                            DocumentId = indv.DocumentId,
                            CacheKey = paged.CacheKey,
                            Expires = paged.Expires,
                            Session = paged.Session,
                            Type = paged.Type
                        };
                        all.Add(subscription);
                        await _storage.Store(subscription).ConfigureAwait(false);
                    }

                    foreach (var interest in all)
                    {
                        var key = interest.Session;
                        if (!notifies.ContainsKey(key))
                            notifies[key] = new List<Responses.Update>();

                        notifies[key].Add(new Responses.Update
                        {
                            Payload = indv.Payload,
                            Etag = indv.Etag,
                            Stamp = indv.Stamp,
                            SubscriptionId = interest.SubscriptionId,
                            Type = indv.Type
                        });
                    }
                }

                // Delete entries from cache (new data == old data stale)
                var keys = interested.Select(x => x.CacheKey).Distinct();
                if (keys.Count() != 0)
                    _cache.RemoveAll(keys.ToArray());
            }

            foreach (var job in notifies)
            {
                if (Logger.IsDebugEnabled)
                    Logger.DebugFormat("Notifying session {0} of {1} values", job.Key, job.Value.Count);
                _sse.NotifySession(job.Key, "Demo.Update", job.Value.ToArray());
            }

            await _storage.Clean().ConfigureAwait(false);
        }
Пример #18
0
 public void RemoveAll(IEnumerable <string> keys)
 {
     cache.RemoveAll(keys.Select(EnsurePrefix));
 }