Beispiel #1
0
        public async Task ShouldEvaluateStringValue()
        {
            FluidTemplate.TryParse("{{ x }}", out var template, out var messages);
            var context = new TemplateContext();

            context.SetValue("x", "abc");

            var result = await template.RenderAsync(context);

            Assert.Equal("abc", result);
        }
Beispiel #2
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (FluidTemplate.TryParse(Template, out var template))
            {
                var templateContext = new TemplateContext();
                templateContext.SetValue("model", Model);
                output.Content.SetHtmlContent(template.Render(templateContext));
            }

            base.Process(context, output);
        }
        public static IRuleBuilderOptions <T, string?> Liquid <T>(this IRuleBuilder <T, string?> ruleBuilder)
        {
            return(ruleBuilder.Must(value =>
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    return true;
                }

                return FluidTemplate.TryParse(value, out _);
            }).WithMessage(Texts.ValidationLiquid));
        }
Beispiel #4
0
        public void renders_deep_nested_object(string ext, string fileContent)
        {
            fileSystem.AddFile(Path.Combine(dataDirectory, $"person.{ext}"), new MockFileData(fileContent));

            var template = FluidTemplate.Parse(@"{{ data.person.address.postalcode }}");

            var templateContext = CreateTemplateContext();

            var result = template.Render(templateContext);

            Assert.Equal("1234", result.Trim());
        }
Beispiel #5
0
        public void renders_nested_folder_object(string ext, string fileContent)
        {
            fileSystem.AddFile(Path.Combine(dataDirectory, $@"users\person.{ext}"), new MockFileData(fileContent));

            var template = FluidTemplate.Parse(@"{{ data.users.person.name }}");

            var templateContext = CreateTemplateContext();

            var result = template.Render(templateContext);

            Assert.Equal("Eric Mill", result.Trim());
        }
Beispiel #6
0
        public AbstractXmlTemplate(TDocument document) : base(document)
        {
            this.PrepareTemplate();

            var stringTemplate = this.GetStringTemplate();

            if (!FluidTemplate.TryParse(stringTemplate, out var fluidTemplate, out var errors))
            {
                throw new SyntaxErrorException(errors.Aggregate((x, y) => x + "\n" + y));
            }
            this.TextTemplate = fluidTemplate;
        }
        private async Task CheckAsync(string source, string expected, Action <TemplateContext> init = null)
        {
            FluidTemplate.TryParse(source, out var template, out var messages);

            var context = new TemplateContext();

            init?.Invoke(context);

            var result = await template.RenderAsync(context);

            Assert.Equal(expected, result);
        }
Beispiel #8
0
        public void renders_nested_lists(string ext, string fileContent)
        {
            fileSystem.AddFile(Path.Combine(dataDirectory, $"members.{ext}"), new MockFileData(fileContent));

            var template = FluidTemplate.Parse(@"{{ data.members | size }}");

            var templateContext = CreateTemplateContext();

            var result = template.Render(templateContext);

            Assert.Equal("3", result.Trim());
        }
Beispiel #9
0
        //TODO: This is currently not supported. See https://jekyllrb.com/docs/datafiles/#example-accessing-a-specific-author
        //            [InlineData("csv", @"dave.name,dave.twitter
        //""David Smith"",""DavidSilvaSmith""")]
        //            [InlineData("tsv", @"dave.name	dave.twitter
        //""David Smith""	""DavidSilvaSmith""")]
        public void renders_dictionary_accessors(string ext, string fileContent)
        {
            fileSystem.AddFile(Path.Combine(dataDirectory, $"people.{ext}"), new MockFileData(fileContent));

            var template = FluidTemplate.Parse(@"{{ data.people['dave'].name }}");

            var templateContext = CreateTemplateContext();

            var result = template.Render(templateContext);

            Assert.Equal("David Smith", result.Trim());
        }
Beispiel #10
0
        public void ShouldParseIntegralNumbers(string source, string expected)
        {
            var result = FluidTemplate.TryParse(source, out var template, out var errors);

            Assert.True(result, String.Join(", ", errors));
            Assert.NotNull(template);
            Assert.Empty(errors);

            var rendered = template.Render();

            Assert.Equal(expected, rendered);
        }
