public static string GenerateArtifact(string resource, object data) { TemplatingHost host = null; try { var contents = GetTemplateResource(resource); var path = Path.ChangeExtension(Path.GetTempFileName(), "txt"); File.WriteAllText(path, contents); host = new TemplatingHost(path, data); var result = new Engine().ProcessTemplate(contents, host); if (host.Errors.Cast<CompilerError>().Where(c => !c.IsWarning).Count() > 0) { throw new Exception(); } return result; } catch { if (host != null) { var sb = new StringBuilder(); foreach (CompilerError error in host.Errors) { sb.AppendLine(error.ErrorText); } throw new Exception(sb.ToString()); } else { throw; } } }
private void GoButton_Click(object sender, EventArgs e) { CustomCmdLineHost host = new CustomCmdLineHost(); var session = new TextTemplatingSession(); string templateFileName = TemplateList.SelectedItem.ToString(); var sessionHost = (ITextTemplatingSessionHost)host; sessionHost.Session = session; foreach (string tableName in TableList.CheckedItems) { sessionHost.Session["tableName"] = tableName; //// Pass another value in CallContext: System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("p2", "test"); Engine engine = new Engine(); host.TemplateFileValue = templateFileName; //Read the text template. string input = File.ReadAllText(templateFileName); //Transform the text template. string output = engine.ProcessTemplate(input, host); string outputFileName = tableName; outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName); outputFileName = outputFileName + "1" + host.FileExtension; File.WriteAllText(outputFileName, output, host.FileEncoding); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ToString()); } } Console.ReadLine(); }
public override void ExecuteProfile(Parser parser) { string file = Path.Combine(Program.Configuration.Output, OutPutPath, GetRelativePath(parser.Filename), Path.GetFileNameWithoutExtension(parser.Filename)); string moduleFile = parser.Fields.Where(entry => entry.Name == "MODULE").Select(entry => entry.Value).SingleOrDefault(); var engine = new Engine(); var host = new TemplateHost(TemplatePath); host.Session["Parser"] = parser; host.Session["Profile"] = this; string output = engine.ProcessTemplate(File.ReadAllText(TemplatePath), host); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ErrorText); } if (host.Errors.Count > 0) Program.Shutdown(); File.WriteAllText(file + host.FileExtension, output); Console.WriteLine("Wrote {0}", file + host.FileExtension); }
public override void ExecuteProfile(Parser parser) { string file = Path.Combine(Program.Configuration.Output, OutPutPath, GetRelativePath(parser.Filename), Path.GetFileNameWithoutExtension(parser.Filename)); var xmlMessage = Program.Configuration.XmlMessagesProfile.SearchXmlPattern(Path.GetFileNameWithoutExtension(parser.Filename)); if (xmlMessage == null) Program.Shutdown(string.Format("File {0} not found", file)); var engine = new Engine(); var host = new TemplateHost(TemplatePath); host.Session["Message"] = xmlMessage; host.Session["Profile"] = this; var output = engine.ProcessTemplate(File.ReadAllText(TemplatePath), host); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ErrorText); } if (host.Errors.Count > 0) Program.Shutdown(); File.WriteAllText(file + host.FileExtension, output); Console.WriteLine("Wrote {0}", file); }
public string BuildCode(string key, object entity) { TextEngineHost host = new TextEngineHost(); host.TemplateFileValue = this.getFilePath(key); host.Session = new TextTemplatingSession(); host.Session.Add("entity", entity); string tpl = this.getTpl(key); string output = new Engine().ProcessTemplate(tpl, host); if (host.Errors.Count > 0) { StringBuilder errorWarn = new StringBuilder(); foreach (CompilerError error in host.Errors) { errorWarn.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ------------------")).Append(error.Line).Append(":").AppendLine(error.ErrorText); } if (!File.Exists("Error.log")) { File.Create("Error.log"); } StreamWriter sw = new StreamWriter("Error.log", true); sw.Write(errorWarn.ToString()); sw.Close(); } return output; }
public CPlusPlusGenerator() { m_textEngine = new Engine(); m_textHost = new CPlusPlusTemplateHost(); m_textHost.Generator = this; Mapper.CreateMap<string, ReferencedType>().ConstructUsing(GetCPlusPlusType); }
static Program() { s_listAssemblies = new List<string>(new [] { c_strMainModule }); s_listTemplates = new List<string>(); s_textEngine = new Engine(); s_textHost = new WrapperTemplateHost(); s_outputPath = Path.Combine(Directory.GetCurrentDirectory(), "../../include/Generated"); }
private static ITextTemplatingEngine GetEngine() { var engine = new Microsoft.VisualStudio.TextTemplating.Engine(); return(engine); //var textTemplating = (ITextTemplatingComponents)Package.GetGlobalService(typeof(STextTemplating)); //return textTemplating.Engine; }
public string GetTemplateContent(string templateName, TextTemplatingSession session) { string fullName = this.Host.ResolvePath(templateName); string templateContent = File.ReadAllText(fullName); var sessionHost = this.Host as ITextTemplatingSessionHost; sessionHost.Session = session; var engine = new Microsoft.VisualStudio.TextTemplating.Engine(); return(engine.ProcessTemplate(templateContent, this.Host)); }
public string GetTemplateContent(string templateName, TextTemplatingSession session) { string fullName = Host.ResolvePath(templateName); string templateContent = File.ReadAllText(fullName); var sessionHost = Host as ITextTemplatingSessionHost; sessionHost.Session = session; Engine engine = new Engine(); return(engine.ProcessTemplate(templateContent, Host)); }
void Exec() { //var arguments = new Dictionary<string, PropertyData>(); //arguments.Add("ClassName", new PropertyData("MyClass", typeof(string))); //arguments.Add("TargetNamespace", new PropertyData("MyNameSpace", typeof(string))); //arguments.Add("HelloMessage", new PropertyData("HelloMessage", typeof(string))); //// Initialize GAX template host //string currentDirectory = Directory.GetCurrentDirectory(); //TemplateHost host = new TemplateHost(currentDirectory, arguments); //host.TemplateFile = Path.Combine(currentDirectory, "ServiceTemplate.tt"); // Transform template //string template = File.ReadAllText(host.TemplateFile); //ITextTemplatingEngine engine = new Engine(); //string output = engine.ProcessTemplate(template, host); //// Save output //string outputFile = Path.ChangeExtension(host.TemplateFile, ".txt"); //File.WriteAllText(outputFile, output); //TextTemplate tt = new TextTemplate(); //tt.Source = "... code here, check example file above ..."; //tt.Compile(); //String output = tt.Generate(singleObjectParameter); CustomCmdLineHost host = new CustomCmdLineHost(); host.TemplateFileValue = templateFileName; Engine engine = new Engine(); //read the text template string input = File.ReadAllText(templateFileName); //transform the text template string output = engine.ProcessTemplate(input, host); string outputFileName = Path.GetFileNameWithoutExtension(templateFileName); outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName); outputFileName = outputFileName + "1" + host.FileExtension; }
public static bool FormatedTemplate(string Modulepath, Dictionary <string, object> paraList, ref string outputCode) { try { // TODO: Implement Functionality Here CSTemplatingEngineHost host = new CSTemplatingEngineHost(); Microsoft.VisualStudio.TextTemplating.Engine engine = new Microsoft.VisualStudio.TextTemplating.Engine(); #region 这里的设置是为了动态的传递参数使用的 host.Session = new Microsoft.VisualStudio.TextTemplating.TextTemplatingSession(); // host.Session.Add("content", "世界你好"); foreach (var item in paraList) { host.Session.Add(item.Key, item.Value); } #endregion //获取当前路径 string path2 = System.Environment.CurrentDirectory; host.TemplateFileValue = "sample.tt"; string templateContent = System.IO.File.ReadAllText(Modulepath); outputCode = engine.ProcessTemplate(templateContent, host); Console.WriteLine(outputCode); string errorInfo = string.Empty; foreach (var element in host.Errors) { errorInfo += element.ToString() + "\r\n"; } if (!string.IsNullOrEmpty(errorInfo)) { outputCode = errorInfo; return(false); } return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(false); //Console.Write("Press any key to continue . . . "); //Console.ReadKey(true); }
static void ProcessTemplate(params string[] args) { string templateFileName = null; if (args.Length == 0) { throw new System.Exception("you must provide a text template file path"); } templateFileName = args[0]; if (templateFileName == null) { throw new ArgumentNullException("the file name cannot be null"); } if (!File.Exists(templateFileName)) { throw new FileNotFoundException("the file cannot be found"); } CustomCmdLineHost host = new CustomCmdLineHost(); Engine engine = new Engine(); host.TemplateFileValue = templateFileName; //Read the text template. string input = File.ReadAllText(templateFileName); input = input.Replace(@"$(ProjectDir)\", ""); //Transform the text template. string output = engine.ProcessTemplate(input, host); string outputFileName = Path.GetFileNameWithoutExtension(templateFileName); outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName); outputFileName = outputFileName + "1" + host.FileExtension; File.WriteAllText(outputFileName, output, host.FileEncoding); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ToString()); } }
public CompiledTemplate CompileTemplate (string content) { if (String.IsNullOrEmpty (content)) throw new ArgumentNullException ("content"); errors.Clear (); encoding = Encoding.UTF8; AppDomain appdomain = ProvideTemplatingAppDomain (content); TemplatingEngine engine; if (appdomain != null) { engine = (TemplatingEngine) appdomain.CreateInstanceAndUnwrap (typeof (TemplatingEngine).Assembly.FullName, typeof (TemplatingEngine).FullName); } else { engine = new TemplatingEngine (); } return engine.CompileTemplate (content, this); }
public void InvokeHostWithModel() { Engine engine = new Engine(); Store store = new Store(typeof(MockDomainModel)); MockDomainModel domainModel = GetModel(store); using (Transaction t = store.TransactionManager.BeginTransaction()) { ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition,string.Empty); TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel,null); string templateContent = GetStandardTemplateHeader() + @" <#= this.Model.DomainModelInfo.Id #>"; string transformResult = engine.ProcessTemplate( templateContent, host); Assert.AreEqual(domainModel.DomainModelInfo.Id, new Guid(transformResult)); t.Rollback(); } }
public static void GenerateFileAsDefault(ITextTemplatingEngineHost host, string templateFilePath, string outputFileName) { Assembly myAssembly = Assembly.GetExecutingAssembly(); Stream myStream = myAssembly.GetManifestResourceStream(templateFilePath); if (myStream != null) { StreamReader reader = new StreamReader(myStream); string text = reader.ReadToEnd(); Engine engine = new Engine(); // use the engine to transfor the template string output = engine.ProcessTemplate(text, host); File.WriteAllText(outputFileName, output, Encoding.UTF8); } //throw new Exception("Wrong template file path"); }
string GetFileName(ClassMapping clazz) { var T4 = new Microsoft.VisualStudio.TextTemplating.Engine(); var host = new CustomHost() { TemplateFile = "config" , Logger = log }; CallContext.LogicalSetData("clazz", clazz); string fileName = T4.ProcessTemplate(GetTemplateForOutputName() , host ).Trim(); if (host.HasError) { throw new Exception(); // errors are logged by the engine } return(fileName); }
static string ProcessTemplate(string exampleTemplateName, DynamicViewModel model) { var templateQualifiedFileName = ExampleTemplates.GetPath(exampleTemplateName); if (!File.Exists(templateQualifiedFileName)) throw new FileNotFoundException("File not found: " + exampleTemplateName); // Read the text template. string input = File.ReadAllText(templateQualifiedFileName); // Transform the text template. using (var host = new DynamicTextTemplatingEngineHost { TemplateFile = templateQualifiedFileName, Model = model }) { string output = new Engine().ProcessTemplate(input, host); if (host.Errors.HasErrors) throw new TemplateProcessingErrorException(host.Errors); return output; } }
public void CanAddProjectReference() { Engine engine = new Engine(); Store store = new Store(typeof(MockDomainModel)); MockDomainModel domainModel = GetModel(store); using (Transaction t = store.TransactionManager.BeginTransaction()) { ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, "test"); serviceModel.ObjectExtender = new MockObjectExtender(); TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, serviceModel); host.StandardAssemblyReferences.Add(typeof(Microsoft.Practices.Modeling.ExtensionProvider.Extension.ObjectExtender<ExtensibleMockModelElement>).Assembly.FullName); string transformResult = engine.ProcessTemplate( GetStandardTemplateHeader() + @" <# AddProjectReference(CurrentExtender.ArtifactLink); #>", host); Assert.AreEqual(1, host.ProjectReferences.Count); t.Rollback(); } }
public static string CreateEntityClass(EntityClassInfo classInfo,string templatePath) { CustomTextTemplatingEngineHost host = new CustomTextTemplatingEngineHost(); host.TemplateFileValue = templatePath; string input = File.ReadAllText(templatePath); host.Session = new TextTemplatingSession(); host.Session.Add("entity", classInfo); string output = new Engine().ProcessTemplate(input, host); StringBuilder errorWarn = new StringBuilder(); foreach (CompilerError error in host.Errors) { errorWarn.Append(error.Line).Append(":").AppendLine(error.ErrorText); } if (!File.Exists("Error.log")) { File.Create("Error.log"); } File.WriteAllText("Error.log", errorWarn.ToString()); return output; }
public static string CreateDataAccessClass(EntityClassInfo classInfo) { string templatePath = string.Empty; try { templatePath = System.Configuration.ConfigurationManager.AppSettings["TemplateDataAccess"].ToString(); } catch (Exception ex) { //MessageBox.Show("读取配置文件错误!TemplateDataAccess" + ex.Message); return null; } if (!File.Exists(templatePath)) { //MessageBox.Show("未找到DataAccess.tt,请修改配置文件!"); return null; } CustomTextTemplatingEngineHost host = new CustomTextTemplatingEngineHost(); host.TemplateFileValue = templatePath; string input = File.ReadAllText(templatePath); host.Session = new TextTemplatingSession(); host.Session.Add("entity", classInfo); string output = new Engine().ProcessTemplate(input, host); StringBuilder errorWarn = new StringBuilder(); foreach (CompilerError error in host.Errors) { errorWarn.Append(error.Line).Append(":").AppendLine(error.ErrorText); } if (!File.Exists("Error.log")) { File.Create("Error.log"); } File.WriteAllText("Error.log", errorWarn.ToString()); return output; }
public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter writer) { Microsoft.VisualStudio.TextTemplating.Engine T4; CallContext.LogicalSetData("clazz", classMapping); CallContext.LogicalSetData("savedToClass", savedToClass); CallContext.LogicalSetData("class2classmap", class2classmap); T4 = new Microsoft.VisualStudio.TextTemplating.Engine(); string res = T4.ProcessTemplate(CustomHost.GetTemplateCode(template) , new CustomHost() { TemplateFile = template , Logger = log } ); log.Debug("Generated File:\n" + res); writer.Write(res); writer.Flush(); if (writer.BaseStream is FileStream) { log.Info("Flushed file:" + (writer.BaseStream as FileStream).Name); } }
private void GenerateOutput(string templateFileName, System.Collections.IList tables) { var host = new T4Host(); var session = new TextTemplatingSession(); var sessionHost = (ITextTemplatingSessionHost)host; sessionHost.Session = session; foreach (Table table in tables) { LogUpdate("Processing table {0}", table.Name); sessionHost.Session["table"] = new SqlTable { Name = table.Name, Schema = table.Schema }; sessionHost.Session["tableName"] = table.Name; sessionHost.Session["namespace"] = NamespaceParameter.Text; //// Pass another value in CallContext: System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("p2", "test"); Engine engine = new Engine(); host.TemplateFile = templateFileName; //Read the text template. string input = File.ReadAllText(templateFileName); //Transform the text template. string output = engine.ProcessTemplate(input, host); string outputFileName = table.Name; outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName) ?? "", outputFileName); outputFileName = outputFileName + "1" + host.FileExtension; File.WriteAllText(outputFileName, output, host.FileEncoding); LogUpdate("Saved to file {0}", outputFileName); StringBuilder sb = new StringBuilder(); foreach (CompilerError error in host.Errors) { sb.AppendLine(error.ToString()); } if (sb.Length > 0) LogUpdate( "Errors: " + sb.ToString()); } LogUpdate("Done."); }
static CompilerErrorCollection ProcessTemplate(string args, string schema, string table) { string templateFileName = null; if (args == null) { throw new Exception("you must provide a text template file path"); } templateFileName = args; if (templateFileName == null) { throw new ArgumentNullException("the file name cannot be null"); } if (!File.Exists(templateFileName)) { throw new FileNotFoundException("the file cannot be found"); } SQLViewsHost host = new SQLViewsHost(); Engine engine = new Engine(); host.TemplateFileValue = templateFileName; //Read the text template. TextTemplatingSession session = new TextTemplatingSession(); session["SchemaName"] = schema; session["TableName"] = table; session["ViewName"] = String.Format("v{0}", table); session["Username"] = "******"; var sessionHost = (ITextTemplatingSessionHost)host; sessionHost.Session = session; string input = File.ReadAllText(templateFileName); //Transform the text template. string output = engine.ProcessTemplate(input, host); string outputFileName = Path.GetFileNameWithoutExtension(String.Format("v{0}", table)); outputFileName = Path.Combine(Path.GetDirectoryName(String.Format("v{0}", table)), outputFileName); outputFileName = outputFileName + host.FileExtension; File.WriteAllText(outputFileName, output, host.FileEncoding); return host.Errors; }
private void GenerateFile(ThreadStateObject threadStateObject) { try { SetLabelText(string.Format("正在生成 {0} ", threadStateObject.TemplateName.ToString()), threadStateObject.LblTip); string templateFolder = string.Format(@"{0}\Templates\", Environment.CurrentDirectory); TextTemplatingSession session = new TextTemplatingSession(); session.Add("t4Parameter", T4Parameters.Default); CustomCmdLineHost host = new CustomCmdLineHost(); host.TemplateFileValue = threadStateObject.TemplateName.ToString(); host.Session = session; Engine engine = new Engine(); //Read the text template. string input = File.ReadAllText(templateFolder + threadStateObject.TemplateName); input = input.Replace(@"$(ProjectDir)\", ""); //Transform the text template. string output = engine.ProcessTemplate(input, host); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ToString()); } } catch { } lock (synObj) { taskFinishedCount = taskFinishedCount + 1; } }
public static Encoding GetEncoding(string filePath) { if (filePath == null) { throw new ArgumentNullException("filePath"); } Encoding currentEncoding = Encoding.Default; if (!File.Exists(filePath)) { return(currentEncoding); } try { using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { if (stream.Length > 0) { using (StreamReader reader = new StreamReader(stream, true)) { char[] chArray = new char[1]; reader.Read(chArray, 0, 1); currentEncoding = reader.CurrentEncoding; reader.BaseStream.Position = 0; if (currentEncoding == Encoding.UTF8) { byte[] preamble = currentEncoding.GetPreamble(); if (stream.Length >= preamble.Length) { byte[] buffer = new byte[preamble.Length]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != preamble[i]) { currentEncoding = Encoding.Default; goto Label_00EF; } } } else { currentEncoding = Encoding.Default; } } } } } } catch (Exception exception) { if (Engine.IsCriticalException(exception)) { throw; } } Label_00EF: if (currentEncoding == null) { currentEncoding = Encoding.UTF8; } return(currentEncoding); }
private void btnGenerator_Click(object sender, EventArgs e) { //string conn = string.Format("Server={0}; Database={1}; User ID={2}; Password={3};", txtServerName.Text, txtDatatName.Text, txtUsername.Text, txtPwd.Text); //var list = ABPGenerator.Common.DapperHelper.GetField(conn, this.cmbDb.Text); try { var _fileName = this.cmbDb.Text.Replace("Tb", ""); CustomTextTemplatingEngineHost host = new CustomTextTemplatingEngineHost(); host.Session = new TextTemplatingSession(); host.Session.Add("classname", _fileName); host.Session.Add("lowername", _fileName.ToLower()); host.Session.Add("permissionName", txtPermissionName.Text.Trim()); //文件保存地址 string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string _save_path = dir + "/" + _fileName + "s"; string _dto_path = _save_path + "/Dto"; if (Directory.Exists(_dto_path) == false) { Directory.CreateDirectory(_dto_path); } string _controller_path = _save_path + "/Controller"; string _view_path = _save_path + "/Controller/Views/" + _fileName; if (cebView.Checked) { if (Directory.Exists(_controller_path) == false) { Directory.CreateDirectory(_controller_path); } if (Directory.Exists(_view_path) == false) { Directory.CreateDirectory(_view_path); } } //保存生成代码后的路径,可以根据实际项目需求修改 Dictionary <string, string> dicPath = new Dictionary <string, string>(); dicPath.Add("/WP.Application/Interface.tt", "/I" + _fileName + "AppService.cs"); //create input dicPath.Add("/WP.Application/EntityAppService.tt", "/" + _fileName + "AppService.cs"); //create input dicPath.Add("/WP.Application/CreateInput.tt", "/Dto/Create" + _fileName + "Input.cs"); //create input dicPath.Add("/WP.Application/Dto.tt", "/Dto/" + _fileName + "Dto.cs"); //Dto dicPath.Add("/WP.Application/GetInput.tt", "/Dto/Get" + _fileName + "Input.cs"); //GetInput dicPath.Add("/WP.Application/EditInput.tt", "/Dto/Edit" + _fileName + "Input.cs"); //EditInput /*Controller*/ if (cebView.Checked) { dicPath.Add("/WP.Web/Controller.tt", "/Controller/" + _fileName + "Controller.cs"); //Controller dicPath.Add("/WP.Web/Views/" + cmbTheme.Text + "/Index.tt", "/Controller/Views/" + _fileName + "/Index.cshtml"); dicPath.Add("/WP.Web/Views/" + cmbTheme.Text + "/Create.tt", "/Controller/Views/" + _fileName + "/Create.cshtml"); dicPath.Add("/WP.Web/Views/" + cmbTheme.Text + "/Edit.tt", "/Controller/Views/" + _fileName + "/Edit.cshtml"); } foreach (var item in dicPath) { #region var templatePath = System.Windows.Forms.Application.StartupPath + "/Template/" + item.Key; host.TemplateFileValue = templatePath; string input = System.IO.File.ReadAllText(templatePath); string output = new Microsoft.VisualStudio.TextTemplating.Engine().ProcessTemplate(input, host); System.IO.File.WriteAllText(_save_path + item.Value, output.TrimStart(), Encoding.UTF8); #endregion } MessageBox.Show("代码生成成功,已保存到桌面"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void TestMethod1() { var templateString = @" <#@ template debug=""false"" hostspecific=""false"" language=""C#"" #> <#@ parameter name=""Column"" type=""Kooboo.CMS.Content.Models.Column"" #> <input name=""{0}"" type=""{1}"" value=""<%= Model["" <#= Column.Name #>""] %>"" />"; Engine engine = new Engine(); var host = new CustomCmdLineHost(); host.Session = new TextTemplatingSession(); host.Session["Column"] = new Column() { Name = "Column1" }; string output = engine.ProcessTemplate(templateString, host); foreach (CompilerError item in host.Errors) { Console.WriteLine(item.ToString()); } Console.WriteLine(output); }
public void CanGetCSharpTypeOutput() { Engine engine = new Engine(); Store store = new Store(typeof(MockDomainModel)); MockDomainModel domainModel = GetModel(store); using (Transaction t = store.TransactionManager.BeginTransaction()) { ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty); TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null); string transformResult = engine.ProcessTemplate( GetStandardTemplateHeader() + @" <#= Utility.GetCSharpTypeOutput(""System.String"") #>", host); Assert.IsTrue(transformResult.Contains("string")); t.Rollback(); } }
public void InvokeHostSimpleTemplate() { Engine engine = new Engine(); string result = engine.ProcessTemplate("Hello World", new TextTemplateHost(null, null, null)); Assert.AreEqual("Hello World", result); }
private string IsValid(bool expectedValue) { Engine engine = new Engine(); Store store = new Store(typeof(MockDomainModel)); MockDomainModel domainModel = GetModel(store); using (Transaction t = store.TransactionManager.BeginTransaction()) { ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty); MockCodeGenerationService cgs = new MockCodeGenerationService(expectedValue); TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, serviceModel, cgs); string transformResult = engine.ProcessTemplate( GetStandardTemplateHeader().Replace("/n","") + @"<#= this.IsValid(CurrentElement.InvalidArtifactLink).ToString()#>", host); t.Rollback(); return transformResult.Trim(); } }
public void HostReturnsEmptyContentOnCancelOutput() { Engine engine = new Engine(); Store store = new Store(typeof(MockDomainModel)); MockDomainModel domainModel = GetModel(store); using (Transaction t = store.TransactionManager.BeginTransaction()) { ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty); TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null); string templateContent = GetStandardTemplateHeader() + @"<# CancelOutput(); #>"; string transformResult = engine.ProcessTemplate(templateContent, host); Assert.AreEqual<int>(0, host.CompilerErrors.Count); Assert.IsFalse(host.GenerateOutput); t.Rollback(); } }
private void ProcessTemplate(params string[] args) { string templateFileName = null; if (args.Length == 0) { throw new System.Exception("you must provide a text template file path"); } templateFileName = args[0]; if (templateFileName == null) { throw new ArgumentNullException("the file name cannot be null"); } if (!File.Exists(templateFileName)) { throw new FileNotFoundException("the file cannot be found"); } OnShowWorkInfoEventHandler(this, new WorkEventArgs(WorkStage.InitializeWork, string.Format("processing template: {0}", Path.GetFileName(templateFileName)))); TextTemplatingSession session = new TextTemplatingSession(); session.Add("t4Parameter", T4Parameters.Default); CustomCmdLineHost host = new CustomCmdLineHost(); host.TemplateFileValue = templateFileName; host.Session = session; Engine engine = new Engine(); //Read the text template. string input = File.ReadAllText(templateFileName); input = input.Replace(@"$(ProjectDir)\", ""); //Transform the text template. string output = engine.ProcessTemplate(input, host); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ToString()); } lock (synObject) { int prograssBarValue = OnGetValueEventHandler(this, null); prograssBarValue++; OnDoWorkEventHandler(this, new WorkEventArgs(WorkStage.DoWork, string.Format("{0} has been processed...", templateFileName), prograssBarValue){ TemplateName=Path.GetFileName(templateFileName)}); } }
private void DoBuild() { int finish = 0; int total = listBox2.Items.Count; //遍历选中的表,一张表对应生成一个代码文件 foreach (object item in listBox2.Items) { SOTable table = item as SOTable; string className = table.Name; if (cbDeleteTablePrifix.Checked)className = table.Name.RemovePrefix(tablePrefix, prefixLevel).Replace(" ", ""); if (cbClassNamePascal.Checked) className = className.InitialToUpperMulti(); if (cbClassNameRemovePlural.Checked) className = className.EndsWith("s") ? className.TrimEnd('s') : className.Trim(); if (cbAddSuffix.Checked) className = txtClassPrefix.Text.Trim() + className + txtClassSuffix.Text.Trim(); templateFile = gbTemplateFile.Text; List<SOColumn> columnList = table.ColumnList;//可能传入的是从PDObject对象转换过来的SODatabase对象 if (columnList == null || columnList.Count == 0) columnList = DbSchemaHelper.Instance.CurrentSchema.GetTableColumnList(table); //生成代码文件 TableHost host = new TableHost(); host.Table = table; host.ColumnList = columnList; host.TemplateFile = templateFile; host.SetValue("NameSpace", nameSpace); host.SetValue("ClassName", className); host.SetValue("TablePrefix", tablePrefix); //host.SetValue("ColumnPrefix", columnPrefix); host.SetValue("PrefixLevel", prefixLevel); Engine engine = new Engine(); string outputContent = engine.ProcessTemplate(File.ReadAllText(templateFile), host); //string outputFile = Path.Combine(outputPath, string.Format("{0}.cs", className)); string outputFile = Path.Combine(outputPath, string.Format("{0}{1}", table.Name, host.FileExtention)); if(cbClassNameIsFileName.Checked)outputFile = Path.Combine(outputPath, string.Format("{0}{1}", className, host.FileExtention)); StringBuilder sb = new StringBuilder(); if (host.ErrorCollection.HasErrors) { foreach (CompilerError err in host.ErrorCollection) { sb.AppendLine(err.ToString()); } outputContent = outputContent + Environment.NewLine + sb.ToString(); outputFile = outputFile + ".error"; } if (Directory.Exists(outputPath) == false) Directory.CreateDirectory(outputPath); File.WriteAllText(outputFile, outputContent, Encoding.UTF8); finish = finish + 1; int percent = ConvertUtil.ToInt32(finish * 100 / total, 0); backgroundWorker1.ReportProgress(percent, table); }//end build code foreach }
private Stream ExecuteT4Template(string templateContent, Dictionary<string, string> propertyBag) { var host = new CustomTemplateHost(); var engine = new Engine(); host.TemplateFileValue = "c:\\foo.t4"; //string input = templateContent; var session = host.CreateSession(); foreach (var property in propertyBag) { session.Add(property.Key, property.Value); } string output = engine.ProcessTemplate(templateContent, host); var stream = new MemoryStream(); var streamWriter = new StreamWriter(stream); streamWriter.Write(output); streamWriter.Flush(); stream.Position = 0L; if (!host.Errors.HasErrors) return stream; var exception = new T4TemplateException("T4 compilation error"); foreach (var error in host.Errors) { exception.AddError(error.ToString()); } throw exception; }
static Program() { s_textEngine = new Engine(); s_textHost = new WrapperTemplateHost(); s_outputPath = Path.Combine(Directory.GetCurrentDirectory(), "include/Talon"); s_listTemplates = new List<TemplateModel> { new TemplateModel { TemplateFile = "TalonHeaderFile.t4", ConcreteTemplateFile = "TalonConcreteHeaderFile.t4", OutputPath = "include/Talon", FileExtension = ".h" }, new TemplateModel { TemplateFile = "TalonSourceFile.t4", ConcreteTemplateFile = "TalonConcreteSourceFile.t4", OutputPath = "src/Talon", FileExtension = ".cpp" } }; // NOTE: The way the template generation works, there can only be one platform without a Conditional set, and it must be at the end of the list! s_filesForType = new Dictionary<ClassType, List<PlatformModel>>() { { ClassType.Platform, new List<PlatformModel>() { new PlatformModel { FullName = "Win32", ShortName = "Win32", Conditional = "TALON_WINDOWS" }, new PlatformModel { FullName = "Mac", ShortName = "Mac", Conditional = "TALON_MAC" }, } }, { ClassType.Graphics, new List<PlatformModel>() { new PlatformModel { FullName = "Direct3D11", ShortName = "D3D11", Conditional = "TALON_GRAPHICS == TALON_GRAPHICS_D3D11" }, new PlatformModel { FullName = "OpenGL", ShortName = "GL", Conditional = "TALON_GRAPHICS == TALON_GRAPHICS_OPENGL" }, } } }; }
public void HostReturnsWarningsFromLogCall() { Engine engine = new Engine(); Store store = new Store(typeof(MockDomainModel)); MockDomainModel domainModel = GetModel(store); const string LogMessage = "Message1"; const string LogTitle = "Title1"; using (Transaction t = store.TransactionManager.BeginTransaction()) { ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty); TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null); string transformResult = engine.ProcessTemplate( GetStandardTemplateHeader() + @" <# LogWarning(""" + LogMessage + @""",""" + LogTitle + @"""); #>", host); Assert.AreEqual<int>(1, host.CompilerErrors.Count); Assert.IsTrue(host.CompilerErrors[0].IsWarning); Assert.IsTrue(host.CompilerErrors[0].ErrorNumber.Contains(LogMessage), "Could not find expected error in compiler errors."); Assert.IsTrue(host.CompilerErrors[0].ErrorText.Contains(LogTitle), "Could not find expected error in compiler errors."); t.Rollback(); } }
public void HostReturnsErrorsInCollection() { Engine engine = new Engine(); Store store = new Store(typeof(MockDomainModel)); MockDomainModel domainModel = GetModel(store); using (Transaction t = store.TransactionManager.BeginTransaction()) { ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty); TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null); string transformResult = engine.ProcessTemplate( GetStandardTemplateHeader() + @" <# throw new global::System.Exception(""TestException""); #>", host); Assert.AreEqual<int>(2, host.CompilerErrors.Count); Assert.IsTrue(host.CompilerErrors[1].ErrorText.Contains("TestException"),"Could not find expected exception in compiler errors."); t.Rollback(); } }