Exemple #1
0
        /// <summary>
        /// Returns Global Attributes from cache.  If they are not already in cache, they
        /// will be read and added to cache
        /// </summary>
        /// <returns></returns>
        private static SystemSettings Read()
        {
            string cacheKey = SystemSettings.CacheKey();

            RockMemoryCache cache          = RockMemoryCache.Default;
            SystemSettings  systemSettings = cache[cacheKey] as SystemSettings;

            if (systemSettings != null)
            {
                return(systemSettings);
            }
            else
            {
                systemSettings            = new SystemSettings();
                systemSettings.Attributes = new List <AttributeCache>();

                var rockContext      = new RockContext();
                var attributeService = new Rock.Model.AttributeService(rockContext);

                foreach (Rock.Model.Attribute attribute in attributeService.GetSystemSettings())
                {
                    var attributeCache = AttributeCache.Read(attribute);
                    systemSettings.Attributes.Add(attributeCache);
                }

                cache.Set(cacheKey, systemSettings, new CacheItemPolicy());

                return(systemSettings);
            }
        }
Exemple #2
0
        /// <summary>
        /// Adds the cached HTML for a specific blockId or, if specified, a specific entityValue (Entity Context)
        /// </summary>
        /// <param name="blockId">The block identifier.</param>
        /// <param name="entityValue">The entity value.</param>
        /// <param name="html">The HTML.</param>
        /// <param name="cacheDuration">Duration of the cache.</param>
        public static void AddCachedContent(int blockId, string entityValue, string html, int cacheDuration)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            cache.Set(HtmlContentCacheKey(blockId, entityValue), html, new CacheItemPolicy {
                AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(cacheDuration)
            });
        }
        private Template GetTemplate()
        {
            RockMemoryCache cache    = RockMemoryCache.Default;
            Template        template = null;

            if (cache[TemplateCacheKey] != null)
            {
                template = (Template)cache[TemplateCacheKey];
            }
            else
            {
                template = Template.Parse(GetAttributeValue("Template"));
                cache.Set(TemplateCacheKey, template, new CacheItemPolicy());
            }

            return(template);
        }
        /// <summary>
        /// Gets the or add existing.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <returns></returns>
        private static List <ConnectionWorkflow> GetOrAddExisting(Func <List <ConnectionWorkflow> > factory)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            var value = cache.Get(CACHE_KEY) as List <ConnectionWorkflow>;

            if (value != null)
            {
                return(value);
            }

            value = factory();
            if (value != null)
            {
                cache.Set(CACHE_KEY, value, new CacheItemPolicy());
            }
            return(value);
        }
Exemple #5
0
        /// <summary>
        /// Gets the or add existing.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="valueFactory">The value factory.</param>
        /// <returns></returns>
        public static Role GetOrAddExisting(string key, Func <Role> valueFactory)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            object cacheValue = cache.Get(key);

            if (cacheValue != null)
            {
                return((Role)cacheValue);
            }

            Role value = valueFactory();

            if (value != null)
            {
                cache.Set(key, value, new CacheItemPolicy());
            }
            return(value);
        }
