Esempio n. 1
0
        public void DotLiquid_FilterRegisteredToDotLiquidFramework_ProducesCorrectResultInLavaLibrary()
        {
            DotLiquid.Template.RegisterFilter(typeof(TestDotLiquidFilter));

            var rockContext = new RockContext();

            var contentChannelItem = new ContentChannelItemService(rockContext)
                                     .Queryable()
                                     .FirstOrDefault(x => x.ContentChannel.Name == "External Website Ads" && x.Title == "SAMPLE: Easter");

            Assert.That.IsNotNull(contentChannelItem, "Required test data not found.");

            var values = new LavaDataDictionary {
                { "Item", contentChannelItem }
            };

            var inputTemplate = @"
{% assign image = Item | Attribute:'Image','Object' %}
{{ image | GetVariableType }}
";

            var expectedOutput = @"BinaryFile";

            var options = new LavaTestRenderOptions {
                MergeFields = values
            };

            TestHelper.AssertTemplateOutput(typeof(RockLiquidEngine), expectedOutput, inputTemplate, options);
        }
        public void Select_KeyValueFromDictionaryCollection_ReturnsListOfValues()
        {
            // The Select filter should work correctly on any collection of objects that supports the
            // IDictionary<string,object> interface.
            var dictionary1 = new Dictionary <string, object>()
            {
                { "Key1", "Value1-1" },
                { "Key2", "Value1-2" },
                { "Key3", "Value1-3" },
            };
            var dictionary2 = new Dictionary <string, object>()
            {
                { "Key1", "Value2-1" },
                { "Key2", "Value2-2" },
                { "Key3", "Value2-3" },
            };

            var mergeValues = new LavaDataDictionary {
                { "Dictionaries", new List <Dictionary <string, object> > {
                      dictionary1, dictionary2
                  } }
            };

            TestHelper.AssertTemplateOutput("Value1-2;Value2-2;",
                                            "{% assign values = Dictionaries | Select:'Key2' %}{% for value in values %}{{ value }};{% endfor %}",
                                            mergeValues);
        }
Esempio n. 3
0
        public void Blank_UpperCaseOrLowerCase_IsNotCaseSensitive()
        {
            var mergeValues = new LavaDataDictionary {
                { "Items", new List <string>() }
            };

            var template = @"
{% if Items == Blank %}
True
{% endif %}
{% if Items == blank %}
true
{% endif %}

{% if Items != Blank %}
False
{% endif %}
{% if Items != blank %}
false
{% endif %}
";

            var expectedOutput = @"True true";

            TestHelper.AssertTemplateOutput(expectedOutput, template, mergeValues, ignoreWhitespace: true);
        }
 /// <summary>
 /// Verify that the specified template is invalid.
 /// </summary>
 /// <param name="inputTemplate"></param>
 /// <returns></returns>
 public void AssertTemplateIsInvalid(string inputTemplate, LavaDataDictionary mergeFields = null)
 {
     ExecuteForActiveEngines((engine) =>
     {
         AssertTemplateIsInvalid(engine, inputTemplate, mergeFields);
     });
 }
