Пример #1
0
 public List <WebApi.Entities.WebSite> GetTopWebsite()
 {
     return(CacheExtensions.Data("topwebsite", () =>
     {
         return ServerApiInvoker.Get_TopWebsite();
     }));
 }
        public async Task <string> Get(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            // if it contains the key, just return
            if (CacheExtensions.TryGetValue(_cache, key, out string cachedValue))
            {
                return(cachedValue);
            }

            var value = await GetOrCreate(key);

            if (value != null)
            {
                // the memory cache is threadsafe so we don't need to acquire the lock. the worst case
                // scenrio is we call the underlying consul service multiple times initially, but it would
                // be faster than getting the lock everytime
                CacheExtensions.Set <string>(_cache, key, value, new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTime.Now.Add(_expirationTimeSpan)
                });
            }

            return(value);
        }
Пример #3
0
 public List <WebApi.Entities.MockUser> GetMockUsers(string userid)
 {
     return(CacheExtensions.Data(userid, () =>
     {
         return ServerApiInvoker.Get_MockUsers(userid);
     }));
 }
Пример #4
0
        public static LoginInfo LoginInfo(string ID)
        {
            string key = LoginCacheName + ID;

            //if (!System.Web.HttpContext.Current.Request.Headers.AllKeys.Contains(key))
            //{
            //    if (!CacheExtensions.CheckCache(key))
            //    {
            //        var employee = MvcCore.Unity.Get<IEmployeeService>().Single(ID);
            //        if (employee == null || employee.IsDisabled.GetValueOrDefault(false))
            //        {
            //            Logout();
            //            throw new UnauthorizedAccessException("用户信息失效!");
            //        }
            //        employee.ToLoginInfo().SetCache();
            //    }
            //    System.Web.HttpContext.Current.Request.Headers.Set(key, CacheExtensions.GetCache<LoginInfo>(key).ToJson());
            //}
            //return HttpContext.Current.Request.Headers.Get(key).FromJson<LoginInfo>();

            if (!CacheExtensions.CheckCache(key))
            {
                var employee = MvcBase.Unity.Get <IEmployeeService>().Single(ID);
                if (employee == null || employee.IsDisabled.GetValueOrDefault(false))
                {
                    Logout();
                    return(null);
                }
                employee.ToLoginInfo().SetCache();
            }
            return(CacheExtensions.GetCache <LoginInfo>(key));
        }
Пример #5
0
        public static void RegisterSetting <T>(this CommandService commands) where T : class, IGroupSetting, new()
        {
            string group = typeof(T).Name.ToLower().Replace("Settings", string.Empty);

            commands.CreateModuleAsync("Settings", module =>
            {
                foreach (var property in CacheExtensions.GetPrimitives <T>())
                {
                    module.CreateCommand <T>("Updated key.", group, property.Name, property, (p, s, args) =>
                                             p.SetValue(s, args.First()));
                }

                foreach (var property in CacheExtensions.GetLists <T>())
                {
                    string name = property.Name;
                    module.CreateCommand <T>("Cleared key.", group, $"clear {name}", property, (p, s, args) =>
                                             (p.GetValue(property) as IList)?.Clear());

                    module.CreateCommand <T>("Added key.", group, name, property, (p, s, args) =>
                    {
                        var list = p.GetValue(property) as IList;
                        foreach (var item in args)
                        {
                            list?.Add(item);
                        }
                    });
                }
            });
        }
