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(); }
private static void Main(string[] args) { var tableName = "Product"; var templateFileName = $@"{AppDomain.CurrentDomain.BaseDirectory}GenerateCode.tt"; var param = new TextTemplatingSession { { "tableName", tableName }, { "varTableName", tableName.ToLower().First() + tableName.Substring(1) } }; var host = new CustomCmdLineHost { TemplateFileValue = "test.tt" }; var engine = new Engine(); var input = File.ReadAllText(templateFileName); host.Session = param; var output = engine.ProcessTemplate(input, host); Console.WriteLine(output); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ToString()); } Console.ReadLine(); }
public void WriteSourceFile(string location) { string path = String.Format("{0}\\{1}.cs", location, ClassName); var template = Activator.CreateInstance<ModelTemplate>(); var session = new TextTemplatingSession(); // add the namespace session["namespce"] = Namespace; // add the class name session["className"] = ClassName; // add the table name session["tableName"] = TableName; // add the properties session["properties"] = PropertyMap; template.Session = session; template.Initialize(); // generate the source file string source = template.TransformText(); // Create a StreamWriter to the output file. using (StreamWriter sw = new StreamWriter(path, false)) { IndentedTextWriter writer = new IndentedTextWriter(sw); writer.Write(source); writer.Close(); } }
public string Generate(Type generatorType, Dictionary <string, object> sessionVariables, bool throwException = false) { try { var generator = Activator.CreateInstance(generatorType); var session = new TextTemplatingSession(); string output; session["DebugCallback"] = new EventHandler(DebugCallback); foreach (var pair in sessionVariables) { session[pair.Key] = pair.Value; } generatorType.GetProperty("Session").SetValue(generator, session, null); generatorType.GetMethod("Initialize").Invoke(generator, null); output = (string)generatorType.GetMethod("TransformText").Invoke(generator, null); return(output); } catch (Exception ex) { if (throwException) { throw ex; } } return(null); }
public void WriteMigrationFile() { // check if migration context base class exists string context = String.Format("{0}\\{1}.cs", Globals.Settings.Paths.Migration, Globals.Settings.Names.MigrationContext); if (!File.Exists(context)) { WriteMigrationContextFile(); } string migrationClass = String.Format(migrationName, Globals.Settings.Names.Database); string path = String.Format("{0}\\{1}.cs", Globals.Settings.Paths.Migration, Migration.ClassFile); var template = Activator.CreateInstance<DatabaseMigrationTemplate>(); var session = new TextTemplatingSession(); // add variables session["migrationClass"] = Migration.ClassFile; session["namespce"] = Globals.Settings.Namespaces.Migration; session["databaseName"] = Globals.Settings.Names.Database; session["connection"] = Globals.BasicConnectionString; template.Session = session; template.Initialize(); // generate the source file string source = template.TransformText(); // Create a StreamWriter to the output file. using (StreamWriter sw = new StreamWriter(path, false)) { IndentedTextWriter writer = new IndentedTextWriter(sw); writer.Write(source); writer.Close(); } }
public override ITextTemplatingSession CreateSession() { ITextTemplatingSession session = new TextTemplatingSession { [nameof(TemplateFile)] = TemplateFile }; return(session); }
private ITextTemplatingSession CreateTemplateSession(string @namespace, string type) { ITextTemplatingSession session = new TextTemplatingSession(); session[TemplateParameterConstants.TimeData.NAMESPACE] = @namespace; session[TemplateParameterConstants.TimeData.TYPE] = type; return(session); }
private TextTemplatingSession CreateSession(Dictionary <string, object> parameters) { TextTemplatingSession session = new TextTemplatingSession(); foreach (string key in parameters.Keys) { session.Add(key, parameters[key]); } return(session); }
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)); }
private ITextTemplatingSession CreateTemplateSession(string messageTypeAttributeNamespace, string messageTypeAttributeName, string namespacePrefix, string @namespace, string type, IEnumerable <string> dependencyList, IEnumerable <Tuple <string, string, string> > constantFieldList, IEnumerable <Tuple <string, string, int> > arrayFieldList, IDictionary <string, string> fieldList) { ITextTemplatingSession session = new TextTemplatingSession(); session[TemplateParameterConstants.RosMessage.ROS_MESSAGE_TYPE_ATTRIBUTE_NAMESPACE] = messageTypeAttributeNamespace; session[TemplateParameterConstants.RosMessage.ROS_MESSAGE_TYPE_ATTRIBUTE_NAME] = messageTypeAttributeName; session[TemplateParameterConstants.RosMessage.NAMESPACE_PREFIX] = namespacePrefix; session[TemplateParameterConstants.RosMessage.NAMESPACE] = @namespace; session[TemplateParameterConstants.RosMessage.TYPE] = type; session[TemplateParameterConstants.RosMessage.DEPENDENCY_LIST] = dependencyList; session[TemplateParameterConstants.RosMessage.CONSTANT_FIELD_LIST] = constantFieldList; session[TemplateParameterConstants.RosMessage.ARRAY_FIELD_LIST] = arrayFieldList; session[TemplateParameterConstants.RosMessage.FIELD_LIST] = fieldList; return(session); }
public void BuildProxies(ProxyModel model) { _ = model ?? throw new ArgumentNullException("model is required."); var session = new TextTemplatingSession { ["Namespace"] = Settings?.Namespace ?? "Proxy", ["Model"] = model }; Host host = new Host(Settings, session); host.Message += (sender, args) => { RaiseMessage(args.Message); }; string input = File.ReadAllText(host.TemplateFile); var engine = new Mono.TextTemplating.TemplatingEngine(); var output = engine.ProcessTemplate(input, host); if (host.Errors.Count > 0) { foreach (var error in host.Errors) { RaiseMessage(error.ToString(), "", eMessageType.Error); } return; } var defaultFileName = Path.ChangeExtension( Path.Combine( host.OutputPath, Path.GetFileName(host.TemplateFile)), host.FileExtension); if (output?.Length > 0) { CreateFile(defaultFileName, output); } else if (File.Exists(defaultFileName)) { RaiseMessage(string.Format("Deleting {0}.", defaultFileName), "", eMessageType.Info); File.Delete(defaultFileName); } }
/// <summary> /// Compile the actions using C# compiler. /// Important: Essential references for subject and executor types are added to the configuration automagically /// </summary> /// <param name="configuration">Compiler configuration</param> /// <returns>Executor object</returns> public IExecutor <S> Compile(ICompilerConfiguration <S> configuration) { ValidateConfiguration(configuration); AddTemplateReferences(configuration); // generate code var codeGenerator = new CSharpExecutorTemplate(configuration); var session = new TextTemplatingSession(); codeGenerator.Session = session; codeGenerator.Initialize(); var code = codeGenerator.TransformText(); var executorTypeName = $"{configuration.GetNamespace()}.{configuration.GetClassName()}"; CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameters = new CompilerParameters { GenerateExecutable = false, CompilerOptions = "/t:library" }; foreach (var reference in configuration.References) { var referenceAssembly = reference.Assembly.GetName().Name; if (!parameters.ReferencedAssemblies.Contains(referenceAssembly)) { parameters.ReferencedAssemblies.Add(referenceAssembly); } } var results = codeProvider.CompileAssemblyFromSource(parameters, code); ValidateCompilationResults(results); var executorType = results.CompiledAssembly.GetType(executorTypeName); var executorInstanceHandle = Activator.CreateInstance(executorType); return((IExecutor <S>)executorInstanceHandle); }
public static string RunT4Template(this List <TemplateFieldItem> templateFields, T4ClassConfig configT4Class, TemplateItem currentTreeviewItem) { var template = new T4TemplateClass(); var session = new TextTemplatingSession(); session["namespaceName"] = !configT4Class.DefaultNamespace.Any() ? T4ClassConsts.Texts.DefaultNamespaceText : configT4Class.DefaultNamespace; session["usingNamespaces"] = configT4Class.UsingStatement; session["classType"] = configT4Class.ClassType.GetClassTypeName(); session["classFields"] = templateFields; session["className"] = currentTreeviewItem.Name.Replace(" ", string.Empty); template.Session = session; template.Initialize(); string textTemplateOutput = template.TransformText(); return(textTemplateOutput.Remove(0, 15)); }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var session = new TextTemplatingSession(); var template1 = new Template1(); session["TestParam"] = Parameter.Text; session["List"] = new System.Collections.Generic.List <string> { "One", "Two" }; template1.Session = session; template1.Initialize(); Output.Text = template1.TransformText(); }
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); }
public string Generate(Type generatorType, Dictionary <string, object> sessionVariables, bool throwException = false) { try { var generator = Activator.CreateInstance(generatorType); var session = new TextTemplatingSession(); session["DebugCallback"] = new EventHandler(DebugCallback); foreach (var pair in sessionVariables) { session[pair.Key] = pair.Value; } generatorType.GetProperty("Session").SetValue(generator, session, null); generatorType.GetMethod("Initialize").Invoke(generator, null); var output = (string)generatorType.GetMethod("TransformText").Invoke(generator, null); return(output); } catch (Exception ex) { if (throwException) { throw ex; } else if (MessageBox.Show(string.Format("Generator threw an error '{0}'. Would you like to debug?", ex.Message), "Generator error", MessageBoxButtons.YesNo) == DialogResult.Yes) { bSkipErrors = false; Debugger.Break(); } else { bSkipErrors = true; } } return(null); }
public static void Main(string[] args) { var directoryInfo = new DirectoryInfo("res/json_schema"); var schemaFiles = directoryInfo.GetFiles("*.json"); var fileNames = schemaFiles.Select(f => f.FullName).ToArray(); var classNames = schemaFiles.Select(f => f.Name).Select(name => name.Split(new string[] { ".json" }, System.StringSplitOptions.None)[0]).ToArray(); if (!Directory.Exists("output")) { Directory.CreateDirectory("output"); } else { Directory.Delete("output", true); Directory.CreateDirectory("output"); } var schemaTT = File.ReadAllText("res/templates/SchemaClass.tt"); for (var i = 0; i < fileNames.Length; i++) { var json = MiniJSON.Json.Deserialize(File.ReadAllText(fileNames[i])) as Dictionary <string, object>; var session = new TextTemplatingSession(); session["ClassName"] = classNames[i]; session["Json"] = json; var host = new TextTemplatingHost(); host.Initialize("res/templates/SchemaClass.tt", session); var engine = new TemplatingEngine(); var result = engine.ProcessTemplate(schemaTT, host); var streamWriter = new StreamWriter(string.Format("output/{0}.cs", classNames[i]), false); streamWriter.Write(result); streamWriter.Close(); } }
public void CanGenerateFile() { DomainObjectGeneratorBase service = Service.ServiceNamed(NAME) .WithField<string>("Firstname") .WithField<string>("Lastname") .WithField<Guid>("SomeId") .Can("CapturePerson") .WithParameter<Guid>("Id") .WithParameter<string>("Firstname") .WithParameter<string>("Lastname") .And() .RespondsTo("PersonCaptured") .WithParameter<Guid>("Id") .WithParameter<string>("Firstname") .WithParameter<string>("Lastname") .Done(); var template = Activator.CreateInstance<AggregateGenerator>(); var session = new TextTemplatingSession(); session["Service"] = service; template.Session = session; Console.WriteLine(template.TransformText()); }
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; }
public void Go() { string template = "<#@parameter type=\"System.Int32\" name=\"p1\"#>" + "<#@parameter type=\"System.String\" name=\"p2\"#>" + "Test <#=p1#> <#=p2#>"; CustomCmdLineHost host = new CustomCmdLineHost(); var session = new TextTemplatingSession(); string templateFileName = "..\\..\\Templates\\TextTemplate2.tt"; var sessionHost = (ITextTemplatingSessionHost)host; sessionHost.Session = session; sessionHost.Session["namespace"] = "mynamespace"; //// 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 = 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()); } Console.ReadLine(); //Engine e = new Engine(); //ITextTemplating t4 = e.GetService(typeof(STextTemplating)) as ITextTemplating; //ITextTemplatingSessionHost host = t4 as ITextTemplatingSessionHost; //host.Session = host.CreateSession(); //// Pass a value in Session: //host.Session["p1"] = 32; //// Pass another value in CallContext: //System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("p2", "test"); //// Process a small template inline: //string result = t4.ProcessTemplate("", // "<#@parameter type=\"System.Int32\" name=\"p1\"#>" // + "<#@parameter type=\"System.String\" name=\"p2\"#>" // + "Test <#=p1#> <#=p2#>"); }
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 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 ITextTemplatingSession CreateSession() { Session = new TextTemplatingSession(); return Session; }
public ITextTemplatingSession CreateSession() { Session = new TextTemplatingSession(); return(Session); }
public Host(ISettings settings, TextTemplatingSession session) { this.Settings = settings ?? throw new ArgumentNullException("settings is required."); this.Session = session ?? throw new ArgumentNullException("session is required."); }
public string TransformText(string templateName, TextTemplatingSession session) { return(this.GetTemplateContent(templateName, session)); }
public void WriteSourceFile() { string path = String.Format("{0}\\{1}.cs", Globals.Settings.Paths.Context, Globals.Settings.Names.Context); var template = Activator.CreateInstance<DatabaseTemplate>(); var session = new TextTemplatingSession(); // add variables session["namespce"] = Globals.Settings.Namespaces.Context; session["modelNamespace"] = Globals.Settings.Namespaces.Model; session["className"] = Globals.Settings.Names.Context; session["connection"] = Globals.InitialConnectionString; session["tables"] = Migration.ModelTableMap; template.Session = session; template.Initialize(); // generate the source file string source = template.TransformText(); // Create a StreamWriter to the output file. using (StreamWriter sw = new StreamWriter(path, false)) { IndentedTextWriter writer = new IndentedTextWriter(sw); writer.Write(source); writer.Close(); } }