private void renderPreview()
        {
            Song previewSong = string.IsNullOrEmpty(winampController.currentSong.Title)
                ? EXAMPLE_SONG
                : winampController.currentSong;

            try {
                templatePreview.Text = TEMPLATE_COMPILER.Compile(templateEditor.Text).Render(previewSong);
            } catch (FormatException e) {
                templatePreview.Text = $"Template format error: {e.Message}";
            }
        }
Esempio n. 2
0
        public string CompileTemplate(string templateText, object model)
        {
            FormatCompiler compiler = new FormatCompiler();
            var            template = compiler.Compile(templateText);

            return(template.Render(model));
        }
Esempio n. 3
0
        private string ParseTemplate(string template, IDictionary <string, string> values)
        {
            var compiler  = new FormatCompiler();
            var generator = compiler.Compile(template);

            return(generator.Render(values));
        }
Esempio n. 4
0
        public void GenerateReport(ISuiteResult results)
        {
            var data     = new Dictionary <string, object>();
            var compiler = new FormatCompiler();

            var assembly  = Assembly.GetExecutingAssembly();
            var stream    = assembly.GetManifestResourceStream("WebDriverRunner.reporters.Trx.template.xml");
            var reader    = new StreamReader(stream);
            var generator = compiler.Compile(reader.ReadToEnd());

            data["Name"] = results.Name;

            data["allCount"]     = results.Results().Count;
            data["passedCount"]  = results.PassedTests.Count;
            data["failedCount"]  = results.FailedTests.Count;
            data["skippedCount"] = results.SkippedTests.Count;

            data["all"] = results.Results();


            var duration = string.Format(" total :{0:%m}min{0:%s}sec ", results.Total);

            data["summary"] = "(" + results.PassedTests.Count + "," +
                              +results.FailedTests.Count + "," +
                              +results.SkippedTests.Count + ")" + duration;

            var content = generator.Render(data);

            var file = new StreamWriter(Output + "/" + "template.trx");

            file.Write(content);
            file.Close();
        }
