示例#1
0
        private static CacheAttribute GetCacheSettings(IMethodInvocation input)
        {
            //get the cache attribute & check if overridden in config:
            var attributes     = input.MethodBase.GetCustomAttributes(typeof(CacheAttribute), false);
            var cacheAttribute = (CacheAttribute)attributes[0];
            var cacheKeyPrefix = CacheKeyBuilder.GetCacheKeyPrefix(input);
            var targetConfig   = CacheConfiguration.Current.Targets[cacheKeyPrefix];

            if (targetConfig != null)
            {
                cacheAttribute.Disabled            = !targetConfig.Enabled;
                cacheAttribute.Days                = targetConfig.Days;
                cacheAttribute.Hours               = targetConfig.Hours;
                cacheAttribute.Minutes             = targetConfig.Minutes;
                cacheAttribute.Seconds             = targetConfig.Seconds;
                cacheAttribute.CacheType           = targetConfig.CacheType;
                cacheAttribute.SerializationFormat = targetConfig.SerializationFormat;
            }
            if (cacheAttribute.SerializationFormat == SerializationFormat.Null)
            {
                cacheAttribute.SerializationFormat = CacheConfiguration.Current.DefaultSerializationFormat;
            }
            if (cacheAttribute.CacheType == CacheType.Null)
            {
                cacheAttribute.CacheType = CacheConfiguration.Current.DefaultCacheType;
            }
            return(cacheAttribute);
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            string key = CacheKeyBuilder.GetCacheKey(input, new BinarySerializer());

            key = key.Replace(".", string.Empty);

            if (Defaults.TipoInicio == 4 && IsInCache(key + "return"))
            {
                var res = FetchFromCache(key + "return");

                GetArgumentToCache(input, key);

                return(input.CreateMethodReturn(res, GetArgument(input)));
            }

            IMethodReturn methodReturn = getNext()(input, getNext);

            if (!input.MethodBase.ToString().Contains("System.Threading.Task") && Utility.ReflectionHelper.IsSerializable(input.MethodBase) && Defaults.HabilitarDistribuidorCache == "1")
            {
                if (methodReturn != null && methodReturn.ReturnValue != null && methodReturn.Exception == null)
                {
                    AddToCache(key + "return", methodReturn);
                }

                AddArgumentToCache(input, key);
            }


            return(methodReturn);
        }
示例#3
0
 public Cache(IDatabase cache) : base(cache)
 {
     KeyFn = query =>
     {
         return(CacheKeyBuilder.Build <GetJobs, Query>(query, m => m.UserId, m => m.PaginationParams.Page, m => m.PaginationParams.PerPage));
     };
 }
示例#4
0
    public IActionResult Index()
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var viewModel     = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(ArchiveController), nameof(Index), authenticated),
            () =>
        {
            var posts = _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished() || authenticated)
                        .ToList();
            var model = new List <PostArchiveViewModel>();
            foreach (var item in posts.GroupBy(x => x.Raw.PublishTime.Year).OrderByDescending(y => y.Key))
            {
                var archiveViewModel = new PostArchiveViewModel
                {
                    Count = item.Count(),
                    Posts = item.ToList(),
                    Link  = $"{item.Key}",
                    Name  = $"{item.Key}年"
                };

                model.Add(archiveViewModel);
            }

            return(model);
        });

        ViewData["Title"]       = "存档";
        ViewData["Image"]       = $"{_blogOptions.BlogRemoteEndpoint}/archive.png";
        ViewData["Description"] = "所有文章的存档。";
        return(View("Index", viewModel));
    }
