Пример #1
0
 public static void CacheSet<T>(this ICacheClient cache, string key, T value, TimeSpan? expiresIn)
 {
     if (expiresIn.HasValue)
         cache.Set(key, value, expiresIn.Value);
     else
         cache.Set(key, value);
 }
Пример #2
0
        public void PlanChanged(string organizationId)
        {
            if (!Settings.Current.EnableSignalR)
            {
                return;
            }

            if (GlobalHost.ConnectionManager == null)
            {
                return;
            }

            IHubContext context = GlobalHost.ConnectionManager.GetHubContext <Notifier>();

            if (context == null)
            {
                return;
            }

            // throttle notifications to one every 2 seconds.
            var lastNotification = _cacheClient.Get <DateTime>(String.Concat("SignalR.Org.", organizationId));

            if (!(DateTime.Now.Subtract(lastNotification).TotalSeconds >= 2))
            {
                return;
            }

            context.Clients.Group(organizationId).planChanged(organizationId);
            _cacheClient.Set(String.Concat("SignalR.Org.", organizationId), DateTime.Now);
        }
Пример #3
0
 public void Set(string key, object value)
 {
     try
     {
         _client.Set <T>(key, value as T);
     }
     catch { }
 }
        public static object Cache(this ICacheClient cacheClient,
                                   string cacheKey,
                                   object responseDto,
                                   IRequest request,
                                   TimeSpan?expireCacheIn = null)
        {
            cacheClient.Set(cacheKey, responseDto, expireCacheIn);

            if (!request.ResponseContentType.IsBinary())
            {
                string serializedDto = HostContext.ContentTypes.SerializeToString(request, responseDto);

                string modifiers = null;
                if (request.ResponseContentType.MatchesContentType(MimeTypes.Json))
                {
                    var jsonp = request.GetJsonpCallback();
                    if (jsonp != null)
                    {
                        modifiers     = ".jsonp," + jsonp.SafeVarName();
                        serializedDto = jsonp + "(" + serializedDto + ")";

                        //Add a default expire timespan for jsonp requests,
                        //because they aren't cleared when calling ClearCaches()
                        if (expireCacheIn == null)
                        {
                            expireCacheIn = HostContext.Config.DefaultJsonpCacheExpiration;
                        }
                    }
                }

                var cacheKeySerialized = GetCacheKeyForSerialized(cacheKey, request.ResponseContentType, modifiers);
                cacheClient.Set(cacheKeySerialized, serializedDto, expireCacheIn);

                var  compressionType = request.GetCompressionType();
                bool doCompression   = compressionType != null;
                if (doCompression)
                {
                    var cacheKeySerializedZip = GetCacheKeyForCompressed(cacheKeySerialized, compressionType);

                    byte[] compressedSerializedDto = serializedDto.Compress(compressionType);
                    cacheClient.Set(cacheKeySerializedZip, compressedSerializedDto, expireCacheIn);

                    return((compressedSerializedDto != null)
                        ? new CompressedResult(compressedSerializedDto, compressionType, request.ResponseContentType)
                        : null);
                }

                return(serializedDto);
            }
            else
            {
                string modifiers          = null;
                byte[] serializedDto      = HostContext.ContentTypes.SerializeToBytes(request, responseDto);
                var    cacheKeySerialized = GetCacheKeyForSerialized(cacheKey, request.ResponseContentType, modifiers);
                cacheClient.Set(cacheKeySerialized, serializedDto, expireCacheIn);
                return(serializedDto);
            }
        }
        private void SetLockerCacheItems(string username, IEnumerable <LockerRelease> lockerReleases, LockerStats totalItems)
        {
            var cacheTtl           = TimeSpan.FromDays(7);
            var lockerCacheKey     = CacheKeys.LockerCacheKey(username);
            var totalItemsCacheKey = CacheKeys.LockerTotalItemsCacheKey(username);

            _cacheClient.Set(totalItemsCacheKey, totalItems, cacheTtl);
            _cacheClient.Set(lockerCacheKey, lockerReleases, cacheTtl);
        }
Пример #6
0
 public static void CacheSet <T>(ICacheClient cacheClient, string cacheKey, T result, TimeSpan?expireCacheIn)
 {
     if (expireCacheIn.HasValue)
     {
         cacheClient.Set(cacheKey, result, expireCacheIn.Value);
     }
     else
     {
         cacheClient.Set(cacheKey, result);
     }
 }
        public void Can_store_and_get_model()
        {
            var model    = ModelWithIdAndName.Create(1);
            var cacheKey = model.CreateUrn();

            cacheClient.Set(cacheKey, model);

            var existingModel = cacheClient.Get <ModelWithIdAndName>(cacheKey);

            ModelWithIdAndName.AssertIsEqual(existingModel, model);
        }