Esempio n. 5
0
        public string GetAfterRegister(string TemplateCode, UserInfo MyUserInfo)
        {
            string      ReturnValue   = "";
            string      TemplateBody  = "";
            string      ParseValue    = "";
            TemplateDTO MyTemplateDTO = new TemplateDTO();

            try
            {
                //Get Template Body from TemplateID
                //MyTemplateDTO = m_TemplateDbService.GetTemplateByTemplateCode(TemplateCode, MyUserInfo);

                TemplateBody = MyTemplateDTO.TemplateBody;
                //Parse Here
                FormatCompiler compiler = new FormatCompiler();

                Generator generator = compiler.Compile(TemplateBody);

                string JSONString = string.Empty;
                JSONString = JsonConvert.SerializeObject(MyUserInfo);
                //var reportData = String.Format("{{ feeTypes: {0} }}", JSONString);
                var     reportData = JSONString;
                JObject jsonData   = JObject.Parse(reportData);
                ParseValue = generator.Render(jsonData);

                ReturnValue = ParseValue;

                return(ReturnValue);
            }

            catch (Exception exp)
            {
                throw;
            }
        }
        public void LoopTest()
        {
            // Arrange
            var data = new
            {
                beginning = "First line",
                tables    = new[]
                {
                    new { name = "Hello", hasComment = true, comment = "World" },
                    new { name = "Hi", hasComment = false, comment = "" },
                    new { name = "Foo", hasComment = true, comment = "Bar" }
                },
                ending = "Last line"
            };

            var template = @"{{beginning}}{{#newline}}
{{#each tables}}    List<{{name}}> {{name}} = null;{{#if hasComment}} // {{comment}}{{/if}}{{#newline}}
{{/each}}{{ending}}";

            // Act
            var parser            = new FormatCompiler();
            var mustacheGenerator = parser.Compile(template);
            var output            = mustacheGenerator.Render(data);

            Console.WriteLine(output);

            // Assert
            Assert.AreEqual(@"First line
    List<Hello> Hello = null; // World
    List<Hi> Hi = null;
    List<Foo> Foo = null; // Bar
Last line", output);
        }
Esempio n. 7
0
        /// <inheritdoc />
        public string Compile(string szTemplate, object data)
        {
            var formatCompiler = new FormatCompiler();
            var generator      = formatCompiler.Compile(szTemplate);

            return(generator.Render(data));
        }
 public void TestCompile_CommentAloneOnlyLine_PrintsSurroundingSpace()
 {
     FormatCompiler compiler = new FormatCompiler();
     Generator generator = compiler.Compile("    {{#! comment }}    ");
     string result = generator.Render(null);
     Assert.AreEqual("        ", result, "The wrong text was generated.");
 }
Esempio n. 9
0
        public StartPage()
        {
            // Prevent duplicate instances
            if (instance != null)
            {
                throw new DuplicateInstanceException(typeof(StartPage));
            }

            InitializeComponent();

            // Set StartPage only dockable to document area
            DockAreas = DockAreas.Document;

            // Set up browser for interfacing
            startPageBrowser.ObjectForScripting = startPageInterface;

            // Load Resource Data
            var compiler = new FormatCompiler();

            template   = compiler.Compile(Resources.StartPageTemplate);
            LayoutCSS  = Resources.StartPageLayout;
            themeDark  = Resources.StartPageDark;
            themeLight = Resources.StartPageLight;

            ColorThemeCSS = themeDark;


            // Load Start Page
            LoadPage();

            AttachEventHandlers(); // This one messes with the browser, so do it last.
        }
Esempio n. 10
0
        public DocumentationGenerator(string resourceTemplateFile)
        {
            string template = null;

            if (string.IsNullOrWhiteSpace(resourceTemplateFile))
            {
                using (var ms = new MemoryStream(Templates.resourceMarkDown))
                    using (var reader = new StreamReader(ms))
                    {
                        template = reader.ReadToEnd();
                    }
            }
            else
            {
                if (!File.Exists(resourceTemplateFile))
                {
                    throw new FileNotFoundException($"Resource MarkDown template not found", resourceTemplateFile);
                }
                template = File.ReadAllText(resourceTemplateFile);
            }

            if (string.IsNullOrWhiteSpace(template))
            {
                throw new InvalidOperationException("Failed to load resource templase");
            }

            FormatCompiler compiler = new FormatCompiler()
            {
                RemoveNewLines = false
            };

            this.resourceMarkDownGenerator              = compiler.Compile(template);
            this.resourceMarkDownGenerator.KeyNotFound += MarkDownGenerator_KeyNotFound;
        }
Esempio n. 11
0
        public string ParseTemplate(int TemplateID, EmailInfo emailInfo, UserInfo MyUserInfo)
        {
            string ReturnValue  = "";
            string TemplateBody = "";
            string ParseValue   = "";

            try
            {
                //Get Template Body from TemplateID
                //TemplateBody = m_TemplateDbService.GetTemplateBodyByTemplateID(TemplateID, MyUserInfo);


                //Parse Here
                FormatCompiler compiler = new FormatCompiler();

                Generator generator = compiler.Compile(TemplateBody);

                string JSONString = string.Empty;
                JSONString = JsonConvert.SerializeObject(emailInfo);
                //var reportData = String.Format("{{ feeTypes: {0} }}", JSONString);
                var     reportData = JSONString;
                JObject jsonData   = JObject.Parse(reportData);
                ParseValue = generator.Render(jsonData);

                ReturnValue = ParseValue;

                return(ReturnValue);
            }

            catch (Exception exp)
            {
                throw;
            }
        }
Esempio n. 12
0
        public string GenerateApi()
        {
            var templateString = File.ReadAllText($@"{Program.TEMPLATES_DIRECTORY_PATH}\{TemplateName}.txt");
            var compiler       = new FormatCompiler();
            var generator      = compiler.Compile(templateString);

            return(generator.Render(this));
        }
 public void TestCompile_LineAllWhitespace_PrintsWhitespace()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "\t    \t";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual(format, result, "The generated text was wrong.");
 }
 public void TestCompile_CommentContentComment_RemovesComment()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "{{#! comment }}Middle{{#! comment }}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new object());
     Assert.AreEqual("Middle", result, "The wrong text was generated.");
 }
 public void TestCompile_CommentBlankComment_RemovesLine()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "{{#! comment }}    {{#! comment }}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new object());
     Assert.AreEqual(String.Empty, result, "The wrong text was generated.");
 }
 public void TestCompile_NoTags_PrintsFormatString()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = "This is an ordinary string.";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual(format, result, "The generated text was wrong.");
 }
 public void TestCompile_Key_ReplacesWithValue()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Name}}!!!";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new { Name = "Bob" });
     Assert.AreEqual("Hello, Bob!!!", result, "The wrong text was generated.");
 }
