Пример #1
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);
        }
        /// <summary>
        /// Process the specified input template and return the result.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <returns></returns>
        public LavaRenderResult GetTemplateRenderResult(ILavaEngine engine, string inputTemplate, LavaRenderParameters parameters = null, LavaTestRenderOptions options = null)
        {
            inputTemplate = inputTemplate ?? string.Empty;

            var context = engine.NewRenderContext();

            if (parameters == null)
            {
                parameters = LavaRenderParameters.WithContext(context);
            }

            // If options are specified, replace the render parameters.
            if (options != null)
            {
                context.SetEnabledCommands(options.EnabledCommands, options.EnabledCommandsDelimiter);
                context.SetMergeFields(options.MergeFields);

                if (options.ExceptionHandlingStrategy != null)
                {
                    parameters.ExceptionHandlingStrategy = options.ExceptionHandlingStrategy;
                }
            }

            var result = engine.RenderTemplate(inputTemplate.Trim(), parameters);

            return(result);
        }
        /// <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);
            }
        }
Пример #4
0
        public void ExceptionHandling_CommandConfigurationException_IsRenderedToOutput()
        {
            // If a RockEntity command block is included without specifying any parameters, the block throws an Exception.
            // The Exception is wrapped in higher-level LavaExceptions, but we want to ensure that the original message
            // is displayed in the render output to alert the user.
            var input = @"
{% person %}
    {% for person in personItems %}
        {{ person.FullName }} <br/>
    {% endfor %}
{% endperson %}
            ";

            TestHelper.ExecuteForActiveEngines((engine) =>
            {
                var context = engine.NewRenderContext();

                context.SetEnabledCommands("RockEntity");

                var renderOptions = new LavaRenderParameters {
                    Context = context, ExceptionHandlingStrategy = ExceptionHandlingStrategySpecifier.RenderToOutput
                };

                var output = TestHelper.GetTemplateRenderResult(engine, input, renderOptions);

                TestHelper.DebugWriteRenderResult(engine, input, output.Text);

                Assert.IsTrue(output.Text.Contains("No parameters were found in your command."), "Expected message not found.");
            });
        }
        /// <summary>
        /// Process the specified input template and return the result.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <returns></returns>
        public string GetTemplateOutput(ILavaEngine engine, string inputTemplate, ILavaRenderContext context)
        {
            inputTemplate = inputTemplate ?? string.Empty;

            var result = engine.RenderTemplate(inputTemplate.Trim(), LavaRenderParameters.WithContext(context));

            return(result.Text);
        }
Пример #6
0
        /// <summary>
        /// Render the Lava template using the DotLiquid rendering engine.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="output"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        protected override LavaRenderResult OnRenderTemplate(ILavaTemplate template, LavaRenderParameters parameters)
        {
            var result = new LavaRenderResult();

            var renderSettings = new RenderParameters();

            // Set the flag to rethrow exceptions generated by the DotLiquid framework, so they can be intercepted and handled as Lava errors.
            // Note that this flag is required in addition to the Context(rethrowErrors) constructor parameter.
            renderSettings.RethrowErrors = true;

            var templateContext = parameters.Context as DotLiquidRenderContext;

            if (templateContext == null)
            {
                throw new LavaException("Invalid LavaContext parameter. This context type is not compatible with the DotLiquid templating engine.");
            }

            var dotLiquidContext = templateContext.DotLiquidContext;

            renderSettings.Context = dotLiquidContext;

            if (parameters.ShouldEncodeStringsAsXml)
            {
                renderSettings.ValueTypeTransformers = new Dictionary <Type, Func <object, object> >();
                renderSettings.ValueTypeTransformers.Add(typeof(string), EncodeStringTransformer);
            }

            // Call the Render method of the underlying DotLiquid template.
            var templateProxy = template as DotLiquidTemplateProxy;

            if (templateProxy == null)
            {
                throw new Exception("Render failed. The provided template instance is not compatible with the DotLiquid engine.");
            }

            result.Text = templateProxy.DotLiquidTemplate.Render(renderSettings);

            if (renderSettings.Context.Errors != null)
            {
                if (renderSettings.Context.Errors.Count > 1)
                {
                    result.Error = new AggregateException(renderSettings.Context.Errors);
                }
                else
                {
                    result.Error = renderSettings.Context.Errors.FirstOrDefault();
                }
            }

            return(result);
        }
Пример #7
0
        /// <summary>
        /// Merges the lava.
        /// </summary>
        /// <param name="lavaTemplate">The lava template.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private string MergeLava(string lavaTemplate, ILavaRenderContext context)
        {
            // Resolve the Lava template contained in this block in a new context.
            var engine = context.GetService <ILavaEngine>();

            var newContext = engine.NewRenderContext();

            newContext.SetMergeFields(context.GetMergeFields());
            newContext.SetInternalFields(context.GetInternalFields());

            // Resolve the inner template.
            var result = engine.RenderTemplate(lavaTemplate, LavaRenderParameters.WithContext(newContext));

            return(result.Text);
        }
