public static System.Reflection.Assembly GenerateCode(ITextTemplatingEngineHost host, ParsedTemplate pt, TemplateSettings settings, CodeCompileUnit ccu) { CompilerParameters pars = new CompilerParameters (); pars.GenerateExecutable = false; if (settings.Debug) { pars.GenerateInMemory = false; pars.IncludeDebugInformation = true; pars.TempFiles.KeepFiles = true; } else { pars.GenerateInMemory = true; pars.IncludeDebugInformation = false; } //resolve and add assembly references HashSet<string> assemblies = new HashSet<string> (); assemblies.UnionWith (settings.Assemblies); assemblies.UnionWith (host.StandardAssemblyReferences); foreach (string assem in assemblies) { string resolvedAssem = host.ResolveAssemblyReference (assem); if (!String.IsNullOrEmpty (resolvedAssem)) { pars.ReferencedAssemblies.Add (resolvedAssem); } else { pt.LogError ("Could not resolve assembly reference '" + assem + "'"); return null; } } CompilerResults results = settings.Provider.CompileAssemblyFromDom (pars, ccu); pt.Errors.AddRange (results.Errors); if (pt.Errors.HasErrors) return null; return results.CompiledAssembly; }
public TemplateUtils(ITextTemplatingEngineHost host, string connectionStrings, StringBuilder template, List <string> filterTableNames = null) { this._connectionString = connectionStrings; this._filterTableNames = filterTableNames; this._mySqlDataTypeTransfer = new MySqlDataTypeTransformation(); this.TemplateManager = Manager.Create(host, template); }
public static void RunCodeGenerator(this TextTransformation transformation, ITextTemplatingEngineHost host, Generator generator) { using (TransformContextScope contextScope = new TransformContextScope(transformation, host)) { generator.Run(); } }
public ProjectManager(ITextTemplatingEngineHost host) { _host = host; IServiceProvider serviceProvider = (IServiceProvider)_host; _dte = serviceProvider.GetService(typeof(DTE)) as DTE; }
// Constructor public VSFilePartsManager(ITextTemplatingEngineHost host, StringBuilder template) : base(host, template) { // Host Service Provider var hostServiceProvider = (IServiceProvider)host; if (hostServiceProvider == null) { throw new ArgumentNullException("Could not obtain IServiceProvider"); } // DTE Dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE)); if (Dte == null) { throw new ArgumentNullException("Could not obtain DTE from host"); } // T4 template item TemplateProjectItem = Dte.Solution.FindProjectItem(host.TemplateFile); // Default checkout action - just checkout using DTE CheckOutAction = (fileName) => Dte.SourceControl.CheckOutItem(fileName); // Default project sync action ProjectSyncAction = () => DefaultProjectSyncActionBody(); }
private MultiFileManager(ITextTemplatingEngineHost host, StringBuilder template) { this.host = host; this.template = template; Header = String.Empty; Error = String.Empty; }
public MySqlORMGenerator(ITextTemplatingEngineHost host, string namespaces, string schemaConnectionString) { this.Host = host; this.SchemaConnectionString = schemaConnectionString; this.Namespaces = namespaces; meta = new MySqlMetaData(this.SchemaConnectionString, this.Namespaces); }
public CompiledTemplate (ParsedTemplate parsedTemplate, ITextTemplatingEngineHost host, Assembly assembly, TemplateSettings settings) { this.host = host; this.assembly = assembly; this.settings = settings; this.parsedTemplate = parsedTemplate; }
public CompiledTemplate(ITextTemplatingEngineHost host, string templateAssemblyFile, string fullName, CultureInfo culture, string[] referenceAssemblyFiles) : this(host, culture, referenceAssemblyFiles) { var assembly = LoadAssemblyFile(templateAssemblyFile); InitializeTemplate(assembly, fullName); }
void Import(ITextTemplatingEngineHost host, Directive includeDirective) { string fileName; if (includeDirective.Attributes.Count > 1 || !includeDirective.Attributes.TryGetValue("file", out fileName)) { LogError("Unexpected attributes in include directive", includeDirective.StartLocation); return; } if (!File.Exists(fileName)) { LogError("Included file '" + fileName + "' does not exist.", includeDirective.StartLocation); return; } string content, resolvedName; if (host.LoadIncludeText(fileName, out content, out resolvedName)) { Parse(host, new Tokeniser(resolvedName, content), true); } else { LogError("Could not resolve include file '" + fileName + "'.", includeDirective.StartLocation); } }
internal T4Context(StringBuilder text, ITextTemplatingEngineHost host) { _text = text; _host = host; _fileItems = new FunctionCache<string, Box<string>>(fileName => new Box<string>("")); _dte = new ValueCache<DTE>(ObtainDTE); }
private void Import(ITextTemplatingEngineHost host, Directive includeDirective, string relativeToDirectory) { string fileName; if (includeDirective.Attributes.Count > 1 || !includeDirective.Attributes.TryGetValue("file", out fileName)) { LogError("Unexpected attributes in include directive", includeDirective.StartLocation); return; } //try to resolve path relative to the file that included it if (relativeToDirectory != null && !Path.IsPathRooted(fileName)) { var possible = Path.Combine(relativeToDirectory, fileName); if (File.Exists(possible)) { fileName = Path.GetFullPath(possible); } } string content, resolvedName; if (host.LoadIncludeText(fileName, out content, out resolvedName)) { Parse(host, new Tokeniser(resolvedName, content), true, true); } else { LogError("Could not resolve include file '" + fileName + "'.", includeDirective.StartLocation); } }
/// <summary> /// Creates new or appends to existing output file. /// </summary> /// <param name="output"> /// An <see cref="OutputInfo"/> object that describes content generated by a template. /// </param> /// <param name="content"> /// A <see cref="String"/> that contains content generated by a template. /// </param> /// <param name="host"> /// An <see cref="ITextTemplatingEngineHost"/> object hosting the <paramref name="transformation"/>. /// </param> /// <param name="transformation"> /// <see cref="TextTransformation"/> object generated by T4 based on top-level .tt file. /// </param> /// <remarks> /// Multiple outputs can be combined in a single output file during code /// generation. This allows user to customize a composite code generator /// to generate output with required granularity without having to modify /// the generator itself. /// </remarks> public void Append(OutputInfo output, string content, ITextTemplatingEngineHost host, TextTransformation transformation) { if (output == null) { throw new ArgumentNullException("output"); } if (host == null) { throw new ArgumentNullException("host"); } string previousDirectory = Environment.CurrentDirectory; Environment.CurrentDirectory = Path.GetDirectoryName(host.TemplateFile); try { Validate(output); if (string.IsNullOrEmpty(output.File)) { this.AppendToStandardOutput(output, content, host, transformation); } else { this.AppendToOutputFile(output, content, host); } } finally { Environment.CurrentDirectory = previousDirectory; } }
internal CompiledTemplate(ITextTemplatingEngineHost host, CompiledAssemblyData compiledAssembly, string fullName, CultureInfo culture, string[] referenceAssemblyFiles) : this(host, culture, referenceAssemblyFiles) { var assembly = LoadInMemoryAssembly(compiledAssembly); InitializeTemplate(assembly, fullName); }
public string PreprocessTemplate(string content, ITextTemplatingEngineHost host, string className, string classNamespace, out string language, out string [] references) { if (content == null) { throw new ArgumentNullException(nameof(content)); } if (host == null) { throw new ArgumentNullException(nameof(host)); } if (className == null) { throw new ArgumentNullException(nameof(className)); } language = null; references = null; var pt = ParsedTemplate.FromTextInternal(content, host); if (pt.Errors.HasErrors) { host.LogErrors(pt.Errors); return(null); } return(PreprocessTemplateInternal(pt, content, host, className, classNamespace, out language, out references)); }
public static Project GetProject(ITextTemplatingEngineHost host) { IServiceProvider hostServiceProvider = (IServiceProvider)host; if (hostServiceProvider == null) { throw new Exception("Host property returned unexpected value (null)."); } DTE dte = (DTE)hostServiceProvider.GetService(typeof(DTE)); if (dte == null) { throw new Exception("Unable to retrieve EnvDTE.DTE"); } Array activeSolutionProjects = (Array)dte.ActiveSolutionProjects; if (activeSolutionProjects == null) { throw new Exception("DTE.ActiveSolutionProjects returned null."); } Project dteProject = (Project)activeSolutionProjects.GetValue(0); if (dteProject == null) { throw new Exception("DTE.ActiveSolutionProjects returned null."); } return(dteProject); }
public virtual void Initialize(ITextTemplatingEngineHost host) { if (host == null) { throw new ArgumentNullException("host"); } }
public string ProcessTemplate (string content, ITextTemplatingEngineHost host) { var tpl = CompileTemplate (content, host); if (tpl != null) return tpl.Process (); return null; }
public CompiledTemplate(ParsedTemplate parsedTemplate, ITextTemplatingEngineHost host, Assembly assembly, TemplateSettings settings) { this.host = host; this.assembly = assembly; this.settings = settings; this.parsedTemplate = parsedTemplate; }
public static List<EnvDTE.CodeClass> GetDefinedTypes(ITextTemplatingEngineHost host) { var listClass = new List<EnvDTE.CodeClass>(); Project project = GetProject(host); foreach (EnvDTE.CodeElement element in project.CodeModel.CodeElements) { if (element.Kind == EnvDTE.vsCMElement.vsCMElementClass) { var type = (EnvDTE.CodeClass)element; // do stuff with that class here //var allProperties = VisualStudioHelper.GetAllCodeElementsOfType(type.Members, EnvDTE.vsCMElement.vsCMElementProperty, true); foreach(EnvDTE.CodeProperty property in type.Members) { if (property.Kind == EnvDTE.vsCMElement.vsCMElementProperty) { //list.Add(property); } } listClass.Add(type); } } return listClass; }
public void Dispose() { host = null; #if !FEATURE_ASSEMBLY_LOAD_CONTEXT assemblyResolver.Dispose(); #endif }
public PreprocessTextTransformation(string className, string classNamespace, ParseResult result, ITextTemplatingEngineHost host) { _className = className; _classNamespace = classNamespace; _result = result; Host = host; }
public static void Static(ITextTemplatingEngineHost host, string qualifiedAssemblyName, GrassOptions codeGenOptions = null) { var options = codeGenOptions ?? new GrassOptions(); var callContext = CallContext.LogicalGetData("NamespaceHint"); var ns = callContext == null ? "ArtisanCode.Grass.GeneratedContent" : callContext.ToString(); var staticClass = new ClassDefinition(qualifiedAssemblyName, ns, options); staticClass.PopulateStaticMethods(codeGenOptions); ICodeGen engine = CreateCodeGenEngine(host); var emittedInterface = engine.EmitInterface(ns, staticClass, options); var emittedStaticWrapper = engine.EmitStaticWrapperClass(ns, staticClass, options); string templateDirectory = Path.GetDirectoryName(host.TemplateFile); string interfaceFilePath = Path.Combine(templateDirectory, emittedInterface.Filename); string classWrapperFilePath = Path.Combine(templateDirectory, emittedStaticWrapper.Filename); WriteCodefileToDisk(engine, emittedInterface.CompilationOutput, interfaceFilePath); WriteCodefileToDisk(engine, emittedStaticWrapper.CompilationOutput, classWrapperFilePath); AddFileToTemplate(host, interfaceFilePath); AddFileToTemplate(host, classWrapperFilePath); }
string GenerateCode (ITextTemplatingEngineHost host, string content, string name, string generatorNewline) { ParsedTemplate pt = ParsedTemplate.FromText (content, host); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } TemplateSettings settings = TemplatingEngine.GetSettings (host, pt); if (name != null) settings.Name = name; if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } var ccu = TemplatingEngine.GenerateCompileUnit (host, content, pt, settings); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } var opts = new System.CodeDom.Compiler.CodeGeneratorOptions (); using (var writer = new System.IO.StringWriter ()) { writer.NewLine = generatorNewline; settings.Provider.GenerateCodeFromCompileUnit (ccu, writer, opts); return writer.ToString (); } }
public CodeBlockManager(ITextTemplatingEngineHost host, StringBuilder generationEnvironment) { this.Host = (IProxyTemplateHost)host ?? throw new ArgumentNullException("host is required"); this.GenerationEnvironment = generationEnvironment ?? throw new ArgumentNullException("generationEnvironment is required"); Host.RaiseMessage("Loaded Code Block Manager.", "", eMessageType.Verbose); }
public static List <EnvDTE.CodeClass> GetDefinedTypes(ITextTemplatingEngineHost host) { var listClass = new List <EnvDTE.CodeClass>(); Project project = GetProject(host); foreach (EnvDTE.CodeElement element in project.CodeModel.CodeElements) { if (element.Kind == EnvDTE.vsCMElement.vsCMElementClass) { var type = (EnvDTE.CodeClass)element; // do stuff with that class here //var allProperties = VisualStudioHelper.GetAllCodeElementsOfType(type.Members, EnvDTE.vsCMElement.vsCMElementProperty, true); foreach (EnvDTE.CodeProperty property in type.Members) { if (property.Kind == EnvDTE.vsCMElement.vsCMElementProperty) { //list.Add(property); } } listClass.Add(type); } } return(listClass); }
internal TransformContext(TextTransformation transformation, ITextTemplatingEngineHost host) { this.Transformation = transformation; this.Host = host; this.Dte = (DTE)((IServiceProvider)host).GetService(typeof(DTE)); this.TemplageProjectItem = this.Dte.Solution.FindProjectItem(host.TemplateFile); }
/// <summary> /// Appends generated <paramref name="content"/> to the specified <see cref="OutputInfo.File"/>. /// </summary> /// <param name="output"> /// An <see cref="OutputInfo"/> object that describes content generated by a template. /// </param> /// <param name="content"> /// A <see cref="String"/> that contains content generated by a template. /// </param> /// <param name="host"> /// An <see cref="ITextTemplatingEngineHost"/> object hosting the transformation. /// </param> private void AppendToOutputFile(OutputInfo output, string content, ITextTemplatingEngineHost host) { // If some content was already generated for this file string filePath = GetFullFilePath(output, host); OutputFile outputFile = this.outputFiles.FirstOrDefault(o => OutputInfo.SamePath(o.File, filePath)); if (outputFile != null) { // Verify that output properties match Validate(output, outputFile); } else { // Otherwise, create a new output container outputFile = new OutputFile(); outputFile.File = filePath; outputFile.Project = GetFullProjectPath(output); outputFile.Encoding = output.Encoding; outputFile.BuildAction = output.BuildAction; outputFile.CustomTool = output.CustomTool; outputFile.CustomToolNamespace = output.CustomToolNamespace; outputFile.CopyToOutputDirectory = output.CopyToOutputDirectory; outputFile.PreserveExistingFile = output.PreserveExistingFile; this.outputFiles.Add(outputFile); } outputFile.Content.Append(content); outputFile.AppendBuildProperties(output.BuildProperties); outputFile.AppendReferences(output.References); }
public void Dispose() { if (host != null) { host = null; AppDomain.CurrentDomain.AssemblyResolve -= ResolveReferencedAssemblies; } }
public static string Run(System.Reflection.Assembly assem, string type, ITextTemplatingEngineHost host, System.Globalization.CultureInfo culture) { Type transformType = assem.GetType(type); TextTransformation tt; IExtendedTextTemplatingEngineHost extendedHost = host as IExtendedTextTemplatingEngineHost; if (extendedHost != null) { tt = extendedHost.CreateInstance(transformType); } else { tt = (TextTransformation)Activator.CreateInstance(transformType); } //set the host property if it exists System.Reflection.PropertyInfo hostProp = transformType.GetProperty("Host", typeof(ITextTemplatingEngineHost)); if (hostProp != null && hostProp.CanWrite) { hostProp.SetValue(tt, host, null); } //set the culture if (culture != null) { tt.FormatProvider = culture; } tt.Initialize(); string output = tt.TransformText(); host.LogErrors(tt.Errors); return(output); }
public TemplateService(ITextTemplatingSessionHost textTemplatingSessionHost, ITextTemplatingEngineHost textTemplatingEngineHost, ITextTemplating textTemplating) { TextTemplatingSessionHost = textTemplatingSessionHost; TextTemplatingEngineHost = textTemplatingEngineHost; TextTemplating = textTemplating; }
public void Dispose() { if (this.host != null) { this.host = null; AppDomain.CurrentDomain.AssemblyResolve -= this.ResolveReferencedAssemblies; } }
private static ProjectItem LocateTemplateFile(ITextTemplatingEngineHost host) { IServiceProvider hostServiceProvider = (IServiceProvider)host; DTE dte = (DTE)hostServiceProvider.GetService(typeof(DTE)); var projectItem = dte.Solution.FindProjectItem(host.TemplateFile); return(projectItem); }
public static void Clean(ITextTemplatingEngineHost host) { var projectItem = LocateTemplateFile(host); foreach (ProjectItem i in projectItem.ProjectItems) { i.Remove(); } }
public string ProcessTemplate (string content, ITextTemplatingEngineHost host) { if (content == null) throw new ArgumentNullException ("content"); if (host == null) throw new ArgumentNullException ("host"); return GetEngine (host, content).ProcessTemplate (content, host); }
public PreprocessTextTransformationTest() { _host = new MockTemplatingHost(); _transformer = new PreprocessTextTransformation("Test", "TestNs", null, _host); var renderAccessor = new PrivateObject(_transformer); _invokeRender = block => renderAccessor.Invoke("Render", new[] { typeof(Block) }, new object[] { block }) as string; }
public CompiledTemplate(ITextTemplatingEngineHost host, CompilerResults results, string fullName, CultureInfo culture, string[] assemblyFiles) : this(host, culture, assemblyFiles) { Assembly assembly = results.PathToAssembly != null ? LoadAssemblyFile(results.PathToAssembly) : results.CompiledAssembly; InitializeTemplate(assembly, fullName); }
public CompiledTemplate(ITextTemplatingEngineHost host, CompilerResults results, string fullName, CultureInfo culture, string[] assemblyFiles) { AppDomain.CurrentDomain.AssemblyResolve += this.ResolveReferencedAssemblies; this.host = host; this.culture = culture; this.assemblyFiles = assemblyFiles; this.Load(results, fullName); }
public CompiledTemplate (ITextTemplatingEngineHost host, CompilerResults results, string fullName, CultureInfo culture, string[] assemblyFiles) { AppDomain.CurrentDomain.AssemblyResolve += ResolveReferencedAssemblies; this.host = host; this.culture = culture; this.assemblyFiles = assemblyFiles; Load (results, fullName); }
ITextTemplatingEngine GetEngine (ITextTemplatingEngineHost host, string content) { var appdomain = host.ProvideTemplatingAppDomain (content); if (appdomain == null) { return new TemplatingEngine (); } else { var type = typeof (TemplatingEngine); return (ITextTemplatingEngine) appdomain.CreateInstanceAndUnwrap (type.Assembly.FullName, type.FullName); } }
public OutputFileManager(IServiceProvider serviceProvider, string inputFile, OutputFile[] outputFiles) { this.serviceProvider = serviceProvider; this.inputFile = inputFile; this.inputDirectory = Path.GetDirectoryName(inputFile); this.outputFiles = outputFiles; this.dte = (DTE)serviceProvider.GetService(typeof(DTE)); this.projects = GetAllProjects(this.dte.Solution); this.input = this.dte.Solution.FindProjectItem(this.inputFile); this.templatingHost = (ITextTemplatingEngineHost)this.serviceProvider.GetService(typeof(STextTemplating)); }
public static List<Type> GetDefinedTypesOnAllAssemblies(ITextTemplatingEngineHost host) { string targetDir = host.ResolveAssemblyReference("$(TargetDir)"); //Directory.SetCurrentDirectory(targetDir); var list = new List<Type>(); DirectoryInfo d = new DirectoryInfo(targetDir); Append("*.dll", d,ref list); Append("*.exe", d, ref list); return list; }
public string ProcessTemplate (string content, ITextTemplatingEngineHost host) { AppDomain appdomain = host.ProvideTemplatingAppDomain (content); ITextTemplatingEngine engine; if (appdomain != null) { engine = (ITextTemplatingEngine) appdomain.CreateInstanceAndUnwrap (typeof (TemplatingEngine).Assembly.FullName, typeof (TemplatingEngine).FullName); } else { engine = new TemplatingEngine (); } return engine.ProcessTemplate (content, host); }
public string PreprocessTemplate (string content, ITextTemplatingEngineHost host, string className, string classNamespace, out string language, out string[] references) { if (content == null) throw new ArgumentNullException ("content"); if (host == null) throw new ArgumentNullException ("host"); if (className == null) throw new ArgumentNullException ("className"); if (classNamespace == null) throw new ArgumentNullException ("classNamespace"); return GetEngine (host, content).PreprocessTemplate (content, host, className, classNamespace, out language, out references); }
public void TestInitialize() { UIThreadDispatcher.Invoke(delegate { this.templatingService = (ITextTemplating)ServiceProvider.GetService(typeof(STextTemplating)); this.templatingHost = (ITextTemplatingEngineHost)this.templatingService; this.provider = (ITransformationContextProvider)ServiceProvider.GetService(typeof(ITransformationContextProvider)); this.project = this.CreateTestProject(); this.folder = this.project.ProjectItems.AddFolder(Path.GetRandomFileName()); this.input = this.CreateTestProjectItem(this.folder.ProjectItems, TextFileItemTemplate); this.output = new OutputFile { File = Path.GetRandomFileName() + ".txt" }; this.output.Content.Append(TestText); this.SimulateTransformation(); }); }
public string ProcessTemplate (string content, ITextTemplatingEngineHost host) { ParsedTemplate pt = ParsedTemplate.FromText (content, host); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } TemplateSettings settings = GetSettings (host, pt); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } CodeCompileUnit ccu = GenerateCompileUnit (host, pt, settings); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } System.Reflection.Assembly results = GenerateCode (host, pt, settings, ccu); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } if (!String.IsNullOrEmpty (settings.Extension)) { host.SetFileExtension (settings.Extension); } if (settings.Encoding != null) { //FIXME: when is this called with false? host.SetOutputEncoding (settings.Encoding, true); } string output = ""; try { output = Run (results, settings.Namespace + "." + settings.Name, host, settings.Culture); } catch (Exception ex) { pt.LogError ("Error running transform: " + ex.ToString ()); } host.LogErrors (pt.Errors); return output; }
public CodeGenerationContext(Model model, string nameSpace, string processID, string modelFileFullName, ITextTemplatingEngineHost textTemplatingHost) { CompileUnit = new CodeCompileUnit(); Model = model; if (string.IsNullOrEmpty(Model.Namespace)) Namespace = nameSpace; else Namespace = Model.Namespace; DTE = DTEHelper.GetDTE(processID); TextTemplatingHost = textTemplatingHost; ModelFileName = modelFileFullName; ProjectItem = DTE.Solution.FindProjectItem(ModelFileName); AssemblyName = DTEHelper.GetAssemblyName(ProjectItem.ContainingProject); Language = DTEHelper.GetProjectLanguage(ProjectItem.ContainingProject); switch (Language) { case CodeLanguage.CSharp: Provider = new CSharpCodeProvider(); break; case CodeLanguage.VB: Provider = new VBCodeProvider(); // use VB default namespace if it was set VSProject project = (VSProject)ProjectItem.ContainingProject.Object; Property DefaultNamespaceProperty = project.Project.Properties.Item("DefaultNamespace"); DefaultNamespace = (string)DefaultNamespaceProperty.Value; break; default: throw new ArgumentException( "Unsupported project type. ActiveWriter currently supports C# and Visual Basic.NET projects."); } Output = new OutputWindowHelper(DTE); }
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"); }
public static Project GetProject(ITextTemplatingEngineHost host) { IServiceProvider hostServiceProvider = (IServiceProvider)host; if (hostServiceProvider == null) throw new Exception("Host property returned unexpected value (null)."); DTE dte = (DTE)hostServiceProvider.GetService(typeof(DTE)); if (dte == null) throw new Exception("Unable to retrieve EnvDTE.DTE"); Array activeSolutionProjects = (Array)dte.ActiveSolutionProjects; if (activeSolutionProjects == null) throw new Exception("DTE.ActiveSolutionProjects returned null."); Project dteProject = (Project)activeSolutionProjects.GetValue(0); if (dteProject == null) throw new Exception("DTE.ActiveSolutionProjects returned null."); return dteProject; }
public void WriteDisclaimer(ITextTemplatingEngineHost host) { var lines = new List<string>(); lines.Add("Auto-generated by T4 template"); lines.Add(string.Empty); if (host != null) { lines.Add(string.Format("Template Path : {0}", host.TemplateFile)); } lines.Add(string.Format("Generated On : {0}", DateTime.Now)); lines.Add(string.Empty); lines.Add("WARNING: Do not modify this file directly. Your changes will be overwritten when the file is regenerated."); var formattedLines = FormatDisclaimerLines(lines); _tt.WriteLines(formattedLines); }
public CompiledTemplate CompileTemplate (string content, ITextTemplatingEngineHost host) { ParsedTemplate pt = ParsedTemplate.FromText (content, host); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } TemplateSettings settings = GetSettings (host, pt); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } CodeCompileUnit ccu = GenerateCompileUnit (host, pt, settings); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } System.Reflection.Assembly results = GenerateCode (host, pt, settings, ccu); if (pt.Errors.HasErrors) { host.LogErrors (pt.Errors); return null; } if (!String.IsNullOrEmpty (settings.Extension)) { host.SetFileExtension (settings.Extension); } if (settings.Encoding != null) { //FIXME: when is this called with false? host.SetOutputEncoding (settings.Encoding, true); } return new CompiledTemplate (pt, host, results, settings); }
/// <summary> /// T4 <see cref="Microsoft.VisualStudio.TextTemplating.Engine"/> calls this /// method in the beginning of template transformation. /// </summary> /// <param name="host"> /// The <see cref="ITextTemplatingEngineHost"/> object hosting the transformation. /// </param> /// <remarks> /// This method stores the <paramref name="host"/> in a static field to allow the /// <see cref="OutputProcessor"/> to access it later during code generation. /// </remarks> public override void Initialize(ITextTemplatingEngineHost host) { base.Initialize(host); DirectiveProcessor.host = host; }
public static T4Context Context(this StringBuilder text, ITextTemplatingEngineHost host) { return new T4Context(text, host); }
public static TemplateSettings GetSettings(ITextTemplatingEngineHost host, ParsedTemplate pt) { string language = null; TemplateSettings settings = new TemplateSettings (); foreach (Directive dt in pt.Directives) { switch (dt.Name) { case "template": string val = dt.Extract ("language"); if (val != null) language = val; val = dt.Extract ("debug"); if (val != null) settings.Debug = string.Compare (val, "true", StringComparison.OrdinalIgnoreCase) == 0; val = dt.Extract ("inherits"); if (val != null) settings.Inherits = val; val = dt.Extract ("culture"); if (val != null) { System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.GetCultureInfo (val); if (culture == null) pt.LogWarning ("Could not find culture '" + val + "'", dt.StartLocation); else settings.Culture = culture; } val = dt.Extract ("hostspecific"); if (val != null) { settings.HostSpecific = string.Compare (val, "true", StringComparison.OrdinalIgnoreCase) == 0; } break; case "assembly": string name = dt.Extract ("name"); if (name == null) pt.LogError ("Missing name attribute in assembly directive", dt.StartLocation); else settings.Assemblies.Add (name); break; case "import": string namespac = dt.Extract ("namespace"); if (namespac == null) pt.LogError ("Missing namespace attribute in import directive", dt.StartLocation); else settings.Imports.Add (namespac); break; case "output": settings.Extension = dt.Extract ("extension"); string encoding = dt.Extract ("encoding"); if (encoding != null) settings.Encoding = Encoding.GetEncoding ("encoding"); break; case "include": throw new InvalidOperationException ("Include is handled in the parser"); default: throw new NotImplementedException ("Custom directives are not supported yet"); } ComplainExcessAttributes (dt, pt); } if (settings.Name == null) settings.Name = string.Format ("GeneratedTextTransformation{0:x}", new System.Random ().Next ()); if (settings.Namespace == null) settings.Namespace = typeof (TextTransformation).Namespace; //resolve the CodeDOM provider if (String.IsNullOrEmpty (language)) { pt.LogError ("No language was specified for the template"); return settings; } if (language == "C#v3.5") { Dictionary<string, string> providerOptions = new Dictionary<string, string> (); providerOptions.Add ("CompilerVersion", "v3.5"); settings.Provider = new CSharpCodeProvider (providerOptions); } else { settings.Provider = CodeDomProvider.CreateProvider (language); } if (settings.Provider == null) { pt.LogError ("A provider could not be found for the language '" + language + "'"); return settings; } return settings; }
public static string Run(System.Reflection.Assembly assem, string type, ITextTemplatingEngineHost host, System.Globalization.CultureInfo culture) { Type transformType = assem.GetType (type); TextTransformation tt; IExtendedTextTemplatingEngineHost extendedHost = host as IExtendedTextTemplatingEngineHost; if (extendedHost != null) { tt = extendedHost.CreateInstance (transformType); } else { tt = (TextTransformation) Activator.CreateInstance (transformType); } //set the host property if it exists System.Reflection.PropertyInfo hostProp = transformType.GetProperty ("Host", typeof (ITextTemplatingEngineHost)); if (hostProp != null && hostProp.CanWrite) hostProp.SetValue (tt, host, null); //set the culture if (culture != null) ToStringHelper.FormatProvider = culture; else ToStringHelper.FormatProvider = System.Globalization.CultureInfo.InvariantCulture; //tt.Initialize (); string output = tt.TransformText (); //host.LogErrors (tt.Errors); ToStringHelper.FormatProvider = System.Globalization.CultureInfo.InvariantCulture; return output; }
public static CodeCompileUnit GenerateCompileUnit(ITextTemplatingEngineHost host, ParsedTemplate pt, TemplateSettings settings) { //prep the compile unit var ccu = new CodeCompileUnit (); var namespac = new CodeNamespace (settings.Namespace); ccu.Namespaces.Add (namespac); var imports = new HashSet<string> (); imports.UnionWith (settings.Imports); imports.UnionWith (host.StandardImports); foreach (string ns in imports) namespac.Imports.Add (new CodeNamespaceImport (ns)); //prep the type var type = new CodeTypeDeclaration (settings.Name); type.IsPartial = true; if (!String.IsNullOrEmpty (settings.Inherits)) type.BaseTypes.Add (new CodeTypeReference (settings.Inherits)); else type.BaseTypes.Add (new CodeTypeReference (typeof (TextTransformation))); namespac.Types.Add (type); //prep the transform method var transformMeth = new CodeMemberMethod () { Name = "TransformText", ReturnType = new CodeTypeReference (typeof (String)), Attributes = MemberAttributes.Public | MemberAttributes.Override }; //method references that will need to be used multiple times var writeMeth = new CodeMethodReferenceExpression (new CodeThisReferenceExpression (), "Write"); var toStringMeth = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (ToStringHelper)), "ToStringWithCulture"); bool helperMode = false; //build the code from the segments foreach (TemplateSegment seg in pt.Content) { CodeStatement st = null; var location = new CodeLinePragma (seg.StartLocation.FileName ?? host.TemplateFile, seg.StartLocation.Line); switch (seg.Type) { case SegmentType.Block: if (helperMode) //TODO: are blocks permitted after helpers? throw new ParserException ("Blocks are not permitted after helpers", seg.StartLocation); st = new CodeSnippetStatement (seg.Text); break; case SegmentType.Expression: st = new CodeExpressionStatement ( new CodeMethodInvokeExpression (writeMeth, new CodeMethodInvokeExpression (toStringMeth, new CodeSnippetExpression (seg.Text)))); break; case SegmentType.Content: st = new CodeExpressionStatement (new CodeMethodInvokeExpression (writeMeth, new CodePrimitiveExpression (seg.Text))); break; case SegmentType.Helper: type.Members.Add (new CodeSnippetTypeMember (seg.Text) { LinePragma = location }); helperMode = true; break; default: throw new InvalidOperationException (); } if (st != null) { if (helperMode) { //convert the statement into a snippet member and attach it to the top level type //TODO: is there a way to do this for languages that use indentation for blocks, e.g. python? using (var writer = new StringWriter ()) { settings.Provider.GenerateCodeFromStatement (st, writer, null); type.Members.Add (new CodeSnippetTypeMember (writer.ToString ()) { LinePragma = location }); } } else { st.LinePragma = location; transformMeth.Statements.Add (st); continue; } } } //complete the transform method transformMeth.Statements.Add (new CodeMethodReturnStatement ( new CodeMethodInvokeExpression ( new CodePropertyReferenceExpression ( new CodeThisReferenceExpression (), "GenerationEnvironment"), "ToString"))); type.Members.Add (transformMeth); //generate the Host property if needed if (settings.HostSpecific) { var hostField = new CodeMemberField (new CodeTypeReference (typeof (ITextTemplatingEngineHost)), "hostValue"); hostField.Attributes = (hostField.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private; type.Members.Add (hostField); var hostProp = new CodeMemberProperty () { Name = "Host", Attributes = MemberAttributes.Public, HasGet = true, HasSet = true, Type = hostField.Type }; var hostFieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "hostValue"); hostProp.SetStatements.Add (new CodeAssignStatement (hostFieldRef, new CodePropertySetValueReferenceExpression ())); hostProp.GetStatements.Add (new CodeMethodReturnStatement (hostFieldRef)); type.Members.Add (hostProp); } return ccu; }
public override void Initialize(ITextTemplatingEngineHost host) { templateEngineHost = host as TextTemplateHost; base.Initialize(host); }