/// <summary>
        /// Use Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">A comma-delimited list of the lava commands that are enabled for this template.</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        public static string RenderLava(this string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands)
        {
            try
            {
                // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
                if (enabledLavaCommands == null)
                {
                    enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
                }

                var context = LavaService.NewRenderContext();

                context.SetEnabledCommands(enabledLavaCommands, ",");

                context.SetMergeField("CurrentPerson", currentPersonOverride);
                context.SetMergeFields(mergeObjects);

                var result = LavaService.RenderTemplate(content, LavaRenderParameters.WithContext(context));

                if (result.HasErrors)
                {
                    throw result.GetLavaException();
                }

                return(result.Text);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                return("Error resolving Lava merge fields: " + ex.Message);
            }
        }
示例#2
0
        /// <summary>
        /// Use Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">A comma-delimited list of the lava commands that are enabled for this template.</param>
        /// <param name="encodeStringOutput">if set to <c>true</c> [encode string output].</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        private static LavaRenderResult ResolveMergeFieldsWithCurrentLavaEngine(string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands, bool encodeStringOutput)
        {
            // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
            if (enabledLavaCommands == null)
            {
                enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
            }

            var context = LavaService.NewRenderContext();

            context.SetEnabledCommands(enabledLavaCommands, ",");

            if (currentPersonOverride != null)
            {
                context.SetMergeField("CurrentPerson", currentPersonOverride);
            }

            context.SetMergeFields(mergeObjects);

            var parameters = LavaRenderParameters.WithContext(context);

            parameters.ShouldEncodeStringsAsXml = encodeStringOutput;

            var result = LavaService.RenderTemplate(content, parameters);

            if (result.HasErrors &&
                LavaService.ExceptionHandlingStrategy == ExceptionHandlingStrategySpecifier.RenderToOutput)
            {
                // If the result is an error, encode the error message to prevent any part of it from appearing as rendered content, and then add markup for line breaks.
                result.Text = result.Text.EncodeHtml().ConvertCrLfToHtmlBr();
            }

            return(result);
        }