Пример #8
0
 public static void Set <T>(this ICacheClient cacheClient, string cacheKey, T value, TimeSpan?expireCacheIn)
 {
     if (expireCacheIn.HasValue)
     {
         cacheClient.Set(cacheKey, value, expireCacheIn.Value);
     }
     else
     {
         cacheClient.Set(cacheKey, value);
     }
 }
Пример #9
0
        public void Can_set_get_and_remove()
        {
            cache.Set("Car", "Audi");
            var response = cache.Get <string>("Car");

            Assert.That(response, Is.EqualTo("Audi"));

            cache.Remove("Car");
            response = cache.Get <string>("Car");
            Assert.That(response, Is.EqualTo(default(string)));
        }
Пример #10
0
 /// <summary>
 /// Add key-value to cache.
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <param name="expirationTime"></param>
 public override void Add(string key, ProfileModel value, DateTime?expirationTime)
 {
     if (expirationTime == null)
     {
         _redisClient.Set(key, value);
     }
     else
     {
         var expireIn = expirationTime.Value - DateTime.Now;
         _redisClient.Set(key, value, expireIn);
     }
 }
Пример #11
0
 public object this[string key]
 {
     get
     {
         return(cacheClient.Get <object>(this.prefixNs + key));
     }
     set
     {
         JsWriter.WriteDynamic(() =>
                               cacheClient.Set(this.prefixNs + key, value));
     }
 }
Пример #12
0
        internal static QueryDataSource <T> CacheMemorySource <T>(this MemoryDataSource <T> response, ICacheClient cache, string cacheKey, TimeSpan?expiresIn)
        {
            if (expiresIn != null)
            {
                cache.Set(cacheKey, response.Data, expiresIn.Value);
            }
            else
            {
                cache.Set(cacheKey, response.Data);
            }

            return(response);
        }
Пример #13
0
        public void Does_flush_all()
        {
            3.Times(i =>
                    Cache.Set(i.ToUrn <Item>(), new Item {
                Id = i, Name = "Name" + i
            }));

            Assert.That(Cache.Get <Item>(1.ToUrn < Item > ()), Is.Not.Null);

            Cache.FlushAll();

            Assert.That(Cache.Get <Item>(1.ToUrn < Item > ()), Is.Null);
        }
Пример #14
0
        private void ScanSingbackIfNecessary()
        {
            if (_singbackIsScanned)
            {
                return;
            }

            foreach (KeyValuePair <string, string> keyValuePair in _singbackScanner.Scan())
            {
                _cacheClient.Set(GetSongNumberKey(keyValuePair.Key), keyValuePair.Value);
            }

            _singbackIsScanned = true;
        }
Пример #15
0
        public static object Cache(this ICacheClient cacheClient,
                                   string cacheKey,
                                   object responseDto,
                                   IRequestContext context,
                                   TimeSpan?expireCacheIn = null)
        {
            cacheClient.Set(cacheKey, responseDto, expireCacheIn);

            string serializedDto = EndpointHost.ContentTypeFilter.SerializeToString(context, responseDto);

            string jsonp = null, modifiers = null;

            if (context.ContentType == ContentType.Json)
            {
                jsonp = context.Get <IHttpRequest>().GetJsonpCallback();
                if (jsonp != null)
                {
                    modifiers     = ".jsonp," + jsonp.SafeVarName();
                    serializedDto = jsonp + "(" + serializedDto + ")";

                    //Add a default expire timespan for jsonp requests,
                    //because they aren't cleared when calling ClearCaches()
                    if (expireCacheIn == null)
                    {
                        expireCacheIn = EndpointHost.Config.DefaultJsonpCacheExpiration;
                    }
                }
            }

            var cacheKeySerialized = GetCacheKeyForSerialized(cacheKey, context.ResponseContentType, modifiers);

            cacheClient.Set <string>(cacheKeySerialized, serializedDto, expireCacheIn);

            bool doCompression = context.CompressionType != null;

            if (doCompression)
            {
                var cacheKeySerializedZip = GetCacheKeyForCompressed(cacheKeySerialized, context.CompressionType);

                byte[] compressedSerializedDto = ServiceStack.Common.StreamExtensions.Compress(serializedDto, context.CompressionType);
                cacheClient.Set <byte[]>(cacheKeySerializedZip, compressedSerializedDto, expireCacheIn);

                return((compressedSerializedDto != null)
                                        ? new CompressedResult(compressedSerializedDto, context.CompressionType, context.ContentType)
                                        : null);
            }

            return(serializedDto);
        }
        public override void EventProcessing(EventContext context)
        {
            var user = context.Event.GetUserIdentity();

            if (user == null || String.IsNullOrEmpty(user.Identity) || !String.IsNullOrEmpty(context.Event.SessionId))
            {
                return;
            }

            string cacheKey  = String.Format("session:{0}:{1}", context.Event.ProjectId, user.Identity);
            var    sessionId = context.Event.Type != Event.KnownTypes.SessionStart ? _cacheClient.Get <string>(cacheKey) : null;

            if (sessionId == null)
            {
                sessionId = Guid.NewGuid().ToString("N");
                _cacheClient.Set(cacheKey, sessionId, _sessionTimeout);
            }
            else
            {
                _cacheClient.SetExpiration(cacheKey, _sessionTimeout);
            }

            context.Event.SessionId = sessionId;

            if (context.Event.Type == Event.KnownTypes.SessionEnd)
            {
                _cacheClient.Remove(cacheKey);
            }
        }
        public void AssertGetSetIntValue(ICacheClient cacheClient)
        {
            cacheClient.Set("test:intkey1", 1);
            var value = cacheClient.Get <int>("test:intkey1");

            Assert.That(value, Is.EqualTo(1));
        }
