Esempio n. 1
0
        public void Random_Integer()
        {
            // Arrange
            var action = _handlebarsContext.Compile("{{Random.Generate Type=\"Integer\" Min=1000 Max=9999}}");

            // Act
            var result = action("");

            // Assert
            int.Parse(result).Should().BeInRange(1000, 9999);
        }
        public void Append(string template, string expected)
        {
            // Arrange
            var action = _handlebarsContext.Compile(template);

            // Act
            var result = action("");

            // Assert
            result.Should().Be(expected);
        }
        public void HumanizeDateTime()
        {
            var template = string.Format("{{{{[Humanizer.Humanize] \"{0}\" }}}}", DateTime.UtcNow.AddHours(-30).ToString("O"));

            // Arrange
            var action = _handlebarsContext.Compile(template);

            // Act
            var result = action("");

            // Assert
            result.Should().Be("yesterday");
        }
        private HandlebarsView GetViewFromCache(ControllerContext controllerContext, string virtualPath)
        {
            CacheKey templateCacheKey = new CacheKey(CacheConfigurationCategoryNames.HandlebarsView)
            {
                Key = virtualPath.Substring(virtualPath.LastIndexOf('/') + 1)
            };

            return(CacheProvider.GetOrAdd(templateCacheKey, () =>
            {
                //First, let's make sure the dependencies exist
                Dictionary <string, HandlebarsView> dependencies = GetDependenciesFromCache(controllerContext,
                                                                                            virtualPath);

                //Then let's compile
                Action <TextWriter, object> compiledTemplate;
                var file = VirtualPathProvider.GetFile(virtualPath);
                using (TextReader template = new StreamReader(file.Open()))
                {
                    compiledTemplate = _handlebars.Compile(template);
                }

                InitMonitorTamplateFiles();

                return new HandlebarsView(compiledTemplate, virtualPath, dependencies);
            }));
        }
        private static void WalkNode(IHandlebars handlebarsContext, JToken node, object context)
        {
            if (node.Type == JTokenType.Object)
            {
                // In case of Object, loop all children. Do a ToArray() to avoid `Collection was modified` exceptions.
                foreach (JProperty child in node.Children <JProperty>().ToArray())
                {
                    WalkNode(handlebarsContext, child.Value, context);
                }
            }
            else if (node.Type == JTokenType.Array)
            {
                // In case of Array, loop all items. Do a ToArray() to avoid `Collection was modified` exceptions.
                foreach (JToken child in node.Children().ToArray())
                {
                    WalkNode(handlebarsContext, child, context);
                }
            }
            else if (node.Type == JTokenType.String)
            {
                // In case of string, try to transform the value.
                string stringValue = node.Value <string>();
                if (string.IsNullOrEmpty(stringValue))
                {
                    return;
                }

                var    templateForStringValue = handlebarsContext.Compile(stringValue);
                string transformedString      = templateForStringValue(context);
                if (!string.Equals(stringValue, transformedString))
                {
                    ReplaceNodeValue(node, transformedString);
                }
            }
        }
Esempio n. 6
0
        public LogService(LogServiceConfig config)
        {
            this.config = config;

            templateEngine = Handlebars.Create();
            this.template  = templateEngine.Compile(this.config.LogTemplate);
        }
        public void Linq()
        {
            // Arrange
            var request = new
            {
                Path = "/test"
            };

            var action = _handlebarsContext.Compile("{{Linq Path 'it'}}");

            // Act
            var result = action(request);

            // Assert
            result.Should().Be("/test");
        }
Esempio n. 8
0
        public Func <object, string> GetRenderView(string path)
        {
            if (File.Exists(path))
            {
                return(_handlebars.CompileView(path));
            }
            else
            {
                return(_handlebars.Compile(path));
            }
            var partials = Path.GetFileNameWithoutExtension(path);

            _dict.TryGetValue(partials, out var renderView);
#if DEBUG
            if (renderView == null)
            {
                Debug.WriteLine($"[ExpressionCache] Require file: {path}, cache status: NOT HIT");
            }
            else
            {
                Debug.WriteLine($"[ExpressionCache] Require file: {path}, cache status: HIT");
            }
#endif

            if (renderView == null)
            {
                renderView = _handlebars.CompileView(path);
                _dict.Add(partials, renderView);
            }

            return(renderView);
        }