Пример #6
0
        // Token: 0x0600017E RID: 382 RVA: 0x00006EDC File Offset: 0x000050DC
        private Task <CompiledViewDescriptor> OnCacheMiss(string normalizedPath)
        {
            object cacheLock = this._cacheLock;
            ViewCompilerWorkItem    viewCompilerWorkItem;
            MemoryCacheEntryOptions memoryCacheEntryOptions;
            TaskCompletionSource <CompiledViewDescriptor> taskCompletionSource;

            lock (cacheLock)
            {
                Task <CompiledViewDescriptor> result;
                if (CacheExtensions.TryGetValue <Task <CompiledViewDescriptor> >(this._cache, normalizedPath, out result))
                {
                    return(result);
                }
                CompiledViewDescriptor precompiledView;
                if (this._precompiledViews.TryGetValue(normalizedPath, out precompiledView))
                {
                    this._logger.ViewCompilerLocatedCompiledViewForPath(normalizedPath);
                    viewCompilerWorkItem = this.CreatePrecompiledWorkItem(normalizedPath, precompiledView);
                }
                else
                {
                    viewCompilerWorkItem = this.CreateRuntimeCompilationWorkItem(normalizedPath);
                }
                memoryCacheEntryOptions = new MemoryCacheEntryOptions();
                for (int i = 0; i < viewCompilerWorkItem.ExpirationTokens.Count; i++)
                {
                    memoryCacheEntryOptions.ExpirationTokens.Add(viewCompilerWorkItem.ExpirationTokens[i]);
                }
                taskCompletionSource = new TaskCompletionSource <CompiledViewDescriptor>();
                if (!viewCompilerWorkItem.SupportsCompilation)
                {
                    taskCompletionSource.SetResult(viewCompilerWorkItem.Descriptor);
                }
                _cacheKeyList.Add(normalizedPath);
                CacheExtensions.Set <Task <CompiledViewDescriptor> >(this._cache, normalizedPath, taskCompletionSource.Task, memoryCacheEntryOptions);
            }
            if (viewCompilerWorkItem.SupportsCompilation)
            {
                CompiledViewDescriptor descriptor = viewCompilerWorkItem.Descriptor;
                if (((descriptor != null) ? descriptor.Item : null) != null && ChecksumValidator.IsItemValid(this._projectEngine.FileSystem, viewCompilerWorkItem.Descriptor.Item))
                {
                    taskCompletionSource.SetResult(viewCompilerWorkItem.Descriptor);
                    return(taskCompletionSource.Task);
                }
                this._logger.ViewCompilerInvalidingCompiledFile(viewCompilerWorkItem.NormalizedPath);
                try
                {
                    CompiledViewDescriptor compiledViewDescriptor = this.CompileAndEmit(normalizedPath);
                    compiledViewDescriptor.ExpirationTokens = memoryCacheEntryOptions.ExpirationTokens;
                    taskCompletionSource.SetResult(compiledViewDescriptor);
                }
                catch (Exception exception)
                {
                    taskCompletionSource.SetException(exception);
                }
            }
            return(taskCompletionSource.Task);
        }
        /// <summary>
        /// Finds the counterparty between us and some other communication party
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="counterpartyHerId">Her id of counterparty</param>
        /// <returns></returns>
        public async Task <CollaborationProtocolProfile> FindAgreementForCounterpartyAsync(ILogger logger, int counterpartyHerId)
        {
            logger.LogDebug($"Start-FindAgreementForCounterpartyAsync {counterpartyHerId}");

            var key    = $"CPA_FindAgreementForCounterpartyAsync_{_settings.MyHerId}_{counterpartyHerId}";
            var result = await CacheExtensions.ReadValueFromCache <CollaborationProtocolProfile>(logger, _cache, key).ConfigureAwait(false);

            if (result != null)
            {
                var errors = CertificateErrors.None;
                errors |= CertificateValidator.Validate(result.EncryptionCertificate, X509KeyUsageFlags.DataEncipherment);
                errors |= CertificateValidator.Validate(result.SignatureCertificate, X509KeyUsageFlags.NonRepudiation);
                // if the certificates are valid, only then do we return a value from the cache
                if (errors == CertificateErrors.None)
                {
                    return(result);
                }
            }

            CPAService.CpaXmlDetails details;

            try
            {
                logger.LogDebug($"StartServiceCall-FindAgreementForCounterparty {counterpartyHerId}");
                details = await FindAgreementForCounterparty(logger, counterpartyHerId).ConfigureAwait(false);

                logger.LogDebug($"EndServiceCall-FindAgreementForCounterparty {counterpartyHerId}");
            }
            catch (FaultException ex)
            {
                // if there are error getting a proper CPA, we fallback to getting CPP.
                logger.LogWarning($"Failed to resolve CPA between {_settings.MyHerId} and {counterpartyHerId}. {ex.Message}");
                return(await FindProtocolForCounterpartyAsync(logger, counterpartyHerId));
            }

            if (string.IsNullOrEmpty(details?.CollaborationProtocolAgreementXml))
            {
                return(null);
            }
            var doc = XDocument.Parse(details.CollaborationProtocolAgreementXml);

            if (doc.Root == null)
            {
                return(null);
            }

            var node = (from x in doc.Root.Elements(_ns + "PartyInfo").Elements(_ns + "PartyId")
                        where x.Value != _settings.MyHerId.ToString()
                        select x.Parent).First();

            result       = MapFrompartyInfo(node);
            result.CpaId = Guid.Parse(doc.Root.Attribute(_ns + "cpaid").Value);

            await CacheExtensions.WriteValueToCache(logger, _cache, key, result, _settings.CachingInterval).ConfigureAwait(false);

            logger.LogDebug($"End-FindAgreementForCounterpartyAsync {counterpartyHerId}");

            return(result);
        }