Esempio n. 18
0
        public string RenderTemplate(object page)
        {
            var template  = File.ReadAllText(path);
            var compiler  = new FormatCompiler();
            var generator = compiler.Compile(template);

            return(generator.Render(page));
        }
 public void TestCompile_CommentNewLineBlank_PrintsBlank()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"    {{#! comment }}
     ";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual("        ", result, "The wrong text was generated.");
 }
    public string RenderView(ControllerContext ctx, string toRender)
    {
        var fc = new FormatCompiler();

        fc.RegisterTag(new IncludeTag(this, ctx, _webServer.StaticFileController), true);
        var generator = fc.Compile(toRender);

        return(generator.Render(ctx));
    }
Esempio n. 21
0
        public void TestGenerate_WithoutIfOnDateTime()
        {
            FormatCompiler compiler  = new FormatCompiler();
            const string   format    = @"{{DateOffCom:yyyy-MM-dd}}";
            Generator      generator = compiler.Compile(format);
            string         result    = generator.Render(new { DateOffCom = new DateTime(2020, 1, 1) });

            Assert.AreEqual("2020-01-01", result.Substring(0, 10));
        }
Esempio n. 22
0
        public void TestGenerate_WithIfOnDateTimeAndExtraString()
        {
            FormatCompiler compiler  = new FormatCompiler();
            const string   format    = @"{{#if DateOffCom}}Date:{{DateOffCom:yyyy-MM-dd}}{{/if}}";
            Generator      generator = compiler.Compile(format);
            string         result    = generator.Render(new { DateOffCom = new DateTime(2020, 1, 1) });

            Assert.AreEqual("Date:2020-01-01", result.Substring(0, 15));
        }
Esempio n. 23
0
        public void TestGenerate_WithIfOnDateTimeDefaultValue()
        {
            FormatCompiler compiler  = new FormatCompiler();
            const string   format    = @"{{#if DateOffCom}}{{DateOffCom:yyyy-MM-dd}}{{/if}}";
            Generator      generator = compiler.Compile(format);
            string         result    = generator.Render(new { DateOffCom = default(DateTime) });

            Assert.AreEqual("", result);
        }
Esempio n. 24
0
        public static string Generate(string template, object parameters)
        {
            FormatCompiler compiler = new FormatCompiler();

            compiler.RemoveNewLines = false;
            Generator generator = compiler.Compile(template);

            return(generator.Render(parameters));
        }
 public void TestCompile_CanUseContextStartEndVariablesToMakeDecisions()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#each this}}{{#if @start}}<li class=""first""></li>{{#elif @end}}<li class=""last""></li>{{#else}}<li class=""middle""></li>{{/if}}{{/each}}";
     Generator generator = compiler.Compile(format);
     string actual = generator.Render(new int[] { 1, 1, 1, 1, });
     string expected = @"<li class=""first""></li><li class=""middle""></li><li class=""middle""></li><li class=""last""></li>";
     Assert.AreEqual(expected, actual, "The string is not valid.");
 }
 public void TestCompile_CanUseContextVariablesToMakeDecisions()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#each this}}{{#if @index}}{{#index}}{{/if}}{{/each}}";
     Generator generator = compiler.Compile(format);
     string actual = generator.Render(new int[] { 1, 1, 1, 1, });
     string expected = "123";
     Assert.AreEqual(expected, actual, "The numbers were not valid.");
 }