Пример #18
0
        public override JobLock Acquire(string lockName)
        {
            int result = 0;

            try {
                var lockValue = _cacheClient.Get <object>("joblock:" + lockName);
                if (lockValue != null)
                {
                    return(new JobLock(this, lockName, false));
                }

                _cacheClient.Set("joblock:" + lockName, DateTime.Now, TimeSpan.FromMinutes(20));

                result = 1;
            } catch (Exception e) {
                Log.Error().Exception(e).Message("Error attempting to acquire job lock '{0}' on {1}.", lockName, Environment.MachineName).Report().Write();
            }

            if (Settings.Current.LogJobLocks)
            {
                string processName = "{Unknown}";
                int    processId   = 0;
                try {
                    Process p = Process.GetCurrentProcess();
                    processId   = p.Id;
                    processName = p.ProcessName;
                } catch {}
                Log.Debug().Message(result == 1
                    ? "Acquired job lock '{0}' on {1}; process {2}:{3}"
                    : "Could not acquire job lock '{0}' on {1}; process {2}:{3}",
                                    lockName, Environment.MachineName, processName, processId).Write();
            }

            return(new JobLock(this, lockName, result == 1));
        }
Пример #19
0
        public async void AsyncMethod()
        {
            ICacheClient client = null;

            await Task.Run(() => Console.WriteLine());

            client.Set <List <Guid> >("", "", new List <Guid>());
        }
 public static bool TrySet <T>(this ICacheClient client, string key, T value, TimeSpan expiresIn)
 {
     try {
         return(client.Set(key, value, expiresIn));
     } catch (Exception) {
         return(false);
     }
 }
        protected static void AssertCacheClientMissingModelValuesAsKeysWithNullValues(
			ICacheClient cacheClient)
        {
            var allKeys = new[] { "test:modelkey1", "test:modelkey2", "test:modelkey3" };
            var expectedValues = new[] { ModelWithIdAndName.Create(1), null, ModelWithIdAndName.Create(1) };
            cacheClient.Set(allKeys[0], expectedValues[0]);
            cacheClient.Set(allKeys[2], expectedValues[2]);

            var keyValues = cacheClient.GetAll<ModelWithIdAndName>(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];

                ModelWithIdAndName.AssertIsEqual(keyValue, expectedValues[keyIndex]);
            }
        }