Пример #8
0
 private List <WebApi.Entities.ScriptObject> GetScripts(string url)
 {
     url = StringHelper.GetDomain(url);
     return(CacheExtensions.Data(url, () =>
     {
         return ServerApiInvoker.GetScriptObjectByUrl(url);
     }));
 }
Пример #9
0
        public static void Logout()
        {
            var id = HttpContext.Current.User.Identity.Name.ToGuid();

            CacheExtensions.ClearCache(LoginCacheName + id);
            Unity.Get <IMenuService>().ClearCache();
            FormsAuthentication.SignOut();
        }
Пример #10
0
 public virtual List <T> ListCache(string cacheName, CacheTimeType cacheTimeType, int cacheTime, Expression <Func <T, bool> > where, int count)
 {
     if (!CacheExtensions.CheckCache(cacheName))
     {
         CacheExtensions.SetCache(cacheName, (object)this.dbset.AsNoTracking <T>().Where <T>(where).Take <T>(count).ToList <T>(), cacheTimeType, cacheTime);
     }
     return(CacheExtensions.GetCache <List <T> >(cacheName));
 }
Пример #11
0
 public virtual List <T> ListCache(string cacheName, CacheTimeType cacheTimeType, int cacheTime)
 {
     if (!CacheExtensions.CheckCache(cacheName))
     {
         CacheExtensions.SetCache(cacheName, (object)this.dbset.AsNoTracking <T>().ToList <T>(), cacheTimeType, cacheTime);
     }
     return(CacheExtensions.GetCache <List <T> >(cacheName));
 }
Пример #12
0
        /// <summary>
        /// Finds a CPA based on an id, and returns the CPP profile for the other communication party
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="id">CPA id</param>
        /// <param name="forceUpdate">Set to true to force cache update.</param>
        /// <returns></returns>
        public async Task <CollaborationProtocolProfile> FindAgreementByIdAsync(ILogger logger, Guid id, bool forceUpdate)
        {
            logger.LogDebug($"FindAgreementByIdAsync {id}");

            var key    = $"CPA_FindAgreementByIdAsync_{id}";
            var result = forceUpdate ? null : await CacheExtensions.ReadValueFromCache <CollaborationProtocolProfile>(logger, _cache, key).ConfigureAwait(false);

            if (result != null)
            {
                var errors = CertificateErrors.None;
                errors |= CertificateValidator.Validate(result.EncryptionCertificate, X509KeyUsageFlags.DataEncipherment);
                errors |= CertificateValidator.Validate(result.SignatureCertificate, X509KeyUsageFlags.NonRepudiation);
                // if the certificates are valid, only then do we return a value from the cache
                if (errors == CertificateErrors.None)
                {
                    return(result);
                }
            }

            CPAService.CpaXmlDetails details;

            try
            {
                details = await FindAgreementById(logger, id).ConfigureAwait(false);
            }
            catch (FaultException ex)
            {
                throw new RegistriesException(ex.Message, ex)
                      {
                          EventId = EventIds.CollaborationAgreement,
                          Data    = { { "CpaId", id } }
                      };
            }

            if (string.IsNullOrEmpty(details?.CollaborationProtocolAgreementXml))
            {
                return(null);
            }
            var doc = XDocument.Parse(details.CollaborationProtocolAgreementXml);

            if (doc.Root == null)
            {
                return(null);
            }

            var node = (from x in doc.Root.Elements(_ns + "PartyInfo").Elements(_ns + "PartyId")
                        where x.Value != _settings.MyHerId.ToString()
                        select x.Parent).First();

            result       = MapFrompartyInfo(node);
            result.CpaId = id;

            await CacheExtensions.WriteValueToCache(logger, _cache, key, result, _settings.CachingInterval).ConfigureAwait(false);

            return(result);
        }
