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
        private void WriteHeaderFileContent(TextWriter writer, string suitePath)
        {
            Stream stream =
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    NewTestSuiteTemplateResourcePath);

            StringTemplateGroup templateGroup = new StringTemplateGroup(
                new StreamReader(stream), typeof(AngleBracketTemplateLexer));

            templateGroup.RegisterAttributeRenderer(typeof(string),
                                                    new NewTestSuiteStringRenderer(suitePath));

            StringTemplate template =
                templateGroup.GetInstanceOf("newSuiteFile");

            // Initialize the options that will be passed into the template.

            Hashtable options = new Hashtable();

            options["suiteName"]       = suiteName;
            options["superclass"]      = superclass;
            options["headerUnderTest"] = headerUnderTest.CanonicalName;
            options["createSetUp"]     = createSetUp;
            options["createTearDown"]  = createTearDown;

            template.SetAttribute("options", options);
            template.SetAttribute("testCases", new List <string>(stubNames));

            template.Write(new AutoIndentWriter(writer));
        }
Example #3
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 #4
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 #5
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 #6
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());
        }
        /// <inheritDoc/>
        public override string ExportPublicationToHtmlDocument(Publication publication, string templatePath, string htmlPath)
        {
            StringTemplate stringTemplate = LoadHtmlTemplate(publication, templatePath);

            TechnicalReport technicalReport = publication.TechnicalReport;

            stringTemplate.SetAttribute("address", technicalReport.Address);
            stringTemplate.SetAttribute("institution", technicalReport.Institution);
            stringTemplate.SetAttribute("number", technicalReport.Number);

            return(SaveHtmlDocument(stringTemplate, htmlPath));
        }
Example #8
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 #9
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 #10
0
        /// <inheritDoc/>
        public override string ExportPublicationToHtmlDocument(Publication publication, string templatePath, string htmlPath)
        {
            StringTemplate stringTemplate = LoadHtmlTemplate(publication, templatePath);

            QualificationThesis qualificationThesis = publication.QualificationThesis;

            stringTemplate.SetAttribute("address", qualificationThesis.Address);
            stringTemplate.SetAttribute("school", qualificationThesis.School);
            stringTemplate.SetAttribute("type", qualificationThesis.ThesisType == TYPE_MASTER_THESIS ?
                                        MastersThesisDescription : PhdThesisDescription);

            return(SaveHtmlDocument(stringTemplate, htmlPath));
        }
Example #11
0
        /// <inheritDoc/>
        public override string ExportPublicationToHtmlDocument(Publication publication, string templatePath, string htmlPath)
        {
            StringTemplate stringTemplate = LoadHtmlTemplate(publication, templatePath);

            JournalArticle journalArticle = publication.JournalArticle;

            stringTemplate.SetAttribute("journaltitle", journalArticle.JournalTitle);
            stringTemplate.SetAttribute("number", journalArticle.Number);
            stringTemplate.SetAttribute("pages", journalArticle.FromPage == journalArticle.ToPage ?
                                        (journalArticle.FromPage + "") :
                                        (journalArticle.FromPage + " - " + journalArticle.ToPage));
            stringTemplate.SetAttribute("identification", journalArticle.ISSN);

            return(SaveHtmlDocument(stringTemplate, htmlPath));
        }
Example #12
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 #13
0
        public static void AddAttributes(StringTemplate st, Dictionary <string, object> @params)
        {
            foreach (string key in @params.Keys)
            {
                object val = @params[key];
                if (val != null)
                {
                    if (val is string && String.IsNullOrEmpty(val as string))
                    {
                        continue;
                    }

                    /*
                     * if (val is ArrayList)
                     * {
                     *  //st.SetAttribute(key, (val as ArrayList).ToArray());
                     *  ArrayList al = val as ArrayList;
                     *  foreach (object o in al)
                     *      st.SetAttribute(key, o);
                     * }
                     * else
                     */
                    st.SetAttribute(key, val);
                }
            }
        }