Beispiel #11
0
        private static void Main(string[] args)
        {
            var app = new CommandLineApplication {
                Name = "dynamo2terraform"
            };

            app.HelpOption("-?|-h|--help");

            var inputFilePathOption = app.Option("-i|--input <path>",
                                                 "The path to the input C# DynamoDB Model decorated with DynamoDBAttributes for parsing",
                                                 CommandOptionType.SingleValue);

            var templateFilePathOption = app.Option("-t|--template <path>",
                                                    "The path to the liquid template to be used for generating the output",
                                                    CommandOptionType.SingleValue);

            app.OnExecute(() => {
                if (!inputFilePathOption.HasValue() || !File.Exists(inputFilePathOption.Value()))
                {
                    Console.WriteLine("Could not find Input file at the path provided");
                    return(0);
                }

                if (!templateFilePathOption.HasValue() || !File.Exists(templateFilePathOption.Value()))
                {
                    Console.WriteLine("Could not find Liquid template file at path provided");
                    return(0);
                }

                var tree  = ClassLoader.GetSyntaxTreeFromPath(inputFilePathOption.Value());
                var table = DynamoParserService.Parse(tree);

                var liquidTemplate = File.ReadAllText(templateFilePathOption.Value());


                IEnumerable <string> errors;
                if (FluidTemplate.TryParse(liquidTemplate, out var template, out errors))
                {
                    var context = new TemplateContext();
                    context.MemberAccessStrategy.Register(typeof(DynamoDbTable));                     // Allows any public property of the model to be used
                    context.MemberAccessStrategy.Register(typeof(DynamoDbAttribute));
                    context.MemberAccessStrategy.Register(typeof(DynamoDbGlobalSecondaryIndex));
                    context.SetValue("table", table);

                    Console.WriteLine(template.Render(context));
                }

                return(0);
            });

            app.Execute(args);
        }
Beispiel #12
0
        public async Task TemplateIsRendered()
        {
            var regressions = new List <Regression>();

            regressions.Add(new Regression
            {
                PreviousResult = new BenchmarksResult
                {
                    Id          = 1,
                    Excluded    = false,
                    DateTimeUtc = DateTime.UtcNow,
                    Session     = "1234",
                    Scenario    = "Json",
                    Description = "Json aspnet-citrine-lin",
                    Document    = File.ReadAllText("assets/benchmarkresult1.json")
                },
                CurrentResult = new BenchmarksResult
                {
                    Id          = 2,
                    Excluded    = false,
                    DateTimeUtc = DateTime.UtcNow,
                    Session     = "1235",
                    Scenario    = "Json",
                    Description = "Json aspnet-citrine-lin",
                    Document    = File.ReadAllText("assets/benchmarkresult2.json")
                },
                Change            = 1000,
                StandardDeviation = 1,
                Average           = 10
            });

            var report = new Report
            {
                Regressions = regressions
            };

            var template = File.ReadAllText("assets/template.fluid");

            var parseIsSuccessful = FluidTemplate.TryParse(template, out var fluidTemplate, out var errors);

            Assert.True(parseIsSuccessful);

            var context = new TemplateContext {
                Model = report
            };

            var body = await fluidTemplate.RenderAsync(context);

            _output.WriteLine(body);

            Assert.NotEmpty(body);
        }
Beispiel #13
0
        public static async Task <IActionResult> GetOrchestrationTabMarkupFunction(
            // Using /a/p/i route prefix, to let Functions Host distinguish api methods from statics
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "a/p/i/orchestrations('{instanceId}')/custom-tab-markup('{templateName}')")] HttpRequest req,
            string instanceId,
            string templateName,
            [DurableClient(TaskHub = "%DFM_HUB_NAME%")] IDurableClient durableClient,
            ILogger log)
        {
            // Checking that the call is authenticated properly
            try
            {
                await Auth.ValidateIdentityAsync(req.HttpContext.User, req.Headers);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Failed to authenticate request");
                return(new UnauthorizedResult());
            }

            var status = await GetInstanceStatus(instanceId, durableClient, log);

            if (status == null)
            {
                return(new NotFoundObjectResult($"Instance {instanceId} doesn't exist"));
            }

            // The underlying Task never throws, so it's OK.
            var templatesMap = DetailedOrchestrationStatus.TabTemplatesTask.Result;

            string templateCode = templatesMap.GetTemplate(status.GetEntityTypeName(), templateName);

            if (templateCode == null)
            {
                return(new NotFoundObjectResult("The specified template doesn't exist"));
            }

            try
            {
                var fluidTemplate = FluidTemplate.Parse(templateCode);
                var fluidContext  = new TemplateContext(status);

                return(new ContentResult()
                {
                    Content = fluidTemplate.Render(fluidContext),
                    ContentType = "text/html; charset=UTF-8"
                });
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex.Message));
            }
        }
