-
Notifications
You must be signed in to change notification settings - Fork 32
/
TemplateCompiler.cs
206 lines (170 loc) · 7.59 KB
/
TemplateCompiler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web.Razor;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
namespace RazorTemplates.Core
{
internal static class TemplateCompiler
{
private const string TEMPLATES_NAMESPACE = "RazorTemplates";
private static readonly string[] _defaultNamespaces = new[]
{
"System",
"System.Collections.Generic",
"System.Linq"
};
private static volatile bool _runtimeBinderLoaded;
private static int _templateNumber;
public static bool Debug { get; set; }
public static TemplateCompilationLanguage Language { get; set; }
internal static TemplateCompilationResult Compile(
Type templateType,
string templateBody,
IEnumerable<string> assemblyFileNames,
IEnumerable<string> namespaces,
string tempDirectory)
{
LoadRuntimeBinder();
string className;
var compileUnit = GetCodeCompileUnit(templateType, namespaces, templateBody, out className);
string sourceCode;
CodeDomProvider codeProvider;
switch (Language)
{
case TemplateCompilationLanguage.CSharp:
codeProvider = new CSharpCodeProvider();
break;
case TemplateCompilationLanguage.VisualBasic:
codeProvider = new VBCodeProvider();
break;
default:
throw new NotSupportedException("Language not supported.");
}
var builder = new StringBuilder();
using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
{
codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
sourceCode = builder.ToString();
}
var parameters = CreateCompilerParameters(tempDirectory, assemblyFileNames);
var compileResult = codeProvider.CompileAssemblyFromDom(parameters, compileUnit);
if (compileResult.Errors != null && compileResult.Errors.Count > 0)
throw new TemplateCompilationException(compileResult.Errors, sourceCode, templateBody);
var fullClassName = TEMPLATES_NAMESPACE + "." + className;
return new TemplateCompilationResult
{
Type = compileResult.CompiledAssembly.GetType(fullClassName),
SourceCode = sourceCode
};
}
private static CompilerParameters CreateCompilerParameters(string tempDirectory, IEnumerable<string> assemblyFileNames)
{
LoadAssemblies(assemblyFileNames);
var parameters = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
IncludeDebugInformation = false,
CompilerOptions = "/target:library /optimize",
};
if (Language == TemplateCompilationLanguage.VisualBasic)
{
parameters.CompilerOptions += " /optioninfer /optioncompare:text /optionstrict /optionexplicit";
}
tempDirectory = string.IsNullOrWhiteSpace(tempDirectory)
? GetTempDirectoryFromEnvironment()
: tempDirectory;
if (!string.IsNullOrWhiteSpace(tempDirectory))
{
tempDirectory = Path.Combine(tempDirectory, Guid.NewGuid().ToString("N"));
if (!Directory.Exists(tempDirectory)) Directory.CreateDirectory(tempDirectory);
parameters.TempFiles = new TempFileCollection(tempDirectory, false);
}
parameters.ReferencedAssemblies.AddRange(GetLoadedAssemblies());
return parameters;
}
private static string GetTempDirectoryFromEnvironment()
{
var tempDirectory = Environment.GetEnvironmentVariable("TEMP");
return !string.IsNullOrEmpty(tempDirectory) ? tempDirectory : Path.GetTempPath();
}
private static void LoadAssemblies(IEnumerable<string> assemblyFileNames)
{
if (assemblyFileNames == null)
{
return;
}
foreach (var assemblyFileName in assemblyFileNames)
{
var assemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyFileName);
var assembly = Assembly.LoadFile(assemblyPath);
AppDomain.CurrentDomain.Load(assembly.GetName());
}
}
private static string[] GetLoadedAssemblies()
{
return AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => !a.IsDynamic)
.GroupBy(a => a.FullName)
.Select(grp => grp.First())
.Select(a => a.Location)
.Where(a => !String.IsNullOrWhiteSpace(a))
.ToArray();
}
private static CodeCompileUnit GetCodeCompileUnit(Type templateType, IEnumerable<string> namespaces, string templateBody, out string className)
{
var engine = CreateRazorEngine(templateType, namespaces, out className);
GeneratorResults results;
using (var textReader = new StringReader(templateBody))
results = engine.GenerateCode(textReader);
return results.GeneratedCode;
}
private static RazorTemplateEngine CreateRazorEngine(Type templateType, IEnumerable<string> namespaces, out string className)
{
RazorEngineHost host;
switch (Language)
{
case TemplateCompilationLanguage.CSharp:
host = new RazorEngineHost(new CSharpRazorCodeLanguage());
break;
case TemplateCompilationLanguage.VisualBasic:
host = new RazorEngineHost(new VBRazorCodeLanguage());
break;
default:
throw new NotSupportedException("Language not supported.");
}
className = "Template_" + GetNextTemplateNumber();
host.DefaultBaseClass = templateType.FullName;
host.DefaultNamespace = TEMPLATES_NAMESPACE;
host.DefaultClassName = className;
foreach (var ns in _defaultNamespaces.Union(namespaces).Distinct())
host.NamespaceImports.Add(ns);
return new RazorTemplateEngine(host);
}
private static string GetNextTemplateNumber()
{
var number = Interlocked.Increment(ref _templateNumber);
return number.ToString(CultureInfo.InvariantCulture);
}
private static void LoadRuntimeBinder()
{
if (_runtimeBinderLoaded) return;
var binderType = typeof(Microsoft.CSharp.RuntimeBinder.Binder);
var binderAssemblyName = binderType.Assembly.FullName;
if (string.IsNullOrEmpty(binderAssemblyName))
throw new InvalidOperationException(
"Could not load 'Microsoft.CSharp.RuntimeBinder.Binder' assembly.");
_runtimeBinderLoaded = true;
}
}
}