示例#1
0
        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));
        }
示例#2
0
        public bool ProcessTemplate(string inputFileName, string inputContent, ref string outputFileName, out string outputContent)
        {
            errors.Clear();
            encoding = Encoding.UTF8;

            outputFile     = outputFileName;
            inputFile      = inputFileName;
            outputContent  = Engine.ProcessTemplate(inputContent, this);
            outputFileName = outputFile;

            return(!errors.HasErrors);
        }
示例#3
0
        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);
        }
示例#4
0
        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 string ProcessTemplate(string content, ITextTemplatingEngineHost host)
 {
     return(engine.ProcessTemplate(content, host));
 }
示例#6
0
        /// <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);
            }
        }