Beispiel #14
0
        private async Task CheckAsync(string source, string expected, Action <TemplateContext> init = null)
        {
            FluidTemplate.TryParse(source, out var template, out var messages);

            var context = new TemplateContext();

            context.MemberAccessStrategy.Register(new { name = "product 1", price = 1 }.GetType());
            init?.Invoke(context);

            var result = await template.RenderAsync(context);

            Assert.Equal(expected, result);
        }
Beispiel #15
0
        protected override void PrepareTemplate()
        {
            this.TemplateDocument.Compile();

            this.TemplateDocument.Flush();

            var mainContentText = this.TemplateDocument.GetEntryTextReader(this.TemplateDocument.MainContentEntryPath).ReadToEnd();

            if (!FluidTemplate.TryParse(mainContentText, out this._fluidTemplate, out var errors))
            {
                throw new SyntaxErrorException(errors.Aggregate((x, y) => x + "\n" + y));
            }
        }
Beispiel #16
0
        public async Task ShouldSetFactoryValue()
        {
            FluidTemplate.TryParse("{{ Test }}", out var template, out var messages);
            bool set     = false;
            var  context = new TemplateContext();

            context.SetValue("Test", () => { set = true; return(set); });

            Assert.False(set);
            var result = await template.RenderAsync(context);

            Assert.Equal("true", result);
            Assert.True(set);
        }
Beispiel #17
0
        public async Task ModelIsUsedAsFallback()
        {
            var source   = "hello {{ firstname }} {{ lastname }}";
            var expected = "hello sebastien ros";

            FluidTemplate.TryParse(source, out var template, out var messages);
            var context = new TemplateContext(new { lastname = "ros" });

            context.SetValue("firstname", "sebastien");

            var result = await template.RenderAsync(context);

            Assert.Equal(expected, result);
        }
        public string Render(string input, TemplateContext context, ContentData contentData = null)
        {
            if (!IsTemplate(input))
            {
                // Has no templating code...
                return(input);
            }

            context = PopulateContextFromContentData(context, contentData);

            var template = FluidTemplate.Parse(input);

            return(template.Render(context));
        }
Beispiel #19
0
        public string RenderTemplate(Context context, string name, object model)
        {
            var source = RenderTemplate(context, name);

            if (FluidTemplate.TryParse(source, out var template))
            {
                var templateContext = new TemplateContext();
                templateContext.MemberAccessStrategy.Register(model.GetType()); // Allows any public property of the model to be used
                templateContext.SetValue("p", model);

                return(template.Render(templateContext));
            }
            return(null);
        }
Beispiel #20
0
        public async Task ShouldEvaluateAsyncMember()
        {
            FluidTemplate.TryParse("{{ Content.Foo }}{{ Content.Baz }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("Content", new Content());
            context.MemberAccessStrategy.Register <Content, string>("Foo", async(obj, name) => { await Task.Delay(100); return("Bar"); });
            context.MemberAccessStrategy.Register <Content, string>(async(obj, name) => { await Task.Delay(100); return(name); });

            var result = await template.RenderAsync(context);

            Assert.Equal("BarBaz", result);
        }
Beispiel #21
0
        /// <summary>
        /// implementing operate on rows (instead of row) to allow loading of external (file based) templates first
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        public override IEnumerable <IRow> Operate(IEnumerable <IRow> rows)
        {
            if (!Run)
            {
                yield break;
            }

            var key = string.Join(':', Context.Process.Id, Context.Entity.Alias, Context.Field.Alias, Context.Operation.Method, Context.Operation.Index);

            if (!_memoryCache.TryGetValue(key, out CachedFluidTransform transform))
            {
                transform = new CachedFluidTransform();

                var fileBasedTemplate = Context.Process.Templates.FirstOrDefault(t => t.Name == Context.Operation.Template);

                if (fileBasedTemplate != null)
                {
                    Context.Operation.Template = fileBasedTemplate.Content;
                }

                var input   = MultipleInput();
                var matches = Context.Entity.GetFieldMatches(Context.Operation.Template);
                transform.Input = input.Union(matches).ToArray();

                if (FluidTemplate.TryParse(Context.Operation.Template, out transform.Template))
                {
                    // any changes to content item will invalidate cache
                    _memoryCache.Set(key, transform, _signal.GetToken(Common.GetCacheKey(Context.Process.Id)));
                }
                else
                {
                    Context.Error("Failed to parse fluid template.");
                    Utility.CodeToError(Context, Context.Operation.Template);
                    yield break;
                }
            }

            var context = new TemplateContext();

            foreach (var row in rows)
            {
                foreach (var field in transform.Input)
                {
                    context.SetValue(field.Alias, row[field]);
                }
                row[Context.Field] = _convert(transform.Template.Render(context));
                yield return(row);
            }
        }
Beispiel #22
0
        public async Task ShouldEvaluateInheritedObjectProperty()
        {
            FluidTemplate.TryParse("{{ e.Name }} {{ e.Salary }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("e", new Employee {
                Name = "John", Salary = 550
            });
            context.MemberAccessStrategy.Register <Employee>();

            var result = await template.RenderAsync(context);

            Assert.Equal("John 550", result);
        }