Example #14
0
        public static string StringTemplate(string str, object data)
        {
            var template = new StringTemplate(str);

            template.SetAttribute("item", data);
            return(template.ToString());
        }
        /// <inheritDoc/>
        public override string ExportPublicationToHtmlDocument(Publication publication, string templatePath, string htmlPath)
        {
            StringTemplate stringTemplate = LoadHtmlTemplate(publication, templatePath);

            ConferenceArticle conferenceArticle = publication.ConferenceArticle;

            stringTemplate.SetAttribute("booktitle", conferenceArticle.BookTitle);
            stringTemplate.SetAttribute("address", conferenceArticle.Address);
            stringTemplate.SetAttribute("publisher", conferenceArticle.Publisher);
            stringTemplate.SetAttribute("pages", conferenceArticle.FromPage == conferenceArticle.ToPage ?
                                        (conferenceArticle.FromPage + "") :
                                        (conferenceArticle.FromPage + " - " + conferenceArticle.ToPage));
            stringTemplate.SetAttribute("identification", !string.IsNullOrEmpty(conferenceArticle.ISBN) ?
                                        ("ISBN " + conferenceArticle.ISBN) : ("ISSN" + conferenceArticle.ISSN));

            return(SaveHtmlDocument(stringTemplate, htmlPath));
        }
Example #16
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 #17
0
        public virtual void WriteLexerTestFile(string lexerName, bool debug)
        {
            StringTemplate outputFileST = GetLexerTestFileTemplate();

            outputFileST.SetAttribute("lexerName", lexerName);

            WriteTestFile(outputFileST.ToString());
        }
Example #18
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 #19
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 #20
0
 private static void SetAttribute(StringTemplate st, IDictionary <string, object> p)
 {
     if (p == null)
     {
         return;
     }
     foreach (KeyValuePair <string, object> kv in p)
     {
         st.SetAttribute(kv.Key, kv.Value);
     }
 }
Example #21
0
        /// <summary>
        /// Načte šablonu ze souboru na zadané cestě (nebo z výchozího souboru, pokud nebyla zadána)
        /// a vypíše do ní základní bibliografické údaje pro HTML export.
        /// </summary>
        /// <param name="publication">publikace</param>
        /// <param name="templatePath">cesta k šabloně</param>
        /// <returns>připravená šablona</returns>
        protected StringTemplate LoadHtmlTemplate(Publication publication, string templatePath)
        {
            string template = null;

            try
            {
                // načtení šablony ze zadaného souboru nebo z výchozí šablony
                string path = string.IsNullOrWhiteSpace(templatePath) ?
                              (DEFAULT_TEMPLATE_FOLDER_NAME + Path.DirectorySeparatorChar + DefaultTemplateFile + "." + DEFAULT_TEMPLATE_EXTENSION) :
                              templatePath;
                template = File.ReadAllText(Path.GetFullPath(path));
            }
            catch (Exception e)
            {
                throw new PublicationException("Chyba při čtení vstupního souboru šablony: " + e.Message);
            }

            // vyplnění základních údajů pro všechny typy publikací
            StringTemplate stringTemplate = new StringTemplate(template);

            stringTemplate.SetAttribute("id", publication.Id);
            stringTemplate.SetAttribute("title", publication.Title);
            stringTemplate.SetAttribute("authors", GenerateAuthorCitationString(publication));
            stringTemplate.SetAttribute("year", publication.Year);
            stringTemplate.SetAttribute("type", TypeDescription);
            stringTemplate.SetAttribute("text", publication.Text.Replace("\n", "<br/>"));

            return(stringTemplate);
        }
    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 #23
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 #24
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 #26
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 #27
0
        private string SetStringTemplate(List <ChangelogEntry> clEntries)
        {
            StringTemplate changeLog = new StringTemplate("$logEntry; separator=\"\\n\"$\r\nGenerated with Subversion Changelog Generator $currentVersion$\r\nCopyright © CharlieFirpo 2009 <*****@*****.**>");

            changeLog.SetAttribute("currentVersion", Program.AssemblyVersion);

            foreach (ChangelogEntry cle in clEntries)
            {
                if (cle.Msg.Count > 0)
                {
                    StringTemplate logEntry = m_ClGrp.GetInstanceOf("Templates/ChangeLog");
                    logEntry.SetAttribute("date", cle.Dates[0]);
                    logEntry.SetAttribute("version", cle.VersionString);
                    logEntry.SetAttribute("revisions", cle.Revisions);
                    logEntry.SetAttribute("msg", cle.Msg);
                    logEntry.SetAttribute("paths", cle.Paths);
                    logEntry.SetAttribute("authors", cle.Authors);
                    changeLog.SetAttribute("logEntry", logEntry);
                }
            }

            return(changeLog.ToString());
        }