示例#3
0
        private void Render()
        {
            string content = null;

            try
            {
                PageCache currentPage = PageCache.Get(RockPage.PageId);
                PageCache rootPage    = null;

                var pageRouteValuePair = GetAttributeValue(AttributeKey.RootPage).SplitDelimitedValues(false).AsGuidOrNullList();
                if (pageRouteValuePair.Any() && pageRouteValuePair[0].HasValue && !pageRouteValuePair[0].Value.IsEmpty())
                {
                    rootPage = PageCache.Get(pageRouteValuePair[0].Value);
                }

                // If a root page was not found, use current page
                if (rootPage == null)
                {
                    rootPage = currentPage;
                }

                int levelsDeep = Convert.ToInt32(GetAttributeValue(AttributeKey.NumberofLevels));

                Dictionary <string, string> pageParameters = null;
                if (GetAttributeValue(AttributeKey.IncludeCurrentParameters).AsBoolean())
                {
                    pageParameters = CurrentPageReference.Parameters;
                }

                NameValueCollection queryString = null;
                if (GetAttributeValue(AttributeKey.IncludeCurrentQueryString).AsBoolean())
                {
                    queryString = CurrentPageReference.QueryString;
                }

                // Get list of pages in current page's hierarchy
                var pageHeirarchy = new List <int>();
                if (currentPage != null)
                {
                    pageHeirarchy = currentPage.GetPageHierarchy().Select(p => p.Id).ToList();
                }

                // Get default merge fields.
                var pageProperties = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                pageProperties.Add("Site", GetSiteProperties(RockPage.Site));
                pageProperties.Add("IncludePageList", GetIncludePageList());
                pageProperties.Add("CurrentPage", this.PageCache);

                using (var rockContext = new RockContext())
                {
                    pageProperties.Add("Page", rootPage.GetMenuProperties(levelsDeep, CurrentPerson, rockContext, pageHeirarchy, pageParameters, queryString));
                }

                if (LavaService.RockLiquidIsEnabled)
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    var lavaTemplate = GetTemplate();
#pragma warning restore CS0618 // Type or member is obsolete

                    // Apply Enabled Lava Commands
                    var enabledCommands = GetAttributeValue(AttributeKey.EnabledLavaCommands);
                    lavaTemplate.Registers.AddOrReplace("EnabledCommands", enabledCommands);

                    content = lavaTemplate.Render(Hash.FromDictionary(pageProperties));

                    // Check for Lava rendering errors.
                    if (lavaTemplate.Errors.Any())
                    {
                        throw lavaTemplate.Errors.First();
                    }
                }
                else
                {
                    var templateText = GetAttributeValue(AttributeKey.Template);

                    // Apply Enabled Lava Commands
                    var lavaContext = LavaService.NewRenderContext(pageProperties);

                    var enabledCommands = GetAttributeValue(AttributeKey.EnabledLavaCommands);

                    lavaContext.SetEnabledCommands(enabledCommands.SplitDelimitedValues());

                    var result = LavaService.RenderTemplate(templateText,
                                                            new LavaRenderParameters {
                        Context = lavaContext, CacheKey = CacheKey()
                    });

                    content = result.Text;

                    if (result.HasErrors)
                    {
                        throw result.GetLavaException("PageMenu Block Lava Error");
                    }
                }

                phContent.Controls.Clear();
                phContent.Controls.Add(new LiteralControl(content));
            }
            catch (Exception ex)
            {
                LogException(ex);

                // Create a block showing the error and the attempted content render.
                // Show the error first to ensure that it is visible, because the rendered content may disrupt subsequent output if it is malformed.
                StringBuilder errorMessage = new StringBuilder();
                errorMessage.Append("<div class='alert alert-warning'>");
                errorMessage.Append("<h4>Warning</h4>");
                errorMessage.Append("An error has occurred while generating the page menu. Error details:<br/>");
                errorMessage.Append(ex.Message);

                if (!string.IsNullOrWhiteSpace(content))
                {
                    errorMessage.Append("<h4>Rendered Content</h4>");
                    errorMessage.Append(content);
                    errorMessage.Append("</div>");
                }

                phContent.Controls.Add(new LiteralControl(errorMessage.ToString()));
            }
        }
        /// <summary>
        /// Uses Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="enabledLavaCommands">The enabled lava commands.</param>
        /// <param name="encodeStrings">if set to <c>true</c> [encode strings].</param>
        /// <param name="throwExceptionOnErrors">if set to <c>true</c> [throw exception on errors].</param>
        /// <returns></returns>
        public static string RenderLava(this string content, IDictionary <string, object> mergeObjects, IEnumerable <string> enabledLavaCommands, bool encodeStrings = false, bool throwExceptionOnErrors = false)
        {
            try
            {
                if (!content.HasMergeFields())
                {
                    return(content ?? string.Empty);
                }

                if (mergeObjects == null)
                {
                    mergeObjects = new Dictionary <string, object>();
                }

                if (GlobalAttributesCache.Get().LavaSupportLevel == Lava.LavaSupportLevel.LegacyWithWarning && mergeObjects.ContainsKey("GlobalAttribute"))
                {
                    if (hasLegacyGlobalAttributeLavaMergeFields.IsMatch(content))
                    {
                        Rock.Model.ExceptionLogService.LogException(new Rock.Lava.LegacyLavaSyntaxDetectedException("GlobalAttribute", ""), System.Web.HttpContext.Current);
                    }
                }

                var context = LavaService.NewRenderContext(mergeObjects);

                if (enabledLavaCommands != null)
                {
                    context.SetEnabledCommands(enabledLavaCommands);
                }

                var renderParameters = new LavaRenderParameters {
                    Context = context
                };

                renderParameters.ShouldEncodeStringsAsXml = encodeStrings;

                // Try and parse the template, or retrieve it from the cache if it has been previously parsed.
                var result = LavaService.RenderTemplate(content, renderParameters);

                if (result.HasErrors)
                {
                    throw result.GetLavaException();
                }

                return(result.Text);
            }
            catch (System.Threading.ThreadAbortException)
            {
                // Do nothing...it's just a Lava PageRedirect that just happened.
                return(string.Empty);
            }
            catch (Exception ex)
            {
                if (throwExceptionOnErrors)
                {
                    throw;
                }
                else
                {
                    ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                    return("Error resolving Lava merge fields: " + ex.Message);
                }
            }
        }
