Ejemplo n.º 1
0
        public void All()
        {
            var cache = new IsolatedMemoryCache <string, string>("Locale");

            // Set
            LocaleUtils.SetThreadLanguage("zh-CN");
            cache.Put("Key", "ValueForCN", TimeSpan.FromSeconds(5));
            LocaleUtils.SetThreadLanguage("en-US");
            cache.Put("Key", "ValueForUS", TimeSpan.FromSeconds(5));
            // Get
            LocaleUtils.SetThreadLanguage("zh-CN");
            Assert.Equals(cache.GetOrDefault("Key"), "ValueForCN");
            LocaleUtils.SetThreadLanguage("en-US");
            Assert.Equals(cache.GetOrDefault("Key"), "ValueForUS");
            // Remove
            LocaleUtils.SetThreadLanguage("zh-CN");
            cache.Remove("Key");
            Assert.Equals(cache.GetOrDefault("Key"), null);
            LocaleUtils.SetThreadLanguage("en-US");
            Assert.Equals(cache.GetOrDefault("Key"), "ValueForUS");
            cache.Remove("Key");
            Assert.Equals(cache.GetOrDefault("Key"), null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Render widget
        /// Return reder result
        /// </summary>
        /// <param name="context">Template context</param>
        /// <param name="widget">Template widget</param>
        /// <returns></returns>
        public virtual string RenderWidget(Context context, TemplateWidget widget)
        {
            // Get from cache
            var info = GetWidgetInfo(widget.Path);
            IsolatedMemoryCache <string, string> renderCache = null;
            string key          = null;
            string renderResult = null;

            if (info.CacheTime > 0)
            {
                renderCache = WidgetRenderCache.GetOrAdd(info.CacheBy ?? "",
                                                         _ => new IsolatedMemoryCache <string, string>(info.GetCacheIsolationPolicyNames()));
                key          = widget.GetCacheKey();
                renderResult = renderCache.GetOrDefault(key);
                if (renderResult != null)
                {
                    return(renderResult);
                }
            }
            // Render widget
            var writer = new StringWriter();

            writer.Write($"<div class='template_widget' data-widget='{key}'>");
            var scope = Hash.FromAnonymousObject(widget.Args);

            context.Stack(scope, () => {
                var includeTag = new Include();
                var htmlPath   = widget.Path + TemplateWidgetInfo.HtmlExtension;
                includeTag.Initialize("include", htmlPath, null);
                includeTag.Render(context, writer);
            });
            writer.Write("</div>");
            renderResult = writer.ToString();
            // Store to cache
            if (info.CacheTime > 0)
            {
                renderCache.Put(key, renderResult, TimeSpan.FromSeconds(info.CacheTime));
            }
            return(renderResult);
        }