示例#5
0
 protected override void GetConnectionKey(CacheKeyBuilder ckb)
 {
     base.GetConnectionKey(ckb);
     ckb.Add(DataSourceName);
     ckb.Add(Login);
     ckb.Add(Password);
 }
        /// <summary>
        /// Performs a validation if current type of margin trading is enabled globally and for the particular client
        /// (which is extracted from the action parameters).
        /// Skips validation if current action method is marked with <see cref="SkipMarginTradingEnabledCheckAttribute"/>.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Using this type of margin trading is restricted for client or
        /// a controller action has more then one ClientId in its parameters.
        /// </exception>
        private async Task ValidateMarginTradingEnabledAsync(ActionExecutingContext context)
        {
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

            if (controllerActionDescriptor == null)
            {
                return;
            }

            var cacheKey       = CacheKeyBuilder.Create(nameof(MarginTradingEnabledFilter), nameof(GetSingleClientIdGetter), controllerActionDescriptor.DisplayName);
            var clientIdGetter = _cacheProvider.Get(cacheKey, () => new CachableResult <ClientIdGetter>(GetSingleClientIdGetter(controllerActionDescriptor), CachingParameters.InfiniteCache));

            if (clientIdGetter != null)
            {
                var clientId = clientIdGetter(context.ActionArguments);
                if (string.IsNullOrWhiteSpace(clientId))
                {
                    await _log.WriteWarningAsync(nameof(MarginTradingEnabledFilter), nameof(ValidateMarginTradingEnabledAsync), context.ActionDescriptor.DisplayName, "ClientId is null but is expected. No validation will be performed");
                }
                else if (!await _marginTradingSettingsCacheService.IsMarginTradingEnabled(clientId, _marginSettings.IsLive))
                {
                    throw new InvalidOperationException("Using this type of margin trading is restricted for client " + clientId);
                }
            }
        }
示例#7
0
        protected TReturn CommandExecute <TReturn>(bool?enableCache, Func <TReturn> execQuery, string sql, object param, string cacheKey, TimeSpan?expire, int?pageIndex = default, int?pageSize = default)
        {
            if (!IsEnableCache(enableCache))
            {
                return(execQuery());
            }
            cacheKey = CacheKeyBuilder.Generate(sql, param, cacheKey, pageIndex, pageSize);
            Logger.LogDebug("Get query results from cache.");
            var cache = Cache.TryGet <TReturn>(cacheKey);

            if (cache.ExistKey)
            {
                Logger.LogDebug("Get value from cache successfully.");
                return(cache.Value);
            }
            Logger.LogDebug("The cache does not exist, acquire a lock, queue to query data from the database.");
            lock (Lock)
            {
                Logger.LogDebug("The lock has been acquired, try again to get the value from the cache.");
                var cacheResult = Cache.TryGet <TReturn>(cacheKey);
                if (cacheResult.ExistKey)
                {
                    Logger.LogDebug("Try again, get value from cache successfully.");
                    return(cacheResult.Value);
                }
                Logger.LogDebug("Try again, still fail to get the value from the cache, start to get the value from the data.");
                var result = execQuery();
                Cache.TrySet(cacheKey, result, expire ?? CacheConfiguration.Expire);
                Logger.LogDebug("Get value from data and write to cache.");
                return(result);
            }
        }
示例#8
0
    public IActionResult Sitemap()
    {
        var sitemap = _cacheClient.GetOrCreate(CacheKeyBuilder.Build(nameof(HomeController), nameof(Sitemap)),
                                               () =>
        {
            var sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.AppendLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>1.0</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/read</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.9</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/about</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.9</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/archive</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/tag</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>");

            foreach (var post in _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished()))
            {
                sb.AppendLine(
                    $"<url><loc>{post.Raw.GetFullPath(_blogOptions.BlogRemoteEndpoint)}</loc><lastmod>{post.Raw.LastUpdateTime.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.6</priority></url>");
            }

            sb.AppendLine("</urlset>");
            return(sb.ToString());
        });

        return(Content(sitemap, "text/xml", Encoding.UTF8));
    }
        /// <summary>
        /// Performs a validation if current type of margin trading is enabled globally and for the particular client
        /// (which is extracted from the action parameters).
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Using this type of margin trading is restricted for client or
        /// a controller action has more then one AccountId in its parameters.
        /// </exception>
        private void ValidateMarginTradingEnabled(ActionExecutingContext context)
        {
            if (!(context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor))
            {
                return;
            }

            var cacheKey = CacheKeyBuilder.Create(nameof(MarginTradingEnabledFilter), nameof(GetSingleAccountIdGetter),
                                                  controllerActionDescriptor.DisplayName);
            var accountIdGetter = _cacheProvider.Get(cacheKey,
                                                     () => new CachableResult <AccountIdGetter>(GetSingleAccountIdGetter(controllerActionDescriptor),
                                                                                                CachingParameters.InfiniteCache));

            if (accountIdGetter != null)
            {
                var accountId = accountIdGetter(context.ActionArguments);
                if (!string.IsNullOrWhiteSpace(accountId))
                {
                    var isAccEnabled = _marginTradingSettingsCacheService.IsMarginTradingEnabledByAccountId(accountId);
                    if (isAccEnabled == null)
                    {
                        throw new InvalidOperationException($"Account {accountId} does not exist");
                    }

                    if (!(bool)isAccEnabled)
                    {
                        throw new InvalidOperationException(
                                  $"Using this type of margin trading is restricted for account {accountId}. Error Code: {CommonErrorCodes.AccountDisabled}");
                    }
                }
            }
        }