Esempio n. 5
0
        /// <summary>
        /// Merges global merge fields into the Header and Footer parts of the document
        /// </summary>
        /// <param name="outputDoc">The output document.</param>
        /// <param name="globalMergeHash">The global merge hash.</param>
        private void HeaderFooterGlobalMerge(WordprocessingDocument outputDoc, LavaDataDictionary globalMergeHash)
        {
            // make sure that all proof codes get removed so that the lava can be found
            MarkupSimplifier.SimplifyMarkup(outputDoc, new SimplifyMarkupSettings {
                RemoveProof = true
            });

            // update the doc headers and footers for any Lava having to do with Global merge fields
            // from http://stackoverflow.com/a/19012057/1755417
            foreach (var headerFooterPart in outputDoc.MainDocumentPart.HeaderParts.OfType <OpenXmlPart>().Union(outputDoc.MainDocumentPart.FooterParts))
            {
                foreach (var currentParagraph in headerFooterPart.RootElement.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>())
                {
                    foreach (var currentRun in currentParagraph.Descendants <DocumentFormat.OpenXml.Wordprocessing.Run>())
                    {
                        foreach (var currentText in currentRun.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>())
                        {
                            string nodeText = currentText.Text.ReplaceWordChars();
                            if (lavaRegEx.IsMatch(nodeText))
                            {
                                currentText.Text = nodeText.ResolveMergeFields(globalMergeHash, true, true);
                            }
                        }
                    }
                }
            }
        }
        public void OrderBy_ExpandoObjectList_CanSortByMultipleTextProperties()
        {
            var members = new List <object>();

            members.Add(new
            {
                GroupRole = new { Name = "Member", IsLeader = false },
                Person    = new { FirstName = "Alex" }
            });
            members.Add(new
            {
                GroupRole = new { Name = "Leader", IsLeader = true },
                Person    = new { FirstName = "Ted" }
            });
            members.Add(new
            {
                GroupRole = new { Name = "Member", IsLeader = false },
                Person    = new { FirstName = "Cindy" }
            });

            var mergeValues = new LavaDataDictionary {
                { "Members", members }
            };

            TestHelper.AssertTemplateOutput("Ted;Alex;Cindy;",
                                            "{% assign items = Members | OrderBy:'GroupRole.IsLeader desc,Person.FirstName' %}{% for item in items %}{{ item.Person.FirstName }};{% endfor %}",
                                            mergeValues);
        }
Esempio n. 7
0
        /// <summary>
        /// Gets the dictionary of values that are active in the local scope.
        /// Values are defined by the outermost container first, and overridden by values defined in a contained scope.
        /// </summary>
        /// <returns></returns>
        public override LavaDataDictionary GetMergeFields()
        {
            var fields = new LavaDataDictionary();

            // First, get all of the variables defined in the local lava context.
            // In DotLiquid, the innermost scope is the first element in the collection.
            foreach (var scope in _context.Scopes)
            {
                foreach (var item in scope)
                {
                    fields.AddOrIgnore(item.Key, item.Value);
                }
            }

            // Second, add any variables defined by the block or container in which the template is being resolved.
            foreach (var environment in _context.Environments)
            {
                foreach (var item in environment)
                {
                    fields.AddOrIgnore(item.Key, item.Value);
                }
            }

            return(fields);
        }
Esempio n. 8
0
        public void Base64EncodeFilter_WithBinaryFileObjectParameter_ReturnsExpectedEncoding()
        {
            var rockContext = new RockContext();

            var contentChannelItem = new ContentChannelItemService(rockContext)
                                     .Queryable()
                                     .FirstOrDefault(x => x.ContentChannel.Name == "External Website Ads" && x.Title == "SAMPLE: Easter");

            Assert.That.IsNotNull(contentChannelItem, "Required test data not found.");

            var values = new LavaDataDictionary {
                { "Item", contentChannelItem }
            };

            var input = @"
{% assign image = Item | Attribute:'Image','Object' %}
Base64Format: {{ image | Base64Encode }}<br/>
";

            var expectedOutput = @"Base64Format: /9j/4AAQSkZJRgABAQEAAAAAAAD/{moreBase64Data}<br/>";

            var options = new LavaTestRenderOptions()
            {
                MergeFields = values, Wildcards = new List <string> {
                    "{moreBase64Data}"
                }
            };

            TestHelper.AssertTemplateOutput(expectedOutput, input, options);
        }