Example #28
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);
        }
        public string GetPathDescriptions(int num)
        {
            StringTemplateGroup group = new StringTemplateGroup("myGroup", @".\Templet");
            StringTemplate      st    = group.GetInstanceOf("PathTemplate");

            st.SetAttribute("Number", num);
            int  i       = 0;
            bool isFirst = true;

            foreach (var vs in VariableStmts)
            {
                var    loc        = vs.Stmt.Locations.FirstOrDefault();
                string lineNumber = "";
                if (loc != null)
                {
                    if (vs.Variable.Location.SourceFileName == loc.SourceFileName)
                    {
                        lineNumber += loc.StartingLineNumber;
                    }
                }

                if (isFirst)
                {
                    if (vs.Variable.Name == "")
                    {
                        return("");
                    }
                    st.SetAttribute("rootVar", vs.Variable.Name);
                    isFirst = false;
                }
                st.SetAttribute("Variable", vs.Variable.Name + "(@line " + lineNumber + ")");
                //st.SetAttribute("Variable", System.Net.WebUtility.HtmlEncode(vs.Stmt.ToString().Replace(" . ", ".")) + "(@line " + lineNumber + ")" );
                i++;
            }
            return(("\n" + st.ToString()).Trim());
        }
Example #30
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 #33
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 #34
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 #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 static void AddAttributes(StringTemplate st, Dictionary<string, object> @params)
 {
     foreach(string key in @params.Keys) {
         object val = @params[key];
         if (val != null) {
             if (val is string && String.IsNullOrEmpty(val as string))
                 continue;
             /*
            if (val is ArrayList)
             {
                 //st.SetAttribute(key, (val as ArrayList).ToArray());
                 ArrayList al = val as ArrayList;
                 foreach (object o in al)
                     st.SetAttribute(key, o);
             }
             else
             */
                 st.SetAttribute(key, val);
         }
     }
 }
Example #37
0
 public void TestStripOpOfListWithNulls()
 {
     StringTemplate e = new StringTemplate(
             "$strip(data)$"
         );
     e = e.GetInstanceOf();
     IList data = new List<object>();
     data.Add( "Hi" );
     data.Add( null );
     data.Add( "mom" );
     data.Add( null );
     e.SetAttribute( "data", data );
     string expecting = "Himom"; // nulls are skipped
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #38
0
 public void TestStripOpOfSingleAlt()
 {
     StringTemplate e = new StringTemplate(
             "$strip(data)$"
         );
     e = e.GetInstanceOf();
     e.SetAttribute( "data", "hi" );
     string expecting = "hi"; // nulls are skipped
     Assert.AreEqual( expecting, e.ToString() );
 }
Example #39
0
        public void TestSubtemplatesAnchorToo()
        {
            String templates =
                    "group test;" + newline +
                    "array(values) ::= <<{ <values; anchor, separator=\", \"> }>>" + newline;
            StringTemplateGroup group =
                    new StringTemplateGroup( new StringReader( templates ) );

            StringTemplate x = new StringTemplate( group, "<\\n>{ <stuff; anchor, separator=\",\\n\"> }<\\n>" );
            x.SetAttribute( "stuff", "1" );
            x.SetAttribute( "stuff", "2" );
            x.SetAttribute( "stuff", "3" );
            StringTemplate a = group.GetInstanceOf( "array" );
            a.SetAttribute( "values", new object[] { "a", x, "b" } );
            String expecting =
                "{ a, " + newline +
                "  { 1," + newline +
                "    2," + newline +
                "    3 }" + newline +
                "  , b }";
            Assert.AreEqual( expecting, a.ToString( 40 ) );
        }
Example #40
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() );
 }