Пример #8
0
        public void ExceptionHandling_RenderErrorWithStrategyNone_ReturnsNullOutput()
        {
            var input = @"{% invalidTagName %}";

            TestHelper.ExecuteForActiveEngines((engine) =>
            {
                var renderOptions = new LavaRenderParameters {
                    ExceptionHandlingStrategy = ExceptionHandlingStrategySpecifier.Ignore
                };

                var result = TestHelper.GetTemplateRenderResult(engine, input, renderOptions);

                Assert.IsNotNull(result.Error, "Expected render exception not returned.");
                Assert.IsNull(result.Text, "Unexpected render output returned.");
            });
        }
Пример #9
0
        public void Render_StringVariableWithXmlEncodingOption_RendersUnencodedString()
        {
            var mergeValues = new LavaDataDictionary {
                { "UnencodedString", "Ted & Cindy" }
            };
            var template       = @"Unencoded String: {{ UnencodedString }}";
            var expectedOutput = @"Unencoded String: Ted & Cindy";

            var parameters = new LavaRenderParameters
            {
                ShouldEncodeStringsAsXml = false,
                Context = LavaRenderContext.FromMergeValues(mergeValues)
            };

            TestHelper.AssertTemplateOutput(expectedOutput, template, parameters);
        }
        /// <summary>
        /// Verify that the specified template is invalid.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <returns></returns>
        public void AssertTemplateIsInvalid(ILavaEngine engine, string inputTemplate, LavaDataDictionary mergeFields = null)
        {
            inputTemplate = inputTemplate ?? string.Empty;

            Assert.That.ThrowsException <LavaException>(
                () =>
            {
                var renderOptions = new LavaRenderParameters
                {
                    Context = engine.NewRenderContext(mergeFields),
                    ExceptionHandlingStrategy = ExceptionHandlingStrategySpecifier.Throw
                };

                _ = engine.RenderTemplate(inputTemplate.Trim(), renderOptions);
            },
                "Invalid template expected.");
        }
Пример #11
0
        /// <summary>
        /// Process the specified input template and return the result.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <returns></returns>
        public string GetTemplateOutput(ILavaEngine engine, string inputTemplate, LavaRenderParameters renderParameters)
        {
            inputTemplate = inputTemplate ?? string.Empty;

            if (engine == null)
            {
                throw new Exception("Engine instance is required.");
            }

            var result = engine.RenderTemplate(inputTemplate.Trim(), renderParameters);

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

            return(result.Text);
        }
        /// <summary>
        /// Process the specified input template and return the result.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <returns></returns>
        public string GetTemplateOutput(ILavaEngine engine, string inputTemplate, LavaTestRenderOptions options)
        {
            inputTemplate = inputTemplate ?? string.Empty;

            var context = engine.NewRenderContext();

            var parameters = LavaRenderParameters.WithContext(context);

            if (options != null)
            {
                context.SetEnabledCommands(options.EnabledCommands, options.EnabledCommandsDelimiter);
                context.SetMergeFields(options.MergeFields);

                parameters.ExceptionHandlingStrategy = options.ExceptionHandlingStrategy;
            }

            var result = engine.RenderTemplate(inputTemplate.Trim(), parameters);

            return(result.Text);
        }
Пример #13
0
        protected override LavaRenderResult OnRenderTemplate(ILavaTemplate inputTemplate, LavaRenderParameters parameters)
        {
            var templateProxy = inputTemplate as FluidTemplateProxy;
            var template      = templateProxy?.FluidTemplate;

            var templateContext = parameters.Context as FluidRenderContext;

            if (templateContext == null)
            {
                throw new LavaException("Invalid LavaContext parameter. This context type is not compatible with the Fluid templating engine.");
            }

            var result = new LavaRenderResult();
            var sb     = new StringBuilder();

            // Set the render options for culture and timezone if they are specified.
            if (parameters.Culture != null)
            {
                templateContext.FluidContext.Options.CultureInfo = parameters.Culture;
            }
            if (parameters.TimeZone != null)
            {
                templateContext.FluidContext.Options.TimeZone = parameters.TimeZone;
            }

            // Set the render options for encoding.
            System.Text.Encodings.Web.TextEncoder encoder;
            if (parameters.ShouldEncodeStringsAsXml)
            {
                encoder = System.Text.Encodings.Web.HtmlEncoder.Default;
            }
            else
            {
                encoder = NullEncoder.Default;
            }

            var writer = new StringWriter(sb);

            try
            {
                template.Render(templateContext.FluidContext, encoder, writer);

                writer.Flush();
                result.Text = sb.ToString();
            }
            catch (LavaInterruptException)
            {
                // The render was terminated intentionally, so return the current buffer content.
                writer.Flush();
                result.Text = sb.ToString();
            }
            finally
            {
                writer.Dispose();
            }

            return(result);
        }
