Example #1
0
    private static void WriteSkinnedMeshJson(SkinnedMeshRenderer skinnedRenderer, WebGLBone[] bones, Stream outStream, Dictionary <Material, WebGLModel> materialModels)
    {
        Mesh mesh = skinnedRenderer.sharedMesh;
        int  i;

        // Map the bones used by each sub-mesh
        foreach (WebGLModel model in materialModels.Values)
        {
            for (i = 0; i < model.meshes.Count; ++i)
            {
                WebGLMesh subMesh = model.meshes[i];

                // Eventually this will have to change, but for now let's just keep things simple:
                subMesh.boneOffset = 0;
                subMesh.boneCount  = bones.Length;

                model.meshes[i] = subMesh;
            }
        }

        StringTemplateGroup templateGroup = new StringTemplateGroup("MG", templatePath, typeof(DefaultTemplateLexer));
        StringTemplate      modelTemplate = templateGroup.GetInstanceOf("WebGLModel");

        modelTemplate.SetAttribute("name", mesh.name);
        modelTemplate.SetAttribute("models", materialModels.Values);
        modelTemplate.SetAttribute("bones", bones);

        string content = modelTemplate.ToString();

        Byte[] bytes = new UTF8Encoding(true).GetBytes(CleanJSON(content));
        outStream.Write(bytes, 0, bytes.Length);
    }
Example #2
0
        public static string StringTemplate(string str, object data)
        {
            var template = new StringTemplate(str);

            template.SetAttribute("item", data);
            return(template.ToString());
        }
Example #3
0
 //= null
 public static string Apply(string template, Dictionary<string, object> @params )
 {
     StringTemplate st = new StringTemplate(template);
     AddDefaultAttributes(st);
     if (@params != null) AddAttributes(st, @params);
     return st.ToString();
 }
Example #4
0
    void OnWizardCreate()
    {
        tex = new List <TransformExportData> ();
        mex = new Hashtable();
        mtx = new Hashtable();

        for (var i = 0; i < transforms.Length; i++)
        {
            RecurseTransform(transforms[i]);
        }

        string meshesPath = EditorUtility.SaveFilePanel("Save meshes", FileExport.lastExportPath, "", "js");
        string scenePath  = meshesPath.Substring(0, meshesPath.Length - 3) + "Scene.js";

        StringTemplate mt = FileExport.LoadTemplate("model");

        mt.SetAttribute("prefix", prefix + "Meshes");
        mt.SetAttribute("meshes", mex.Values);
        FileExport.SaveContentsAsFile(mt.ToString(), meshesPath);

        StringTemplate st = FileExport.LoadTemplate("scene");

        st.SetAttribute("prefix", prefix + "Scene");
        st.SetAttribute("meshPrefix", prefix + "Meshes");
        st.SetAttribute("transforms", tex);
        st.SetAttribute("root", tex[0]);
        st.SetAttribute("meshes", mex.Values);
        st.SetAttribute("materials", mtx.Values);
        FileExport.SaveContentsAsFile(st.ToString(), scenePath);

        FileExport.lastExportPath = meshesPath;
    }
Example #5
0
        static void Main(string[] args)
        {
            const string fileName = "Template";

            List <Person> _list = new List <Person>();

            _list.Add(new Person("idCustomer", "integer"));
            _list.Add(new Person("Name", "Alphanumeric"));

            StringTemplateGroup grp = new StringTemplateGroup(Environment.CurrentDirectory);
            StringTemplate      tmp = grp.GetInstanceOf(fileName);


            tmp.SetAttribute("ProcessorType", "validationFile.Processor.standardProcessor");
            tmp.SetAttribute("ProcessorPath", ".");

            tmp.SetAttribute("HandlerType", "ValidationInputFileDataFlowSSIS.pipellineBufferHandler");
            tmp.SetAttribute("HandlerPath", @"C:\Proyects\petSSISCustomTask\ValidationInputFileDataFlowSSIS\bin\Debug\ValidationInputFileDataFlowSSIS.dll");

            tmp.SetAttribute("MessageType", "ValidationInputFileDataFlowSSIS.KOMessageProvider");
            tmp.SetAttribute("MessagePath", @"C:\Proyects\petSSISCustomTask\ValidationInputFileDataFlowSSIS\bin\Debug\ValidationInputFileDataFlowSSIS.dll");

            tmp.SetAttribute("Fields", _list);

            Console.Write(tmp);
            StreamWriter sw = new StreamWriter("output.xml");

            sw.Write(tmp.ToString());
            sw.Close();
            Console.ReadKey();
        }
