コード例 #1
0
        /// <summary>
        /// Generate content based on template (uses mustache syntax)
        /// </summary>
        protected string GenerateContent(string template, NotificationData data, bool stripHtml, bool removeDiacritics = false)
        {
            if (removeDiacritics)
            {
                // remove sms-unsupported symbols
                var props = data.GetType().GetProperties();
                foreach (var prop in props)
                {
                    if (prop.PropertyType == typeof(string) && prop.CanWrite)
                    {
                        prop.SetValue(data, prop.GetValue(data)?.ToString().RemoveDiacritics());
                    }
                }
            }

            var result = !string.IsNullOrWhiteSpace(template)
                ? removeDiacritics
                    ? _stubbleRenderer.Render(template, data,
                                              data.Properties.ToDictionary(i => i.Key, i => i.Value.ToString()), new RenderSettings()
            {
                SkipHtmlEncoding = true
            })
                    : _stubbleRenderer.Render(template, data,
                                              data.Properties.ToDictionary(i => i.Key, i => i.Value.ToString()))
                : template;

            if (stripHtml)
            {
                result = result?.StripHtml()?.Trim();
            }

            return(result);
        }
コード例 #2
0
        public Task <Result> SendInvite(string email, string token)
        {
            Result <EmailEntity> mailResult = GetMail(EmailTypes.Invite);

            if (mailResult.Failure)
            {
                return(Task.FromResult(Result.Fail(mailResult.Errors)));
            }

            EmailEntity mail = mailResult.Value;
            string      body = _stubble.Render(mail.Body, new { token = token });

            return(Send(email, mail.Subject, body));
        }
コード例 #3
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Doesnt_Error_When_Partial_Is_Used_But_None_Are_Given()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("{{> inner}}", new { Foo = "Bar" });

            Assert.Equal("", output);
        }
コード例 #4
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Can_Render_WithoutData()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("I Have No Data :(", null);

            Assert.Equal("I Have No Data :(", output);
        }
コード例 #5
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Can_Render_With_LambdaToken_NoDynamic()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("{{Foo}}", new { Foo = new Func <object>(() => "Bar") });

            Assert.Equal("Bar", output);
        }
コード例 #6
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Can_Render_With_LambdaSection_NoDynamic()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("{{#Foo}}Foo{{/Foo}}", new { Foo = new Func <string, object>((str) => str + " Bar") });

            Assert.Equal("Foo Bar", output);
        }
コード例 #7
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Can_Render_WithoutPartials()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("{{Foo}}", new { Foo = "Bar" });

            Assert.Equal("Bar", output);
        }
コード例 #8
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Can_Render_With_LambdaToken_Dynamic()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("{{Foo}}", new { BarValue = "Bar", Foo = new Func <dynamic, object>((context) => context.BarValue) });

            Assert.Equal("Bar", output);
        }
コード例 #9
0
        public void StringRendererSpecTest(SpecTest data)
        {
            OutputStream.WriteLine(data.Name);
            var stubble = new StubbleVisitorRenderer();
            var output  = data.Partials != null?stubble.Render(data.Template, data.Data, data.Partials) : stubble.Render(data.Template, data.Data);

            OutputStream.WriteLine("Expected \"{0}\", Actual \"{1}\"", data.Expected, output);
            Assert.Equal(data.Expected, output);
        }
コード例 #10
0
 public string FillInputPy(StubbleVisitorRenderer renderer, string v, Dictionary <string, string> dictionary)
 {
     return(renderer.Render(v, dictionary, new RenderSettings
     {
         SkipHtmlEncoding = true,
         SkipRecursiveLookup = false,
         ThrowOnDataMiss = true
     }));
 }
コード例 #11
0
ファイル: SpecTestBase.cs プロジェクト: nexmart/Stubble
        public void It_Can_Pass_Spec_Tests(SpecTest data)
        {
            OutputStream.WriteLine(data.name);
            var stubble = new StubbleVisitorRenderer();
            var output  = data.partials != null?stubble.Render(data.template, data.data, data.partials) : stubble.Render(data.template, data.data);

            OutputStream.WriteLine("Expected \"{0}\", Actual \"{1}\"", data.expected, output);
            Assert.Equal(data.expected, output);
        }