Exemple #6
0
        private Template GetTemplate()
        {
            string cacheKey = CacheKey();

            RockMemoryCache cache    = RockMemoryCache.Default;
            Template        template = cache[cacheKey] as Template;

            if (template != null)
            {
                return(template);
            }
            else
            {
                template = Template.Parse(GetAttributeValue("Template"));

                var cachePolicy = new CacheItemPolicy();
                cache.Set(cacheKey, template, cachePolicy);

                return(template);
            }
        }
        /// <summary>
        /// Writes the <see cref="T:System.Web.UI.WebControls.CompositeControl" /> content to the specified <see cref="T:System.Web.UI.HtmlTextWriter" /> object, for display on the client.
        /// </summary>
        /// <param name="writer">An <see cref="T:System.Web.UI.HtmlTextWriter" /> that represents the output stream to render HTML content on the client.</param>
        protected override void Render(HtmlTextWriter writer)
        {
            var blockCache = _rockBlock.BlockCache;

            string preHtml   = string.Empty;
            string postHtml  = string.Empty;
            string appRoot   = _rockBlock.ResolveRockUrl("~/");
            string themeRoot = _rockBlock.ResolveRockUrl("~~/");

            if (_rockBlock.Visible)
            {
                if (!string.IsNullOrWhiteSpace(blockCache.PreHtml))
                {
                    preHtml = blockCache.PreHtml.Replace("~~/", themeRoot).Replace("~/", appRoot);
                }

                if (!string.IsNullOrWhiteSpace(blockCache.PostHtml))
                {
                    postHtml = blockCache.PostHtml.Replace("~~/", themeRoot).Replace("~/", appRoot);
                }

                if (preHtml.HasMergeFields() || postHtml.HasMergeFields())
                {
                    var mergeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(_rockBlock.CurrentPerson);
                    mergeFields.Add("CurrentPerson", _rockBlock.CurrentPerson);
                    mergeFields.Add("Campuses", CampusCache.All());
                    mergeFields.Add("PageParameter", _rockBlock.PageParameters());

                    var contextObjects = new Dictionary <string, object>();
                    foreach (var contextEntityType in _rockBlock.RockPage.GetContextEntityTypes())
                    {
                        var contextEntity = _rockBlock.RockPage.GetCurrentContext(contextEntityType);
                        if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                        {
                            var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                            if (type != null)
                            {
                                contextObjects.Add(type.Name, contextEntity);
                            }
                        }
                    }

                    if (contextObjects.Any())
                    {
                        mergeFields.Add("Context", contextObjects);
                    }

                    preHtml  = preHtml.ResolveMergeFields(mergeFields);
                    postHtml = postHtml.ResolveMergeFields(mergeFields);
                }
            }

            StringBuilder  sbOutput = null;
            StringWriter   swOutput = null;
            HtmlTextWriter twOutput = null;

            if (_rockBlock.BlockCache.OutputCacheDuration > 0)
            {
                sbOutput = new StringBuilder();
                swOutput = new StringWriter(sbOutput);
                twOutput = new HtmlTextWriter(swOutput);
            }

            // Create block wrapper
            string blockTypeCss = blockCache.BlockType != null ? blockCache.BlockType.Name : "";
            var    parts        = blockTypeCss.Split(new char[] { '>' });

            if (parts.Length > 1)
            {
                blockTypeCss = parts[parts.Length - 1].Trim();
            }
            blockTypeCss = blockTypeCss.Replace(' ', '-').ToLower();
            string blockInstanceCss = "block-instance " +
                                      blockTypeCss +
                                      (string.IsNullOrWhiteSpace(blockCache.CssClass) ? "" : " " + blockCache.CssClass.Trim()) +
                                      (_rockBlock.UserCanEdit || _rockBlock.UserCanAdministrate ? " can-configure " : "");

            writer.Write(preHtml);
            writer.AddAttribute(HtmlTextWriterAttribute.Id, string.Format("bid_{0}", blockCache.Id));
            writer.AddAttribute("data-zone-location", blockCache.BlockLocation.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Class, blockInstanceCss);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-content");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            if (blockCache.OutputCacheDuration > 0)
            {
                twOutput.Write(preHtml);
                twOutput.AddAttribute(HtmlTextWriterAttribute.Id, string.Format("bid_{0}", blockCache.Id));
                twOutput.AddAttribute("data-zone-location", blockCache.BlockLocation.ToString());
                twOutput.AddAttribute(HtmlTextWriterAttribute.Class, blockInstanceCss);
                twOutput.RenderBeginTag(HtmlTextWriterTag.Div);

                twOutput.AddAttribute(HtmlTextWriterAttribute.Class, "block-content");
                twOutput.RenderBeginTag(HtmlTextWriterTag.Div);
            }

            if (_rockBlock.PageCache.IncludeAdminFooter && _adminControls.Any())
            {
                // Add the config buttons
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-configuration config-bar");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, "#");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "fa fa-arrow-circle-right");
                writer.RenderBeginTag(HtmlTextWriterTag.I);
                writer.RenderEndTag();
                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-configuration-bar");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(string.IsNullOrWhiteSpace(blockCache.Name) ? blockCache.BlockType.Name : blockCache.Name);
                writer.RenderEndTag();

                foreach (Control configControl in _adminControls)
                {
                    configControl.RenderControl(writer);
                }

                writer.RenderEndTag();  // block-configuration-bar
                writer.RenderEndTag();  // config-bar
            }

            _rockBlock.RenderControl(writer);

            writer.RenderEndTag();  // block-content
            writer.RenderEndTag();  // block-instance
            writer.Write(postHtml);

            if (blockCache.OutputCacheDuration > 0)
            {
                base.Render(twOutput);

                twOutput.RenderEndTag();  // block-content
                twOutput.RenderEndTag();  // block-instance
                twOutput.Write(postHtml);

                CacheItemPolicy cacheDuration = new CacheItemPolicy();
                cacheDuration.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(blockCache.OutputCacheDuration);

                RockMemoryCache cache          = RockMemoryCache.Default;
                string          _blockCacheKey = string.Format("Rock:BlockOutput:{0}", blockCache.Id);
                cache.Set(_blockCacheKey, sbOutput.ToString(), cacheDuration);
            }
        }