Пример #14
0
        /// <summary>
        /// Render the Lava template using the DotLiquid rendering engine.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="output"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        protected override LavaRenderResult OnRenderTemplate(ILavaTemplate template, LavaRenderParameters parameters)
        {
            var result = new LavaRenderResult();

            try
            {
                var renderSettings = new RenderParameters();

                // Set the flag to rethrow exceptions generated by the DotLiquid framework, so they can be intercepted and handled as Lava errors.
                // Note that this flag is required in addition to the Context(rethrowErrors) constructor parameter.
                renderSettings.RethrowErrors = true;

                var templateContext = parameters.Context as RockLiquidRenderContext;

                if (templateContext == null)
                {
                    throw new LavaException("Invalid LavaContext parameter. This context type is not compatible with the RockLiquid templating engine.");
                }

                var dotLiquidContext = templateContext.DotLiquidContext;

                renderSettings.Context = dotLiquidContext;

                if (parameters.ShouldEncodeStringsAsXml)
                {
                    renderSettings.ValueTypeTransformers = new Dictionary <Type, Func <object, object> >();
                    renderSettings.ValueTypeTransformers.Add(typeof(string), EncodeStringTransformer);
                }

                // Call the Render method of the underlying DotLiquid template.
                var templateProxy = template as DotLiquidTemplateProxy;

                result.Text = templateProxy.DotLiquidTemplate.Render(renderSettings);

                if (renderSettings.Context.Errors != null)
                {
                    if (renderSettings.Context.Errors.Count > 1)
                    {
                        result.Error = new AggregateException(renderSettings.Context.Errors);
                    }
                    else
                    {
                        result.Error = renderSettings.Context.Errors.FirstOrDefault();
                    }
                }
            }
            catch (LavaInterruptException)
            {
                // Ignore this exception, it is thrown by custom Lava components to terminate the render process prematurely.
            }
            catch (Exception ex)
            {
                string output;

                ProcessException(ex, parameters.ExceptionHandlingStrategy, out output);

                result.Text  = output;
                result.Error = ex;
            }

            return(result);
        }
        /// <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);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void OnRender(ILavaRenderContext context, TextWriter result)
        {
            var rockContext = LavaHelper.GetRockContextFromLavaContext(context);

            // Get enabled security commands
            _enabledSecurityCommands = context.GetEnabledCommands().JoinStrings(",");

            using (TextWriter writer = new StringWriter())
            {
                bool filterProvided = false;

                base.OnRender(context, writer);

                var parms              = ParseMarkup(_markup, context);
                var lookAheadDays      = parms[LOOK_AHEAD_DAYS].AsInteger();
                var scheduleCategoryId = parms[SCHEDULE_CATEGORY_ID].AsIntegerOrNull();
                var asAtDate           = parms[AS_AT_DATE].AsDateTime();

                var now = asAtDate ?? RockDateTime.Now;

                var scheduleIds = new List <int>();

                var requestedSchedules = parms[SCHEDULE_ID].StringToIntList();

                var schedulesQry = new ScheduleService(rockContext).Queryable().AsNoTracking()
                                   .Where(s => s.IsActive == true);

                if (requestedSchedules.Count() > 0)
                {
                    schedulesQry   = schedulesQry.Where(s => requestedSchedules.Contains(s.Id));
                    filterProvided = true;
                }

                if (scheduleCategoryId.HasValue)
                {
                    schedulesQry   = schedulesQry.Where(s => s.CategoryId == scheduleCategoryId.Value);
                    filterProvided = true;
                }

                // If neither a schedule id nor a schedule category id was provided stop
                if (!filterProvided)
                {
                    return;
                }

                // Get the schedules are order them by the next start time
                var schedules = schedulesQry.ToList()
                                .Where(s => s.GetNextStartDateTime(now) != null)
                                .OrderBy(s => s.GetNextStartDateTime(now));

                if (schedules.Count() == 0)
                {
                    return;
                }

                var nextSchedule = schedules.FirstOrDefault();

                var      nextStartDateTime     = nextSchedule.GetNextStartDateTime(now);
                var      isLive                = false;
                DateTime?occurrenceEndDateTime = null;

                // Determine if we're live
                if (nextSchedule.WasScheduleActive(now))
                {
                    isLive = true;
                    var occurrences      = nextSchedule.GetICalOccurrences(now, now.AddDays(lookAheadDays)).Take(2);
                    var activeOccurrence = occurrences.FirstOrDefault();
                    occurrenceEndDateTime = (DateTime)activeOccurrence.Period.EndTime.Value;

                    // Set the next occurrence to be the literal next occurrence (vs the current occurrence)
                    nextStartDateTime = null;
                    if (occurrences.Count() > 1)
                    {
                        nextStartDateTime = occurrences.Last().Period.EndTime.Value;
                    }
                }

                // Determine when not to show the content
                if ((parms[SHOW_WHEN] == "notlive" && isLive) ||
                    (parms[SHOW_WHEN] == "live" && !isLive))
                {
                    return;
                }

                // Check role membership
                var roleId = parms[ROLE_ID].AsIntegerOrNull();

                if (roleId.HasValue)
                {
                    var currentPerson = GetCurrentPerson(context);

                    var isInRole = new GroupMemberService(rockContext).Queryable()
                                   .Where(m =>
                                          m.GroupId == roleId &&
                                          m.PersonId == currentPerson.Id
                                          )
                                   .Any();

                    if (!isInRole)
                    {
                        return;
                    }
                }

                var mergeFields = context.GetMergeFields();

                mergeFields.Add("NextOccurrenceDateTime", nextStartDateTime);
                mergeFields.Add("OccurrenceEndDateTime", occurrenceEndDateTime);
                mergeFields.Add("Schedule", nextSchedule);
                mergeFields.Add("IsLive", isLive);

                var engine = context.GetService <ILavaEngine>();

                var renderContext = engine.NewRenderContext(mergeFields, _enabledSecurityCommands.SplitDelimitedValues());

                var results = engine.RenderTemplate(_blockMarkup.ToString(), LavaRenderParameters.WithContext(renderContext));

                result.Write(results.Text.Trim());
            }
        }