示例#10
0
        private async Task UpdateMemoryPostsAsync()
        {
            var memPosts  = GetPosts();
            var filePosts = await GetPostsFromFileAsync();

            var posts = new List <BlogPost>();

            foreach (var filePost in filePosts)
            {
                if (StringEqualsHelper.IgnoreCase(filePost.GitHubPath, BlogConstant.TemplatePostGitHubPath))
                {
                    continue;
                }

                var memPost = memPosts.FirstOrDefault(p =>
                                                      StringEqualsHelper.IgnoreCase(p.Link, filePost.Link));
                if (memPost != null)
                {
                    filePost.Visits = Math.Max(filePost.Visits, memPost.Visits);
                }

                posts.Add(filePost);
            }

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "post", "all"), posts);
        }
        /// <summary>
        /// Returns previously cached response or invokes method and caches response
        /// </summary>
        /// <param name="input"></param>
        /// <param name="getNext"></param>
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            //if caching is disabled, leave:
            if (!CacheConfiguration.Current.Enabled)
            {
                return(Proceed(input, getNext));
            }

            //get the cache settings from the attribute & config:
            var cacheAttribute = GetCacheSettings(input);

            if (cacheAttribute.Disabled)
            {
                return(Proceed(input, getNext));
            }

            //if there's no cache provider, leave:
            var cache      = Cache.Get(cacheAttribute.CacheType);
            var serializer = Serializer.GetCurrent(cacheAttribute.SerializationFormat);

            if (cache == null || cache.CacheType == CacheType.Null || serializer == null)
            {
                return(Proceed(input, getNext));
            }

            // Log cache request here

            var returnType  = ((MethodInfo)input.MethodBase).ReturnType;
            var cacheKey    = CacheKeyBuilder.GetCacheKey(input, serializer);
            var cachedValue = cache.Get(returnType, cacheKey, cacheAttribute.SerializationFormat);

            if (cachedValue == null)
            {
                // missed the cache
                // Log here for instrumentation

                //call the intended method to set the return value
                var methodReturn = Proceed(input, getNext);
                //only cache if we have a real return value & no exception:
                if (methodReturn != null && methodReturn.ReturnValue != null && methodReturn.Exception == null)
                {
                    var lifespan = cacheAttribute.Lifespan;
                    if (lifespan.TotalSeconds > 0)
                    {
                        cache.Set(cacheKey, methodReturn.ReturnValue, lifespan, cacheAttribute.SerializationFormat);
                    }
                    else
                    {
                        cache.Set(cacheKey, methodReturn.ReturnValue, cacheAttribute.SerializationFormat);
                    }
                }
                return(methodReturn);
            }
            else
            {
                // hit the cache
                // Log here for instrumentation
            }
            return(input.CreateMethodReturn(cachedValue));
        }
        public async Task SetsCorrectCacheEntry_WhenOptimizeRouteResultIsSuccess_AndRequestOrderIsUpdated()
        {
            var optimizeRouteService = new Mock <IOptimizeRouteService>();

            optimizeRouteService.Setup(x => x.OptimizeRoute(It.IsAny <OptimizeRouteCriteria>()))
            .ReturnsAsync(new OptimizeRouteResult {
                Distance = 10, Duration = 10, RequestIds = new List <Guid> {
                    Request4Id, Request1Id
                }
            });

            var cache = new MemoryCache(new MemoryCacheOptions());

            var sut = new OptimizeRouteCommandHandler(Context, optimizeRouteService.Object, cache);

            await sut.Handle(new OptimizeRouteCommand { ItineraryId = 1, UserId = "123" });

            var expectedCacheKey = CacheKeyBuilder.BuildOptimizeRouteCacheKey("123", 1);

            OptimizeRouteResultStatus cachedStatus = null;
            var keyExists = cache.TryGetValue(expectedCacheKey, out cachedStatus);

            keyExists.ShouldBeTrue();
            cachedStatus.IsSuccess.ShouldBeTrue();
            cachedStatus.StatusMessage.ShouldBe(OptimizeRouteStatusMessages.OptimizeSucess);
        }