Пример #13
0
        public static List <LoginInfo> LoginInfo()
        {
            List <LoginInfo> result = new List <LoginInfo>();

            foreach (var key in CacheExtensions.GetAllCache().Where(s => s.StartsWith(LoginCacheName)))
            {
                result.Add(CacheExtensions.GetCache <LoginInfo>(key));
            }
            return(result);
        }
 public void Clear(string key)
 {
     if (string.IsNullOrWhiteSpace(key))
     {
         throw new ArgumentNullException(nameof(key));
     }
     if (CacheExtensions.TryGetValue(_cache, key, out string value))
     {
         this._cache.Remove(key);
     }
 }
Пример #15
0
        /// <summary>
        /// Gets the CPP profile for a specific communication party
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="counterpartyHerId">Her Id of communication party</param>
        /// <returns></returns>
        public async Task <CollaborationProtocolProfile> FindProtocolForCounterpartyAsync(ILogger logger, int counterpartyHerId)
        {
            logger.LogDebug($"FindProtocolForCounterpartyAsync {counterpartyHerId}");

            var key    = $"CPA_FindProtocolForCounterpartyAsync_{counterpartyHerId}";
            var result = await CacheExtensions.ReadValueFromCache <CollaborationProtocolProfile>(logger, _cache, key).ConfigureAwait(false);

            var xmlString = string.Empty;

            if (result != null)
            {
                var errors = CertificateErrors.None;
                errors |= CertificateValidator.Validate(result.EncryptionCertificate, X509KeyUsageFlags.DataEncipherment);
                errors |= CertificateValidator.Validate(result.SignatureCertificate, X509KeyUsageFlags.NonRepudiation);
                // if the certificates are valid, only then do we return a value from the cache
                if (errors == CertificateErrors.None)
                {
                    return(result);
                }
            }
            try
            {
                xmlString = await FindProtocolForCounterparty(logger, counterpartyHerId).ConfigureAwait(false);
            }
            catch (FaultException <CPAService.GenericFault> ex)
            {
                // if this happens, we fall back to the dummy profile further down
                logger.LogWarning($"Error resolving protocol for counterparty. ErrorCode: {ex.Detail.ErrorCode} Message: {ex.Detail.Message}");
            }
            catch (Exception ex)
            {
                throw new RegistriesException(ex.Message, ex)
                      {
                          EventId = EventIds.CollaborationProfile,
                          Data    = { { "HerId", counterpartyHerId } }
                      };
            }
            if (string.IsNullOrEmpty(xmlString))
            {
                result = CreateDummyCollaborationProtocolProfile(counterpartyHerId,
                                                                 await _adressRegistry.GetCertificateDetailsForEncryptionAsync(logger, counterpartyHerId).ConfigureAwait(false),
                                                                 await _adressRegistry.GetCertificateDetailsForValidatingSignatureAsync(logger, counterpartyHerId).ConfigureAwait(false));
            }
            else
            {
                var doc = XDocument.Parse(xmlString);
                result = doc.Root == null ? null : MapFrompartyInfo(doc.Root.Element(_ns + "PartyInfo"));
            }

            await CacheExtensions.WriteValueToCache(logger, _cache, key, result, _settings.CachingInterval).ConfigureAwait(false);

            return(result);
        }
Пример #16
0
 public T Get <T>(string key)
 {
     if (!CacheExtensions.TryGetValue <T>(this._cache, key, ref V_0))
     {
         V_1 = default(T);
         return(V_1);
     }
     if (!this._clone)
     {
         return(V_0);
     }
     return(Utils.DeepClone <T>(V_0));
 }
Пример #17
0
        public void Store(string key, object content, int duration)
        {
            object cached;

            if (Cache.TryGetValue(key, out cached))
            {
                Cache.Remove(key);
            }

            CacheExtensions.Set(Cache, key, content,
                                new MemoryCacheEntryOptions
            {
                AbsoluteExpiration = DateTime.Now + TimeSpan.FromSeconds(duration),
                Priority           = CacheItemPriority.Low
            });
        }