Esempio n. 9
0
        public void Scope_LocalVariableWithSameNameAsContainerVariable_ContainerVariableIsReturned()
        {
            var input          = @"
{% execute type:'class' %}
    using Rock;
    using Rock.Data;
    using Rock.Model;
    
    public class MyScript 
    {
        public string Execute() {
            using(RockContext rockContext = new RockContext()){
                var person = new PersonService(rockContext).Get({{ CurrentPerson | Property: 'Id' }});
                
                return person.FullName;
            }
        }
    }
{% endexecute %}
";
            var expectedOutput = @"Admin Admin"; // NOT 'Ted Decker'

            var values = new LavaDataDictionary {
                { "CurrentPerson", TestHelper.GetTestPersonTedDecker() }
            };

            var options = new LavaTestRenderOptions()
            {
                EnabledCommands = "execute", MergeFields = values
            };

            TestHelper.AssertTemplateOutput(expectedOutput, input, options);
        }
Esempio n. 10
0
        public void ExecuteBlock_WithContextValues_ResolvesContextValuesCorrectly()
        {
            var input = @"
{% execute type:'class' %}
    using Rock;
    using Rock.Data;
    using Rock.Model;
    
    public class MyScript 
    {
        public string Execute() {
            using(RockContext rockContext = new RockContext()) {
                var person = new PersonService(rockContext).Get(""{{ Person | Property: 'Guid' }}"".AsGuid());
                
                return person.FullName;
            }
        }
    }
{% endexecute %}
";

            var expectedOutput = @"Ted Decker";

            var context = new LavaDataDictionary();

            context.Add("Person", TestHelper.GetTestPersonTedDecker());

            var options = new LavaTestRenderOptions()
            {
                EnabledCommands = "execute", MergeFields = context
            };

            TestHelper.AssertTemplateOutput(expectedOutput, input, options);
        }
        public void EntityPropertyAccess_ForPersonAttributeValues_ReturnsCorrectValues()
        {
            var rockContext = new RockContext();

            var testPerson = new PersonService(rockContext).Queryable().First(x => x.NickName == "Ted" && x.LastName == "Decker");

            testPerson.LoadAttributes();

            var values = new LavaDataDictionary {
                { "Person", testPerson }
            };

            var input          = @"
{% for av in Person.AttributeValues %}
    {% if av.ValueFormatted != null and av.ValueFormatted != '' %}
        {{ av.AttributeName }}: {{ av.ValueFormatted }}<br>
    {% endif %}
{% endfor %}
";
            var expectedOutput = @"
 Employer: Rock Solid Church<br>
";

            var options = new LavaTestRenderOptions()
            {
                MergeFields = values, OutputMatchType = LavaTestOutputMatchTypeSpecifier.Contains
            };

            TestHelper.AssertTemplateOutput(expectedOutput, input, options);
        }
Esempio n. 12
0
        public void LavaDataObjectType_DotNotationPropertyAccess_ReturnsPropertyValue()
        {
            var mergeValues = new LavaDataDictionary {
                { "CurrentPerson", GetLavaDataObjectTestPersonTedDecker() }
            };

            TestHelper.AssertTemplateOutput("Decker", "{{ CurrentPerson.LastName }}", mergeValues);
        }
Esempio n. 13
0
        public void RockDynamicType_DotNotationNestedPropertyAccess_ReturnsPropertyValue()
        {
            var mergeValues = new LavaDataDictionary {
                { "CurrentPerson", GetRockDynamicTestPersonTedDecker() }
            };

            TestHelper.AssertTemplateOutput("North Campus", "{{ CurrentPerson.Campus.Name }}", mergeValues);
        }
Esempio n. 14
0
        public void Property_AnonymousObjectSecondLevelPropertyAccess_ReturnsValue()
        {
            var mergeValues = new LavaDataDictionary {
                { "CurrentPerson", TestHelper.GetTestPersonTedDecker() }
            };

            TestHelper.AssertTemplateOutput("North Campus", "{{ CurrentPerson | Property:'Campus.Name' }}", mergeValues);
        }