示例#5
0
        /// <summary>
        /// Shows the wall.
        /// </summary>
        private void ShowWall()
        {
            var pageRef = CurrentPageReference;

            pageRef.Parameters.AddOrReplace("Page", "PageNum");

            var prayerRequests = new List <PrayerRequest>();

            var qry = new PrayerRequestService(new RockContext())
                      .Queryable()
                      .AsNoTracking()
                      .Where(r => r.ExpirationDate >= RockDateTime.Now &&
                             r.IsApproved == true &&
                             r.IsPublic == true);

            var categoryGuids = (GetAttributeValue("CategoryFilter") ?? string.Empty).SplitDelimitedValues().AsGuidList();

            if (categoryGuids.Any())
            {
                qry = qry.Where(a => a.CategoryId.HasValue && (categoryGuids.Contains(a.Category.Guid) || (a.Category.ParentCategoryId.HasValue && categoryGuids.Contains(a.Category.ParentCategory.Guid))));
            }

            var campusEntity = RockPage.GetCurrentContext(EntityTypeCache.Get(typeof(Campus)));

            if (campusEntity != null)
            {
                var campusId = campusEntity.Id;
                qry = qry.Where(r => r.CampusId.HasValue && r.CampusId == campusId);
            }

            var sortOrder = GetAttributeValue("SortOrder").AsInteger();

            switch (sortOrder)
            {
            case 0:
                qry = qry.OrderByDescending(a => a.EnteredDateTime);
                break;

            case 1:
                qry = qry.OrderBy(a => a.EnteredDateTime);
                break;
            }

            prayerRequests = qry.ToList();

            var pagination = new Pagination();

            pagination.ItemCount   = prayerRequests.Count();
            pagination.PageSize    = GetAttributeValue("PageSize").AsInteger();
            pagination.CurrentPage = PageParameter("Page").AsIntegerOrNull() ?? 1;
            pagination.UrlTemplate = pageRef.BuildUrl();

            var currentPrayerRequests = pagination.GetCurrentPageItems(prayerRequests);

            var commonMergeFields = LavaHelper.GetCommonMergeFields(RockPage);

            var mergeFields = new Dictionary <string, object>(commonMergeFields);

            mergeFields.Add("Pagination", pagination);
            mergeFields.Add("PrayerRequests", currentPrayerRequests);

            Template      template     = null;
            ILavaTemplate lavaTemplate = null;
            var           error        = string.Empty;

            try
            {
                if (LavaService.RockLiquidIsEnabled)
                {
                    template = Template.Parse(GetAttributeValue("LavaTemplate"));

                    LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue("LavaTemplate"));
                }
                else
                {
                    var parseResult = LavaService.ParseTemplate(GetAttributeValue("LavaTemplate"));

                    lavaTemplate = parseResult.Template;
                }
            }
            catch (Exception ex)
            {
                error = string.Format("Lava error: {0}", ex.Message);
            }
            finally
            {
                if (error.IsNotNullOrWhiteSpace())
                {
                    nbError.Text    = error;
                    nbError.Visible = true;
                }

                if (template != null || lavaTemplate != null)
                {
                    if (LavaService.RockLiquidIsEnabled)
                    {
                        template.Registers["EnabledCommands"] = GetAttributeValue("EnabledLavaCommands");
                        lContent.Text = template.Render(Hash.FromDictionary(mergeFields));
                    }
                    else
                    {
                        var lavaContext = LavaService.NewRenderContext(mergeFields, GetAttributeValue("EnabledLavaCommands").SplitDelimitedValues());
                        var result      = LavaService.RenderTemplate(lavaTemplate, lavaContext);

                        lContent.Text = result.Text;
                    }
                }
            }
        }