Example #6
0
        /// <summary>
        /// 获取设置白名单的url
        /// </summary>
        /// <param name="whiteIp"></param>
        /// <returns></returns>
        public string GetWhiteIpUrl(string whiteIp)
        {
            StringTemplate st = new StringTemplate(WhiteIpTemplate);

            st.SetAttribute("whiteIp", whiteIp);
            return(st.ToString());
        }
Example #7
0
 static void TestStringTemplate()
 {
     string text = "$entity.Account$您好!<br/> 请点击连接重置您的秘密<br><a href=\"$url$\">$url$</a>";
     StringTemplate st = new StringTemplate(text);
     st.SetAttribute("entity", new Demo() { Account = "fengpengbin" });
     st.SetAttribute("url", "http://www.aporeboy.com/vail");
     Console.WriteLine(st.ToString());
 }
Example #8
0
        public virtual void WriteLexerTestFile(string lexerName, bool debug)
        {
            StringTemplate outputFileST = GetLexerTestFileTemplate();

            outputFileST.SetAttribute("lexerName", lexerName);

            WriteTestFile(outputFileST.ToString());
        }
Example #9
0
        public static string GetMsg(string key, object data)
        {
            var template = new StringTemplate(GetSetting(key, string.Empty));

            template.SetAttribute("item", data);

            return(template.ToString());
        }
Example #10
0
        private static void CreateHqDocumentationTxt(string docPath, string template, string lang)
        {
            var stringTemplate = new StringTemplate(File.ReadAllText(Path.Combine(docPath, template)));

            stringTemplate.SetAttribute("langName", hcNames[lang]);
            stringTemplate.SetAttribute("appName", "hc");
            File.WriteAllText(Path.Combine(docPath, @"Readme.hc." + lang + ".txt"), stringTemplate.ToString(),
                              Encoding.UTF8);
        }
Example #11
0
        public void StringTemplateExample()
        {
            var template = new StringTemplate("{greeting} {name} on {date:dddd, MMMM dd, yyyy}!");

            template["greeting"] = "Hello";
            template["name"]     = "World";
            template["date"]     = DateTime.Now;
            Debug.WriteLine(template.ToString());
        }
Example #12
0
        public static string StringTemplate(string value, object data)
        {
            var template = new StringTemplate(value);

            template.SetAttribute("item", data);
            var result = template.ToString();

            return(result);
        }
Example #13
0
    protected void AddExportedJson(StringTemplate pContent, string pObjectId)
    {
        if (_exportedFiles.ContainsKey(pObjectId))
        {
            Debug.LogError("Duplicate file: " + pObjectId);
            throw new ArgumentException();
        }

        _exportedFiles.Add(pObjectId, CleanJSON(pContent.ToString()));
    }
Example #14
0
        public void DateFormatTest()
        {
            var template = new StringTemplate("Test date: {date:d}");
            var dt       = new DateTime(2000, 1, 1, 12, 0, 0);

            template["date"] = dt;
            var actual = template.ToString();

            Assert.AreEqual(string.Format("Test date: {0:d}", dt), actual);
        }
Example #15
0
        public static string Apply(string template, Dictionary <string, object> @params)//= null
        {
            StringTemplate st = new StringTemplate(template);

            AddDefaultAttributes(st);
            if (@params != null)
            {
                AddAttributes(st, @params);
            }
            return(st.ToString());
        }
Example #16
0
        public string Generate(IEnumerable <OntologyClass> classes, Options opts)
        {
            StringTemplate template = stringTemplateGroup.GetInstanceOf("classes");

            template.SetAttribute("classes", classes);
            template.SetAttribute("handle", opts.OntologyPrefix);
            template.SetAttribute("uri", opts.OntologyNamespace);
            template.SetAttribute("opts", opts);
            template.SetAttribute("refs", opts.DotNetNamespaceReferences.Split(','));
            return(template.ToString());
        }
Example #17
0
        public virtual void WriteTemplateTestFile(string parserName, string lexerName, string parserStartRuleName)
        {
            StringTemplate outputFileST   = GetTemplateTestFileTemplate();
            StringTemplate createParserST = GetParserCreationTemplate();

            outputFileST.SetAttribute("createParser", createParserST);
            outputFileST.SetAttribute("parserName", parserName);
            outputFileST.SetAttribute("lexerName", lexerName);
            outputFileST.SetAttribute("parserStartRuleName", parserStartRuleName);

            WriteTestFile(outputFileST.ToString());
        }