示例#13
0
 public Cache(IDatabase cache) : base(cache)
 {
     KeyFn = query =>
     {
         return(CacheKeyBuilder.Build <GetChats, Query>(query, m => m.UserId));
     };
 }
示例#14
0
        //public override bool IsSingleDatabase
        //{
        //    get { return m_isSingleDatabase; }
        //}

        //[XmlElem("IsSingleDatabase")]
        //public bool IsSingleDatabase_Origin
        //{
        //    get { return m_isSingleDatabase; }
        //    set { m_isSingleDatabase = value; }
        //}

        //[XmlElem]
        //public override string ExplicitDatabaseName { get; set; }

        protected override void GetConnectionKey(CacheKeyBuilder ckb)
        {
            base.GetConnectionKey(ckb);
            ckb.Add(ConnectionString);
            ckb.Add(FactoryName);
            ckb.Add(DriverName);
        }
示例#15
0
 public void Clear(long userId)
 {
     UserDataChangeTime.Update(userId, DateTime.UtcNow);
     foreach (var k in CacheKeyBuilder.GetAllKeys(userId))
     {
         cache.Remove(k);
     }
 }
示例#16
0
 public override void GetConnectionKey(CacheKeyBuilder ckb)
 {
     ckb.Add(Encoding);
     ckb.Add(EncodingStyle);
     ckb.Add(Url);
     ckb.Add(HttpLogin);
     ckb.Add(HttpPassword);
 }
示例#17
0
        public List <BlogCategory> GetCategories()
        {
            if (!_memoryCacheClient.TryGet <List <BlogCategory> >(CacheKeyBuilder.Build(SiteComponent.Blog, "category", "all"), out var categories))
            {
                categories = new List <BlogCategory>();
            }

            return(categories);
        }
示例#18
0
        public List <BlogPost> GetPosts()
        {
            if (!_memoryCacheClient.TryGet <List <BlogPost> >(CacheKeyBuilder.Build(SiteComponent.Blog, "post", "all"), out var posts))
            {
                posts = new List <BlogPost>();
            }

            return(posts);
        }
示例#19
0
        public List <BlogTag> GetTags()
        {
            if (!_memoryCacheClient.TryGet <List <BlogTag> >(CacheKeyBuilder.Build(SiteComponent.Blog, "tag", "all"), out var tags))
            {
                tags = new List <BlogTag>();
            }

            return(tags);
        }
        private void SetOptimizeCache(string userId, int itineraryId, OptimizeRouteResultStatus message)
        {
            if (!string.IsNullOrEmpty(userId))
            {
                var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(1));

                _cache.Set(CacheKeyBuilder.BuildOptimizeRouteCacheKey(userId, itineraryId), message, cacheEntryOptions);
            }
        }
        /// <summary>Gets a People by Id.</summary>
        /// <param name="key">The key.</param>
        /// <returns>The People.</returns>
        public Entities.People Get(int key)
        {
            var cacheKey = new CacheKeyBuilder("People.Service.V1_0_0").New(key);

            var result = CacheGateway.Instance()
                                     .Get(cacheKey, () => this.context.PeopleSet.FirstOrDefault(x => x.Id == key));

            return result;
        }