Пример #18
0
        public void TestFiveSecondTimeoutStruct()
        {
            var key = "time2";

            var now = DateTime.Now;

            _cache.Add(key, CacheExtensions.Wrap(now, DateTime.UtcNow.Add(new TimeSpan(0, 0, 5))));

            Thread.Sleep(new TimeSpan(0, 0, 2));

            var cached = CacheExtensions.Unwrap(_cache.Get <DateTime>(key));

            Assert.Equal(now, cached);

            Thread.Sleep(new TimeSpan(0, 0, 5));

            Assert.Null(_cache.Get <string>(key));
        }
        public async Task <T> Get <T>(string key, TimeSpan expireIn, Func <Task <T> > method)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            var result = CacheExtensions.Get(this._cache, key);

            if (result != null)
            {
                return((T)result);
            }

            var keyLock = _locks.GetOrAdd(key, x => new SemaphoreSlim(1));
            await keyLock.WaitAsync();

            try
            {
                result = CacheExtensions.Get(this._cache, key);
                if (result != null)
                {
                    return((T)result);
                }

                var cacheItemPolicy = new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = new DateTimeOffset(DateTime.Now.Add(expireIn))
                };
                result = await method();

                if (result != null)
                {
                    CacheExtensions.Set(this._cache, key, result, cacheItemPolicy);
                }
            }
            finally
            {
                keyLock.Release();
            }

            return((T)(result ?? default(T)));
        }
Пример #20
0
        /// <inheritdoc />
        // Token: 0x0600017D RID: 381 RVA: 0x00006E8C File Offset: 0x0000508C
        public Task <CompiledViewDescriptor> CompileAsync(string relativePath)
        {
            if (relativePath == null)
            {
                throw new ArgumentNullException("relativePath");
            }
            Task <CompiledViewDescriptor> result;

            if (CacheExtensions.TryGetValue <Task <CompiledViewDescriptor> >(this._cache, relativePath, out result))
            {
                return(result);
            }
            string normalizedPath = this.GetNormalizedPath(relativePath);

            if (CacheExtensions.TryGetValue <Task <CompiledViewDescriptor> >(this._cache, normalizedPath, out result))
            {
                return(result);
            }
            result = this.OnCacheMiss(normalizedPath);
            return(result);
        }
Пример #21
0
        /// <summary>
        /// Returns communication details for a specific counterparty
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="herId">Her id of counterpary</param>
        /// <param name="forceUpdate">Set to true to force cache update.</param>
        /// <returns>Communication details if found, otherwise null</returns>
        public async Task <CommunicationPartyDetails> FindCommunicationPartyDetailsAsync(ILogger logger, int herId, bool forceUpdate)
        {
            var key   = $"AR_FindCommunicationPartyDetailsAsync_{herId}";
            var party = forceUpdate ? null : await CacheExtensions.ReadValueFromCache <CommunicationParty>(logger, _cache, key).ConfigureAwait(false);

            if (party == null)
            {
                try
                {
                    party = await FindCommunicationPartyDetails(logger, herId).ConfigureAwait(false);
                }
                catch (FaultException ex)
                {
                    throw new RegistriesException(ex.Message, ex)
                          {
                              EventId = EventIds.CommunicationPartyDetails,
                              Data    = { { "HerId", herId } }
                          };
                }
                await CacheExtensions.WriteValueToCache(logger, _cache, key, party, _settings.CachingInterval).ConfigureAwait(false);
            }
            return(party == null ? default(CommunicationPartyDetails) : MapCommunicationPartyDetails(party));
        }
Пример #22
0
        /// <summary>
        /// Returns the signature certificate for a specific communication party.
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="herId">Her-ID of the communication party</param>
        /// <param name="forceUpdate">Set to true to force cache update.</param>
        /// <returns></returns>
        public async Task <Abstractions.CertificateDetails> GetCertificateDetailsForValidatingSignatureAsync(ILogger logger, int herId, bool forceUpdate)
        {
            var key = $"AR_GetCertificateDetailsForValidationSignature{herId}";
            var certificateDetails = forceUpdate ? null : await CacheExtensions.ReadValueFromCache <AddressService.CertificateDetails>(logger, _cache, key).ConfigureAwait(false);

            if (certificateDetails == null)
            {
                try
                {
                    certificateDetails = await GetCertificateDetailsForValidatingSignatureInternal(logger, herId).ConfigureAwait(false);
                }
                catch (FaultException ex)
                {
                    throw new RegistriesException(ex.Message, ex)
                          {
                              EventId = EventIds.CerificateDetails,
                              Data    = { { "HerId", herId } }
                          };
                }
                await CacheExtensions.WriteValueToCache(logger, _cache, key, certificateDetails, _settings.CachingInterval).ConfigureAwait(false);
            }
            return(certificateDetails == null ? default(Abstractions.CertificateDetails) : MapCertificateDetails(herId, certificateDetails));
        }