Example #18
0
        public void EvalTemplateTest()
        {
            var template = new StringTemplate("Hello {name}");

            template["name"] = "World";
            Assert.AreEqual("Hello World", template.ToString());

            template             = new StringTemplate("{greeting} {name}");
            template["greeting"] = "Hello";
            template["name"]     = "World";
            Assert.AreEqual("Hello World", template.ToString());
        }
        public string GetTemplateBody(Dictionary <string, object> tmpltItemDict, string url)
        {
            StringTemplate strTmplt = new StringTemplate();
            string         filePath = string.Empty;

            filePath = HttpContext.Current.Server.MapPath(url);
            if (System.IO.File.Exists(filePath))
            {
                strTmplt.Template   = File.ReadAllText(filePath);
                strTmplt.Attributes = tmpltItemDict;
            }
            return(strTmplt.ToString());
        }
    static void GenerateFileFromTemplate(string templateDir, string path, Dictionary <string, string> dictionary)
    {
        string         targetPath = path.Substring(templateDir.Length + 1);
        StringTemplate ST         = new StringTemplate(FileSystemUtil.ReadTxtInFile(path));

        foreach (string key in dictionary.Keys)
        {
            ST.SetAttribute(key, dictionary[key]);
        }
        FileSystemUtil.EnsureParentExists(targetPath);
        Console.WriteLine("Generating file {0} from {1}.", targetPath, templateDir);
        FileSystemUtil.SaveTxtInFile(ST.ToString(), targetPath);
    }
Example #21
0
    private static void WriteMeshJson(Mesh mesh, Stream outStream, Dictionary <Material, WebGLModel> materialModels)
    {
        StringTemplateGroup templateGroup = new StringTemplateGroup("MG", templatePath, typeof(DefaultTemplateLexer));
        StringTemplate      modelTemplate = templateGroup.GetInstanceOf("WebGLModel");

        modelTemplate.SetAttribute("name", mesh.name);
        modelTemplate.SetAttribute("models", materialModels.Values);

        string content = modelTemplate.ToString();

        Byte[] bytes = new UTF8Encoding(true).GetBytes(CleanJSON(content));
        outStream.Write(bytes, 0, bytes.Length);
    }
Example #22
0
        /// <summary>
        /// 把实体的数据融合到模板中,并返回融合结果,会保留数据的空格,换行,减少空间占用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">实体类</param>
        /// <param name="templateNames">模板名称,可以有多级,多级用“.”分隔,对于小模板只需提供节点名称就可以了</param>
        /// <returns></returns>
        public string EntityToStr <T>(T entity, string templateName)
        {
            StringTemplate stringTemplate = new StringTemplate(_cache[templateName]);

            if (_attrRendererMap.ContainsKey(templateName))
            {
                foreach (KeyValuePair <Type, IAttributeRenderer> keyVal in _attrRendererMap[templateName])
                {
                    stringTemplate.RegisterRenderer(keyVal.Key, keyVal.Value);
                }
            }
            stringTemplate.SetAttribute("entity", entity);
            return(stringTemplate.ToString().Trim());
        }
        public string Export(IList dbObjects, string templatePath)
        {
            StringTemplate template = new StringTemplate();

            var text = File.ReadAllText(templatePath);

            //remove all tabs - it used only to format template code, not output code
            template.Template = text.Replace("\t", "");

            template.SetAttribute("dbObjects", dbObjects);
            var output = template.ToString();

            return output;
        }
Example #24
0
        public static string Generate(string input, Dictionary<string, object> data)
        {
            var template = new StringTemplate(input);

            foreach (var d in data)
                template.SetAttribute(d.Key, d.Value);

            string result = template.ToString();
            ;
            template.Reset();
            data.Clear();
            template = null;
            return result;
        }
Example #25
0
        public static string StringTemp(string filename, object data)
        {
            var path     = HttpContext.Current.Server.MapPath("~/");
            var filepath = Path.Combine(path, filename);
            var result   = string.Empty;

            using (StreamReader reader = new StreamReader(filepath))
            {
                string         sttemplate = reader.ReadToEnd();
                StringTemplate template   = new StringTemplate(sttemplate);
                template.SetAttribute("item", data);
                result = template.ToString();
            }
            return(result);
        }