Esempio n. 15
0
        public void Property_InvalidPropertyName_ReturnsEmptyString()
        {
            var mergeValues = new LavaDataDictionary {
                { "CurrentPerson", TestHelper.GetTestPersonTedDecker() }
            };

            TestHelper.AssertTemplateOutput(string.Empty, "{{ CurrentPerson | Property:'NonexistentProperty' }}", mergeValues);
        }
        public void Size_ForArrayTarget_ReturnsItemCount()
        {
            var mergeValues = new LavaDataDictionary {
                { "TestList", _TestNameList }
            };

            TestHelper.AssertTemplateOutput(_TestNameList.Count.ToString(), "{{ TestList | Size }}", mergeValues);
        }
Esempio n. 17
0
        public void Property_AnonymousObjectFirstLevelPropertyAccess_ReturnsPropertyValue()
        {
            var mergeValues = new LavaDataDictionary {
                { "CurrentPerson", TestHelper.GetTestPersonTedDecker() }
            };

            TestHelper.AssertTemplateOutput("Decker", "{{ CurrentPerson | Property:'LastName' }}", mergeValues);
        }
        public void Index_IndexExceedsItemCount_ProducesEmptyString()
        {
            var mergeValues = new LavaDataDictionary {
                { "TestList", _TestNameList }
            };

            TestHelper.AssertTemplateOutput("", "{{ TestList | Index:999 }}", mergeValues);
        }
Esempio n. 19
0
        public void RockDynamicType_DotNotationInvalidPropertyName_ReturnsEmptyString()
        {
            var mergeValues = new LavaDataDictionary {
                { "CurrentPerson", GetRockDynamicTestPersonTedDecker() }
            };

            TestHelper.AssertTemplateOutput(string.Empty, "{{ CurrentPerson.NonexistentProperty }}", mergeValues);
        }
        /// <summary>
        /// Process the specified input template and return the result.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <returns></returns>
        public string GetTemplateOutput(ILavaEngine engine, string inputTemplate, LavaDataDictionary mergeFields = null)
        {
            inputTemplate = inputTemplate ?? string.Empty;

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

            return(result.Text);
        }
        public void Size_ForStringTarget_ReturnsCharacterCount()
        {
            var testString = "123456789";

            var mergeValues = new LavaDataDictionary {
                { "TestString", testString }
            };

            TestHelper.AssertTemplateOutput(testString.Length.ToString(), "{{ TestString | Size }}", mergeValues);
        }
        public void Distinct_OnStringCollectionWithTwoDuplicateEntries_RemovesTwoDuplicateEntries()
        {
            var mergeValues = new LavaDataDictionary {
                { "TestList", _TestDuplicateStringList }
            };

            var lavaTemplate = "{{ TestList | Distinct | Join:',' }}";

            TestHelper.AssertTemplateOutput("Item 1,Item 2 (duplicate),Item 3", lavaTemplate, mergeValues);
        }
        public void OrderBy_ExpandoObjectList_CanSortByNestedObjectProperty()
        {
            var mergeValues = new LavaDataDictionary {
                { "Items", GetOrderByTestCollection() }
            };

            TestHelper.AssertTemplateOutput("A;B;C;D;",
                                            "{% assign items = Items | OrderBy:'Order, Nested.Order DESC' %}{% for item in items %}{{ item.Title }};{% endfor %}",
                                            mergeValues);
        }
Esempio n. 24
0
        public void AsString_AnonymousObjectWithToStringMethodOverride_ReturnsToStringForObject()
        {
            var person = TestHelper.GetTestPersonAlishaMarble();

            var mergeValues = new LavaDataDictionary {
                { "CurrentPerson", person }
            };

            TestHelper.AssertTemplateOutput("Alisha Marble", "{{ CurrentPerson | AsString }}", mergeValues);
        }