Esempio n. 27
0
        public List <TemplateParseModel> ParseTemplate(int TemplateID, List <EmailInfo> emailInfoList, string templateBody, UserInfo MyUserInfo)
        {
            string ReturnValue  = "";
            string TemplateBody = "";
            string ParseValue   = "";
            List <TemplateParseModel> MyTemplateParseModel = new List <TemplateParseModel>();

            try
            {
                //Get Template Body from TemplateID
                //TemplateBody = m_TemplateDbService.GetTemplateBodyByTemplateID(TemplateID, MyUserInfo);
                TemplateBody = templateBody;

                //Parse Here
                FormatCompiler compiler = new FormatCompiler();

                foreach (EmailInfo emf in emailInfoList)
                {
                    TemplateParseModel TemplateParseModelInfo = new TemplateParseModel();
                    try
                    {
                        Generator generator = compiler.Compile(TemplateBody);

                        string JSONString = string.Empty;
                        JSONString = JsonConvert.SerializeObject(emf);
                        //var reportData = String.Format("{{ feeTypes: {0} }}", JSONString);
                        var     reportData = JSONString;
                        JObject jsonData   = JObject.Parse(reportData);
                        ParseValue = generator.Render(jsonData);

                        TemplateParseModelInfo.ProfileId  = emf.Profileid;
                        TemplateParseModelInfo.Email      = emf.Email;
                        TemplateParseModelInfo.ParseValue = ParseValue;
                        TemplateParseModelInfo.ProfileURL = emf.Url;
                        TemplateParseModelInfo.Status     = "SUCCESS";

                        MyTemplateParseModel.Add(TemplateParseModelInfo);
                    }
                    catch (Exception exp)
                    {
                        TemplateParseModelInfo.ProfileId  = emf.Profileid;
                        TemplateParseModelInfo.Email      = emf.Email;
                        TemplateParseModelInfo.ParseValue = ParseValue;
                        TemplateParseModelInfo.ProfileURL = emf.Url;
                        TemplateParseModelInfo.Status     = "ERROR";
                        continue;
                    }
                }
                return(MyTemplateParseModel);
            }

            catch (Exception exp)
            {
                throw;
            }
        }
        public static string GetCard(AzureDevOpsWorkItem workItem)
        {
            var filePath = $"Cards\\{typeof(BugCard).Name}.mustache";
            var fileContentsWithMustachePlaceholders = File.ReadAllText(filePath);
            var compiler      = new FormatCompiler();
            var generator     = compiler.Compile(fileContentsWithMustachePlaceholders);
            var processedCard = generator.Render(BugViewModel.CreateFrom(workItem));

            return(processedCard);
        }
Esempio n. 29
0
        public MustacheResponse(string templateFile, object args)
        {
            compiler = new FormatCompiler();
            compiler.RemoveNewLines = false;
            this.args = args;

            customTags.ForEach(x => compiler.RegisterTag(x, true));

            generator = compiler.Compile(File.ReadAllText(templateFile));
        }
        public string Render(string relativePathToTemplate, object values)
        {
            var            template  = GetFileContents(GetFullPathToTemplate(relativePathToTemplate));
            FormatCompiler compiler  = new FormatCompiler();
            var            generator = compiler.Compile(template);

            var body = generator.Render(values);

            return(body);
        }
Esempio n. 31
0
        /// <summary>
        /// Returns generator from cache or creates and caches it.
        /// </summary>
        /// <param name="template"></param>
        /// <returns></returns>
        protected Generator GetGenerator(string template)
        {
            if (_cache.ContainsKey(template))
            {
                return(_cache[template]);
            }

            var generator = _compiler.Compile(template);

            return(_cache[template] = generator);
        }
Esempio n. 32
0
 public Task <string> Render(dynamic obj)
 {
     // TODO: Pull this out to an injected interface to abstract this away.
     return(Task.Factory.StartNew <string>(() =>
     {
         var compiler = new FormatCompiler {
             RemoveNewLines = false
         };
         var template = compiler.Compile(ProcessedTemplate);
         return template.Render(obj);
     }));
 }