Example #26
0
        public override string RenderContent()
        {
            int recordCount = 0;
            IEnumerable <IDictionary <string, object> > entities = GetData();

            if (entities.IsNullOrEmpty())
            {
                return(EmptyTemplate);
            }
            StringBuilder result = new StringBuilder();

            if (AllowPaging)
            {
                Pager.TargetId = Id;
                if (PagerPosition == PagerPosition.Top || PagerPosition == PagerPosition.Both)
                {
                    result.AppendLine(Pager.Render());
                }
            }
            Pager.RecordCount = recordCount;
            var content = new List <string>();

            entities.ForEach((entity) =>
            {
                StringTemplate query = new StringTemplate(ItemTemplate);
                query.SetAttribute(entity);
                content.Add(query.ToString());
            });
            result.AppendLine(string.Join(SeperatorTemplate, content.ToArray()));
            if (AllowPaging)
            {
                if (PagerPosition == PagerPosition.Bottom || PagerPosition == PagerPosition.Both)
                {
                    result.AppendLine(Pager.Render());
                }
            }
            if (SubContainerTag != SubContainerTag.none)
            {
                var subContainer = new TagBuilder(SubContainerTag.ToString());
                if (!SubContainerCssClass.IsNullOrEmpty())
                {
                    subContainer.AddCssClass(SubContainerCssClass);
                }
                subContainer.InnerHtml = result.ToString();
                return(subContainer.ToString());
            }
            return(result.ToString());
        }
        public void ListIterator_SingleItem()
        {
            // Arrange
            var template = new StringTemplate("$user:{ u | $u.FirstName$ is a super user? $u.IsSuperUser$. But his last name is $u.LastName$.}$");
            template.SetAttribute("user", new
                                              {
                                                  FirstName = "Ian",
                                                  LastName = "Robinson",
                                                  IsSuperUser = false
                                              });
            // Act
            var renderedText = template.ToString();

            // Assert
            Assert.AreEqual(renderedText, "Ian is a super user? False. But his last name is Robinson.");
        }
        public void ListIterator_MultipleItems()
        {
            // Arrange
            var template = new StringTemplate("$user:{ u | <p>$u.FirstName$ is a super user? $u.IsSuperUser$. But his last name is $u.LastName$.</p>}$");
            var user = new { FirstName = "Ian", LastName = "Robinson", IsSuperUser = false };
            var userList = (new[] {user}).ToList();
            userList.Add(new { FirstName = "Gertrude", LastName = "Schmuckbucket", IsSuperUser = true});

            template.SetAttribute("user", userList);

            // Act
            var renderedText = template.ToString();

            // Assert
            Assert.AreEqual(renderedText, "<p>Ian is a super user? False. But his last name is Robinson.</p><p>Gertrude is a super user? True. But his last name is Schmuckbucket.</p>");
        }
Example #29
0
        public static string Generate(string input, Dictionary <string, object> data)
        {
            var template = new StringTemplate(input);

            foreach (var d in data)
            {
                template.SetAttribute(d.Key, d.Value);
            }

            string result = template.ToString();

            ;
            template.Reset();
            data.Clear();
            template = null;
            return(result);
        }
Example #30
0
    static void WriteLevel(WebGLLevel level, Stream outStream)
    {
        if (EditorUtility.DisplayCancelableProgressBar("Exporting Level", "Writing JSON", 1.0f))
        {
            throw new Exception("User canceled export");
        }

        // Write out JSON
        StringTemplateGroup templateGroup = new StringTemplateGroup("MG", templatePath, typeof(DefaultTemplateLexer));
        StringTemplate      animTemplate  = templateGroup.GetInstanceOf("WebGLLevel");

        animTemplate.SetAttribute("level", level);

        string content = animTemplate.ToString();

        Byte[] bytes = new UTF8Encoding(true).GetBytes(CleanJSON(content));
        outStream.Write(bytes, 0, bytes.Length);
    }
Example #31
0
        public void Generate(string path)
        {
            StringTemplateGroup group        = new StringTemplateGroup("myGroup", @".\Templet");
            StringTemplate      st           = group.GetInstanceOf("Home");
            int           ID                 = 1;
            List <String> allMethodSigniture = new List <string>();

            foreach (var testSummary in AllTestSummary)
            {
                string methodSignature = testSummary.GetMethodSignature();
                st.SetAttribute("IDNum", ID++);
                st.SetAttribute("MethodSignature", methodSignature);
                var method       = testSummary.Method;
                var methodString = GetEntireMethodString(method);
                st.SetAttribute("SourceCode", methodString);
                bool bStartTests = false;
                if (testSummary.SwumSummary.StartsWith("test"))
                {
                    bStartTests = true;
                }
                st.SetAttribute("NotStartTests", !bStartTests);
                st.SetAttribute("SwumDesc", testSummary.SwumSummary.ToLower());

                st.SetAttribute("MethodBodyDesc", testSummary.GetBodyDescriptions());
                allMethodSigniture.Add(methodSignature);
            }
            allMethodSigniture.Sort();
            //hyper index
            foreach (var ms in allMethodSigniture)
            {
                st.SetAttribute("MethodLinkID", ms);
            }


            //st.SetAttribute("Message", "hello ");
            String result = st.ToString(); // yields "int x = 0;"
            //Console.WriteLine(result);

            StreamWriter writetext = new StreamWriter(path);

            writetext.WriteLine(result);
            writetext.Close();
        }
        public void NestedProperties()
        {
            // Arrange
            IDictionary<string, object> ret = new Dictionary<string, object>();
            ret["elem1"] = true;
            ret["elem2"] = false;

            var nestedObj = new Dictionary<string, object>();
            nestedObj["nestedProp"] = 100;
            ret["elem3"] = nestedObj;

            var template = new StringTemplate("$elem1$ or $elem2$ and value: $elem3.nestedProp$") { Attributes = ret };

            // Act
            var renderedText = template.ToString();

            // Assert
            Assert.AreEqual(renderedText, "True or False and value: 100");
        }