コード例 #12
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Can_Render_WithPartials()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("{{> inner}}", new { Foo = "Bar" }, new Dictionary <string, string> {
                { "inner", "{{Foo}}" }
            });

            Assert.Equal("Bar", output);
        }
コード例 #13
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Should_Error_After_N_Recursions()
        {
            const string rowTemplate = @"
            <div class='row'>
                {{#content}}
                    {{#is_column}}
                        {{>column}}
                    {{/is_column}}
                {{/content}}
            </div>";

            const string columnTemplate = @"
            <div class='column'>
                {{#content}}
                    {{#is_text}}
                        {{>text}}
                    {{/is_text}}
                    {{#is_row}}
                        {{>row}}
                    {{/is_row}}
                {{/content}}
            </div>";

            const string textTemplate = @"
            <span class='text'>
                {{text}}
            </span>";

            var treeData = new
            {
                is_row  = true,
                content = new
                {
                    is_column = true,
                    content   = new[]
                    {
                        new
                        {
                            is_text = true,
                            text    = "Hello World!"
                        }
                    }
                }
            };

            var stubble = new StubbleVisitorRenderer();
            var ex      =
                Assert.Throws <StubbleException>(() => stubble.Render(rowTemplate, treeData, new Dictionary <string, string>
            {
                { "row", rowTemplate },
                { "column", columnTemplate },
                { "text", textTemplate }
            }));

            Assert.Equal("You have reached the maximum recursion limit of 256.", ex.Message);
        }
コード例 #14
0
        public override Task Handle(SendUserFormatAction request, CancellationToken cancellationToken)
        {
            var context  = request.Context;
            var output   = Regex.Unescape(request.Output);
            var rendered = _renderer.Render(output, context.ItemsCache);

            Console.Write(rendered);

            return(Task.CompletedTask);
        }
コード例 #15
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Can_Render_With_LambdaSection_Dynamic()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render("{{#Foo}}Foo{{/Foo}}", new
            {
                BarValue = "Bar",
                Foo      = new Func <dynamic, string, object>((context, str) => str + " " + context.BarValue)
            });

            Assert.Equal("Foo Bar", output);
        }
コード例 #16
0
        public Model.Document CreateReportModel(dynamic data)
        {
            var yamlDeserializer   = new DeserializerBuilder().Build();
            var yamlSerializerJson = new SerializerBuilder().JsonCompatible().Build();

            RenderedYamlDocument = _stubbleRenderer.Render(_yamlTemplateContent, data);
            var renderedYamlObj = yamlDeserializer.Deserialize <object>(RenderedYamlDocument);

            RenderedJsonDocument = yamlSerializerJson.Serialize(renderedYamlObj);
            return(JsonConvert.DeserializeObject <Model.Document>(RenderedJsonDocument));
        }
コード例 #17
0
 private string Render(string name, string input, object view)
 {
     try
     {
         return(_stubble.Render(input, view));
     }
     catch (Exception ex)
     {
         throw new Exception("Error rendering " + name, ex);
     }
 }
コード例 #18
0
        private static void SubstituteName(FileSystemInfo info, StubbleVisitorRenderer stubble, Dictionary <string, string> variables)
        {
            var substitutedPath = stubble.Render(info.FullName, variables);

            if (substitutedPath.Equals(info.FullName))
            {
                return;
            }

            (info as DirectoryInfo)?.MoveTo(substitutedPath);
            (info as FileInfo)?.MoveTo(substitutedPath);
        }
コード例 #19
0
        public ProcessingResultBase Process(Item item, MustacheTemplate template)
        {
            var textItem       = (TextItem)item;
            var templateString = Encoding.UTF8.GetString(template.Content);

            var renderedTemplate = _compiler.Render(templateString, textItem);

            var extension = item.SourceKey.Split(".").Last();
            var htmlPath  = item.SourceKey.Replace("." + extension, ".html");

            return(new HtmlResult(renderedTemplate, htmlPath));
        }
コード例 #20
0
        public void StringRendererSpecTest(SpecTest data)
        {
            var settings = RenderSettings.GetDefaultRenderSettings();

            settings.CultureInfo = data.CultureInfo ?? settings.CultureInfo;

            OutputStream.WriteLine(data.Name);
            var stubble = new StubbleVisitorRenderer();
            var output  = data.Partials != null?stubble.Render(data.Template, data.Data, data.Partials, settings) : stubble.Render(data.Template, data.Data, settings);

            OutputStream.WriteLine("Expected \"{0}\", Actual \"{1}\"", data.Expected, output);
            Assert.Equal(data.Expected, output);
        }
コード例 #21
0
        private string GetCacheKey()
        {
            var methodProperties     = new ExpandoObject();
            var expandoObjCollection = (ICollection <KeyValuePair <string, object> >)methodProperties;
            var parameters           = _targetMethod.GetParameters();

            for (int parameterIndex = 0; parameterIndex < parameters.Length; parameterIndex++)
            {
                var parameterName = parameters[parameterIndex].Name;
                var value         = _args[parameterIndex];
                expandoObjCollection.Add(new KeyValuePair <string, object>(parameterName, value));
            }

            return(_stubbleTemplate.Render(CacheConfiguration.KeyTemplate, methodProperties));
        }
コード例 #22
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Should_Be_Able_To_Skip_Recursive_Lookups()
        {
            var settings =
                new RenderSettings
            {
                SkipRecursiveLookup = true
            };
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render(
                "{{FooValue}} {{#Foo}}{{FooValue}}{{BarValue}}{{/Foo}}",
                new
            {
                FooValue = "Foo",
                Foo      = new
                {
                    BarValue = "Bar"
                }
            },
                settings);

            Assert.Equal("Foo Bar", output);
        }
コード例 #23
0
ファイル: StubbleTest.cs プロジェクト: mmhantea/Stubble
        public void It_Should_Be_Able_To_Take_Partials_And_Render_Settings()
        {
            var stubble = new StubbleVisitorRenderer();
            var output  = stubble.Render(
                "{{FooValue}} {{#Foo}}{{> FooBar}}{{/Foo}}",
                new
            {
                FooValue = "Foo",
                Foo      = new
                {
                    BarValue = "Bar"
                }
            },
                new Dictionary <string, string>
            {
                { "FooBar", "{{FooValue}}{{BarValue}}" }
            },
                new RenderSettings {
                SkipRecursiveLookup = true
            });

            Assert.Equal("Foo Bar", output);
        }
コード例 #24
0
        public string Render(string template, JObject data)
        {
            ApplyBarcodeTranslatorsIfAny(data);

            return(_stubble.Render(template, data));
        }
コード例 #25
0
        /* ----------------------------------------------------------------- *
         * methods                                                           *
         * ----------------------------------------------------------------- */

        /// <inheritdoc/>
        public Project GenerateProject(ProjectSpec spec)
        {
            var template = _projectTemplateRegistry.Lookup(spec);
            if (template is null)
            {
                Logger.LogDebug("No project template found for spec: {ProjectSpec}", spec);
                return null;
            }

            var parameters = new Dictionary<string, object>
            {
                ["Name"] = spec.Name,
                ["Description"] = spec.Description,
                ["Namespace"] = spec.Namespace,
                ["SteeltoeVersion"] = spec.SteeltoeVersion,
                ["DotNetFramework"] = spec.DotNetFramework,
                ["DotNetTemplate"] = spec.DotNetTemplate,
                ["Language"] = spec.Language,
            };
            if (spec.Dependencies != null)
            {
                foreach (var dependency in spec.Dependencies?.Split(','))
                {
                    parameters[dependency] = true;
                }
            }

            if (template.Parameters != null)
            {
                foreach (var templateParameter in template.Parameters)
                {
                    if (templateParameter.Value != null)
                    {
                        parameters[templateParameter.Name] = templateParameter.Value;
                    }
                    else if (templateParameter.Expression != null)
                    {
                        parameters[templateParameter.Name] =
                            new ExpressionParser(templateParameter.Expression).Evaluate(parameters);
                    }
                }
            }

            var project = new Project();
            project.FileEntries.Add(new FileEntry { Path = $"{spec.Name}/" });
            foreach (var fileEntry in template.Manifest)
            {
                if (fileEntry.Dependencies != null)
                {
                    var dependencySatisfied = false;
                    foreach (var fileEntryDependency in fileEntry.Dependencies.Split(','))
                    {
                        parameters.TryGetValue(fileEntryDependency, out var dependency);
                        if (dependency != null)
                        {
                            if (dependency is bool)
                            {
                                if ((bool)dependency)
                                {
                                    dependencySatisfied = true;
                                }
                            }
                            else
                            {
                                dependencySatisfied = true;
                            }

                            if (dependencySatisfied)
                            {
                                break;
                            }
                        }
                    }

                    if (!dependencySatisfied)
                    {
                        continue;
                    }
                }

                var path = fileEntry.Rename is null ? fileEntry.Path : _renderer.Render(fileEntry.Rename, parameters);
                var text = fileEntry.Text is null ? null : _renderer.Render(fileEntry.Text, parameters);
                project.FileEntries.Add(new FileEntry { Path = Path.Join(spec.Name, path), Text = text });
            }

            return project;
        }
コード例 #26
0
        public string Stubble_Benchmark()
        {
            var testCase = TestCaseParams.Params[Index - 1];

            return(StubbleVisitorRenderer.Render(testCase.Key, testCase.Value));
        }
コード例 #27
0
 public string Render(Template template, IProviderModel model)
 {
     model.Imports = template.Imports;
     return(_stubbleVisitorRenderer.Render(template.TemplateText, model));
 }
コード例 #28
0
        /// <summary>
        /// Build the JavaScript content and add it to the supplied
        /// <see cref="IFlowData"/> instance.
        /// </summary>
        /// <param name="data">
        /// The <see cref="IFlowData"/> instance to populate with the
        /// resulting <see cref="JavaScriptBuilderElementData"/>
        /// </param>
        /// <param name="jsonObject">
        /// The JSON data object to include in the JavaScript.
        /// </param>
        /// <param name="supportsPromises">
        /// True to build JavaScript that uses promises. False to
        /// build JavaScript that does not use promises.
        /// </param>
        /// <param name="url">
        /// The callback URL for the JavaScript to send a request to
        /// when it has new evidence values to supply.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if the supplied flow data is null.
        /// </exception>
        protected void BuildJavaScript(IFlowData data, string jsonObject, bool supportsPromises, Uri url)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            JavaScriptBuilderElementData elementData = (JavaScriptBuilderElementData)
                                                       data.GetOrAdd(
                ElementDataKeyTyped,
                CreateElementData);

            // Try and get the requested object name from evidence.
            if (data.TryGetEvidence(Constants.EVIDENCE_OBJECT_NAME, out string objectName) == false ||
                string.IsNullOrWhiteSpace(objectName))
            {
                objectName = ObjName;
            }

            var ubdateEnabled = url != null &&
                                url.AbsoluteUri.Length > 0;

            JavaScriptResource javaScriptObj = new JavaScriptResource(
                objectName,
                jsonObject,
                supportsPromises,
                url,
                EnableCookies,
                ubdateEnabled);

            string content = _stubble.Render(_template, javaScriptObj.AsDictionary() /*, _renderSettings*/);

            string minifiedContent = content;

            if (_minify)
            {
                // Minimize the script.
                var ugly = Uglify.Js(content);

                if (ugly.HasErrors)
                {
                    // If there were are errors then log them and
                    // return the non-minified response.

                    minifiedContent = content;

                    if (_lastRequestWasError == false)
                    {
                        StringBuilder errorText = new StringBuilder();
                        errorText.AppendLine("Errors occurred when minifying JavaScript.");
                        foreach (var error in ugly.Errors)
                        {
                            errorText.AppendLine($"{error.ErrorCode}: {error.Message}. " +
                                                 $"Line(s) {error.StartLine}-{error.EndLine}. " +
                                                 $"Column(s) {error.StartColumn}-{error.EndColumn}");
                        }
                        errorText.AppendLine(content);
                        Logger.LogError(errorText.ToString());
                        _lastRequestWasError = true;
#pragma warning disable CS0618 // Type or member is obsolete
                        // This usage should be replaced with the
                        // CancellationToken implementation once it
                        // is available.
                        data.Stop = true;
#pragma warning restore CS0618 // Type or member is obsolete
                    }
                }
                else
                {
                    minifiedContent = ugly.Code;
                }
            }

            elementData.JavaScript = minifiedContent;
        }
コード例 #29
0
ファイル: TwitterBenchmark.cs プロジェクト: wizofaus/Stubble
 public string TimelineBenchmark_Visitor() => StubbleVisitorRenderer.Render("timeline", Timeline);
コード例 #30
0
        /// <summary>
        /// Build the JavaScript content and add it to the supplied
        /// <see cref="IFlowData"/> instance.
        /// </summary>
        /// <param name="data">
        /// The <see cref="IFlowData"/> instance to populate with the
        /// resulting <see cref="JavaScriptBuilderElementData"/>
        /// </param>
        /// <param name="jsonObject">
        /// The JSON data object to include in the JavaScript.
        /// </param>
        /// <param name="sessionId">
        /// The session Id to use in the JavaScript response.
        /// </param>
        /// <param name="sequence">
        /// The sequence value to use in the JavaScript response.
        /// </param>
        /// <param name="supportsPromises">
        /// True to build JavaScript that uses promises. False to
        /// build JavaScript that does not use promises.
        /// </param>
        /// <param name="supportsFetch">
        /// True to build JavaScript that makes use of the
        /// fetch API. Otherwise, the template will fall back to using
        /// XMLHttpRequest.
        /// </param>
        /// <param name="url">
        /// The callback URL for the JavaScript to send a request to
        /// when it has new evidence values to supply.
        /// </param>
        /// <param name="parameters">The parameters to append to the URL</param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if the supplied flow data is null.
        /// </exception>
        protected void BuildJavaScript(
            IFlowData data,
            string jsonObject,
            string sessionId,
            int sequence,
            bool supportsPromises,
            bool supportsFetch,
            Uri url,
            string parameters)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            JavaScriptBuilderElementData elementData = (JavaScriptBuilderElementData)
                                                       data.GetOrAdd(
                ElementDataKeyTyped,
                CreateElementData);

            string objectName = ObjName;

            // Try and get the requested object name from evidence.
            if (data.TryGetEvidence(Constants.EVIDENCE_OBJECT_NAME,
                                    out object objObjectName))
            {
                objectName = objObjectName?.ToString() ?? ObjName;
            }

            var ubdateEnabled = url != null &&
                                url.AbsoluteUri.Length > 0;

            // This check won't be 100% fool-proof but it only needs to be
            // reasonably accurate and not take too long.
            var hasDelayedProperties = jsonObject != null &&
                                       jsonObject.Contains("delayexecution");

            JavaScriptResource javaScriptObj = new JavaScriptResource(
                objectName,
                jsonObject,
                sessionId,
                sequence,
                supportsPromises,
                supportsFetch,
                url,
                parameters,
                EnableCookies,
                ubdateEnabled,
                hasDelayedProperties);

            string content = _stubble.Render(_template, javaScriptObj.AsDictionary());

            string minifiedContent = content;

            if (_minify)
            {
                // Minimize the script.
                var ugly = Uglify.Js(content);

                if (ugly.HasErrors)
                {
                    // If there were are errors then log them and
                    // return the non-minified response.

                    minifiedContent = content;

                    if (_lastRequestWasError == false)
                    {
                        StringBuilder errorText = new StringBuilder();
                        errorText.AppendLine("Errors occurred when minifying JavaScript.");
                        foreach (var error in ugly.Errors)
                        {
                            errorText.AppendLine($"{error.ErrorCode}: {error.Message}. " +
                                                 $"Line(s) {error.StartLine}-{error.EndLine}. " +
                                                 $"Column(s) {error.StartColumn}-{error.EndColumn}");
                        }
                        errorText.AppendLine(content);
                        Logger.LogError(errorText.ToString());
                        _lastRequestWasError = true;
#pragma warning disable CS0618 // Type or member is obsolete
                        // This usage should be replaced with the
                        // CancellationToken implementation once it
                        // is available.
                        data.Stop = true;
#pragma warning restore CS0618 // Type or member is obsolete
                    }
                }
                else
                {
                    minifiedContent = ugly.Code;
                }
            }

            elementData.JavaScript = minifiedContent;
        }