Ejemplo n.º 1
0
        public void SubPropertyShouldNotBeAccessible()
        {
            var options = new TemplateOptions();

            options.MemberAccessStrategy.Register <Person>(x => x.Firstname);

            var john = new Person {
                Firstname = "John", Lastname = "Wick", Address = new Address {
                    City = "Redmond", State = "Washington"
                }
            };

            var template = _parser.Parse("{{Firstname}};{{Lastname}};{{Address.City}};{{Address.State}}");

            Assert.Equal("John;;;", template.Render(new TemplateContext(john, options, false)));
        }
Ejemplo n.º 2
0
        public async Task ShouldNotReleaseScopeAsynchronously()
        {
            var parser = new FluidParser();

            parser.RegisterEmptyBlock("sleep", async(statements, writer, encoder, context) =>
            {
                context.EnterChildScope();
                context.IncrementSteps();
                context.SetValue("id", "0");
                await Task.Delay(100);
                await statements.RenderStatementsAsync(writer, encoder, context);
                context.ReleaseScope();
                return(Completion.Normal);
            });

            var context = new TemplateContext {
            };

            context.SetValue("id", "1");
            var template = parser.Parse(@"{{id}}{%sleep%}{{id}}{%endsleep%}{{id}}");

            var output = await template.RenderAsync(context);

            Assert.Equal("101", output);
        }
        private void ParseContainerName(MediaBlobStorageOptions options, TemplateContext templateContext)
        {
            // Use Fluid directly as this is transient and cannot invoke _liquidTemplateManager.
            try
            {
                var template = _fluidParser.Parse(options.ContainerName);

                // container name must be lowercase
                options.ContainerName = template.Render(templateContext, NullEncoder.Default).ToLower();
                options.ContainerName = options.ContainerName.Replace("\r", String.Empty).Replace("\n", String.Empty);
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Unable to parse Azure Media Storage container name.");
                throw;
            }
        }
Ejemplo n.º 4
0
        private string GetBlobContainerName(string connectionString)
        {
            var containerName = _configuration.GetValue("OrchardCore_DataProtection_Azure:ContainerName", "dataprotection");

            // Use Fluid directly as the service provider has not been built.
            try
            {
                var templateOptions = new TemplateOptions();
                templateOptions.MemberAccessStrategy.Register <ShellSettings>();
                var templateContext = new TemplateContext(templateOptions);
                templateContext.SetValue("ShellSettings", _shellSettings);

                var template = _fluidParser.Parse(containerName);

                // container name must be lowercase
                containerName = template.Render(templateContext, NullEncoder.Default).ToLower();
                containerName.Replace("\r", String.Empty).Replace("\n", String.Empty);
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Unable to parse data protection connection string.");
                throw;
            }

            var createContainer = _configuration.GetValue("OrchardCore_DataProtection_Azure:CreateContainer", true);

            if (createContainer)
            {
                try
                {
                    _logger.LogDebug("Testing data protection container {ContainerName} existence", containerName);
                    var _blobContainer = new BlobContainerClient(connectionString, containerName);
                    var response       = _blobContainer.CreateIfNotExistsAsync(PublicAccessType.None).GetAwaiter().GetResult();
                    _logger.LogDebug("Data protection container {ContainerName} created.", containerName);
                }
                catch (Exception)
                {
                    _logger.LogCritical("Unable to connect to Azure Storage to configure data protection storage. Ensure that an application setting containing a valid Azure Storage connection string is available at `Modules:OrchardCore.DataProtection.Azure:ConnectionString`.");

                    throw;
                }
            }

            return(containerName);
        }
Ejemplo n.º 5
0
        static HTMLRenderer()
        {
            var files = Directory.EnumerateFiles(templateDirectory, "*.liquid", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                var normalizedFile = file.Replace('/', '\\');
                var rawTemplate    = File.ReadAllText(file);
                var template       = parser.Parse(rawTemplate);
                templateCache[normalizedFile] = template;
            }

            CommonController.LogDebug("Templates found:");
            foreach (var file in templateCache)
            {
                CommonController.LogDebug($"\t{file.Key}");
            }

            InitWatcher();
        }