Example #41
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() );
 }
Example #42
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 #43
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 #44
0
        private void PrepareElementTypes(StringTemplate stringTemplate, ICollection<ITypeInfo> typeGenerationInfos)
        {
            stringTemplate.SetAttribute("namespace", BaseNamespace);

            foreach (ITypeInfo info in typeGenerationInfos)
            {
                stringTemplate.SetAttribute("types.{name,f}", nameConverter.ConvertTypeName(info.BaseName),"f  ");
            }
        }
Example #45
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 #46
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 #47
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 #48
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 #49
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 #50
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 #51
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 #52
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() );
 }
Example #53
0
        private void PrepareTreeElementTemplate(ITypeInfo typeGenerationInfo, StringTemplate stringTemplate, string baseName)
        {
            stringTemplate.SetAttribute("namespace", BaseNamespace);
            stringTemplate.SetAttribute("name", baseName);

            stringTemplate.SetAttribute("noemptybody", true);

            foreach (IAttributeInfo info in typeGenerationInfo.AttributesInfo)
            {
                stringTemplate.SetAttribute("attributes.{type,name,xmlName}", "IXmlAttribute", nameConverter.ConvertAttributeName(info.Name), info.Name);
            }

            int childRoleCount = 20;
            foreach (INestedElementInfo nestedElementInfo in typeGenerationInfo.NestedElementsInfo)
            {
                if (!nestedElementInfo.IsCollection)
                {
                    stringTemplate.SetAttribute("elements.{isCollection,type,name,role,xmlName}", false,nameConverter.ConvertTypeName(nestedElementInfo.Element.TypeInfo.BaseName),
                                                nameConverter.ConvertElementName(nestedElementInfo.Element.Name), childRoleCount++, nestedElementInfo.Element.Name);
                }
                else
                {
                    foreach (IElementInfo collectionElementInfo in nestedElementInfo.Elements)
                    {
                        string name = nameConverter.ConvertElementName(collectionElementInfo.Name);
                        name = pluralProvider.Plural(name);
                        stringTemplate.SetAttribute("elements.{isCollection,type,name,role,xmlName}", true, nameConverter.ConvertTypeName(collectionElementInfo.TypeInfo.BaseName),
                                                    name, childRoleCount++, collectionElementInfo.Name);
                    }
                }
            }

            stringTemplate.SetAttribute("attitional", ";;");
        }
Example #54
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 #55
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 #56
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 #57
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 #58
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() );
 }
 public virtual string ToString( bool showTemplatePatterns )
 {
     StringBuilder buf = new StringBuilder();
     buf.Append( "group " + Name + ";" + _newline );
     StringTemplate formalArgs = new StringTemplate( "$args;separator=\",\"$" );
     foreach ( var template in _templates.OrderBy( item => (string)item.Key ) )
     {
         string tname = template.Key;
         StringTemplate st = template.Value;
         if ( st != NOT_FOUND_ST )
         {
             formalArgs = formalArgs.GetInstanceOf();
             formalArgs.SetAttribute( "args", st.FormalArguments );
             buf.Append( tname + "(" + formalArgs + ")" );
             if ( showTemplatePatterns )
             {
                 buf.Append( " ::= <<" );
                 buf.Append( st.Template );
                 buf.Append( ">>" + _newline );
             }
             else
             {
                 buf.Append( _newline );
             }
         }
     }
     return buf.ToString();
 }
Example #60
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 );
 }