Example #33
0
        //[Test] // This can take a little bit to run so take it out
        public void PerfTest()
        {
            var count = 1000000;
            var sw    = new Stopwatch();

            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string.Format("Hello {0}: {1,2}", "World", i);
            }
            sw.Stop();
            var stringFormatTime = sw.ElapsedMilliseconds; // (double)sw.ElapsedMilliseconds / (double)count;

            sw.Reset();
            sw.Start();
            var template = new StringTemplate("Hello {name}: {num,2}");

            for (int i = 0; i < count; i++)
            {
                template["name"] = "World";
                template["num"]  = i;
                template.ToString();
            }
            sw.Stop();
            var textTemplateTime = sw.ElapsedMilliseconds; // (double)sw.ElapsedMilliseconds / (double)count;

            sw.Reset();
            sw.Start();
            var str = "Hello {name}: {num}";

            for (int i = 0; i < count; i++)
            {
                var str2 = str.Replace("{name}", "World");
                str2 = str.Replace("{num}", i.ToString());
            }
            sw.Stop();
            var stringReplaceTime = sw.ElapsedMilliseconds; // (double)sw.ElapsedMilliseconds / (double)count;

            Debug.WriteLine(string.Format("String.Format: {0}", stringFormatTime));
            Debug.WriteLine(string.Format("TextTemplate.ToString: {0}", textTemplateTime));
            Debug.WriteLine(string.Format("String.Replace: {0}", stringReplaceTime));
            Debug.WriteLine(string.Format("Diff: {0}", (double)textTemplateTime / (double)stringFormatTime));
        }
Example #34
0
        public static void emitPartialType(string name, ClassDescriptorSerialized serTy)
        {
            JavaPrettyPrint outputMaker = new JavaPrettyPrint(null);

            outputMaker.Filename         = serTy.FileName;
            outputMaker.TraceDestination = Console.Error;
            outputMaker.TemplateLib      = templates;
            outputMaker.Cfg = cfg;

            StringTemplate pkgST = outputMaker.emitPackage(serTy);

            if (cfg.DebugLevel >= 1)
            {
                Console.Out.WriteLine("Writing out {0}", serTy.FileName);
            }
            StreamWriter javaW = new StreamWriter(serTy.FileName);

            javaW.Write(pkgST.ToString());
            javaW.Close();
        }
Example #35
0
        /// <summary>
        /// 把实体的数据融合到模板中,并返回融合结果,会把数据整合为一行,减少空间占用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">实体类</param>
        /// <param name="templateNames">模板名称,可以有多级,多级用“.”分隔,对于小模板只需提供节点名称就可以了</param>
        /// <returns></returns>
        public string EntityToRow <T>(T entity, string templateName)
        {
            StringBuilder templateSb = new StringBuilder();

            foreach (string row in _cache[templateName].Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                templateSb.Append(row);
            }
            StringTemplate stringTemplate = new StringTemplate(templateSb.ToString());

            if (_attrRendererMap.ContainsKey(templateName))
            {
                foreach (KeyValuePair <Type, IAttributeRenderer> keyVal in _attrRendererMap[templateName])
                {
                    stringTemplate.RegisterRenderer(keyVal.Key, keyVal.Value);
                }
            }
            stringTemplate.SetAttribute("entity", entity);
            return(stringTemplate.ToString().Trim());
        }