Пример #17
0
        /// <summary>
        /// For each of the currently enabled Lava Engines, process the specified input template and verify against the expected output.
        /// </summary>
        /// <param name="expectedOutput"></param>
        /// <param name="inputTemplate"></param>
        public void AssertTemplateOutput(string expectedOutput, string inputTemplate, LavaRenderParameters parameters, bool ignoreWhitespace = false)
        {
            var engines = GetActiveTestEngines();

            var exceptions = new List <Exception>();

            foreach (var engine in engines)
            {
                try
                {
                    AssertTemplateOutput(engine, expectedOutput, inputTemplate, parameters, ignoreWhitespace);
                }
                catch (Exception ex)
                {
                    Debug.Write($"**\n** ERROR\n**\n{ex.Message}");

                    exceptions.Add(new Exception($"Engine \"{ engine.EngineName }\" reported an error.", ex));
                }
            }

            if (exceptions.Any())
            {
                throw new AggregateException("At least one engine reported errors.", exceptions);
            }
        }
Пример #18
0
        /// <summary>
        /// For each of the currently enabled Lava Engines, process the specified input template and verify against the expected output.
        /// </summary>
        /// <param name="expectedOutput"></param>
        /// <param name="inputTemplate"></param>
        public void AssertTemplateOutput(string expectedOutput, string inputTemplate, LavaDataDictionary mergeValues = null, bool ignoreWhitespace = false)
        {
            var parameters = LavaRenderParameters.WithContext(LavaRenderContext.FromMergeValues(mergeValues));

            AssertTemplateOutput(expectedOutput, inputTemplate, parameters, ignoreWhitespace);
        }
Пример #19
0
        /// <summary>
        /// Process the specified input template and verify against the expected output.
        /// </summary>
        /// <param name="expectedOutput"></param>
        /// <param name="inputTemplate"></param>
        public void AssertTemplateOutput(ILavaEngine engine, string expectedOutput, string inputTemplate, LavaDataDictionary mergeValues = null, bool ignoreWhitespace = false)
        {
            var context = engine.NewRenderContext(mergeValues);

            AssertTemplateOutput(engine, expectedOutput, inputTemplate, LavaRenderParameters.WithContext(context), ignoreWhitespace);
        }
Пример #20
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.");
                }
            }
        }
Пример #21
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.");
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Process the specified input template and verify against the expected output.
        /// </summary>
        /// <param name="expectedOutput"></param>
        /// <param name="inputTemplate"></param>
        public void AssertTemplateOutput(ILavaEngine engine, string expectedOutput, string inputTemplate, LavaRenderParameters renderParameters, bool ignoreWhitespace = false)
        {
            var outputString = GetTemplateOutput(engine, inputTemplate, renderParameters);

            var debugString = outputString;

            if (ignoreWhitespace)
            {
                expectedOutput = expectedOutput.RemoveWhiteSpace();
                outputString   = outputString.RemoveWhiteSpace();

                debugString += "\n(Comparison ignores WhiteSpace)";
            }

            DebugWriteRenderResult(engine, inputTemplate, debugString);

            Assert.That.Equal(expectedOutput, outputString);
        }