Beispiel #23
0
        public async Task ShouldEvaluateObjectProperty()
        {
            FluidTemplate.TryParse("{{ p.Name }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Person {
                Name = "John"
            });
            context.MemberAccessStrategy.Register <Person>();

            var result = await template.RenderAsync(context);

            Assert.Equal("John", result);
        }
Beispiel #24
0
        private void ParseBasePath(MediaS3StorageOptions options, TemplateContext templateContext)
        {
            try
            {
                var template = FluidTemplate.Parse(options.S3BasePath);

                options.S3BasePath = template.Render(templateContext, NullEncoder.Default);
                options.S3BasePath = options.S3BasePath.Replace("\r", String.Empty).Replace("\n", String.Empty);
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Unable to parse Azure Media Storage base path.");
                throw;
            }
        }
Beispiel #25
0
        public async Task IgonreCasing()
        {
            FluidTemplate.TryParse("{{ p.NaMe }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Person {
                Name = "John"
            });
            context.MemberAccessStrategy.IgnoreCasing = true;
            context.MemberAccessStrategy.Register <Person>();

            var result = await template.RenderAsync(context);

            Assert.Equal("John", result);
        }
Beispiel #26
0
        public void caches_result(string ext, string fileContent)
        {
            fileSystem.Directory.CreateDirectory(dataDirectory);

            var fileName = Path.Combine(dataDirectory, $"person.{ext}");

            fileSystem.AddFile(fileName, new MockFileData(fileContent));

            var template = FluidTemplate.Parse(@"{{ data.person.name }} {{ data.person.email }}");

            var templateContext = CreateTemplateContext();

            var result = template.Render(templateContext);

            Assert.Equal("Eric Mill [email protected]", result.Trim());
        }
Beispiel #27
0
        public async Task ShouldEvaluateObjectPropertyWhenInterfaceRegisteredAsGlobal()
        {
            TemplateContext.GlobalMemberAccessStrategy.Register <IAnimal>();

            FluidTemplate.TryParse("{{ p.Age }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Dog {
                Age = 12
            });

            var result = await template.RenderAsync(context);

            Assert.Equal("12", result);
        }
Beispiel #28
0
        public async Task ShouldNotAllowNotRegisteredInterfaceMembers()
        {
            TemplateContext.GlobalMemberAccessStrategy.Register <IAnimal>();

            FluidTemplate.TryParse("{{ p.Name }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Dog {
                Name = "Rex"
            });

            var result = await template.RenderAsync(context);

            Assert.Equal("", result);
        }
Beispiel #29
0
        public async Task ShouldRegisterValueMappingWithInterface()
        {
            FluidValue.ValueConverters.Add(x => x is IPet pet ? new PetValue(pet) : null);

            FluidTemplate.TryParse("{{ p.Name }}", out var template, out var messages);

            var context = new TemplateContext();

            context.SetValue("p", new Dog {
                Name = "Rex"
            });

            var result = await template.RenderAsync(context);

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

                options.ContainerName = template.Render(templateContext, NullEncoder.Default);
                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 e;
            }
        }