Пример #23
0
 public void Set <T>(string key, T value)
 {
     dummyVar0 = CacheExtensions.Set <T>(this._cache, key, value);
     return;
 }
Пример #24
0
 public List <PersonModel> GetPeopleCache(string lastNameKey)
 {
     Console.WriteLine("People data with last name from cache");
     return((List <PersonModel>)CacheExtensions.Get(Cache, lastNameKey));
 }
Пример #25
0
 public PersonModel GetPersonCache(string key)
 {
     Console.WriteLine("Person data from cache");
     return((PersonModel)CacheExtensions.Get(Cache, key));
 }
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var keyGenerator     = new StringBuilder();
            var referenceTypeKey = new StringBuilder();
            var valueTypeKey     = new StringBuilder();

            var methodName = CacheExtensions.IsCustomKey(_customKey)
                ? args.MethodNameWithClassName()
                : _customKey.WhiteSpaceRemove();

            keyGenerator.Append(methodName);

            var arguments = args.Arguments.ToList();

            foreach (var dataArgument in arguments)
            {
                if (dataArgument != null)
                {
                    var getTypeInfo = dataArgument.GetType().GetTypeInfo().ToString();
                    var getBaseType = dataArgument.GetType().BaseType?.ToString();

                    if (getTypeInfo != "System.String" && getBaseType != "System.ValueType")
                    {
                        var getObjectName = dataArgument.GetType().Name;

                        referenceTypeKey.AppendFormat($"{getObjectName}RT/");

                        var getPropertiesValue =
                            dataArgument.GetType().GetProperties().Select(x => x.GetValue(dataArgument));

                        foreach (var value in getPropertiesValue)
                        {
                            referenceTypeKey.AppendFormat(value == null ? "<Null>/" : $"{value}/");
                        }
                    }

                    if (getTypeInfo == "System.String" || getBaseType == "System.ValueType")
                    {
                        valueTypeKey.AppendFormat($"{dataArgument}-");
                    }
                }

                else
                {
                    valueTypeKey.AppendFormat("<Null>-");
                }
            }

            if (!IsNullOrEmpty(referenceTypeKey.ToString()))
            {
                referenceTypeKey.Remove(referenceTypeKey.Length - 1, 1);
                keyGenerator.Append("&" + referenceTypeKey);
            }

            if (!IsNullOrEmpty(valueTypeKey.ToString()))
            {
                valueTypeKey = valueTypeKey.Remove(valueTypeKey.Length - 1, 1);
                keyGenerator.Append("&VT" + valueTypeKey);
            }

            var clearKeyData = keyGenerator.ToString().WhiteSpaceRemove();

            if (_cacheManager.IsAdd(clearKeyData))
            {
                var cacheValue = _cacheManager.Get <object>(clearKeyData);

                switch (_cacheType.Name)
                {
                case "MicrosoftMemoryCacheManager":

                    args.ReturnValue = cacheValue;
                    return;

                case "RedisCacheManager":

                    var methodInfo = args.Method as MethodInfo;
                    if (methodInfo == null)
                    {
                        return;
                    }
                    var methodReturnType = methodInfo.ReturnType;

                    args.ReturnValue = JsonConvert.DeserializeObject(cacheValue.ToString(), methodReturnType);
                    return;

                default:
                    return;
                }
            }

            base.OnInvoke(args);

            _cacheManager.Add(clearKeyData, args.ReturnValue, _cacheByMinute);
        }
 new public void SetObject(string key, object value)
 {
     key = CacheExtensions.GenerateSiteSpecificCacheKey(key);
     base.SetObject(key, value);
 }
 new public object GetObject(string key)
 {
     key = CacheExtensions.GenerateSiteSpecificCacheKey(key);
     return(base.GetObject(key));
 }
 new public void Remove(string key)
 {
     key = CacheExtensions.GenerateSiteSpecificCacheKey(key);
     base.Remove(key);
 }