Example #36
0
        public void ProcessRequest(HttpContext context)
        {
            var Response = context.Response;
            var Request  = context.Request;

            Response.ContentType = "text/html";

            var filename = System.IO.Path.GetFileNameWithoutExtension(Request.Path);

            var pages     = new WDK.ContentManagement.Pages.Manager();
            var foundPage = pages.getPageByFilename(filename);

            if (foundPage.title.ToLower().Contains("not found"))
            {
                Response.Write(foundPage.content);
            }
            else
            {
                var pathToMasterPage = AppDomain.CurrentDomain.BaseDirectory + foundPage.masterPage;
                if (System.IO.File.Exists(pathToMasterPage))
                {
                    var sr       = new System.IO.StreamReader(pathToMasterPage);
                    var template = sr.ReadToEnd();
                    sr.Close();

                    var q = new StringTemplate(template);
                    q.SetAttribute("show_search_results", true);
                    q.SetAttribute("year", DateTime.Now.Year);
                    q.SetAttribute("title", foundPage.title);
                    q.SetAttribute("content", foundPage.content);

                    Response.Write(q.ToString());
                }
                else
                {
                    Response.Write(foundPage.content);
                }
            }
        }
Example #37
0
        /// <summary>
        /// Uloží ze šablony vygenerovaný HTML dokument do výstupního souboru na zadané cestě.
        /// </summary>
        /// <param name="stringTemplate">vyplněná šablona</param>
        /// <param name="htmlPath">cesta k dokumentu</param>
        /// <returns>obsah HTML dokumentu nebo NULL v případě zápisu do souboru</returns>
        protected string SaveHtmlDocument(StringTemplate stringTemplate, string htmlPath)
        {
            string html = stringTemplate.ToString();

            // vrácení hotového HTML dokumentu, pokud nebyl zadán výstupní soubor
            if (string.IsNullOrWhiteSpace(htmlPath))
            {
                return(html);
            }

            try
            {
                // zápis HTML do souboru
                File.WriteAllText(Path.GetFullPath(htmlPath), html);
            }
            catch (Exception e)
            {
                throw new PublicationException("Chyba při zápisu výstupního HTML dokumentu: " + e.Message);
            }

            return(null);
        }
Example #38
0
 public void TestTemplateApplicationAsOptionValue()
 {
     StringTemplate st = new StringTemplate(
             "Tokens : <rules; separator=names:{<it>}> ;",
             typeof( AngleBracketTemplateLexer ) );
     st.SetAttribute( "rules", "A" );
     st.SetAttribute( "rules", "B" );
     st.SetAttribute( "names", "Ter" );
     st.SetAttribute( "names", "Tom" );
     string expecting = "Tokens : ATerTomB ;";
     Assert.AreEqual( expecting, st.ToString() );
 }
 private string GetTemplate(string templateSlug)
 {
     var template = new StringTemplate(_contentRepository.Get(templateSlug, "email-template").ContentText);
     return template.ToString();
 }
Example #40
0
 public void TestTemplateApplicationAsRHSOfAssignment()
 {
     StringTemplateGroup group = new StringTemplateGroup( "test" );
     StringTemplate hostname = group.DefineTemplate( "hostname", "$machine$.jguru.com" );
     StringTemplate bold = group.DefineTemplate( "bold", "<b>$x$</b>" );
     StringTemplate italics = group.DefineTemplate( "italics", "<i>$it$</i>" );
     StringTemplate t = new StringTemplate( group, "$bold(x=hostname(machine=\"www\"):italics())$" );
     string expecting = "<b><i>www.jguru.com</i></b>";
     Assert.AreEqual( expecting, t.ToString() );
 }
Example #41
0
 public void TestTemplateNameExpression()
 {
     StringTemplateGroup group =
             new StringTemplateGroup( "test" );
     StringTemplate foo = group.DefineTemplate( "foo", "hi there!" );
     StringTemplate t = new StringTemplate( group, "$(name)()$" );
     t.SetAttribute( "name", "foo" );
     //System.out.println(t);
     string expecting = "hi there!";
     Assert.AreEqual( expecting, t.ToString() );
 }