Ejemplo n.º 6
0
        public void LiquidModelHasDictionry_KeyAccessShouldWork()
        {
            /// Arrange
            var model = new TestModel();

            model.Bar["Baz"] = "abc";

            /// Act
            var context = new TemplateContext(model)
            {
                CultureInfo = CultureInfo.InvariantCulture
            };
            var parser   = new FluidParser();
            var template = parser.Parse("Hi {{ Foo }} {{ Bar[\"Baz\"] }}");
            var text     = template.Render(context);

            /// Assert
            Assert.Equal("Hi Foo. abc", text);
        }
Ejemplo n.º 7
0
        public void UseDifferentModelsWithSameMemberName()
        {
            // Arrange
            var parser   = new FluidParser();
            var template = parser.Parse("Hi {{Name}}");
            var model1   = new TestClass {
                Name = "TestClass"
            };
            var model2 = new AnotherTestClass {
                Name = "AnotherTestClass"
            };

            // Act
            template.Render(new TemplateContext(model1));
            template.Render(new TemplateContext(model2));
            template.Render(new TemplateContext(model2));
            template.Render(new TemplateContext(model2));
            template.Render(new TemplateContext(model1));
            template.Render(new TemplateContext(model2));
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            var parser = new FluidParser();
            Dictionary <string, IFluidTemplate> templates = new Dictionary <string, IFluidTemplate>();
            var templateFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.tpl");

            foreach (var item in templateFiles)
            {
                var fluidTemplate = parser.Parse(File.ReadAllText(item, Encoding.UTF8));
                templates.Add(Path.GetFileName(item), fluidTemplate);
            }
            Dictionary <string, Language[]> languages = JsonSerializer.Deserialize <Dictionary <string, Language[]> >(File.ReadAllText("Languages.json", Encoding.UTF8));

            foreach (var item in templates)
            {
                StringBuilder sqlBuilder = new StringBuilder();
                foreach (var lan in languages.SelectMany(m =>
                {
                    foreach (var item in m.Value)
                    {
                        item.LanKey = m.Key;
                    }
                    return(m.Value);
                }))
                {
                    Console.WriteLine("{0}: {1}", item.Key, lan.LanKey);
                    lan.LanValue = lan.LanValue.Replace("'", "''");
                    var    context = new TemplateContext(lan);
                    string sql     = item.Value.Render(context);
                    sqlBuilder.AppendLine(sql);
                    sqlBuilder.AppendLine();
                }
                if (!Directory.Exists("Script"))
                {
                    Directory.CreateDirectory("Script");
                }
                File.WriteAllText(Path.Combine("Script", item.Key.Replace(".tpl", ".sql")), sqlBuilder.ToString(), Encoding.UTF8);
            }
        }
Ejemplo n.º 9
0
        static Templates()
        {
            var assembly = Assembly.GetExecutingAssembly();

            var templateResourceNames = assembly
                                        .GetManifestResourceNames()
                                        .Where(name => name.StartsWith(s_TemplateResourcePrefix) && name.EndsWith(s_TemplateResourceSuffix));

            foreach (var resourceName in templateResourceNames)
            {
                var templateName = resourceName
                                   .Replace(s_TemplateResourcePrefix, "")
                                   .Replace(s_TemplateResourceSuffix, "");


                s_Templates.Add(templateName, new Lazy <IFluidTemplate>(() =>
                {
                    var templateSource = EmbeddedResource.Load(resourceName);
                    var parser         = new FluidParser();
                    return(parser.Parse(templateSource));
                }));
            }
        }
Ejemplo n.º 10
0
        public void LiquidModelHasNestedDictionaryAndLists_KeyAccessAndListIterationShouldWork()
        {
            /// Arrange
            var model = new TestModel();

            model.Bar["Baz"] = new[] { new Dictionary <string, object> {
                                           { "key1", "value1" },
                                           { "key2", "value2" }
                                       } };

            var liquid = "{% assign x = Bar[\"Baz\"] -%}{% for i in x -%}key1={{ i[\"key1\"] }},key2={{ i[\"key2\"] }}{% endfor -%}";

            /// Act
            var context = new TemplateContext(model)
            {
                CultureInfo = CultureInfo.InvariantCulture
            };
            var parser   = new FluidParser();
            var template = parser.Parse(liquid);
            var text     = template.Render(context);

            /// Assert
            Assert.Equal("key1=value1,key2=value2", text);
        }
Ejemplo n.º 11
0
 public override object Parse()
 {
     return(_parser.Parse(ProductTemplate));
 }
Ejemplo n.º 12
0
 public void ShouldThrowParseExceptionMissingTag(string template)
 {
     Assert.Throws <ParseException>(() => _parser.Parse(template));
 }