Exemple #8
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            RockPage page = HttpContext.Current.Handler as RockPage;

            var parms = ParseMarkup(_markup, context);

            using (TextWriter twStylesheet = new StringWriter())
            {
                base.Render(context, twStylesheet);

                var stylesheet = twStylesheet.ToString();

                if (parms.ContainsKey("compile"))
                {
                    if (parms["compile"] == "less")
                    {
                        DotlessConfiguration dotLessConfiguration = new DotlessConfiguration();
                        dotLessConfiguration.MinifyOutput = true;

                        if (parms.ContainsKey("import"))
                        {
                            // import statements should go at the end to allow for default variable assignment in the beginning
                            // to help reduce the number of Less errors we automatically add the bootstrap and core rock variables files
                            var importStatements = string.Empty;

                            var importSource = "~/Styles/Bootstrap/variables.less,~/Styles/_rock-variables.less," + parms["import"];

                            var importFiles = importSource.Split(',');
                            foreach (var importFile in importFiles)
                            {
                                var filePath = string.Empty;
                                if (!importFile.StartsWith("~"))
                                {
                                    filePath = $"~~/Styles/{importFile}";
                                }
                                else
                                {
                                    filePath = importFile;
                                }

                                filePath = page.ResolveRockUrl(filePath);

                                var fullPath = page.MapPath("~/") + filePath;

                                if (File.Exists(fullPath))
                                {
                                    importStatements = $"{importStatements}{Environment.NewLine}@import \"{fullPath}\";";
                                }
                            }

                            stylesheet = $"{stylesheet}{Environment.NewLine}{importStatements}";
                        }

                        // ok we have our less stylesheet let's see if it's been cached (less can take ~100ms to compile so let's try not to do that if necessary)
                        if (parms.ContainsKey("cacheduration"))
                        {
                            var             cacheKey         = stylesheet.GetHashCode().ToString();
                            RockMemoryCache cache            = RockMemoryCache.Default;
                            var             cachedStylesheet = cache[cacheKey] as string;

                            if (cachedStylesheet.IsNotNullOrWhitespace())
                            {
                                stylesheet = cachedStylesheet;
                            }
                            else
                            {
                                stylesheet = LessWeb.Parse(stylesheet, dotLessConfiguration);

                                // check if we should cache this
                                if (parms.ContainsKey("cacheduration") && stylesheet.IsNotNullOrWhitespace())
                                {
                                    int cacheDuration = 0;
                                    Int32.TryParse(parms["cacheduration"], out cacheDuration);

                                    if (cacheDuration > 0)
                                    {
                                        cache.Set(cacheKey, stylesheet, new CacheItemPolicy {
                                            AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(cacheDuration)
                                        });
                                    }
                                }
                            }
                        }
                        else
                        {
                            stylesheet = LessWeb.Parse(stylesheet, dotLessConfiguration);
                        }
                    }

                    if (stylesheet == string.Empty)
                    {
                        if (parms.ContainsKey("id"))
                        {
                            result.Write($"An error occurred compiling the Less for this stylesheet (id: {parms["id"]}).");
                        }
                        else
                        {
                            result.Write("An error occurred compiling the Less for this stylesheet.");
                        }
                        return;
                    }
                }

                if (parms.ContainsKey("id"))
                {
                    var identifier = parms["id"];
                    if (identifier.IsNotNullOrWhitespace())
                    {
                        var controlId = "css-" + identifier;

                        var cssControl = page.Header.FindControl(controlId);
                        if (cssControl == null)
                        {
                            cssControl    = new System.Web.UI.LiteralControl($"{Environment.NewLine}<style>{stylesheet}</style>{Environment.NewLine}");
                            cssControl.ID = controlId;
                            page.Header.Controls.Add(cssControl);
                        }
                    }
                }
                else
                {
                    page.Header.Controls.Add(new System.Web.UI.LiteralControl($"{Environment.NewLine}<style>{stylesheet}</style>{Environment.NewLine}"));
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Reads the specified label by guid.
        /// </summary>
        /// <param name="guid">The unique identifier.</param>
        /// <returns></returns>
        public static KioskLabel Read(Guid guid)
        {
            string cacheKey = KioskLabel.CacheKey(guid);

            RockMemoryCache cache = RockMemoryCache.Default;
            KioskLabel      label = cache[cacheKey] as KioskLabel;

            if (label != null)
            {
                return(label);
            }
            else
            {
                using (var rockContext = new RockContext())
                {
                    var file = new BinaryFileService(rockContext).Get(guid);
                    if (file != null)
                    {
                        label = new KioskLabel();

                        label.Guid        = file.Guid;
                        label.Url         = string.Format("{0}GetFile.ashx?id={1}", System.Web.VirtualPathUtility.ToAbsolute("~"), file.Id);
                        label.MergeFields = new Dictionary <string, string>();
                        label.FileContent = file.ContentsToString();

                        file.LoadAttributes(rockContext);
                        string attributeValue = file.GetAttributeValue("MergeCodes");
                        if (!string.IsNullOrWhiteSpace(attributeValue))
                        {
                            string[] nameValues = attributeValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string nameValue in nameValues)
                            {
                                string[] nameAndValue = nameValue.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries);
                                if (nameAndValue.Length == 2 && !label.MergeFields.ContainsKey(nameAndValue[0]))
                                {
                                    label.MergeFields.Add(nameAndValue[0], nameAndValue[1]);

                                    int definedValueId = int.MinValue;
                                    if (int.TryParse(nameAndValue[1], out definedValueId))
                                    {
                                        var definedValue = DefinedValueCache.Read(definedValueId);
                                        if (definedValue != null)
                                        {
                                            string mergeField = definedValue.GetAttributeValue("MergeField");
                                            if (mergeField != null)
                                            {
                                                label.MergeFields[nameAndValue[0]] = mergeField;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        cache.Set(cacheKey, label, new CacheItemPolicy {
                            AbsoluteExpiration = DateTimeOffset.Now.Date.AddDays(1)
                        });

                        return(label);
                    }
                }
            }

            return(null);
        }