Пример #30
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var cacheKey = _keyGenerator.GenerateKey(input);

            var methodIsTask = input.MethodBase.IsGenericTask();
            var returnType   = input.MethodBase.GetReturnType();

            var cachedResult = typeof(ICache).GetMethod("Get")
                               .MakeGenericMethod(returnType)
                               .Invoke(_cache, new object[] { cacheKey });

            object unwrappedResult = null;

            var scheduleDurableRefresh = false;

            //Force cache miss for durable results that are behind
            if (cachedResult != null && AbsoluteExpiration != null)
            {
                var lastUpdate = (DateTime)CacheExtensions.GetLastUpdate((dynamic)cachedResult);
                var expires    = (DateTime)CacheExtensions.GetExpires((dynamic)cachedResult);

                if (DateTime.UtcNow.Subtract(lastUpdate).TotalSeconds > MaximumStaleness.TotalSeconds)
                {
                    if (RescheduleStale && DateTime.UtcNow.Add(Expiration) < expires)
                    {
                        scheduleDurableRefresh = true;
                    }
                    else
                    {
                        cachedResult = null;
                    }
                }
            }

            // Nothing is cached for this method
            if (cachedResult == null)
            {
                // Get a new result
                var newResult = getNext()(input, getNext);

                //Do not cache exceptions
                if (newResult.Exception == null)
                {
                    if (methodIsTask)
                    {
                        newResult.ReturnValue = (dynamic)typeof(CacheExtensions).GetMethod("AddToCacheAsync")
                                                .MakeGenericMethod(returnType)
                                                .Invoke(null, new object[] { _cache, newResult.ReturnValue,
                                                                             cacheKey, DateTime.UtcNow.Add(AbsoluteExpiration ?? Expiration) });
                    }
                    else
                    {
                        typeof(CacheExtensions).GetMethod("AddToCache")
                        .MakeGenericMethod(returnType)
                        .Invoke(null, new object[] { _cache, newResult.ReturnValue,
                                                     cacheKey, DateTime.UtcNow.Add(AbsoluteExpiration ?? Expiration) });
                    }

                    //queue refresh if configured by the user
                    scheduleDurableRefresh = AbsoluteExpiration != null;
                }

                unwrappedResult = newResult.ReturnValue;
            }
            else
            {
                if (methodIsTask)
                {
                    var unwrappedResultMissingTask = CacheExtensions.Unwrap((dynamic)cachedResult);

                    unwrappedResult = typeof(Task).GetMethod("FromResult")
                                      .MakeGenericMethod(input.MethodBase.GetGenericReturnTypeArguments())
                                      .Invoke(null, new object[] { unwrappedResultMissingTask });
                }
                else
                {
                    unwrappedResult = CacheExtensions.Unwrap((dynamic)cachedResult);
                }
            }

            if (scheduleDurableRefresh)
            {
                var parameters = new object[input.Inputs.Count];
                input.Inputs.CopyTo(parameters, 0);

                var queue = _container.Resolve <IDurableCacheQueue>();

                queue.ScheduleRefresh(new DurableCacheRefreshEvent
                {
                    AbsoluteExpiration = AbsoluteExpiration.Value,
                    CacheName          = _cacheName,
                    Key    = cacheKey,
                    Method = new DurableMethod
                    {
                        DeclaringType = input.Target.GetType(),
                        Interface     = input.MethodBase.DeclaringType,
                        Name          = input.MethodBase.Name,
                        Parameters    = input.MethodBase.GetParameters()
                                        .Select(p => p.ParameterType).ToArray()
                    },
                    Parameters  = parameters,
                    RefreshTime = Expiration,
                    UtcLifetime = cachedResult != null ? (DateTime)CacheExtensions.GetExpires((dynamic)cachedResult) :
                                  DateTime.UtcNow.Add(AbsoluteExpiration.Value),
                });
            }

            var arguments = new object[input.Inputs.Count];

            input.Inputs.CopyTo(arguments, 0);

            return(new VirtualMethodReturn(input, unwrappedResult, arguments));
        }