Пример #22
0
        public override async Task EventProcessingAsync(EventContext context)
        {
            if (Settings.Current.WebsiteMode == WebsiteMode.Dev)
            {
                return;
            }

            var project = _projectRepository.GetById(context.Event.ProjectId);

            if (project == null || !project.DeleteBotDataEnabled)
            {
                return;
            }

            // Throttle errors by client ip address to no more than X every 5 minutes.
            var ri = context.Event.GetRequestInfo();

            if (ri == null || String.IsNullOrEmpty(ri.ClientIpAddress))
            {
                return;
            }

            if (ri.ClientIpAddress.IsPrivateNetwork())
            {
                return;
            }

            string throttleCacheKey = String.Concat("bot:", ri.ClientIpAddress, ":", DateTime.Now.Floor(_throttlingPeriod).Ticks);
            var    requestCount     = _cacheClient.Get <int?>(throttleCacheKey);

            if (requestCount != null)
            {
                _cacheClient.Increment(throttleCacheKey, 1);
                requestCount++;
            }
            else
            {
                _cacheClient.Set(throttleCacheKey, 1, _throttlingPeriod);
                requestCount = 1;
            }

            if (requestCount < Settings.Current.BotThrottleLimit)
            {
                return;
            }

            await _metricsClient.CounterAsync(MetricNames.EventsBotThrottleTriggered);

            Log.Info().Message("Bot throttle triggered. IP: {0} Time: {1} Project: {2}", ri.ClientIpAddress, DateTime.Now.Floor(_throttlingPeriod), context.Event.ProjectId).Project(context.Event.ProjectId).Write();

            // TODO: We should kick this off into a long running task.
            // the throttle was triggered, go and delete all the errors that triggered the throttle to reduce bot noise in the system
            _eventRepository.HideAllByClientIpAndDateAsync(context.Event.OrganizationId, ri.ClientIpAddress, DateTime.Now.Floor(_throttlingPeriod), DateTime.Now.Ceiling(_throttlingPeriod));
            context.IsCancelled = true;
        }
Пример #23
0
        public object Post(IssueLicense issueRequest)
        {
            var machineKeySection = WebConfigurationManager.GetSection("system.web/machineKey") as MachineKeySection;

            if (machineKeySection == null || StringComparer.OrdinalIgnoreCase.Compare(machineKeySection.Decryption, "Auto") == 0)
            {
                throw new Exception(Properties.Resources.InvalidMachineKeySection);
            }

            var license = documentSession
                          .Include <Model.License, Customer>(lic => lic.CustomerId)
                          .Include <Product>(lic => lic.ProductId)
                          .Load <Model.License>(issueRequest.Id);

            if (license == null)
            {
                HttpError.NotFound("License not found!");
            }

            var customer = documentSession.Load <Customer>(license.CustomerId);
            var product  = documentSession.Load <Product>(license.ProductId);

            var licenseFile =
                Portable.Licensing.License.New()
                .WithUniqueIdentifier(license.LicenseId)
                .As(license.LicenseType)
                .WithMaximumUtilization(license.Quantity)
                .ExpiresAt(license.Expiration)
                .LicensedTo(c =>
            {
                c.Name    = customer.Name;
                c.Email   = customer.Email;
                c.Company = customer.Company;
            })
                .WithProductFeatures(license.ProductFeatures)
                .WithAdditionalAttributes(license.AdditionalAttributes)
                .CreateAndSignWithPrivateKey(product.KeyPair.EncryptedPrivateKey,
                                             machineKeySection.DecryptionKey);

            var issueToken = Guid.NewGuid();

            cacheClient.Set(UrnId.Create <Model.License>("IssueToken", issueToken.ToString()), licenseFile, new TimeSpan(0, 5, 0));

            return(new HttpResult(new IssueLicenseResponse {
                Token = issueToken
            })
            {
                StatusCode = HttpStatusCode.Created,
                Headers =
                {
                    { HttpHeaders.Location, Request.AbsoluteUri.AddQueryParam("token", issueToken) }
                }
            });
        }
        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]));
            }
        }
Пример #25
0
        /// <summary>
        /// Caches the specified item using the context information
        /// </summary>
        /// <typeparam name="T">Type of object to cache</typeparam>
        /// <param name="cache">Cache to store the object</param>
        /// <param name="context">Context information for how to cache the object</param>
        /// <param name="key">Cache key</param>
        /// <param name="item">Item to cache</param>
        public static void CacheAndSetTriggers <T>(this ICacheClient cache, CacheContext context, string key, T item)
        {
            // Don't cache if there is no context
            if (context == null)
            {
                return;
            }

            // Don't cache if there are no profile durations configured
            if (CacheStackSettings.CacheProfileDurations == null)
            {
                return;
            }

            var expiration = CacheStackSettings.CacheProfileDurations(context.CacheProfile);

            cache.Set(key, item, expiration);

            // Rip through all other keys for this object type and add the item under those cache keys too
            var itemType = typeof(T);

            if (CacheStackSettings.CacheKeysForObject != null && CacheStackSettings.CacheKeysForObject.ContainsKey(itemType))
            {
                var keys = CacheStackSettings.CacheKeysForObject[itemType](item).ToList();
                // Only setup the other cache keys if the current key exists in them. Should prevent some undesirable results if caching partial objects
                if (keys.Any(x => x == key))
                {
                    foreach (var k in keys)
                    {
                        if (k == key)
                        {
                            continue;
                        }
                        cache.Set(k, item, expiration);
                        AddKeyToTriggers(context, k);
                    }
                }
            }

            AddKeyToTriggers(context, key);
        }