示例#22
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            #region Check cache is enabled
            if (!CacheConfiguration.Current.Enabled)
            {
                return(Proceed(input, getNext));
            }
            #endregion

            #region NoCache is checking
            var nocache = input.MethodBase.GetCustomAttributes(typeof(NoCacheAttribute), false);
            if (nocache.Count() != 0)
            {
                return(Proceed(input, getNext));
            }
            #endregion

            #region Instanciate AppFabric Cache. if it is no working, return.
            var cache = Caching.Cache.AppFabric;
            if (cache == null /* or cache is disabled inside the webconfig*/)
            {
                return(Proceed(input, getNext));
            }
            #endregion

            ExpireRegions(input, cache);

            #region Check Void Methods
            if (((MethodInfo)input.MethodBase).ReturnType.Name == "Void") // specific behavior for Void Methods
            {
                return(Proceed(input, getNext));
            }


            #endregion

            #region Check the Cache
            string cacheKey    = CacheKeyBuilder.GetCacheKey(input);
            string region      = CacheKeyBuilder.GetRegion(input);
            var    cachedValue = cache.Get(cacheKey, region);

            if (cachedValue == null)
            {
                var methodReturn = Proceed(input, getNext);
                if (methodReturn != null && methodReturn.ReturnValue != null && methodReturn.Exception == null)
                {
                    cache.Set(cacheKey, region, methodReturn.ReturnValue);
                }
                return(methodReturn);
            }
            else
            {
                return(input.CreateMethodReturn(cachedValue));
            }
            #endregion
        }
示例#23
0
        private async Task UpdateMemoryAboutAsync()
        {
            var zhAbout = await GetAboutFromFileAsync(RequestLang.Chinese);

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "about", RequestLang.Chinese), zhAbout);

            var enAbout = await GetAboutFromFileAsync(RequestLang.English);

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "about", RequestLang.English), enAbout);
        }
示例#24
0
        public string GetAboutHtml(RequestLang lang = RequestLang.Chinese)
        {
            var cacheKey = CacheKeyBuilder.Build(SiteComponent.Blog, "about", lang);

            if (!_memoryCacheClient.TryGet <string>(cacheKey, out var html))
            {
                html = string.Empty;
            }

            return(html);
        }
示例#25
0
        public void ShouldCreateFromObjectProperties()
        {
            var sut = new
            {
                A = 1,
                B = "abc",
                C = (object)null,
                D = new[] { 1, 2, 3 }
            };

            Assert.Equal("{1}{abc}{}{:1:2:3:}", CacheKeyBuilder.CreateFromObjectProperties(sut));
        }
示例#26
0
 public void ShouldCreate()
 {
     Assert.AreEqual("{A}", CacheKeyBuilder.Create("A"));
     Assert.AreEqual("{A}{B}", CacheKeyBuilder.Create("A", "B"));
     Assert.AreEqual("{A}{B}{C}", CacheKeyBuilder.Create("A", "B", "C"));
     Assert.AreEqual("{A}{}{C}", CacheKeyBuilder.Create("A", null, "C"));
     Assert.AreEqual("{:1:2:3:}", CacheKeyBuilder.Create(new[] { 1, 2, 3 }));
     Assert.AreEqual("{A}{:1:2:3:}", CacheKeyBuilder.Create("A", new[] { 1, 2, 3 }));
     Assert.AreEqual("{A}{B}{:1:2:3:}", CacheKeyBuilder.Create("A", "B", new[] { 1, 2, 3 }));
     Assert.AreEqual("{A}{B}{:1:2:3:}{C}", CacheKeyBuilder.Create("A", "B", new[] { 1, 2, 3 }, "C"));
     Assert.AreEqual("{A}{}{:1:2:3:}{}", CacheKeyBuilder.Create("A", null, new[] { 1, 2, 3 }, null));
     Assert.AreEqual("{A}{::1:2:::3:4:::5:6::}", CacheKeyBuilder.Create("A", new[] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5, 6 } }));
 }
示例#27
0
 protected override void GetConnectionKey(CacheKeyBuilder ckb)
 {
     base.GetConnectionKey(ckb);
     ckb.Add(DataSource);
     ckb.Add(Login);
     ckb.Add(CharacterSet);
     ckb.Add(Password);
     ckb.Add(Port);
     if (TunnelDriver != null)
     {
         TunnelDriver.GetConnectionKey(ckb);
     }
 }