Esempio n. 9
0
        private void OnMixExportClick(object sender, EventArgs e)
        {
            if (saveFileDialogExport.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    Action <TextWriter, object> template;
                    using (var stream = new MemoryStream(R.default_template))
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            template = _Handlebars.Compile(reader);
                        }
                    }

                    using (var stream = new FileStream(saveFileDialogExport.FileName, FileMode.Create, FileAccess.Write))
                    {
                        using (var writer = new StreamWriter(stream, Encoding.UTF8))
                        {
                            template.Invoke(writer, new { mix = _MixModel });
                        }
                    }

                    System.Diagnostics.Process.Start(saveFileDialogExport.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, string.Format(R.ErrorFailedToExport, ex.Message), R.AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        public void SelectToken_With_String()
        {
            // Arrange
            var request = new
            {
                body = "{ \"Price\": 99 }"
            };

            var action = _handlebarsContext.Compile("{{JsonPath.SelectToken body \"..Price\"}}");

            // Act
            var result = action(request);

            // Assert
            int.Parse(result).Should().Be(99);
        }
Esempio n. 11
0
        public string Convert(string source, IDictionary <string, object> extraData = null)
        {
            var template = handlebars.Compile(source);

            var data = new ExpandoObject() as IDictionary <string, object>;

            data.Add("now", DateTime.Now);
            data.Add("site", topLevelConfig.Site);

            foreach ((string key, object value) in extraData ?? new Dictionary <string, object>())
            {
                data.Add(key, value);
            }

            return(template(data));
        }
Esempio n. 12
0
        public async Task <string> ParseAsync <T>(string template, T model, bool isHtml = true)
        {
            var compiledTemplate = _engine.Compile(template);

            var result = compiledTemplate(model);

            return(await Task.FromResult(result));
        }
Esempio n. 13
0
        private static Action <TextWriter, object> LoadTemplateFile(IHandlebars hb, string path)
        {
            var file = new FileInfo(path);

            using (StreamReader reader = file.OpenText())
            {
                return(hb.Compile(reader));
            }
        }
Esempio n. 14
0
        public string Tokenize(string template, dynamic context, IServiceProvider serviceProvider)
        {
            context.ServiceProvider = serviceProvider;

            return(_tokens.Replace(template, match =>
            {
                var render = _renderers.GetOrAdd(match.Value, t => _handlebars.Compile(t));
                return render.Invoke(context);
            }));
        }
Esempio n. 15
0
        private static Action <TextWriter, object> LoadTemplateFile(IHandlebars hb, string directory, string fileName)
        {
            var dir  = new DirectoryInfo(directory);
            var file = new FileInfo(Path.Combine(dir.FullName, fileName));

            using (StreamReader reader = file.OpenText())
            {
                return(hb.Compile(reader));
            }
        }
        public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
        {
            var responseMessage = new ResponseMessage {
                StatusCode = original.StatusCode
            };

            var template = new { request = requestMessage };

            switch (original.BodyData.DetectedBodyType)
            {
            case BodyType.Json:
                TransformBodyAsJson(template, original, responseMessage);
                break;

            case BodyType.File:
                TransformBodyAsFile(template, original, responseMessage);
                break;

            case BodyType.String:
                responseMessage.BodyOriginal = original.BodyData.BodyAsString;
                TransformBodyAsString(template, original, responseMessage);
                break;
            }

            // Headers
            var newHeaders = new Dictionary <string, WireMockList <string> >();

            foreach (var header in original.Headers)
            {
                var templateHeaderKey    = HandlebarsContext.Compile(header.Key);
                var templateHeaderValues = header.Value
                                           .Select(HandlebarsContext.Compile)
                                           .Select(func => func(template))
                                           .ToArray();

                newHeaders.Add(templateHeaderKey(template), new WireMockList <string>(templateHeaderValues));
            }

            responseMessage.Headers = newHeaders;

            return(responseMessage);
        }
        private static void TransformBodyAsFile(IHandlebars handlebarsContext, object template, ResponseMessage original, ResponseMessage responseMessage)
        {
            var templateBodyAsFile = handlebarsContext.Compile(original.BodyData.BodyAsFile);

            responseMessage.BodyData = new BodyData
            {
                DetectedBodyType = original.BodyData.DetectedBodyType,
                DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
                BodyAsFile = templateBodyAsFile(template)
            };
        }
        public void Constants(string template, string expected)
        {
            // Arrange
            var action = _handlebarsContext.Compile(template);

            // Act
            var result = action("");

            // Assert
            result.Should().StartWith(expected);
        }
        public void JsonTestIfTruthy(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"truthy\":true}");

            var source = "{{#if truthy}}{{truthy}}{{/if}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("True", output);
        }
        public void ArrayIndexPropertiesNested(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("[{}, {\"Items\": [\"Index0\", \"Index1\"]}]");

            var source = "{{@root.1.Items.1}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("Index1", output);
        }
        public void JsonTestIfFalsyValue(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"myfield\":\"test1\",\"falsy\":null}");

            var source = "{{myfield}}{{#if falsy}}{{falsy}}{{/if}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("test1", output);
        }