Пример #26
0
        public static void UpdateCache <T>(this T obj, ICacheClient cache) where T : class, IHasGuidId
        {
            var key = UrnId.Create <T>(obj.Id);

            Wrapper <T> wrapper = key.FromCache <T>(cache)
                                  ?? obj.Wrap();

            wrapper.Payload = obj;
            wrapper.Version++;

            cache.Set(key, wrapper.ToJson());
        }
        public static T GetOrCreate <T>(this ICacheClient cache,
                                        string key, TimeSpan expiresIn, Func <T> createFn)
        {
            var value = cache.Get <T>(key);

            if (Equals(value, default(T)))
            {
                value = createFn();
                cache.Set(key, value, expiresIn);
            }
            return(value);
        }
        protected static void AssertCacheClientMissingModelValuesAsKeysWithNullValues(
            ICacheClient cacheClient)
        {
            var allKeys        = new[] { "test:modelkey1", "test:modelkey2", "test:modelkey3" };
            var expectedValues = new[] { ModelWithIdAndName.Create(1), null, ModelWithIdAndName.Create(1) };

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

            var keyValues = cacheClient.GetAll <ModelWithIdAndName>(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];

                ModelWithIdAndName.AssertIsEqual(keyValue, expectedValues[keyIndex]);
            }
        }
Пример #29
0
        public IActionResult TestCache()
        {
            DateTime?dt = _cacheClient.Get <DateTime?>("time");

            if (dt == null)
            {
                dt = DateTime.Now;
                _cacheClient.Set <DateTime?>("time", dt.Value, TimeSpan.FromMinutes(1));
            }

            return(Content(dt.Value.ToString()));
        }
        public async Task StartSubscription(CancellationToken ct = default(CancellationToken))
        {
            if (_subscriptionTask == null)
            {
                await _mutex.WaitAsync(ct).ConfigureAwait(false);

                try
                {
                    if (_subscriptionTask == null)
                    {
                        var serviceUris = await _serviceSubscriber.Endpoints(ct).ConfigureAwait(false);

                        _cache.Set(_id, serviceUris);
                        _subscriptionTask = StartSubscriptionLoop(serviceUris);
                    }
                }
                finally
                {
                    _mutex.Release();
                }
            }
        }
        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]));
            }
        }
Пример #32
0
        public static async Task <T> GetOrCreateAsync <T>(this ICacheClient cache,
                                                          string key, Func <Task <T> > createFn)
        {
            var value = cache.Get <T>(key);

            if (Equals(value, default(T)))
            {
                value = await createFn();

                cache.Set(key, value);
            }
            return(value);
        }
Пример #33
0
        public static void CacheAllWorlds(this IDbConnection db, ICacheClient cache)
        {
            cache.FlushAll();

            // concurrently create a list of world ids
            var worlds = db.GetWorlds();

            Parallel.ForEach<World>(worlds, w =>
            {
                var cacheKey = UrnId.Create<World>("Id", w.id.ToString());

                cache.Set<World>(cacheKey, w);
            });
        }
Пример #34
0
        public static void CacheAllWorlds(this MongoDatabase db, ICacheClient cache, string dbType)
        {
            cache.FlushAll();

            // concurrently create a list of world ids
            var worlds = db.GetWorlds();

            Parallel.ForEach<World>(worlds, w =>
            {
                var cacheKey = UrnId.CreateWithParts<World>(new string[] { dbType, w.id.ToString() });

                cache.Set<World>(cacheKey, w);
            });
        }
Пример #35
0
        public void UpdateSession(ICacheClient cacheClient)
        {
            string sessionKey = SessionFeature.GetSessionKey(this.Id);

            CustomUserSession session = cacheClient.Get<CustomUserSession>(sessionKey);
            session.UserId = UserId;

            //The sesion  never expiered.
            cacheClient.Set(sessionKey, session);
        }
 public void AssertGetSetIntValue(ICacheClient cacheClient)
 {
     cacheClient.Set("test:intkey1", 1);
     var value = cacheClient.Get<int>("test:intkey1");
     Assert.That(value, Is.EqualTo(1));
 }