public async Task RemoteProcedureTestWithDummyHost() { IProcessTransformationRunFactory factory = await RemotingServices.ConnectAsync <IProcessTransformationRunFactory>(new Uri($"ipc://{TransformationRunFactory.TransformationRunFactoryService}/{TransformationRunFactory.TransformationRunFactoryMethod}")); IProcessTextTemplatingEngine engine = new TemplatingEngine(); if (factory?.IsRunFactoryAlive() ?? default) { IProcessTransformationRunner runner = engine.PrepareTransformationRunner(Samples.template, new DummyHost(), factory); runner.Should().NotBeNull(); ITextTemplatingCallback result = factory.StartTransformation(runner.RunnerId); if (result.Errors.HasErrors) { foreach (TemplateError error in result.Errors) { Console.Out.WriteLine(error.Message); } } result.TemplateOutput.Should().Be(Samples.outcome); } }
public string GeneratePart(string templatePathPart, ILogger log, IReadOnlyDictionary <string, object> options) { if (templatePathPart == null) { throw new ArgumentNullException(nameof(templatePathPart)); } if (log == null) { throw new ArgumentNullException(nameof(log)); } var expandoOptions = new ExpandoObject(); var expandoOptionsAsDictionary = (IDictionary <string, object>)expandoOptions; foreach (var option in options) { expandoOptionsAsDictionary[option.Key] = option.Value; } var templateDirectory = new FileInfo(FilePath).Directory; var sourceFilePath = Path.Combine(templateDirectory.FullName, templatePathPart); var content = File.ReadAllText(sourceFilePath); var engine = new TemplatingEngine(); var host = new ProjectTemplatingHost(log, sourceFilePath, templateDirectory.FullName, expandoOptions, Assemblies.Select(assembly => assembly.FullPath)); return(engine.ProcessTemplate(content, host)); }
public void GenerateStaticPropertyForParameterCanInitilialize(string value) { var engine = new TemplatingEngine(); var host = new DummyHost() { TemplateFile = "test.tt" }; host.Parameters.Add("TestParameter", value); var tt = engine.CompileTemplate(T4ParameterSample, host); foreach (TemplateError error in host.Errors) { Console.Error.WriteLine(error.Message); } Type ttType = tt.textTransformation?.GetType(); Assert.IsNotNull(ttType); var initMethod = ttType.GetMethod("Initialize"); var parameter = ttType.GetProperty("TestParameter", BindingFlags.Public | BindingFlags.Static); initMethod.Invoke(tt.textTransformation, null); Assert.AreEqual(value, parameter.GetValue(null)); }
public string GetTemplateSourceCode(string name) { string sourceCode = File.ReadAllText(GetTemplateFileName(name)); var host = T4Generator as ITextTemplatingEngineHost; ParsedTemplate pt = ParsedTemplate.FromText(sourceCode, T4Generator); if (pt.Errors.HasErrors) { host.LogErrors(pt.Errors); return(null); } TemplateSettings settings = TemplatingEngine.GetSettings(T4Generator, pt); var ccu = TemplatingEngine.GenerateCompileUnit(host, sourceCode, pt, settings); var opts = new CodeGeneratorOptions(); using (var writer = new StringWriter()) { settings.Provider.GenerateCodeFromCompileUnit(ccu, writer, opts); return(writer.ToString()); } }
static void Generate(TemplateGenerator host, ProjectFile file, out string outputFile) { outputFile = null; string content; try { content = File.ReadAllText(file.FilePath); } catch (IOException ex) { host.Errors.Add(new CompilerError { ErrorText = GettextCatalog.GetString("Could not read input file '{0}':\n{1}", file.FilePath, ex) }); return; } var pt = ParsedTemplate.FromText(content, host); if (pt.Errors.HasErrors) { host.Errors.AddRange(pt.Errors); return; } var settings = TemplatingEngine.GetSettings(host, pt); if (pt.Errors.HasErrors) { host.Errors.AddRange(pt.Errors); return; } outputFile = file.FilePath.ChangeExtension(settings.Provider.FileExtension); settings.Name = settings.Provider.CreateValidIdentifier(file.FilePath.FileNameWithoutExtension); settings.Namespace = CustomToolService.GetFileNamespace(file, outputFile); settings.IncludePreprocessingHelpers = string.IsNullOrEmpty(settings.Inherits); settings.IsPreprocessed = true; var ccu = TemplatingEngine.GenerateCompileUnit(host, content, pt, settings); host.Errors.AddRange(pt.Errors); if (pt.Errors.HasErrors) { return; } try { using (var writer = new StreamWriter(outputFile, false, System.Text.Encoding.UTF8)) { settings.Provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions()); } } catch (IOException ex) { host.Errors.Add(new CompilerError { ErrorText = GettextCatalog.GetString("Could not write output file '{0}':\n{1}", outputFile, ex) }); } }
public override string GetClassCodeForProcessingRun() { var hostProp = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Host"); return(TemplatingEngine.GenerateIndentedClassCode( languageProvider, CreateIsTrueMethod(hostProp), CreateTagsProperty(hostProp) )); }
public void DefaultLanguage() { DummyHost host = new DummyHost(); string template = @"<#= DateTime.Now #>"; ParsedTemplate pt = ParsedTemplate.FromText(template, host); Assert.AreEqual(0, host.Errors.Count); TemplateSettings settings = TemplatingEngine.GetSettings(host, pt); Assert.AreEqual(settings.Language, "C#"); }
public void DefaultLanguage() { var host = new DummyHost(); string template = @"<#= DateTime.Now #>"; var pt = ParsedTemplate.FromTextInternal(template, host); Assert.Empty(host.Errors); TemplateSettings settings = TemplatingEngine.GetSettings(host, pt); Assert.Equal("C#", settings.Language); }
private static void GenerateModelFiles(ResourceLoader loader, DirectoryInfo outputDirectory, out Dictionary <string, string> geometryToClass) { var outDir = Path.Combine(outputDirectory.FullName, "Models"); if (!Directory.Exists(outDir)) { Directory.CreateDirectory(outDir); } geometryToClass = new Dictionary <string, string>(); Mono.TextTemplating.TemplatingEngine engine = new TemplatingEngine(); var template = engine.CompileTemplate(File.ReadAllText("../../../Templates/EntityTemplate.tt"), new TemplateGenerator()); // // var template = new EntityTemplate(); //template.Initialize(); // template.Session["EntityModels"] = loader.EntityModels; ResourceConverterContext.EntityModels = loader.EntityModels; int count = 0; int totalCount = loader.EntityModels.Count; foreach (var model in loader.EntityModels) { var pct = 100D * ((double)count / (double)totalCount); Log.Info($"Starting Template Processing for '{model.Key}'"); //template.Session["CurrentModelName"] = model.Key; //template.Session["CurrentModel"] = model.Value; ResourceConverterContext.CurrentModelName = CodeTypeName(model.Value.Name); ResourceConverterContext.CurrentModel = model.Value; var output = template.Process(); var outputPath = Path.Combine(outDir, CodeTypeName(model.Value.Name) + "Model.cs"); if (File.Exists(outputPath)) { Log.Warn($"Class already exists: {outputPath} ({count}/{totalCount}) - {pct:F1}%"); } else { geometryToClass.Add(model.Key, ResourceConverterContext.CurrentModelName + "Model"); File.WriteAllText(outputPath, output); Log.Info($"Successfully Processed Template for entity '{model.Key}' ({count}/{totalCount}) - {pct:F1}%"); } count++; // Log.Info($"Successfully Processed Template for entity '{model.Key}' ({count}/{totalCount}) - {pct:F1}%"); } }
string Preprocess (string input) { DummyHost host = new DummyHost (); string className = "PreprocessedTemplate"; string classNamespace = "Templating"; string language = null; string[] references = null; TemplatingEngine engine = new TemplatingEngine (); string output = engine.PreprocessTemplate (input, host, className, classNamespace, out language, out references); output = output.Replace ("\r\n", "\n"); return TemplatingEngineHelper.StripHeader (output, "\n"); }
public void FieldAndPropertyGenerated() { var provider = CodeDomProvider.CreateProvider("C#"); var field = CreateBoolField(); var property = CreateBoolProperty(); string output = TemplatingEngine.GenerateIndentedClassCode(provider, field, property); output = FixOutput(output); string expectedOutput = FixOutput(MethodAndFieldGeneratedOutput); Assert.AreEqual(expectedOutput, output); }
public async Task Execute() { var loggers = new List <ILog> { new ConsoleLog() }; if (!string.IsNullOrEmpty(LogTo)) { loggers.Add(new FileLog(LogTo)); } var engine = TemplatingEngine.Init(loggers.ToArray()); var projectDirectory = TemplatePaths .Select(x => Path.Combine(x, $"projects\\{Template}")) .FirstOrDefault(Directory.Exists); if (string.IsNullOrEmpty(projectDirectory)) { projectDirectory = TemplatePaths .Select(x => Path.Combine(x, "projects\\base")) .FirstOrDefault(Directory.Exists); } var substitutions = new ReadOnlyDictionary <string, string>(new Dictionary <string, string> { { "PROJECT_NAME", Name }, { "SOLUTION", Solution }, { "PROJECT_GUID", ProjectGuid } }); if (!string.IsNullOrEmpty(projectDirectory)) { await engine.RunTemplate( new ProjectTemplateType(Name, Solution, Location, Path.Combine(Location, $"src\\{Name}"), ProjectGuid, substitutions), projectDirectory).ConfigureAwait(false); await new AlterCommand { Name = Name, Solution = Solution, Location = Location, TemplatePaths = TemplatePaths, Template = Template, LogTo = LogTo }.Execute().ConfigureAwait(false); } }
static string Preprocess(string input, DummyHost host) { string className = "PreprocessedTemplate"; string classNamespace = "Templating"; var engine = new TemplatingEngine(); string output = engine.PreprocessTemplate(input, host, className, classNamespace, out _, out _); ReportErrors(host.Errors); if (output != null) { return(TemplatingEngineHelper.CleanCodeDom(output, "\n")); } return(null); }
string Preprocess (string input, DummyHost host) { string className = "PreprocessedTemplate"; string classNamespace = "Templating"; string language = null; string[] references = null; TemplatingEngine engine = new TemplatingEngine (); string output = engine.PreprocessTemplate (input, host, className, classNamespace, out language, out references); ReportErrors (host.Errors); if (output != null) { return TemplatingEngineHelper.CleanCodeDom (output, "\n"); } return null; }
string Preprocess(string input) { DummyHost host = new DummyHost(); string className = "PreprocessedTemplate"; string classNamespace = "Templating"; string language = null; string[] references = null; TemplatingEngine engine = new TemplatingEngine(); string output = engine.PreprocessTemplate(input, host, className, classNamespace, out language, out references); output = output.Replace("\r\n", "\n"); return(TemplatingEngineHelper.StripHeader(output, "\n")); }
public void GenerateStaticPropertyForParameter() { var engine = new TemplatingEngine(); var host = new DummyHost(); var output = engine.PreprocessTemplate(T4ParameterSample, host, "ParameterTestClass", "Testing", out string language, out string[] references); foreach (TemplateError error in host.Errors) { Console.Error.WriteLine(error.Message); } Assert.IsTrue(output.Contains("public static string TestParameter")); Console.Out.WriteLine(output); }
public void WithEngine() { var engine = new TemplatingEngine(); var host = new TemplateGenerator(); host.Refs.Add("System.CodeDom"); var session = host.GetOrCreateSession(); session["Count"] = 2; var templateString = File.ReadAllText("RuntimeTextTemplateForEngine.tt"); string output = engine.ProcessTemplate(templateString, host); Console.WriteLine(output); }
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)); }
string Preprocess(string input, DummyHost host) { string className = "PreprocessedTemplate"; string classNamespace = "Templating"; string language = null; string[] references = null; TemplatingEngine engine = new TemplatingEngine(); string output = engine.PreprocessTemplate(input, host, className, classNamespace, out language, out references); ReportErrors(host.Errors.ToCompilerErrorCollection()); if (output != null) { return(TemplatingEngineHelper.CleanCodeDom(output, "\n")); } return(null); }
static string GenerateCode(ITextTemplatingEngineHost host, string content, string name, string generatorNewline) { var pt = ParsedTemplate.FromTextInternal(content, host); if (pt.Errors.HasErrors) { host.LogErrors(pt.Errors); return(null); } TemplateSettings settings = TemplatingEngine.GetSettings(host, pt); if (name != null) { settings.Namespace = 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 CodeGeneratorOptions(); using var writer = new StringWriter() { NewLine = generatorNewline }; settings.Provider.GenerateCodeFromCompileUnit(ccu, writer, opts); return(writer.ToString()); }
internal static void GenerateCode(ITextTemplatingEngineHost host, string content, string namespac, string name, TextWriter writer) { ParsedTemplate pt = ParsedTemplate.FromText(content, host); if (pt.Errors.HasErrors) { host.LogErrors(pt.Errors); return; } TemplateSettings settings = TemplatingEngine.GetSettings(host, pt); if (name != null) { settings.Name = name; } if (namespac != null) { settings.Namespace = namespac; } if (pt.Errors.HasErrors) { host.LogErrors(pt.Errors); return; } var ccu = TemplatingEngine.GenerateCompileUnit(host, pt, settings); if (pt.Errors.HasErrors) { host.LogErrors(pt.Errors); return; } var opts = new System.CodeDom.Compiler.CodeGeneratorOptions(); settings.Provider.GenerateCodeFromCompileUnit(ccu, writer, opts); }
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 async Task Execute() { var loggers = new List <ILog> { new ConsoleLog() }; if (!string.IsNullOrEmpty(LogTo)) { loggers.Add(new FileLog(LogTo)); } var engine = TemplatingEngine.Init(loggers.ToArray()); var alterationDirectories = TemplatePaths .Select(x => Path.Combine(x, "alterations\\base")) .Where(Directory.Exists) .ToList(); alterationDirectories.AddRange(TemplatePaths .Select(x => Path.Combine(x, $"alterations\\{Template}")) .Where(Directory.Exists)); var substitutions = new ReadOnlyDictionary <string, string>(new Dictionary <string, string> { { "PROJECT_NAME", Name }, { "SOLUTION", Solution } }); foreach (var alterationDirectory in alterationDirectories) { await engine.RunTemplate( new AlterationTemplateType(Name, Location, Path.Combine(Location, $"src\\{Name}"), substitutions), alterationDirectory).ConfigureAwait(false); } }
public override string GetClassCodeForProcessingRun() { using (CodeDomProvider provider = Settings.GetCodeDomProvider()) { return(TemplatingEngine.GenerateIndentedClassCode(provider, members)); } }
public override string GetClassCodeForProcessingRun() { var code = TemplatingEngine.GenerateIndentedClassCode(provider, members); return(code); }
public override string GetPostInitializationCodeForProcessingRun() { return(TemplatingEngine.IndentSnippetText(provider, StatementsToCode(postStatements), " ")); }
public static void UseInProcessCompiler(this TemplatingEngine engine) { UseInProcessCompilerMethod.Invoke(null, new object[] { engine }); }
public override string GetClassCodeForProcessingRun() { return(TemplatingEngine.GenerateIndentedClassCode(this.provider, this.members)); }
private static TemplateGenerationResult GenerateTemplate( string templateFile, DeserializedLarancaFile larancaFile, string folder, string collectorTypesAsm, string genUtilsAsm, string newtonsoftAsm, string projFile) { var generator = new ToolTemplateGenerator(); var inputFile = templateFile; string inputContent; try { inputContent = File.ReadAllText(inputFile); } catch (IOException ex) { Console.Error.WriteLine("Could not read input file '" + inputFile + "':\n" + ex); return(new TemplateGenerationResult() { StatusCode = 1 }); } if (inputContent.Length == 0) { Console.Error.WriteLine("Input is empty"); return(new TemplateGenerationResult() { StatusCode = 1 }); } var pt = ParsedTemplate.FromText(inputContent, generator); var larnacaPropertiesExtractResult = TemplateLarnacaProperties.Extract(pt); if (larnacaPropertiesExtractResult.Fail()) { Console.Error.WriteLine($"Failed to parse larnaca propertsions of template: {templateFile}. {larnacaPropertiesExtractResult.StatusMessage}"); } var settings = TemplatingEngine.GetSettings(generator, pt); settings.Log = Console.Out; if (pt.Errors.Count > 0) { foreach (var currentError in pt.Errors) { var currentCompilerError = (CompilerError)currentError; if (currentCompilerError.IsWarning) { Console.WriteLine(currentCompilerError.ToString()); } else { Console.Error.WriteLine(currentCompilerError.ToString()); generator.Errors.Add(currentCompilerError); } } } var outputFile = inputFile; if (Path.HasExtension(outputFile)) { var dir = Path.GetDirectoryName(outputFile); var fn = Path.GetFileNameWithoutExtension(outputFile); outputFile = Path.Combine(dir, fn + (settings.Extension ?? ".txt")); } else { outputFile = outputFile + (settings.Extension ?? ".txt"); } HashSet <string> assemblyNamesToRemove = new HashSet <string>(new[] { Path.GetFileName(collectorTypesAsm), Path.GetFileName(genUtilsAsm), Path.GetFileName(newtonsoftAsm), }, StringComparer.OrdinalIgnoreCase); //fix template assemblies path foreach (var x in settings.Assemblies.ToArray()) { if (assemblyNamesToRemove.Contains(Path.GetFileName(x))) { settings.Assemblies.Remove(x); } else { settings.Assemblies.Add(FixPath(x, folder)); } } settings.Assemblies.Add(collectorTypesAsm); settings.Assemblies.Add(genUtilsAsm); settings.Assemblies.Add(newtonsoftAsm); string outputContent = null; if (!generator.Errors.HasErrors) { var larnacaDirective = pt.Directives.FirstOrDefault(d => d.Name.Equals("larnaca", StringComparison.OrdinalIgnoreCase)); if (larancaFile?.DatabaseMeta != null) { generator.AddParameter(null, null, "dbMeta", larancaFile.DatabaseMeta); } generator.AddParameter(null, null, "projFile", projFile); outputContent = generator.ProcessTemplate(pt, inputFile, inputContent, ref outputFile, settings); } if (!generator.Errors.HasErrors) { try { if (outputFile.EndsWith(".g.g.cs", StringComparison.OrdinalIgnoreCase)) { outputFile = outputFile.Substring(0, outputFile.Length - ".g.g.cs".Length) + ".g.cs"; } File.WriteAllText(outputFile, outputContent, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); if (outputFile.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)) { if (larnacaPropertiesExtractResult.Data?.DoNotCompile ?? false) { return(new TemplateGenerationResult()); } else { return(new TemplateGenerationResult() { CSFileToCompile = outputFile }); } } else if (outputFile.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) { if ((larnacaPropertiesExtractResult.Data?.Type ?? ETemplateType.undefined) == ETemplateType.Analysis) { return(new TemplateGenerationResult() { AnalysisProjectFileToBuild = outputFile }); } else { return(new TemplateGenerationResult()); } } else { return(new TemplateGenerationResult()); } } catch (IOException ex) { Console.Error.WriteLine("Could not write output file '" + outputFile + "':\n" + ex); return(new TemplateGenerationResult() { StatusCode = 1 }); } } else { Console.Error.WriteLine(inputFile == null ? "Processing failed." : $"Processing '{inputFile}' failed."); return(new TemplateGenerationResult() { StatusCode = 1 }); } }
public async ThreadingTasks.Task <string> ProcessTemplateAsync(string inputFilename, string content, ITextTemplatingCallback callback, object hierarchy, bool debugging = false) { if (this is ITextTemplatingComponents Component) { Component.Hierarchy = hierarchy; Component.Callback = callback; Component.TemplateFile = inputFilename; LastInvocationRaisedErrors = false; Component.Host.SetFileExtension(SearchForLanguage(content, "C#") ? ".cs" : ".vb"); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { try { runFactory = await GetTransformationRunFactoryAsync(subSonicOutput.GetOutputTextWriter(), SubSonicCoreVisualStudioAsyncPackage.Singleton.CancellationTokenSource.Token); } catch (Exception ex) { await LogErrorAsync(string.Format(CultureInfo.CurrentCulture, SubSonicCoreErrors.ExceptionStartingRunFactoryProcess, ex), new Location(inputFilename)); runFactory = null; } if (runFactory == null) { await LogErrorAsync(SubSonicCoreErrors.ErrorStartingRunFactoryProcess, new Location(TemplateFile)); if (debugging) { ProcessTemplateEventArgs args = new ProcessTemplateEventArgs { TemplateOutput = SubSonicCoreErrors.DebugErrorOutput, Succeeded = false }; this.OnTransformProcessCompleted(args); } return(SubSonicCoreErrors.DebugErrorOutput); } if (!SubSonicCoreVisualStudioAsyncPackage.Singleton.CancellationTokenSource.IsCancellationRequested) { // we have not been cancelled so let's continue // we need to prepare the transformation and send the important parts over to the T4 Host Process if (Engine.PrepareTransformationRunner(content, Component.Host, runFactory, debugging) is IProcessTransformationRunner runner) { if (!debugging) { // if we are not debugging we can wait for the process to finish // and we do not need to attach to the host process. try { if (runFactory.StartTransformation(runner.RunnerId) is TextTemplatingCallback result) { if (result.Errors.HasErrors) { Callback.Errors.AddRange(result.Errors); foreach (var templateError in result.Errors) { await LogErrorAsync(templateError.Message, templateError.Location, templateError.IsWarning); } } Component.Callback.SetFileExtension(result.Extension); return(result.TemplateOutput); } else if (runFactory.GetErrors(runner.RunnerId) is TemplateErrorCollection errors) { Callback.Errors.AddRange(errors); foreach (var templateError in errors) { await LogErrorAsync(templateError.Message, templateError.Location, templateError.IsWarning); } } } catch (Exception ex) { if (TemplatingEngine.IsCriticalException(ex)) { throw; } await LogErrorAsync(ex.ToString(), new Location(Host.TemplateFile)); } finally { runFactory.DisposeOfRunner(runner.RunnerId); // clean up the runner } } else { // when debugging this we will attach to the process // the ui thread will be waiting for a callback from process to complete generation of file. bool success = false; try { foreach (EnvDTE.Process process in package.DTE.Debugger.LocalProcesses) { if (process.ProcessID == (this.transformProcess?.Id ?? default)) { process.Attach(); success = true; break; } } } catch (Exception attachException) { await LogErrorAsync(string.Format(CultureInfo.CurrentCulture, SubSonicCoreErrors.ExceptionAttachingToRunFactoryProcess, attachException), new Location(inputFilename)); } if (success) { Dispatcher uiDispatcher = Dispatcher.CurrentDispatcher; this.debugThread = new Thread(() => StartTransformation(inputFilename, runner, uiDispatcher)); this.debugThread.Start(); } else { await LogErrorAsync(SubSonicCoreErrors.ErrorAttachingToRunFactoryProcess, new Location(inputFilename)); ProcessTemplateEventArgs args = new ProcessTemplateEventArgs { TemplateOutput = SubSonicCoreErrors.DebugErrorOutput, Succeeded = false }; this.OnTransformProcessCompleted(args); } } } else { ProcessTemplateEventArgs args = new ProcessTemplateEventArgs(); if (debugging) { args.TemplateOutput = SubSonicCoreErrors.DebugErrorOutput; args.Succeeded = false; this.OnTransformProcessCompleted(args); } await LogErrorsAsync(transformationHost.Errors.ToCompilerErrorCollection()); } } } catch (IOException) { if (transformProcess != null) { try { transformProcess.Kill(); } catch (Exception) { } finally { transformProcess = null; } } RemotingServices.Disconnect(new Uri($"ipc://{TransformationRunFactory.TransformationRunFactoryService}")); } } return(SubSonicCoreErrors.DebugErrorOutput); }
/// <summary> /// Generates this project template to the specified output directory. /// </summary> /// <param name="outputDirectory">The output directory.</param> /// <param name="projectName">Name of the project.</param> /// <param name="projectGuid">The project unique identifier.</param> /// <param name="log">The log to output errors to.</param> /// <param name="options">The options arguments that will be made available through the Session property in each template.</param> /// <param name="generatedOutputFiles">The generated files.</param> /// <exception cref="System.ArgumentNullException">outputDirectory /// or /// projectName</exception> /// <exception cref="System.InvalidOperationException">FilePath cannot be null on this instance</exception> public void Generate(string outputDirectory, string projectName, Guid projectGuid, ILogger log, IReadOnlyDictionary <string, object> options = null, List <string> generatedOutputFiles = null) { if (outputDirectory == null) { throw new ArgumentNullException(nameof(outputDirectory)); } if (projectName == null) { throw new ArgumentNullException(nameof(projectName)); } if (log == null) { throw new ArgumentNullException(nameof(log)); } if (FilePath == null) { throw new InvalidOperationException("FilePath cannot be null on this instance"); } try { // Check Project template filepath var templateDirectory = new FileInfo(FilePath).Directory; if (templateDirectory == null || !templateDirectory.Exists) { log.Error($"Invalid ProjectTemplate directory [{FilePath}]"); return; } // Creates the output directory var directory = new DirectoryInfo(outputDirectory); if (!directory.Exists) { directory.Create(); } // Create expando object from options valid for the whole life of generating a project template var expandoOptions = new ExpandoObject(); var expandoOptionsAsDictionary = (IDictionary <string, object>)expandoOptions; expandoOptionsAsDictionary["ProjectName"] = projectName; expandoOptionsAsDictionary["ProjectGuid"] = projectGuid; if (options != null) { foreach (var option in options) { expandoOptionsAsDictionary[option.Key] = option.Value; } } var engine = new TemplatingEngine(); // In case this project template is dynamic, we need to generate its content first through T4 if (IsDynamicTemplate) { var content = File.ReadAllText(FilePath); var host = new ProjectTemplatingHost(log, FilePath, templateDirectory.FullName, expandoOptions, Assemblies.Select(assembly => assembly.FullPath)); var newTemplateAsString = engine.ProcessTemplate(content, host); Files.Clear(); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(newTemplateAsString))) { var newTemplate = (ProjectTemplate)YamlSerializer.Default.Deserialize(stream); Files.AddRange(newTemplate.Files); } } // Iterate on each files foreach (var fileItem in Files) { if (fileItem.Source == null) { log.Warning($"Invalid empty file item [{fileItem}] with no source location"); continue; } var sourceFilePath = Path.Combine(templateDirectory.FullName, fileItem.Source); var targetLocation = fileItem.Target ?? fileItem.Source; if (Path.IsPathRooted(targetLocation)) { log.Error($"Invalid file item [{fileItem}]. TargetLocation must be a relative path"); continue; } var targetLocationExpanded = Expand(targetLocation, expandoOptionsAsDictionary, log); // If this is a template file, turn template on by default if (fileItem.IsTemplate) { var targetPath = Path.GetDirectoryName(targetLocationExpanded); var targetFileName = Path.GetFileName(targetLocationExpanded); targetLocationExpanded = targetPath != null?Path.Combine(targetPath, targetFileName) : targetFileName; } var targetFilePath = Path.Combine(outputDirectory, targetLocationExpanded); try { // Make sure that the target directory does exist var targetDirectory = new FileInfo(targetFilePath).Directory; if (!targetDirectory.Exists) { targetDirectory.Create(); } bool fileGenerated = false; if (fileItem.IsTemplate) { var content = File.ReadAllText(sourceFilePath); // Replace the default platform with the selected one from the ProjectItemTemplate. object oldPlatform = null; if (fileItem.CurrentPlatform != null) { if (expandoOptionsAsDictionary.ContainsKey(nameof(fileItem.CurrentPlatform))) { oldPlatform = expandoOptionsAsDictionary[nameof(fileItem.CurrentPlatform)]; } expandoOptionsAsDictionary[nameof(fileItem.CurrentPlatform)] = fileItem.CurrentPlatform; } var host = new ProjectTemplatingHost(log, sourceFilePath, templateDirectory.FullName, expandoOptions, Assemblies.Select(assembly => assembly.FullPath)); var newContent = engine.ProcessTemplate(content, host); if (fileItem.CurrentPlatform != null) { if (oldPlatform != null) { expandoOptionsAsDictionary[nameof(fileItem.CurrentPlatform)] = oldPlatform; } else { expandoOptionsAsDictionary.Remove(nameof(fileItem.CurrentPlatform)); } } if (newContent != null) { fileGenerated = true; File.WriteAllText(targetFilePath, newContent); } } else { fileGenerated = true; File.Copy(sourceFilePath, targetFilePath, true); } if (generatedOutputFiles != null && fileGenerated) { generatedOutputFiles.Add(targetFilePath); } } catch (Exception ex) { log.Error($"Unexpected exception while processing [{fileItem}]", ex); } } } catch (Exception ex) { log.Error($"Unexpected exception while processing project template [{projectName}] to directory [{outputDirectory}]", ex); } }
public static void UseInProcessCompiler(this TemplatingEngine engine) { engine.SetCompilerFunc(() => new RoslynCodeCompiler(RuntimeInfo.GetRuntime())); }