forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRazorPageHost.cs
More file actions
464 lines (393 loc) · 17 KB
/
Copy pathRazorPageHost.cs
File metadata and controls
464 lines (393 loc) · 17 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Razor;
using System.Web.Razor.Generator;
using System.Web.Razor.Parser;
using System.Web.Razor.Parser.SyntaxTree;
using System.Web.Razor.Text;
using ServiceStack.Common.Extensions;
using ServiceStack.DataAnnotations;
using ServiceStack.Html;
using ServiceStack.IO;
using ServiceStack.Logging;
using ServiceStack.MiniProfiler;
using ServiceStack.Text;
namespace ServiceStack.Razor.Compilation
{
public class RazorPageHost : RazorEngineHost, IRazorHost
{
private static ILog log = LogManager.GetLogger(typeof(RazorPageHost));
private static readonly IEnumerable<string> _defaultImports = new[] {
"System",
"System.Collections.Generic",
"System.IO",
"System.Linq",
"System.Net",
"System.Text",
"ServiceStack.Text",
"ServiceStack.Html",
};
private readonly IRazorCodeTransformer _codeTransformer;
private readonly CodeDomProvider _codeDomProvider;
private readonly IDictionary<string, string> _directives;
private string _defaultClassName;
public IVirtualPathProvider PathProvider { get; protected set; }
public IVirtualFile File { get; protected set; }
public RazorPageHost(IVirtualPathProvider pathProvider,
IVirtualFile file,
IRazorCodeTransformer codeTransformer,
CodeDomProvider codeDomProvider,
IDictionary<string, string> directives)
: base(new CSharpRazorCodeLanguage())
{
this.PathProvider = pathProvider;
this.File = file;
if (codeTransformer == null)
{
throw new ArgumentNullException("codeTransformer");
}
if (this.PathProvider == null)
{
throw new ArgumentNullException("pathProvider");
}
if (this.File == null)
{
throw new ArgumentNullException("file");
}
if (codeDomProvider == null)
{
throw new ArgumentNullException("codeDomProvider");
}
_codeTransformer = codeTransformer;
_codeDomProvider = codeDomProvider;
_directives = directives;
base.DefaultNamespace = "ASP";
EnableLinePragmas = true;
base.GeneratedClassContext = new GeneratedClassContext(
executeMethodName: GeneratedClassContext.DefaultExecuteMethodName,
writeMethodName: GeneratedClassContext.DefaultWriteMethodName,
writeLiteralMethodName: GeneratedClassContext.DefaultWriteLiteralMethodName,
writeToMethodName: "WriteTo",
writeLiteralToMethodName: "WriteLiteralTo",
templateTypeName: typeof(HelperResult).FullName,
defineSectionMethodName: "DefineSection",
beginContextMethodName: "BeginContext",
endContextMethodName: "EndContext"
)
{
ResolveUrlMethodName = "Href",
};
base.DefaultBaseClass = typeof(ViewPage).FullName;
foreach (var import in _defaultImports)
{
base.NamespaceImports.Add(import);
}
}
public override string DefaultClassName
{
get
{
return _defaultClassName ?? GetClassName();
}
set
{
if (!String.Equals(value, "__CompiledTemplate", StringComparison.OrdinalIgnoreCase))
{
// By default RazorEngineHost assigns the name __CompiledTemplate. We'll ignore this assignment
_defaultClassName = value;
}
}
}
public ParserBase Parser { get; set; }
public RazorCodeGenerator CodeGenerator { get; set; }
public bool EnableLinePragmas { get; set; }
public GeneratorResults Generate()
{
lock (this)
{
_codeTransformer.Initialize(this, _directives);
// Create the engine
var engine = new RazorTemplateEngine(this);
// Generate code
GeneratorResults results = null;
try
{
using (var stream = File.OpenRead())
using (var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
{
results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: this.File.RealPath);
}
}
catch (Exception e)
{
throw new HttpParseException(e.Message, e, this.File.VirtualPath, null, 1);
}
//Throw the first parser message to generate the YSOD
//TODO: Is there a way to output all errors at once?
if (results.ParserErrors.Count > 0)
{
var error = results.ParserErrors[0];
throw new HttpParseException(error.Message, null, this.File.VirtualPath, null, error.Location.LineIndex + 1);
}
return results;
}
}
public Dictionary<string, string> DebugSourceFiles = new Dictionary<string, string>();
public Type Compile()
{
Type forceLoadOfRuntimeBinder = typeof(Microsoft.CSharp.RuntimeBinder.Binder);
if (forceLoadOfRuntimeBinder == null)
{
log.Warn("Force load of .NET 4.0+ RuntimeBinder in Microsoft.CSharp.dll");
}
var razorResults = Generate();
var @params = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
IncludeDebugInformation = false,
CompilerOptions = "/target:library /optimize",
TempFiles = { KeepFiles = true }
};
var assemblies = CompilerServices
.GetLoadedAssemblies()
.Where(a => !a.IsDynamic)
.Select(a => a.Location)
.ToArray();
@params.ReferencedAssemblies.AddRange(assemblies);
//Compile the code
var results = _codeDomProvider.CompileAssemblyFromDom(@params, razorResults.GeneratedCode);
var tempFilesMarkedForDeletion = new TempFileCollection(null);
@params.TempFiles
.OfType<string>()
.ForEach(file => tempFilesMarkedForDeletion.AddFile(file, false));
using (tempFilesMarkedForDeletion)
{
if (results.Errors != null && results.Errors.HasErrors)
{
//check if source file exists, read it.
//HttpCompileException is sealed by MS. So, we'll
//just add a property instead of inheriting from it.
var sourceFile = results.Errors
.OfType<CompilerError>()
.First(ce => !ce.IsWarning)
.FileName;
var sourceCode = "";
if (!string.IsNullOrEmpty(sourceFile) && System.IO.File.Exists(sourceFile))
{
sourceCode = System.IO.File.ReadAllText(sourceFile);
}
else
{
foreach (string tempFile in @params.TempFiles)
{
if (tempFile.EndsWith(".cs"))
{
sourceCode = System.IO.File.ReadAllText(tempFile);
}
}
}
throw new HttpCompileException(results, sourceCode);
}
#if DEBUG
foreach (string tempFile in @params.TempFiles)
{
if (tempFile.EndsWith(".cs"))
{
var sourceCode = System.IO.File.ReadAllText(tempFile);
//sourceCode.Print();
}
}
#endif
return results.CompiledAssembly.GetTypes().First();
}
}
public string GenerateSourceCode()
{
var razorResults = Generate();
using (var writer = new StringWriter())
{
var options = new CodeGeneratorOptions
{
BlankLinesBetweenMembers = false,
BracingStyle = "C"
};
//Generate the code
writer.WriteLine("#pragma warning disable 1591");
_codeDomProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
writer.WriteLine("#pragma warning restore 1591");
writer.Flush();
// Perform output transformations and return
string codeContent = writer.ToString();
codeContent = _codeTransformer.ProcessOutput(codeContent);
return codeContent;
}
}
public override void PostProcessGeneratedCode(CodeGeneratorContext context)
{
_codeTransformer.ProcessGeneratedCode(context.CompileUnit, context.Namespace, context.GeneratedClass, context.TargetMethod);
}
public override RazorCodeGenerator DecorateCodeGenerator(RazorCodeGenerator incomingCodeGenerator)
{
var codeGenerator = CodeGenerator ?? base.DecorateCodeGenerator(incomingCodeGenerator);
codeGenerator.GenerateLinePragmas = EnableLinePragmas;
return codeGenerator;
}
protected virtual string GetClassName()
{
string filename = Path.GetFileNameWithoutExtension(this.File.VirtualPath);
return "__" + ParserHelpers.SanitizeClassName(filename);
}
public override ParserBase DecorateCodeParser(ParserBase incomingCodeParser)
{
if (incomingCodeParser is System.Web.Razor.Parser.CSharpCodeParser)
return new ServiceStackCSharpCodeParser();
return base.DecorateCodeParser(incomingCodeParser);
}
}
public class ServiceStackCSharpRazorCodeGenerator : CSharpRazorCodeGenerator
{
private const string DefaultModelTypeName = "dynamic";
private const string HiddenLinePragma = "#line hidden";
public ServiceStackCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
: base(className, rootNamespaceName, sourceFileName, host)
{
}
protected override void Initialize(CodeGeneratorContext context)
{
base.Initialize(context);
context.GeneratedClass.Members.Insert(0, new CodeSnippetTypeMember(HiddenLinePragma));
}
}
public class ServiceStackCSharpCodeParser : System.Web.Razor.Parser.CSharpCodeParser
{
private const string ModelKeyword = "model";
private const string GenericTypeFormatString = "{0}<{1}>";
private SourceLocation? _endInheritsLocation;
private bool _modelStatementFound;
public ServiceStackCSharpCodeParser()
{
MapDirectives(ModelDirective, ModelKeyword);
}
protected override void InheritsDirective()
{
// Verify we're on the right keyword and accept
AssertDirective(SyntaxConstants.CSharp.InheritsKeyword);
AcceptAndMoveNext();
_endInheritsLocation = CurrentLocation;
InheritsDirectiveCore();
CheckForInheritsAndModelStatements();
}
private void CheckForInheritsAndModelStatements()
{
if (_modelStatementFound && _endInheritsLocation.HasValue)
{
Context.OnError(_endInheritsLocation.Value, String.Format(CultureInfo.CurrentCulture, MvcResources.MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword, ModelKeyword));
}
}
protected virtual void ModelDirective()
{
// Verify we're on the right keyword and accept
AssertDirective(ModelKeyword);
AcceptAndMoveNext();
SourceLocation endModelLocation = CurrentLocation;
BaseTypeDirective(string.Format(CultureInfo.CurrentCulture,
MvcResources.MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName, ModelKeyword),
CreateModelCodeGenerator);
if (_modelStatementFound)
{
Context.OnError(endModelLocation, String.Format(CultureInfo.CurrentCulture,
MvcResources.MvcRazorCodeParser_OnlyOneModelStatementIsAllowed, ModelKeyword));
}
_modelStatementFound = true;
CheckForInheritsAndModelStatements();
}
private SpanCodeGenerator CreateModelCodeGenerator(string model)
{
return new SetModelTypeCodeGenerator(model, GenericTypeFormatString);
}
protected override void LayoutDirective()
{
AssertDirective(SyntaxConstants.CSharp.LayoutKeyword);
AcceptAndMoveNext();
BaseTypeDirective(MvcResources.MvcRazorCodeParser_OnlyOneModelStatementIsAllowed.Fmt("layout"), CreateLayoutCodeGenerator);
}
private SpanCodeGenerator CreateLayoutCodeGenerator(string layoutPath)
{
return new SetLayoutCodeGenerator(layoutPath);
}
public class SetLayoutCodeGenerator : SpanCodeGenerator
{
public SetLayoutCodeGenerator(string layoutPath)
{
LayoutPath = layoutPath != null ? layoutPath.Trim(' ', '"') : null;
}
public string LayoutPath { get; set; }
public override void GenerateCode(Span target, CodeGeneratorContext context)
{
if (!context.Host.DesignTimeMode && !String.IsNullOrEmpty(context.Host.GeneratedClassContext.LayoutPropertyName))
{
context.GeneratedClass.CustomAttributes.Add(
new CodeAttributeDeclaration(typeof(MetaAttribute).FullName,
new CodeAttributeArgument(new CodePrimitiveExpression("Layout")),
new CodeAttributeArgument(new CodePrimitiveExpression(LayoutPath))
));
context.TargetMethod.Statements.Add(
new CodeAssignStatement(
new CodePropertyReferenceExpression(null, context.Host.GeneratedClassContext.LayoutPropertyName),
new CodePrimitiveExpression(LayoutPath)));
}
}
public override string ToString()
{
return "Layout: " + LayoutPath;
}
public override bool Equals(object obj)
{
var other = obj as SetLayoutCodeGenerator;
return other != null && String.Equals(other.LayoutPath, LayoutPath, StringComparison.Ordinal);
}
public override int GetHashCode()
{
return LayoutPath.GetHashCode();
}
}
internal class SetModelTypeCodeGenerator : SetBaseTypeCodeGenerator
{
private readonly string _genericTypeFormat;
public SetModelTypeCodeGenerator(string modelType, string genericTypeFormat)
: base(modelType)
{
_genericTypeFormat = genericTypeFormat;
}
protected override string ResolveType(CodeGeneratorContext context, string baseType)
{
var typeString = string.Format(
CultureInfo.InvariantCulture, _genericTypeFormat, context.Host.DefaultBaseClass, baseType);
return typeString;
}
public override bool Equals(object obj)
{
var other = obj as SetModelTypeCodeGenerator;
return other != null &&
base.Equals(obj) &&
String.Equals(_genericTypeFormat, other._genericTypeFormat, StringComparison.Ordinal);
}
public override int GetHashCode()
{
return (base.GetHashCode() + _genericTypeFormat).GetHashCode();
}
public override string ToString()
{
return "Model:" + BaseType;
}
}
}
}