示例#6
0
        private void LoadFeedItem(string feedItemId)
        {
            string feedUrl = GetAttributeValue(AttributeKey.RSSFeedUrl);
            Dictionary <string, string> messages = new Dictionary <string, string>();
            bool isError = false;

            try
            {
                Dictionary <string, object> feedDictionary = SyndicationFeedHelper.GetFeed(feedUrl, RockPage.Guid.ToString(), GetAttributeValue(AttributeKey.CacheDuration).AsInteger(), ref messages, ref isError);

                if (feedDictionary != null && feedDictionary.Count > 0)
                {
                    if (!String.IsNullOrWhiteSpace(GetAttributeValue(AttributeKey.RSSFeedUrl)) && GetAttributeValue(AttributeKey.IncludeRSSLink).AsBoolean())
                    {
                        string rssLink = string.Format("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{0}\" href=\"{1}\" />",
                                                       feedDictionary.ContainsKey("title") ? feedDictionary["title"].ToString() : "RSS",
                                                       GetAttributeValue(AttributeKey.RSSFeedUrl));

                        Page.Header.Controls.Add(new LiteralControl(rssLink));
                    }

                    Dictionary <string, object> previousItem = null;
                    Dictionary <string, object> selectedItem = null;
                    Dictionary <string, object> nextItem     = null;
                    if (feedDictionary.ContainsKey("item") || feedDictionary.ContainsKey("entry"))
                    {
                        List <Dictionary <string, object> > items = ((List <Dictionary <string, object> >)feedDictionary.Where(i => i.Key == "item" || i.Key == "entry").FirstOrDefault().Value);
                        for (int i = 0; i < items.Count; i++)
                        {
                            if (items[i]["articleHash"].ToString() == feedItemId)
                            {
                                selectedItem = items[i];


                                if (i > 0)
                                {
                                    nextItem = items[i - 1];
                                }

                                if (i < (items.Count - 1))
                                {
                                    previousItem = items[i + 1];
                                }
                                break;
                            }
                        }
                    }

                    Dictionary <string, object> feedFinal = new Dictionary <string, object>();
                    feedFinal.Add("Feed", feedDictionary);
                    feedFinal.Add("SelectedItem", selectedItem);
                    feedFinal.Add("PreviousItem", previousItem);
                    feedFinal.Add("NextItem", nextItem);

                    if (selectedItem == null)
                    {
                        messages.Add("Requested item not available", "The item that you requested is currently not available.");
                    }
                    else
                    {
                        string content;

                        if (LavaService.RockLiquidIsEnabled)
                        {
#pragma warning disable CS0618 // Type or member is obsolete
                            content = GetTemplate().Render(Hash.FromDictionary(feedFinal));
#pragma warning restore CS0618 // Type or member is obsolete
                        }
                        else
                        {
                            var renderParameters = new LavaRenderParameters
                            {
                                Context  = LavaService.NewRenderContext(feedFinal),
                                CacheKey = this.TemplateCacheKey
                            };

                            var result = LavaService.RenderTemplate(GetAttributeValue(AttributeKey.Template), renderParameters);

                            content = result.Text;
                        }

                        if (content.Contains("No such template"))
                        {
                            System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(GetAttributeValue(AttributeKey.Template), @"'([^']*)");
                            if (match.Success)
                            {
                                messages.Add("Warning", string.Format("Could not find the template _{0}.liquid in {1}.", match.Groups[1].Value, ResolveRockUrl("~~/Assets/Liquid")));
                                isError = true;
                            }
                            else
                            {
                                messages.Add("Warning", "Unable to parse the template name from settings.");
                                isError = true;
                            }
                        }
                        else
                        {
                            phFeedItem.Controls.Clear();
                            phFeedItem.Controls.Add(new LiteralControl(content));
                            pnlContent.Visible = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (IsUserAuthorized(Rock.Security.Authorization.ADMINISTRATE))
                {
                    throw ex;
                }
                else
                {
                    messages.Add("Content not available.", "Oops. The requested content is not currently available. Please try again later.");
                    isError = true;
                }
            }


            if (messages.Count > 0)
            {
                if (IsUserAuthorized(Rock.Security.Authorization.ADMINISTRATE))
                {
                    SetNotificationBox(messages.FirstOrDefault().Key, messages.FirstOrDefault().Value, isError ? NotificationBoxType.Warning : NotificationBoxType.Info);
                }
                else
                {
                    SetNotificationBox("Content not available", "Oops. The requested content is not currently available. Please try again later.");
                }
            }
        }
示例#7
0
        private void LoadFeed()
        {
            string feedUrl = GetAttributeValue(AttributeKey.RSSFeedUrl);

            Dictionary <string, string> messages = new Dictionary <string, string>();
            bool isError = false;

            try
            {
                Dictionary <string, object> feedDictionary = SyndicationFeedHelper.GetFeed(feedUrl, GetAttributeValue(AttributeKey.DetailPage), GetAttributeValue(AttributeKey.CacheDuration).AsInteger(), ref messages, ref isError);

                if (feedDictionary != null)
                {
                    int    articlesPerPage = GetAttributeValue(AttributeKey.Resultsperpage).AsInteger();
                    int    currentPage     = 0;
                    string baseUrl         = new PageReference(RockPage.PageId).BuildUrl();

                    int.TryParse(PageParameter(PageParameterKey.ArticlePage), out currentPage);

                    if (feedDictionary.ContainsKey("ResultsPerPage"))
                    {
                        feedDictionary["ResultsPerPage"] = articlesPerPage;
                    }
                    else
                    {
                        feedDictionary.Add("ResultsPerPage", articlesPerPage);
                    }


                    if (feedDictionary.ContainsKey("CurrentPage"))
                    {
                        feedDictionary["CurrentPage"] = currentPage;
                    }
                    else
                    {
                        feedDictionary.Add("CurrentPage", currentPage);
                    }

                    if (feedDictionary.ContainsKey("BaseUrl"))
                    {
                        feedDictionary["BaseUrl"] = baseUrl;
                    }
                    else
                    {
                        feedDictionary.Add("BaseUrl", baseUrl);
                    }


                    if (!String.IsNullOrWhiteSpace(GetAttributeValue(AttributeKey.RSSFeedUrl)) && GetAttributeValue(AttributeKey.IncludeRSSLink).AsBoolean())
                    {
                        string rssLink = string.Format("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{0}\" href=\"{1}\" />",
                                                       feedDictionary.ContainsKey("title") ? feedDictionary["title"].ToString() : "RSS",
                                                       GetAttributeValue(AttributeKey.RSSFeedUrl));

                        Page.Header.Controls.Add(new LiteralControl(rssLink));
                    }


                    // rearrange the dictionary for cleaning purposes
                    if (feedDictionary.ContainsKey("entry"))
                    {
                        var item = feedDictionary["entry"];

                        if (item != null)
                        {
                            feedDictionary.Remove("entry");
                            feedDictionary["Entries"] = item;
                        }
                    }


                    // remove the link item
                    if (feedDictionary.ContainsKey("link"))
                    {
                        var item = feedDictionary["link"];

                        if (item != null)
                        {
                            feedDictionary.Remove("link");
                        }
                    }

                    string content = String.Empty;

                    if (LavaService.RockLiquidIsEnabled)
                    {
#pragma warning disable CS0618 // Type or member is obsolete
                        content = GetTemplate().Render(Hash.FromDictionary(feedDictionary));
#pragma warning restore CS0618 // Type or member is obsolete
                    }
                    else
                    {
                        var renderParameters = new LavaRenderParameters
                        {
                            Context  = LavaService.NewRenderContext(feedDictionary),
                            CacheKey = this.TemplateCacheKey
                        };

                        var result = LavaService.RenderTemplate(GetAttributeValue(AttributeKey.Template), renderParameters);

                        content = result.Text;
                    }

                    if (content.Contains("No such template"))
                    {
                        System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(GetAttributeValue(AttributeKey.Template), @"'([^']*)");
                        if (match.Success)
                        {
                            messages.Add("Warning", string.Format("Could not find the template _{0}.liquid in {1}.", match.Groups[1].Value, ResolveRockUrl("~~/Assets/Liquid")));
                            isError = true;
                        }
                        else
                        {
                            messages.Add("Warning", "Unable to parse the template name from settings.");
                            isError = true;
                        }
                    }
                    else
                    {
                        phRSSFeed.Controls.Clear();
                        phRSSFeed.Controls.Add(new LiteralControl(content));
                    }

                    pnlContent.Visible = true;
                }
            }
            catch (Exception ex)
            {
                if (IsUserAuthorized(Authorization.ADMINISTRATE))
                {
                    throw ex;
                }
                else
                {
                    messages.Add("exception", "An exception has occurred.");
                }
            }

            if (messages.Count > 0)
            {
                if (IsUserAuthorized(Authorization.ADMINISTRATE))
                {
                    SetNotificationBox(messages.FirstOrDefault().Key, messages.FirstOrDefault().Value, isError ? NotificationBoxType.Warning : NotificationBoxType.Info);
                }
                else
                {
                    SetNotificationBox("Content not available", "Oops. The requested content is not currently available. Please try again later.");
                }
            }
        }