示例#28
0
    public IActionResult Rss()
    {
        var rss = _cacheClient.GetOrCreate(CacheKeyBuilder.Build(nameof(HomeController), nameof(Rss)), () =>
        {
            var feed = new SyndicationFeed(Constants.BlogTitle, Constants.BlogDescription,
                                           new Uri($"{_blogOptions.BlogRemoteEndpoint}/rss"),
                                           Constants.ApplicationName, DateTimeOffset.UtcNow)
            {
                Copyright = new TextSyndicationContent(
                    $"&#x26;amp;#169; {DateTime.Now.Year} {_blogOptions.AdminChineseName}")
            };
            feed.Authors.Add(new SyndicationPerson(_blogOptions.AdminEmail,
                                                   _blogOptions.AdminChineseName,
                                                   _blogOptions.BlogRemoteEndpoint));
            feed.BaseUri  = new Uri(_blogOptions.BlogRemoteEndpoint);
            feed.Language = "zh-cn";
            var items     = new List <SyndicationItem>();
            foreach (var post in _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished()))
            {
                items.Add(new SyndicationItem(post.Raw.Title, post.HtmlContent,
                                              new Uri(post.Raw.GetFullPath(_blogOptions.BlogRemoteEndpoint)),
                                              post.Raw.GetFullPath(_blogOptions.BlogRemoteEndpoint),
                                              new DateTimeOffset(post.Raw.LastUpdateTime, TimeSpan.FromHours(8))));
            }

            feed.Items   = items;
            var settings = new XmlWriterSettings
            {
                Encoding            = Encoding.UTF8,
                NewLineHandling     = NewLineHandling.Entitize,
                NewLineOnAttributes = false,
                Async  = true,
                Indent = true
            };

            using var ms = new MemoryStream();
            using (var xmlWriter = XmlWriter.Create(ms, settings))
            {
                var rssFormatter = new Rss20FeedFormatter(feed, false);
                rssFormatter.WriteTo(xmlWriter);
                xmlWriter.Flush();
            }

            return(Encoding.UTF8.GetString(ms.ToArray()));
        });

        return(Content(rss, "application/rss+xml", Encoding.UTF8));
    }
示例#29
0
 public override void Set(string key, object value, DateTime expiresAt)
 {
     try
     {
         var itemBytes = Serializer.Binary.Serialize(value) as byte[];
         var item      = new CacheItem()
         {
             ItemBytes = itemBytes
         };
         var serializedItem = Serializer.Json.Serialize(item);
         var cacheKey       = CacheKeyBuilder.GetCacheKey(key);
         Current.SetInternal(cacheKey, serializedItem, expiresAt);
     }
     catch (Exception ex)
     {
         //Log.Warn("CacheBase.Set - failed, item not cached. Message: {0}", ex.Message);
     }
 }
示例#30
0
        protected TReturn CommandExecute <TReturn>(bool?enableCache, Func <TReturn> execQuery, string sql, object param, string cacheKey, TimeSpan?expire, int?pageIndex = default, int?pageSize = default)
        {
            if (!IsEnableCache(enableCache))
            {
                return(execQuery());
            }
            cacheKey = CacheKeyBuilder.Generate(sql, param, cacheKey, pageIndex, pageSize);
            var cache = Cache.TryGet <TReturn>(cacheKey);

            if (cache.HasKey)
            {
                return(cache.Value);
            }
            var result = execQuery();

            Cache.TrySet(cacheKey, result, expire ?? CacheConfiguration.Expire);
            return(result);
        }
示例#31
0
    public IActionResult Index([FromQuery] int page)
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var viewModel     = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(HomeController), nameof(Index), page, authenticated),
            () =>
        {
            var posts =
                _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished() || authenticated).ToList();
            var toppedPosts = posts.Where(x => x.Raw.IsTopping).ToList();
            foreach (var blogPost in toppedPosts)
            {
                posts.Remove(blogPost);
            }

            posts.InsertRange(0, toppedPosts);

            var postsPerPage = Convert.ToInt32(_blogOptions.PostsPerPage);
            var model        = new PagedViewModel <PostViewModel>(page, posts.Count, postsPerPage)
            {
                Url = Request.Path
            };

            foreach (var blogPost in posts.Chunk(postsPerPage).ElementAtOrDefault(model.CurrentPage - 1) ??
                     Enumerable.Empty <BlogPostRuntime>())
            {
                var postViewModel = new PostViewModel {
                    Current = blogPost
                };
                postViewModel.SetAdditionalInfo();
                model.Items.Add(postViewModel);
            }

            return(model);
        });

        if (viewModel.CurrentPage > 1)
        {
            ViewData["RobotsEnabled"] = false;
            ViewData["Title"]         = $"首页:第{viewModel.CurrentPage}页";
        }

        return(View(viewModel));
    }
 public ICacheKeyBuilder CreateKey()
 {
     var builder = new CacheKeyBuilder(_tagManager);
     return builder;
 }