Esempio n. 33
0
        private Generator GetGenerator(string fileName)
        {
            var path = Path.Combine(EmailTemplatesPath, fileName);

            var compiler = new FormatCompiler();

            using var streamReader = new StreamReader(path, Encoding.UTF8);

            var generator = compiler.Compile(streamReader.ReadToEnd());

            return(generator);
        }
        public void TestCompile_OutputNewLineBlank_PrintsBothLines()
        {
            FormatCompiler compiler = new FormatCompiler();
            const string format = @"Hello{{#newline}}
    ";

            const string expected = @"Hello
    ";
            Generator generator = compiler.Compile(format);
            string result = generator.Render(null);
            Assert.AreEqual(expected, result, "The wrong text was generated.");
        }
        public static string Format(EmailTemplateData templateObj)
        {
            string emailBody = "";

            using (StreamReader reader = new StreamReader(Path.Combine(templateObj.Url, templateObj.FileName)))
            {
                emailBody = reader.ReadToEnd();
                var compiler  = new FormatCompiler();
                var generator = compiler.Compile(emailBody);
                return(generator.Render(templateObj));
            }
            return("");
        }
 public void TestCompile_CanUseContextVariableToToggle()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#set even}}{{#each this}}{{#if @even}}Even {{#else}}Odd {{/if}}{{#set even}}{{/each}}";
     Generator generator = compiler.Compile(format);
     generator.ValueRequested += (sender, e) =>
     {
         e.Value = !(bool)(e.Value ?? false);
     };
     string actual = generator.Render(new int[] { 1, 1, 1, 1 });
     string expected = "Even Odd Even Odd ";
     Assert.AreEqual(expected, actual, "The context variable was not toggled.");
 }
Esempio n. 37
0
        /// <summary>
        /// Parse a Mustache template with arguments and return the results as a string
        /// </summary>
        /// <param name="path">Path to the tempalte</param>
        /// <param name="args">Class, struct, dynamic or anonymous object</param>
        /// <returns></returns>
        public static string FromFile(string path, object args)
        {
            var compiler = new FormatCompiler();

            compiler.RemoveNewLines = false;
            customTags.ForEach(x => compiler.RegisterTag(x, true));

            var writer    = new StringWriter();
            var generator = compiler.Compile(cache[Path.GetFullPath(path)]);

            generator.Render(args, writer);

            return(writer.ToString());
        }
Esempio n. 38
0
        public static string Transform(string template, object data)
        {
            if (data == null || template == null)
            {
                return(template);
            }

            // Thanks to the awesome work by Travis Parks and Keith Williams for the Mustache# for .NET Core library
            // which is available at https://github.com/SunBrandingSolutions/mustache-sharp
            var parser            = new FormatCompiler();
            var mustacheGenerator = parser.Compile(template.Replace("\n", string.Empty).Replace("\r", string.Empty));

            return(mustacheGenerator.Render(data));
        }
Esempio n. 39
0
        /// <summary>
        /// Parse a Mustache template with arguments and return the results as a string
        /// </summary>
        /// <param name="mustache"Mustache template source</param>
        /// <param name="args">Class, struct, dynamic or anonymous object</param>
        /// <returns></returns>
        public static string Parse(string mustache, object args)
        {
            var compiler = new FormatCompiler();

            compiler.RemoveNewLines = false;
            customTags.ForEach(x => compiler.RegisterTag(x, true));

            var writer    = new StringWriter();
            var generator = compiler.Compile(mustache);

            generator.Render(args, writer);

            return(writer.ToString());
        }
