using RazorEngine; using RazorEngine.Configuration; using RazorEngine.Templating; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Tango.CodeGeneration { /// /// Contains several code generation helper methods. /// public static class Helper { static Helper() { var config = new TemplateServiceConfiguration { Debug = true, ReferenceResolver = new CustomResolver() }; Engine.Razor = RazorEngineService.Create(config); } /// /// Gets a code template by the code object type. /// /// The type. /// public static String GetTemplate(Type type) { return GetTemplate(type.Name); } /// /// Gets a code template by name. /// /// The name. /// public static String GetTemplate(String name) { var assembly = Assembly.GetAssembly(typeof(Helper)); var resourceName = typeof(Helper).Namespace + ".Templates." + name + ".cshtml"; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } /// /// Parses the template using Razor Engine. /// /// The template. /// The model. /// public static String ParseTemplate(String template, object model) { return Engine.Razor.RunCompile(template, Guid.NewGuid().ToString(), model.GetType(), model).Replace("
", "").Replace("
", ""); } /// /// Parses the specified text. /// /// The text. /// The model. /// public static String Parse(String text,object model) { return Engine.Razor.RunCompile(text, Guid.NewGuid().ToString(), model.GetType(), model); } /// /// Indents the c sharp code. /// /// The code. /// public static string IndentCSharpCode(string code) { const string INDENT_STEP = " "; if (string.IsNullOrWhiteSpace(code)) { return code; } var result = new StringBuilder(); var indent = string.Empty; var lineContent = false; var stringDefinition = false; for (var i = 0; i < code.Length; i++) { var ch = code[i]; if (ch == '"' && !stringDefinition) { result.Append(ch); stringDefinition = true; continue; } if (ch == '"' && stringDefinition) { result.Append(ch); stringDefinition = false; continue; } if (stringDefinition) { result.Append(ch); continue; } if (ch == '{' && !stringDefinition) { if (lineContent) { result.AppendLine(); } result.Append(indent).Append("{"); if (lineContent) { result.AppendLine(); } indent += INDENT_STEP; lineContent = false; continue; } if (ch == '}' && !stringDefinition) { if (indent.Length != 0) { indent = indent.Substring(0, indent.Length - INDENT_STEP.Length); } if (lineContent) { result.AppendLine(); } result.Append(indent).Append("}"); if (lineContent) { result.AppendLine(); } lineContent = false; continue; } if (ch == '\r') { continue; } if ((ch == ' ' || ch == '\t') && !lineContent) { continue; } if (ch == '\n') { lineContent = false; result.AppendLine(); continue; } if (!lineContent) { result.Append(indent); lineContent = true; } result.Append(ch); } return result.ToString(); } } }