Esempio n. 25
0
        public void Render_EnumType_RendersAsEnumName()
        {
            var enumValue = ContentChannelItemStatus.Approved;

            var mergeValues = new LavaDataDictionary {
                { "EnumValue", enumValue }
            };

            TestHelper.AssertTemplateOutput("Approved", "{{ EnumValue }}", mergeValues);
        }
Esempio n. 26
0
        public void FluidEqual_EnumOperands_PerformsEnumComparison(string expression, bool expectedResult)
        {
            var values = new LavaDataDictionary();

            values.Add("DayOfWeekMonday", DayOfWeek.Monday);

            var template = "{% if " + expression + " %}True{% else %}False{% endif %}";

            TestHelper.AssertTemplateOutput(expectedResult.ToString(), template, values, ignoreWhitespace: true);
        }
        public void LavaDataDictionary_WithKeysDifferingOnlyByCase_ReturnsMatchingValueForKey()
        {
            var mergeValues = new LavaDataDictionary()
            {
                { "case", "lower" },
                { "CASE", "upper" },
                { "Case", "mixed" }
            };

            TestHelper.AssertTemplateOutput(typeof(FluidEngine), "lower,upper,mixed", "{{ case }},{{ CASE }},{{ Case }}", mergeValues);
        }
Esempio n. 28
0
        public void FluidEngineValueConverterPerformance_DictionaryKeyResolution_OutputsPerformanceMeasures()
        {
            var totalSets             = 10;
            var totalIterationsPerSet = 1000000;

            // Create a Fluid engine with template caching disabled.
            var engineOptions = new LavaEngineConfigurationOptions {
                CacheService = new MockTemplateCacheService()
            };

            var engine = LavaService.NewEngineInstance(typeof(FluidEngine), engineOptions);

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

            var formatString = new string( '0', totalIterationsPerSet.ToString().Length );

            for (int i = 0; i < totalIterationsPerSet; i++)
            {
                standardLavaDictionary.Add(i.ToString(formatString), i);
            }

            var mergeFields = new LavaDataDictionary {
                { "Dictionary", standardLavaDictionary }
            };

            var totalTime = TestHelper.ExecuteAndGetElapsedTime(() =>
            {
                engine.ClearTemplateCache();

                for (int repeatCount = 1; repeatCount <= totalSets; repeatCount++)
                {
                    var elapsedTime = TestHelper.ExecuteAndGetElapsedTime(() =>
                    {
                        for (int i = 0; i < totalIterationsPerSet; i++)
                        {
                            var template = "{{ Dictionary['" + i.ToString(formatString) + "']}}";

                            var options = new LavaTestRenderOptions {
                                MergeFields = mergeFields
                            };

                            var output = TestHelper.GetTemplateOutput(engine, template, mergeFields);

                            // Verify that the correct entry was retrieved.
                            Assert.AreEqual(i.ToString(), output);
                        }
                    });

                    Debug.Print($"Pass {repeatCount} Elapsed Time: {elapsedTime.TotalMilliseconds} ");
                }
            });

            Debug.Print($"Average Time: {totalTime.TotalMilliseconds / totalSets} ");
        }
Esempio n. 29
0
        /// <summary>
        /// Gets the collection of variables defined for internal use only.
        /// Internal values are not available to be resolved in the Lava Template.
        /// </summary>
        public override LavaDataDictionary GetInternalFields()
        {
            var values = new LavaDataDictionary();

            foreach (var item in _context.AmbientValues)
            {
                values.AddOrReplace(item.Key, item.Value);
            }

            return(values);
        }
        public void Index_IndexReferencesReturnExpectedItems(int index, string expectedValue)
        {
            var mergeValues = new LavaDataDictionary {
                { "TestList", _TestOrderedList }
            };

            var lavaTemplate = "{{ TestList | Index:<index> }}";

            lavaTemplate = lavaTemplate.Replace("<index>", index.ToString());

            TestHelper.AssertTemplateOutput(expectedValue, lavaTemplate, mergeValues);
        }