Example #42
0
 public void TestCatWithTemplateApplicationAsElement()
 {
     StringTemplate e = new StringTemplate(
             "$[names:{$it$!},phones]; separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "names", "Ter" );
     e.SetAttribute( "names", "Tom" );
     e.SetAttribute( "phones", "1" );
     e.SetAttribute( "phones", "2" );
     string expecting = "Ter!, Tom!, 1, 2";
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #43
0
        public void TestUnicodeLiterals()
        {
            StringTemplate st = new StringTemplate(
                    "Foo <\\uFEA5\\n\\u00C2> bar" + newline,
                    typeof( AngleBracketTemplateLexer )
                    );
            string expecting = "Foo \xfea5" + newline + "\x00C2 bar" + newline;
            string result = st.ToString();
            Assert.AreEqual( expecting, result );

            st = new StringTemplate(
                    "Foo $\\uFEA5\\n\\u00C2$ bar" + newline );
            expecting = "Foo \xfea5" + newline + "\x00C2 bar" + newline;
            result = st.ToString();
            Assert.AreEqual( expecting, result );

            st = new StringTemplate(
                    "Foo$\\ $bar$\\n$" );
            expecting = "Foo bar" + newline;
            result = st.ToString();
            Assert.AreEqual( expecting, result );
        }
Example #44
0
        public void TestFirstWithListOfMaps2()
        {
            StringTemplate e = new StringTemplate(
                    "$first(maps):{ m | $m.Ter$ }$"
                );
            IDictionary m1 = new Dictionary<object, object>();
            IDictionary m2 = new Dictionary<object, object>();
            m1.Add( "Ter", "x5707" );
            e.SetAttribute( "maps", m1 );
            m2.Add( "Tom", "x5332" );
            e.SetAttribute( "maps", m2 );
            string expecting = "x5707";
            Assert.AreEqual( expecting, e.ToString() );

            e = e.GetInstanceOf();
            IList list = new List<object>() { m1, m2 };
            e.SetAttribute( "maps", list );
            expecting = "x5707";
            Assert.AreEqual( expecting, e.ToString() );
        }
Example #45
0
 public void TestCatListAndSingleAttribute()
 {
     // replace first of yours with first of mine
     StringTemplate e = new StringTemplate(
             "$[mine,yours]; separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "mine", "1" );
     e.SetAttribute( "mine", "2" );
     e.SetAttribute( "mine", "3" );
     e.SetAttribute( "yours", "a" );
     string expecting = "1, 2, 3, a";
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #46
0
 public void TestCatWithIFAsElement()
 {
     StringTemplate e = new StringTemplate(
             "$[{$if(names)$doh$endif$},phones]; separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "names", "Ter" );
     e.SetAttribute( "names", "Tom" );
     e.SetAttribute( "phones", "1" );
     e.SetAttribute( "phones", "2" );
     string expecting = "doh, 1, 2";
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #47
0
 public void TestCombinedOp()
 {
     // replace first of yours with first of mine
     StringTemplate e = new StringTemplate(
             "$[first(mine),rest(yours)]; separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "mine", "1" );
     e.SetAttribute( "mine", "2" );
     e.SetAttribute( "mine", "3" );
     e.SetAttribute( "yours", "a" );
     e.SetAttribute( "yours", "b" );
     string expecting = "1, b";
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #48
0
 public void TestCollectionAttributes()
 {
     StringTemplateGroup group =
             new StringTemplateGroup( "test" );
     StringTemplate bold = group.DefineTemplate( "bold", "<b>$it$</b>" );
     StringTemplate t =
         new StringTemplate( group, "$data$, $data:bold()$, " +
                                   "$list:bold():bold()$, $array$, $a2$, $a3$, $a4$" );
     List<object> v = new List<object>();
     v.Add( "1" );
     v.Add( "2" );
     v.Add( "3" );
     IList list = new List<object>();
     list.Add( "a" );
     list.Add( "b" );
     list.Add( "c" );
     t.SetAttribute( "data", v );
     t.SetAttribute( "list", list );
     t.SetAttribute( "array", new string[] { "x", "y" } );
     t.SetAttribute( "a2", new int[] { 10, 20 } );
     t.SetAttribute( "a3", new float[] { 1.2f, 1.3f } );
     t.SetAttribute( "a4", new double[] { 8.7, 9.2 } );
     //System.out.println(t);
     string expecting = "123, <b>1</b><b>2</b><b>3</b>, " +
         "<b><b>a</b></b><b><b>b</b></b><b><b>c</b></b>, xy, 1020, 1.21.3, 8.79.2";
     Assert.AreEqual( expecting, t.ToString() );
 }
Example #49
0
 public void TestChangingAttrValueTemplateApplicationToVector()
 {
     StringTemplateGroup group =
             new StringTemplateGroup( "test" );
     StringTemplate bold = group.DefineTemplate( "bold", "<b>$x$</b>" );
     StringTemplate t = new StringTemplate( group, "$names:bold(x=it)$" );
     t.SetAttribute( "names", "Terence" );
     t.SetAttribute( "names", "Tom" );
     //System.out.println("'"+t.toString()+"'");
     string expecting = "<b>Terence</b><b>Tom</b>";
     Assert.AreEqual( expecting, t.ToString() );
 }
Example #50
0
 public void TestChangingAttrValueRepeatedTemplateApplicationToVector()
 {
     StringTemplateGroup group = new StringTemplateGroup( "dummy", "." );
     StringTemplate bold = group.DefineTemplate( "bold", "<b>$item$</b>" );
     StringTemplate italics = group.DefineTemplate( "italics", "<i>$it$</i>" );
     StringTemplate members = new StringTemplate( group, "$members:bold(item=it):italics(it=it)$" );
     members.SetAttribute( "members", "Jim" );
     members.SetAttribute( "members", "Mike" );
     members.SetAttribute( "members", "Ashar" );
     //System.out.println("members="+members);
     string expecting = "<i><b>Jim</b></i><i><b>Mike</b></i><i><b>Ashar</b></i>";
     Assert.AreEqual( expecting, members.ToString() );
 }
Example #51
0
 public void TestCatListAndEmptyAttributes()
 {
     // + is overloaded to be cat strings and cat lists so the
     // two operands (from left to right) determine which way it
     // goes.  In this case, x+mine is a list so everything from their
     // to the right becomes list cat.
     StringTemplate e = new StringTemplate(
             "$[x,mine,y,yours,z]; separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "mine", "1" );
     e.SetAttribute( "mine", "2" );
     e.SetAttribute( "mine", "3" );
     e.SetAttribute( "yours", "a" );
     string expecting = "1, 2, 3, a";
     Assert.AreEqual( expecting, e.ToString() );
 }
 public string CleanJSON(StringTemplate json)
 {
     return Regex.Replace(json.ToString(), @",(\s*)([\},\]])", @"$1$2", RegexOptions.Multiline);
 }
Example #53
0
        public void ProxiedObjectsHandled()
        {
            StringTemplate template = new StringTemplate("Testing $person.Name$");

            ProxyGenerator generator = new ProxyGenerator();
            object person = generator.CreateClassProxy(typeof(Person), new NothingInterceptor(), new object[] { "Sean" });

            template.SetAttribute("person", person);

            string result = template.ToString();

            Assert.AreEqual("Testing Sean", result);
        }
Example #54
0
 public void TestCatWithNullTemplateApplicationAsElement()
 {
     StringTemplate e = new StringTemplate(
             "$[names:{$it$!},\"foo\"]:{x}; separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "phones", "1" );
     e.SetAttribute( "phones", "2" );
     string expecting = "x";  // only one since template application gives nothing
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #55
0
 private string RenderEmail(Customer customer, State state)
 {
     string path = string.Format("template/{0}.txt", state.name);
     string content = File.ReadAllText(path);
     StringTemplate tmpl = new StringTemplate(content);
     tmpl.SetAttribute("NAME", customer.name);
     tmpl.SetAttribute("DATE", customer.update_on.ToShortDateString());
     return tmpl.ToString();
 }
Example #56
0
 public void TestTruncOp()
 {
     StringTemplate e = new StringTemplate(
             "$trunc(names); separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "names", "Ter" );
     e.SetAttribute( "names", "Tom" );
     e.SetAttribute( "names", "Sriram" );
     string expecting = "Ter, Tom";
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #57
0
 public void TestCat2AttributesWithApply()
 {
     StringTemplate e = new StringTemplate(
             "$[names,phones]:{a|$a$.}$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "names", "Ter" );
     e.SetAttribute( "names", "Tom" );
     e.SetAttribute( "phones", "1" );
     e.SetAttribute( "phones", "2" );
     string expecting = "Ter.Tom.1.2.";
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #58
0
 public void TestAttributeRefButtedUpAgainstEndifAndWhitespace()
 {
     StringTemplateGroup group =
             new StringTemplateGroup( "test" );
     StringTemplate a = new StringTemplate( group,
                                           "$if (!firstName)$$email$$endif$" );
     a.SetAttribute( "email", "*****@*****.**" );
     string expecting = "*****@*****.**";
     Assert.AreEqual( a.ToString(), expecting );
 }
Example #59
0
 // Removes trailing commas from JSON files, so that it can be parsed by JSON.parse() on JS side
 public static string CleanJSON(StringTemplate st)
 {
     return Regex.Replace (st.ToString(), @",(\s*)[\},\]]", @"$1}", RegexOptions.Multiline);
 }
Example #60
0
 public void TestCat3Attributes()
 {
     StringTemplate e = new StringTemplate(
             "$[names,phones,salaries]; separator=\", \"$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "names", "Ter" );
     e.SetAttribute( "names", "Tom" );
     e.SetAttribute( "phones", "1" );
     e.SetAttribute( "phones", "2" );
     e.SetAttribute( "salaries", "big" );
     e.SetAttribute( "salaries", "huge" );
     string expecting = "Ter, Tom, 1, 2, big, huge";
     Assert.AreEqual( expecting, e.ToString() );
 }