forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRazorFormat.cs
More file actions
734 lines (603 loc) · 25.6 KB
/
Copy pathRazorFormat.cs
File metadata and controls
734 lines (603 loc) · 25.6 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using ServiceStack.Common;
using ServiceStack.Html;
using ServiceStack.Logging;
using ServiceStack.Razor.Templating;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.VirtualPath;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Extensions;
using ServiceStack.WebHost.Endpoints.Support;
namespace ServiceStack.Razor
{
public enum RazorPageType
{
ContentPage = 1,
ViewPage = 2,
SharedViewPage = 3,
Template = 4,
}
public class RazorFormat : IRazorViewEngine, IPlugin, IRazorPlugin
{
private static readonly ILog Log = LogManager.GetLogger(typeof(RazorFormat));
private static RazorFormat instance;
public static RazorFormat Instance
{
get { return instance ?? (instance = new RazorFormat()); }
}
public static bool IsRegistered
{
get { return instance != null; }
}
private const string ErrorPageNotFound = "Could not find Razor page '{0}'";
public static string DefaultTemplateName = "_Layout.cshtml";
public static string DefaultTemplate = "_Layout";
public static string DefaultPage = "default";
public static string TemplatePlaceHolder = "@RenderBody()";
// ~/View - Dynamic Pages
public Dictionary<string, ViewPageRef> ViewPages;
// ~/View/Shared - Dynamic Shared Pages
public Dictionary<string, ViewPageRef> ViewSharedPages;
//Content Pages outside of ~/View
public Dictionary<string, ViewPageRef> ContentPages;
public Dictionary<string, ViewPageRef> MasterPageTemplates;
public IAppHost AppHost { get; set; }
public Dictionary<string, string> ReplaceTokens { get; set; }
public Func<string, IEnumerable<ViewPageRef>> FindRazorPagesFn { get; set; }
public IVirtualPathProvider VirtualPathProvider { get; set; }
public HashSet<string> TemplateNamespaces { get; set; }
public bool WatchForModifiedPages { get; set; }
public Dictionary<string, Type> RazorExtensionBaseTypes { get; set; }
public TemplateProvider TemplateProvider { get; set; }
public List<string> SkipPaths { get; set; }
public Type DefaultBaseType
{
get
{
Type baseType;
return RazorExtensionBaseTypes.TryGetValue("cshtml", out baseType) ? baseType : null;
}
set
{
RazorExtensionBaseTypes["cshtml"] = value;
}
}
public TemplateService TemplateService
{
get
{
TemplateService templateService;
return templateServices.TryGetValue("cshtml", out templateService) ? templateService : null;
}
}
public RazorFormat()
{
this.FindRazorPagesFn = FindRazorPages;
this.ReplaceTokens = new Dictionary<string, string>();
this.TemplateNamespaces = new HashSet<string> {
"System",
"System.Collections.Generic",
"System.Linq",
"ServiceStack.Html",
"ServiceStack.Razor",
};
this.RazorExtensionBaseTypes = new Dictionary<string, Type>(StringComparer.CurrentCultureIgnoreCase) {
{"cshtml", typeof(ViewPage<>) },
{"rzr", typeof(ViewPage<>) },
};
this.TemplateProvider = new TemplateProvider(DefaultTemplateName) {
CompileInParallelWithNoOfThreads = 0,
};
//Skip scanning common VS.NET extensions
this.SkipPaths = new List<string> {
"/obj/",
"/bin/",
};
}
public void Register(IAppHost appHost)
{
if (instance == null) instance = this;
Configure(appHost);
}
static readonly char[] DirSeps = new[] { '\\', '/' };
static HashSet<string> catchAllPathsNotFound = new HashSet<string>();
public void Configure(IAppHost appHost)
{
this.AppHost = appHost;
appHost.ViewEngines.Add(this);
//Default to watching modfied pages in DebugMode
if (!WatchForModifiedPages)
WatchForModifiedPages = appHost.Config.DebugMode;
//Default to parallel execution in DebugMode
if (this.TemplateProvider.CompileInParallelWithNoOfThreads <= 0)
this.TemplateProvider.CompileInParallelWithNoOfThreads = appHost.Config.DebugMode
? Environment.ProcessorCount * 2
: 0;
foreach (var ns in EndpointHostConfig.RazorNamespaces)
TemplateNamespaces.Add(ns);
this.ReplaceTokens = appHost.Config.HtmlReplaceTokens ?? new Dictionary<string, string>();
var webHostUrl = appHost.Config.WebHostUrl;
if (!webHostUrl.IsNullOrEmpty())
this.ReplaceTokens["~/"] = webHostUrl.WithTrailingSlash();
if (VirtualPathProvider == null)
VirtualPathProvider = AppHost.VirtualPathProvider;
Init();
RegisterRazorPages(appHost.Config.WebHostPhysicalPath);
appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => {
ViewPageRef razorPage = null;
if (catchAllPathsNotFound.Contains(pathInfo))
return null;
razorPage = FindByPathInfo(pathInfo);
if (WatchForModifiedPages)
ReloadIfNeeeded(razorPage);
if (razorPage == null)
{
foreach(var entry in RazorExtensionBaseTypes)
{
if (pathInfo.EndsWith("." + entry.Key))
{
pathInfo = pathInfo.EndsWith(DefaultPage + "." + entry.Key, StringComparison.InvariantCultureIgnoreCase)
? pathInfo.Substring(0, pathInfo.Length - (DefaultPage + "." + entry.Key).Length)
: pathInfo.WithoutExtension();
return new RedirectHttpHandler {
AbsoluteUrl = webHostUrl.IsNullOrEmpty()
? null
: webHostUrl.CombineWith(pathInfo),
RelativeUrl = webHostUrl.IsNullOrEmpty()
? pathInfo
: null
};
}
}
if (catchAllPathsNotFound.Count > 1000) //prevent DDOS
catchAllPathsNotFound = new HashSet<string>();
var tmp = new HashSet<string>(catchAllPathsNotFound) { pathInfo };
catchAllPathsNotFound = tmp;
return null;
}
return new RazorHandler(pathInfo) {
RazorFormat = this,
RazorPage = razorPage,
RequestName = "RazorPage",
};
});
}
public ViewPageRef FindByPathInfo(string pathInfo)
{
var normalizedPathInfo = pathInfo.IsNullOrEmpty() ? DefaultPage : pathInfo.TrimStart(DirSeps);
var razorPage = GetContentPage(
normalizedPathInfo,
normalizedPathInfo.CombineWith(DefaultPage));
return razorPage;
}
public bool ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, object dto)
{
ViewPageRef razorPage;
if ((razorPage = GetViewPageByResponse(dto, httpReq)) == null)
return false;
if (WatchForModifiedPages)
ReloadIfNeeeded(razorPage);
return ProcessRazorPage(httpReq, razorPage, dto, httpRes);
}
public bool HasView(string viewName, IHttpRequest httpReq=null)
{
return GetTemplateService(viewName, httpReq) != null;
}
public string RenderPartial(string pageName, object model, bool renderHtml, IHttpRequest httpReq = null)
{
var template = GetTemplateService(pageName, httpReq);
if (template == null)
{
string result = null;
foreach (var viewEngine in AppHost.ViewEngines)
{
if (viewEngine == this || !viewEngine.HasView(pageName, httpReq)) continue;
result = viewEngine.RenderPartial(pageName, model, renderHtml, httpReq);
if (result != null) break;
}
return result ?? "<!--{0} not found-->".Fmt(pageName);
}
//Razor writes partial to static StringBuilder so don't return or it will write zx2
template.RenderPartial(model, pageName);
//return template.Result;
return null;
}
private Dictionary<string, TemplateService> templateServices;
private TemplateService[] templateServicesArray;
public void Init()
{
ViewPages = new Dictionary<string, ViewPageRef>(StringComparer.CurrentCultureIgnoreCase);
// ~/View/Shared - Dynamic Shared Pages
ViewSharedPages = new Dictionary<string, ViewPageRef>(StringComparer.CurrentCultureIgnoreCase);
//Content Pages outside of ~/View
ContentPages = new Dictionary<string, ViewPageRef>(StringComparer.CurrentCultureIgnoreCase);
MasterPageTemplates = new Dictionary<string, ViewPageRef>(StringComparer.CurrentCultureIgnoreCase);
//Force Binder to load
var loaded = typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly != null;
if (!loaded)
throw new ConfigurationErrorsException("Microsoft.CSharp not properly loaded");
templateServices = new Dictionary<string, TemplateService>(StringComparer.CurrentCultureIgnoreCase);
foreach (var entry in RazorExtensionBaseTypes)
{
var razorBaseType = entry.Value;
if (razorBaseType != null && !razorBaseType.HasInterface(typeof(ITemplatePage)))
throw new ConfigurationErrorsException(razorBaseType.FullName + " must inherit from RazorBasePage");
var ext = entry.Key[0] == '.' ? entry.Key.Substring(1) : entry.Key;
templateServices[ext] = new TemplateService(this, razorBaseType) {
Namespaces = TemplateNamespaces
};
}
templateServicesArray = templateServices.Values.ToArray();
}
public bool ProcessRazorPage(IHttpRequest httpReq, ViewPageRef razorPage, object dto, IHttpResponse httpRes)
{
//Add extensible way to control caching
//httpRes.AddHeaderLastModified(razorPage.GetLastModified());
var razorTemplate = ExecuteTemplate(dto, razorPage.PageName, razorPage.Template, httpReq, httpRes);
var html = razorTemplate.Result;
var htmlBytes = html.ToUtf8Bytes();
//var hasBom = html.Contains((char)65279);
//TODO: Replace sad hack replacing the BOM with whitespace (ASP.NET+Mono):
for (var i=0; i < htmlBytes.Length - 3; i++)
{
if (htmlBytes[i] == 0xEF && htmlBytes[i + 1] == 0xBB && htmlBytes[i + 2] == 0xBF)
{
htmlBytes[i] = (byte)' ';
htmlBytes[i + 1] = (byte)' ';
htmlBytes[i + 2] = (byte)' ';
}
}
httpRes.OutputStream.Write(htmlBytes, 0, htmlBytes.Length);
var disposable = razorTemplate as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
httpRes.EndServiceStackRequest(skipHeaders: true);
return true;
}
public void ReloadIfNeeeded(ViewPageRef razorPage)
{
if (razorPage == null || razorPage.FilePath == null || !WatchForModifiedPages) return;
var latestPage = GetLatestPage(razorPage);
if (latestPage.LastModified > razorPage.LastModified)
razorPage.Reload(GetPageContents(latestPage), latestPage.LastModified);
ViewPageRef template;
if (razorPage.Template != null
&& this.MasterPageTemplates.TryGetValue(razorPage.Template, out template))
{
latestPage = GetLatestPage(template);
if (latestPage.LastModified > template.LastModified)
template.Reload(GetPageContents(latestPage), latestPage.LastModified);
}
}
private IVirtualFile GetLatestPage(ViewPageRef razorPage)
{
var file = VirtualPathProvider.GetFile(razorPage.FilePath);
return file;
}
private ViewPageRef GetViewPageByResponse(object dto, IHttpRequest httpReq)
{
var httpResult = dto as IHttpResult;
if (httpResult != null)
{
dto = httpResult.Response;
}
//If View was specified don't look for anything else.
var viewName = httpReq.GetView();
if (!string.IsNullOrEmpty(viewName))
return GetViewPage(viewName);
//Since the Request DTO Name should be unique, look for a viewName with that first
if (httpReq != null && httpReq.OperationName != null)
{
var pageRef = GetViewPage(httpReq.OperationName);
if (pageRef != null)
return pageRef;
}
if (dto != null)
{
var responseTypeName = dto.GetType().Name;
var pageRef = GetViewPage(responseTypeName);
if (pageRef != null) return pageRef;
}
return null;
}
public IViewPage GetView(string name)
{
return GetViewPage(name);
}
public void EnsureAllCompiled()
{
TemplateProvider.EnsureAllCompiled();
}
public ViewPageRef GetViewPage(string pageName)
{
if (pageName == null) return null;
ViewPageRef razorPage;
ViewPages.TryGetValue(pageName, out razorPage);
if (razorPage != null)
{
if (WatchForModifiedPages)
ReloadIfNeeeded(razorPage);
razorPage.EnsureCompiled();
return razorPage;
}
ViewSharedPages.TryGetValue(pageName, out razorPage);
if (razorPage != null)
{
if (WatchForModifiedPages)
ReloadIfNeeeded(razorPage);
razorPage.EnsureCompiled();
}
return razorPage;
}
private void RegisterRazorPages(string razorSearchPath)
{
foreach (var page in FindRazorPagesFn(razorSearchPath))
{
AddPage(page);
}
try
{
TemplateProvider.CompileQueuedPages();
}
catch (Exception ex)
{
HandleCompilationException(null, ex);
}
}
public IEnumerable<ViewPageRef> FindRazorPages(string dirPath)
{
var hasReloadableWebPages = false;
foreach (var entry in templateServices)
{
var ext = entry.Key;
var csHtmlFiles = VirtualPathProvider.GetAllMatchingFiles("*." + ext).ToList();
foreach (var csHtmlFile in csHtmlFiles)
{
if (ShouldSkipPath(csHtmlFile)) continue;
if (csHtmlFile.GetType().Name != "ResourceVirtualFile")
hasReloadableWebPages = true;
var pageName = csHtmlFile.Name.WithoutExtension();
var pageContents = GetPageContents(csHtmlFile);
var pageType = RazorPageType.ContentPage;
if (VirtualPathProvider.IsSharedFile(csHtmlFile))
pageType = RazorPageType.SharedViewPage;
else if (VirtualPathProvider.IsViewFile(csHtmlFile))
pageType = RazorPageType.ViewPage;
var templateService = entry.Value;
templateService.RegisterPage(csHtmlFile.VirtualPath, pageName);
var templatePath = pageType == RazorPageType.ContentPage
? TemplateProvider.GetTemplatePath(csHtmlFile.Directory)
: null;
yield return new ViewPageRef(this, csHtmlFile.VirtualPath, pageName, pageContents, pageType) {
Template = templatePath,
LastModified = csHtmlFile.LastModified,
Service = templateService
};
}
}
if (!hasReloadableWebPages)
WatchForModifiedPages = false;
}
private bool ShouldSkipPath(IVirtualFile csHtmlFile)
{
foreach (var skipPath in SkipPaths)
{
if (csHtmlFile.VirtualPath.StartsWith(skipPath, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
public void AddPage(ViewPageRef page)
{
try
{
TemplateProvider.QueuePageToCompile(page);
AddViewPage(page);
}
catch (Exception ex)
{
HandleCompilationException(page, ex);
}
try
{
var templatePath = page.Template;
if (page.Template == null) return;
if (MasterPageTemplates.ContainsKey(templatePath)) return;
var templateFile = VirtualPathProvider.GetFile(templatePath);
var templateContents = GetPageContents(templateFile);
AddTemplate(templatePath, templateContents);
}
catch (Exception ex)
{
Log.Error("Error compiling template " + page.Template + ": " + ex.Message, ex);
}
}
private void HandleCompilationException(ViewPageRef page, Exception ex)
{
var tcex = ex as TemplateCompilationException;
if (page == null)
{
Log.Error("Error compiling Razor page", ex);
if (tcex != null)
{
Log.Error(tcex.Errors.Dump());
}
return;
}
if (tcex != null)
{
Log.Error("Error compiling page {0}".Fmt(page.Name));
Log.Error(tcex.Errors.Dump());
}
var errorViewPage = new ErrorViewPage(this, ex) {
Name = page.Name,
PageType = page.PageType,
FilePath = page.FilePath,
};
errorViewPage.Compile();
AddViewPage(errorViewPage);
Log.Error("Razor AddViewPage() page.Prepare(): " + ex.Message, ex);
}
private void AddViewPage(ViewPageRef page)
{
switch (page.PageType)
{
case RazorPageType.ViewPage:
ViewPages.Add(page.Name, page);
break;
case RazorPageType.SharedViewPage:
ViewSharedPages.Add(page.Name, page);
break;
case RazorPageType.ContentPage:
ContentPages.Add(page.FilePath.WithoutExtension().TrimStart(DirSeps), page);
break;
}
}
public ViewPageRef AddTemplate(string templatePath, string templateContents)
{
var templateFile = VirtualPathProvider.GetFile(templatePath);
var templateName = templateFile.Name.WithoutExtension();
TemplateService templateService;
if (!templateServices.TryGetValue(templateFile.Extension, out templateService))
throw new ConfigurationErrorsException(
"No BaseType registered with extension " + templateFile.Extension + " for template " + templateFile.Name);
var template = new ViewPageRef(this, templatePath, templateName, templateContents, RazorPageType.Template) {
LastModified = templateFile.LastModified,
Service = templateService,
};
MasterPageTemplates.Add(templatePath, template);
try
{
//template.Compile();
TemplateProvider.QueuePageToCompile(template);
return template;
}
catch (Exception ex)
{
Log.Error("AddViewPage() template.Prepare(): " + ex.Message, ex);
return null;
}
}
private string GetPageContents(IVirtualFile page)
{
return ReplaceContentWithRewriteTokens(page.ReadAllText());
}
private string ReplaceContentWithRewriteTokens(string contents)
{
foreach (var replaceToken in ReplaceTokens)
{
contents = contents.Replace(replaceToken.Key, replaceToken.Value);
}
return contents;
}
public ViewPageRef GetContentPage(string pageFilePath)
{
ViewPageRef razorPage;
if (ContentPages.TryGetValue(pageFilePath, out razorPage))
{
razorPage.EnsureCompiled();
}
return razorPage;
}
public ViewPageRef GetContentPage(params string[] pageFilePaths)
{
foreach (var pageFilePath in pageFilePaths)
{
var razorPage = GetContentPage(pageFilePath);
if (razorPage != null)
return razorPage;
}
return null;
}
public string GetTemplate(string name)
{
ViewPageRef template;
MasterPageTemplates.TryGetValue(name, out template); //e.g. /NoModelNoController.cshtml
if (template != null)
{
ReloadIfNeeeded(template);
template.EnsureCompiled();
return template.Contents;
}
return null;
}
public ITemplate CreateInstance(Type type)
{
var instance = type.CreateInstance();
var templatePage = instance as ITemplatePage;
if (templatePage != null)
{
templatePage.AppHost = AppHost;
templatePage.ViewEngine = this;
}
var template = (ITemplate)instance;
return template;
}
public string RenderStaticPage(string filePath)
{
if (filePath == null)
throw new ArgumentNullException("filePath");
filePath = filePath.WithoutExtension();
ViewPageRef razorPage;
if (!ContentPages.TryGetValue(filePath, out razorPage))
throw new InvalidDataException(ErrorPageNotFound.FormatWith(filePath));
return RenderStaticPage(razorPage);
}
private string RenderStaticPage(ViewPageRef markdownPage)
{
var template = ExecuteTemplate((object)null,
markdownPage.PageName, markdownPage.Template);
return template.Result;
}
public IRazorTemplate ExecuteTemplate<T>(T model, string name, string templatePath)
{
return ExecuteTemplate(model, name, templatePath, null, null);
}
public bool HasTemplate(string pagePathOrName)
{
return GetTemplateService(pagePathOrName) != null;
}
public TemplateService GetTemplateService(string pagePathOrName)
{
foreach (var templateService in templateServicesArray)
{
if (TemplateService.ContainsPagePath(pagePathOrName))
return templateService;
}
foreach (var templateService in templateServicesArray)
{
if (TemplateService.ContainsPageName(pagePathOrName))
return templateService;
}
return null;
}
public TemplateService GetTemplateService(string pagePathOrName, IHttpRequest httpReq)
{
var serviceWithView = GetTemplateService(pagePathOrName);
if (serviceWithView != null) return serviceWithView;
if (httpReq == null || httpReq.PathInfo == null) return null;
var normalizedPathInfo = httpReq.PathInfo;
if (!httpReq.RawUrl.EndsWith("/"))
normalizedPathInfo = normalizedPathInfo.ParentDirectory();
normalizedPathInfo = normalizedPathInfo.CombineWith(pagePathOrName).TrimStart(DirSeps);
var razorPage = GetContentPage(
normalizedPathInfo,
normalizedPathInfo.CombineWith(DefaultPage));
if (razorPage != null && razorPage.FilePath != null)
return GetTemplateService(razorPage.FilePath);
return null;
}
public IRazorTemplate ExecuteTemplate<T>(T model, string name, string templatePath, IHttpRequest httpReq, IHttpResponse httpRes)
{
return GetTemplateService(name).ExecuteTemplate(model, name, templatePath, httpReq, httpRes);
}
}
}