Esempio n. 22
0
        public Action <TextWriter, object> GetRenderFn()
        {
            if (_compiledTemplateInstance == null)
            {
                using (var reader = new StringReader(GetTemplateText()))
                {
                    _compiledTemplateInstance = _handlebars.Compile(reader);
                }
            }

            return(_compiledTemplateInstance);
        }
        public void ArrayCount(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("[{\"Key\": \"Key1\", \"Value\": \"Val1\"},{\"Key\": \"Key2\", \"Value\": \"Val2\"}]");

            var source = "{{this.Count}} = {{this.Length}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("2 = 2", output);
        }
Esempio n. 24
0
        public void JsonTestArrayCount(IHandlebars handlebars)
        {
            var model = JsonConvert.DeserializeObject("[{\"Key\": \"Key1\", \"Value\": \"Val1\"},{\"Key\": \"Key2\", \"Value\": \"Val2\"}]");

            var source = "{{this.Count}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("2", output);
        }
        public void ObjectIterator(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"Key1\": \"Val1\", \"Key2\": \"Val2\"}");

            var source = "{{#each this}}{{@key}}{{@value}}{{/each}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("Key1Val1Key2Val2", output);
        }
Esempio n. 26
0
        public void JsonTestArrays(IHandlebars handlebars)
        {
            var model = JsonConvert.DeserializeObject("[{\"Key\": \"Key1\", \"Value\": \"Val1\"},{\"Key\": \"Key2\", \"Value\": \"Val2\"}]");

            var source = "{{#each this}}{{Key}}{{Value}}{{/each}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("Key1Val1Key2Val2", output);
        }
        public void ObjectIteratorProperties(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"Key1\": \"Val1\", \"Key2\": \"Val2\"}");

            var source = "{{#each this}}{{@index}}-{{@first}}-{{@last}}-{{@key}}-{{@value}};{{/each}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("0-True--Key1-Val1;1-False--Key2-Val2;", output);
        }
        public void JsonTestIfFalsyMissingField(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"myfield\":\"test1\"}");

            var source = "{{myfield}}{{#if mymissingfield}}{{mymissingfield}}{{/if}}";

            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("test1", output);
        }
        public void ArrayListProperties(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("[{\"Key\": \"Key1\", \"Value\": \"Val1\"},{\"Key\": \"Key2\", \"Value\": \"Val2\"}]");

            var source = "{{listProperties this}}";

            handlebars.RegisterHelper(new ListPropertiesHelper());
            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("length", output);
        }
        public void JsonTestIfFalsy(IHandlebars handlebars)
        {
            var model = JsonDocument.Parse("{\"falsy\":false}");

            var source = "{{#if (not falsy)}}{{falsy}}{{/if}}";

            handlebars.RegisterHelper("not", (context, arguments) => !arguments.At <bool>(0));
            var template = handlebars.Compile(source);

            var output = template(model);

            Assert.Equal("False", output);
        }