Esempio n. 40
0
        /// <summary>
        /// Instance a new Mustache response with object, dynamic or anonymous parameter
        /// </summary>
        /// <param name="templateFile">Path to the template</param>
        /// <param name="args">Class, struct, dynamic or anonymous object</param>
        public MustacheTemplate(string templateFile, object args)
        {
            this.templateFile = templateFile;

            if (File.Exists(templateFile))
            {
                compiler = new FormatCompiler();
                compiler.RemoveNewLines = false;
                this.args = args;

                customTags.ForEach(x => compiler.RegisterTag(x, true));

                generator = compiler.Compile(cache[Path.GetFullPath(templateFile)]);
            }
        }
        public string Parse(string template, object data)
        {
            try
            {
                var compiler  = new FormatCompiler();
                var generator = compiler.Compile(template);
                var result    = generator.Render(data);

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 42
0
        public void TestEach()
        {
            Dictionary<string, object> allparameters = new Dictionary<string, object>();
            allparameters.Add("stuName", "Jason");
            allparameters.Add("schoolName", "SH LJZ");
            //-----------------------------------------------------
            var class1 = new Dictionary<string, object>();
            class1.Add("Address", "Tong ren road 258号");
            class1.Add("Date", DateTime.Now);

            var Class2 = new Dictionary<string, object>();
            Class2.Add("Address", "People square");
            Class2.Add("Date", DateTime.Now);

            List<object> classes = new List<object>();
            classes.Add(class1);
            classes.Add(Class2);
            //-------------------------------------------------------
            allparameters.Add("Classes", classes);
            //--------------------------------------------------------
            var school1 = new Dictionary<string, object>();
            school1.Add("SchoolName", "LJZ");
            school1.Add("StuCount", 10);

            var school2 = new Dictionary<string, object>();
            school2.Add("SchoolName", "PSQ");
            school2.Add("StuCount", "20");

            List<object> schools = new List<object>();
            schools.Add(school1);
            schools.Add(school2);
            //---------------------------------------------------------
            allparameters.Add("Schools", schools);
            FormatCompiler compiler = new FormatCompiler();
            Generator generator = compiler.Compile(template);
            string actual = generator.Render(allparameters);
            Assert.IsNotNull(actual);
        }
 public void TestCompile_Each_PopulatedCollection_PrintsContentForEach()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#each this}}{{this}}{{/each}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(new int[] { 1, 2, 3 });
     Assert.AreEqual("Before123After", result, "The wrong text was generated.");
 }
 public void TestCompile_MissingDefaultParameter_ProvidesDefault()
 {
     FormatCompiler compiler = new FormatCompiler();
     compiler.RegisterTag(new DefaultTagDefinition(), true);
     const string format = @"{{#default}}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(null);
     Assert.AreEqual("123", result, "The wrong text was generated.");
 }
 public void TestCompile_MissingKey_CallsKeyNotFoundHandler()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Name}}!!!";
     Generator generator = compiler.Compile(format);
     generator.KeyNotFound += (obj, args) =>
     {
         args.Substitute = "Unknown";
         args.Handled = true;
     };
     string actual = generator.Render(new object());
     string expected = "Hello, Unknown!!!";
     Assert.AreEqual(expected, actual, "The wrong message was generated.");
 }
 public void TestCompile_KeyWithFormat_AppliesFormatting()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{When:yyyyMMdd}}!!!";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new { When = new DateTime(2012, 01, 31) });
     Assert.AreEqual("Hello, 20120131!!!", result, "The wrong text was generated.");
 }
 public void TestCompile_KeyWithPositiveAlignment_OptionalPlus_AppliesAlignment()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Name,+10}}!!!";
     Generator generator = compiler.Compile(format);
     string result = generator.Render(new { Name = "Bob" });
     Assert.AreEqual("Hello,        Bob!!!", result, "The wrong text was generated.");
 }
 public void TestCompile_FindsVariables_RecordsVariables()
 {
     FormatCompiler compiler = new FormatCompiler();
     HashSet<string> variables = new HashSet<string>();
     compiler.VariableFound += (o, e) =>
     {
         variables.Add(e.Name);
     };
     compiler.Compile(@"{{@FirstName}}{{@LastName}}");
     string[] expected = new string[] { "FirstName", "LastName" };
     string[] actual = variables.OrderBy(s => s).ToArray();
     CollectionAssert.AreEqual(expected, actual, "Not all variables were found.");
 }
 public void TestCompile_KeyKey_PrintsBothLines()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{this}}{{#newline}}
     {{this}}";
     Generator generator = compiler.Compile(format);
     string result = generator.Render("Content");
     const string expected = @"Content
     Content";
     Assert.AreEqual(expected, result, "The wrong text was generated.");
 }
        public void TestCompile_ExitContext_RemoveContext()
        {
            FormatCompiler compiler = new FormatCompiler();
            Context[] context = null;
            compiler.PlaceholderFound += (o, e) =>
            {
                context = e.Context;
            };
            compiler.Compile(@"{{#with Address}}{{/with}}{{FirstName}}");

            Assert.IsNotNull(context, "The context was not set.");
            Assert.AreEqual(1, context.Length, "The context did not contain the right number of items.");

            Assert.AreEqual(String.Empty, context[0].TagName, "The top-most context had the wrong tag type.");
        }
 public void TestCompile_If_EvaluatesToTrue_PrintsContent()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if this}}Content{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(true);
     Assert.AreEqual("BeforeContentAfter", result, "The wrong text was generated.");
 }
 public void TestCompile_IfNewLineEndIfNewLineContentNewLineIfNewLineEndIf_PrintsContent()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = @"{{#if this}}
     {{/if}}
     Content
     {{#if this}}
     {{/if}}";
     Generator generator = parser.Compile(format);
     string result = generator.Render(true);
     const string expected = @"Content";
     Assert.AreEqual(expected, result, "The wrong text was generated.");
 }
 public void TestCompile_IfNewLineEndIf_PrintsNothing()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = @"{{#if this}}
     {{/if}}";
     Generator generator = parser.Compile(format);
     string result = generator.Render(true);
     Assert.AreEqual(String.Empty, result, "The wrong text was generated.");
 }
 public void TestCompile_IfElse_TwoElses_IncludesSecondElseInElse_Throws()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if this}}Yay{{#else}}Nay{{#else}}Bad{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(false);
     Assert.AreEqual("BeforeNay{{#else}}BadAfter", result, "The wrong text was generated.");
 }
 public void TestCompile_IfElse_EvaluatesToFalse_PrintsElse()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if this}}Yay{{#else}}Nay{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(false);
     Assert.AreEqual("BeforeNayAfter", result, "The wrong text was generated.");
 }
 public void TestCompile_IfElif_ElifFalse_PrintsNothing()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "Before{{#if First}}First{{#elif Second}}Second{{/if}}After";
     Generator generator = parser.Compile(format);
     string result = generator.Render(new { First = false, Second = false });
     Assert.AreEqual("BeforeAfter", result, "The wrong text was generated.");
 }
 public void TestCompile_Each_Index_PrintsIndexOfItem()
 {
     FormatCompiler parser = new FormatCompiler();
     const string format = "<ul>{{#each this}}<li value=\"{{this}}\">Item {{#index}}</li>{{/each}}</ul>";
     Generator generator = parser.Compile(format);
     string result = generator.Render(new int[] { 1, 2, 3 });
     const string expected = @"<ul><li value=""1"">Item 0</li><li value=""2"">Item 1</li><li value=""3"">Item 2</li></ul>";
     Assert.AreEqual(expected, result, "The wrong text was generated.");
 }
 public void TestCompile_KeyInParent_LooksUpKeyInParent()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"{{#with Address}}{{FirstName}} from {{City}}{{/with}}";
     Generator generator = compiler.Compile(format);
     string actual = generator.Render(new
     {
         FirstName = "Bob",
         Address = new
         {
             City = "Philadelphia",
         }
     });
     string expected = "Bob from Philadelphia";
     Assert.AreEqual(expected, actual, "The wrong message was generated.");
 }
 public void TestCompile_FindsPlaceholders_RecordsPlaceholders()
 {
     FormatCompiler compiler = new FormatCompiler();
     HashSet<string> keys = new HashSet<string>();
     compiler.PlaceholderFound += (o, e) =>
     {
         keys.Add(e.Key);
     };
     compiler.Compile(@"{{FirstName}} {{LastName}}");
     string[] expected = new string[] { "FirstName", "LastName" };
     string[] actual = keys.OrderBy(s => s).ToArray();
     CollectionAssert.AreEqual(expected, actual, "Not all placeholders were found.");
 }
        public void TestCompile_FindsPlaceholders_ProvidesContext()
        {
            FormatCompiler compiler = new FormatCompiler();
            Context[] context = null;
            compiler.PlaceholderFound += (o, e) =>
            {
                context = e.Context;
            };
            compiler.Compile(@"{{#with Address}}{{ZipCode}}{{/with}}");

            Assert.IsNotNull(context, "The context was not set.");
            Assert.AreEqual(2, context.Length, "The context did not contain the right number of items.");

            Assert.AreEqual(String.Empty, context[0].TagName, "The top-most context had the wrong tag type.");
            Assert.AreEqual("with", context[1].TagName, "The bottom context had the wrong tag type.");

            Assert.AreEqual(0, context[0].Parameters.Length, "The top-most context had the wrong number of parameters.");
            Assert.AreEqual(1, context[1].Parameters.Length, "The bottom context had the wrong number of parameters.");
            Assert.AreEqual("Address", context[1].Parameters[0].Argument, "The bottom context had the wrong argument.");
        }