-
Notifications
You must be signed in to change notification settings - Fork 0
/
T4MVC.tt
1549 lines (1288 loc) · 61.3 KB
/
T4MVC.tt
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
/*
T4MVC Version 2.6.31
Find latest version and documentation at http://mvccontrib.codeplex.com/wikipage?title=T4MVC
Discuss on StackOverflow or on the MVC forum (http://forums.asp.net/1146.aspx)
T4MVC is part of the MvcContrib project (http://mvccontrib.codeplex.com)
Maintained by David Ebbo, with much feedback from the MVC community (thanks all!)
http://twitter.com/davidebbo
http://blogs.msdn.com/davidebb
Related blog posts: http://blogs.msdn.com/davidebb/archive/tags/T4MVC/default.aspx
Please use in accordance to the MvcContrib license (http://mvccontrib.codeplex.com/license)
*/
#>
<#@ template language="C#" debug="true" hostspecific="true" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="Microsoft.VisualStudio.Shell.Interop.8.0" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="EnvDTE80" #>
<#@ assembly name="VSLangProj" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="Microsoft.VisualStudio.Shell.Interop" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#PrepareDataToRender(this); #>
<#var manager = Manager.Create(Host, GenerationEnvironment); #>
<#manager.StartHeader(); #>// <auto-generated />
// This file was generated by a T4 template.
// Don't change it directly as your change would get overwritten. Instead, make changes
// to the .tt file (i.e. the T4 template) and save it to regenerate this file.
// Make sure the compiler doesn't complain about missing Xml comments
#pragma warning disable 1591
#region T4MVC
using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using <#=T4MVCNamespace #>;
<#foreach (var referencedNamespace in ReferencedNamespaces) { #>
using <#=referencedNamespace #>;
<#} #>
<#manager.EndBlock(); #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public static class <#=HelpersPrefix #> {
<#if (IncludeAreasToken) { #>
public static class Areas {
<#} #>
<#foreach (var area in Areas.Where(a => !string.IsNullOrEmpty(a.Name))) { #>
static readonly <#=area.Name #>Class s_<#=area.Name #> = new <#=area.Name #>Class();
public static <#=area.Name #>Class <#=EscapeID(area.Namespace) #> { get { return s_<#=area.Name #>; } }
<#} #>
<#if (IncludeAreasToken) { #>
}
<#} #>
<#foreach (var controller in DefaultArea.GetControllers()) { #>
public static <#=controller.FullClassName #> <#=controller.Name #> = new <#=controller.FullDerivedClassName #>();
<#} #>
}
namespace <#=T4MVCNamespace #> {
<#foreach (var area in Areas.Where(a => !string.IsNullOrEmpty(a.Name))) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class <#=area.Name #>Class {
public readonly string Name = "<#=ProcessAreaOrControllerName(area.Name) #>";
<#foreach (var controller in area.GetControllers()) { #>
public <#=controller.FullClassName #> <#=controller.Name #> = new <#=controller.FullDerivedClassName #>();
<#} #>
}
<#} #>
}
namespace System.Web.Mvc {
[<#= GeneratedCode #>, DebuggerNonUserCode]
public static class T4Extensions {
public static <#=HtmlStringType #> ActionLink(this HtmlHelper htmlHelper, string linkText, ActionResult result) {
return htmlHelper.RouteLink(linkText, result.GetRouteValueDictionary());
}
public static <#=HtmlStringType #> ActionLink(this HtmlHelper htmlHelper, string linkText, ActionResult result, object htmlAttributes) {
return ActionLink(htmlHelper, linkText, result, new RouteValueDictionary(htmlAttributes));
}
public static <#=HtmlStringType #> ActionLink(this HtmlHelper htmlHelper, string linkText, ActionResult result, IDictionary<string, object> htmlAttributes) {
return htmlHelper.RouteLink(linkText, result.GetRouteValueDictionary(), htmlAttributes);
}
public static MvcForm BeginForm(this HtmlHelper htmlHelper, ActionResult result, FormMethod formMethod) {
return htmlHelper.BeginForm(result, formMethod, null);
}
public static MvcForm BeginForm(this HtmlHelper htmlHelper, ActionResult result, FormMethod formMethod, object htmlAttributes) {
return BeginForm(htmlHelper, result, formMethod, new RouteValueDictionary(htmlAttributes));
}
public static MvcForm BeginForm(this HtmlHelper htmlHelper, ActionResult result, FormMethod formMethod, IDictionary<string, object> htmlAttributes) {
var callInfo = result.GetT4MVCResult();
return htmlHelper.BeginForm(callInfo.Action, callInfo.Controller, callInfo.RouteValueDictionary, formMethod, htmlAttributes);
}
<#if (MvcVersion >= 2) {#>
public static void RenderAction(this HtmlHelper htmlHelper, ActionResult result) {
var callInfo = result.GetT4MVCResult();
htmlHelper.RenderAction(callInfo.Action, callInfo.Controller, callInfo.RouteValueDictionary);
}
public static MvcHtmlString Action(this HtmlHelper htmlHelper, ActionResult result) {
var callInfo = result.GetT4MVCResult();
return htmlHelper.Action(callInfo.Action, callInfo.Controller, callInfo.RouteValueDictionary);
}
<#} #>
public static string Action(this UrlHelper urlHelper, ActionResult result) {
return urlHelper.RouteUrl(result.GetRouteValueDictionary());
}
public static string ActionAbsolute(this UrlHelper urlHelper, ActionResult result) {
return string.Format("{0}{1}",urlHelper.RequestContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority),
urlHelper.RouteUrl(result.GetRouteValueDictionary()));
}
public static <#=HtmlStringType #> ActionLink(this AjaxHelper ajaxHelper, string linkText, ActionResult result, AjaxOptions ajaxOptions) {
return ajaxHelper.RouteLink(linkText, result.GetRouteValueDictionary(), ajaxOptions);
}
public static <#=HtmlStringType #> ActionLink(this AjaxHelper ajaxHelper, string linkText, ActionResult result, AjaxOptions ajaxOptions, object htmlAttributes) {
return ajaxHelper.RouteLink(linkText, result.GetRouteValueDictionary(), ajaxOptions, new RouteValueDictionary(htmlAttributes));
}
public static <#=HtmlStringType #> ActionLink(this AjaxHelper ajaxHelper, string linkText, ActionResult result, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {
return ajaxHelper.RouteLink(linkText, result.GetRouteValueDictionary(), ajaxOptions, htmlAttributes);
}
public static Route MapRoute(this RouteCollection routes, string name, string url, ActionResult result) {
return MapRoute(routes, name, url, result, null /*namespaces*/);
}
public static Route MapRoute(this RouteCollection routes, string name, string url, ActionResult result, object defaults) {
return MapRoute(routes, name, url, result, defaults, null /*constraints*/, null /*namespaces*/);
}
public static Route MapRoute(this RouteCollection routes, string name, string url, ActionResult result, string[] namespaces) {
return MapRoute(routes, name, url, result, null /*defaults*/, namespaces);
}
public static Route MapRoute(this RouteCollection routes, string name, string url, ActionResult result, object defaults, object constraints) {
return MapRoute(routes, name, url, result, defaults, constraints, null /*namespaces*/);
}
public static Route MapRoute(this RouteCollection routes, string name, string url, ActionResult result, object defaults, string[] namespaces) {
return MapRoute(routes, name, url, result, defaults, null /*constraints*/, namespaces);
}
public static Route MapRoute(this RouteCollection routes, string name, string url, ActionResult result, object defaults, object constraints, string[] namespaces) {
// Create and add the route
var route = CreateRoute(url, result, defaults, constraints, namespaces);
routes.Add(name, route);
return route;
}
<#if (MvcVersion >= 2) {#>
// Note: can't name the AreaRegistrationContext methods 'MapRoute', as that conflicts with the existing methods
public static Route MapRouteArea(this AreaRegistrationContext context, string name, string url, ActionResult result) {
return MapRouteArea(context, name, url, result, null /*namespaces*/);
}
public static Route MapRouteArea(this AreaRegistrationContext context, string name, string url, ActionResult result, object defaults) {
return MapRouteArea(context, name, url, result, defaults, null /*constraints*/, null /*namespaces*/);
}
public static Route MapRouteArea(this AreaRegistrationContext context, string name, string url, ActionResult result, string[] namespaces) {
return MapRouteArea(context, name, url, result, null /*defaults*/, namespaces);
}
public static Route MapRouteArea(this AreaRegistrationContext context, string name, string url, ActionResult result, object defaults, object constraints) {
return MapRouteArea(context, name, url, result, defaults, constraints, null /*namespaces*/);
}
public static Route MapRouteArea(this AreaRegistrationContext context, string name, string url, ActionResult result, object defaults, string[] namespaces) {
return MapRouteArea(context, name, url, result, defaults, null /*constraints*/, namespaces);
}
public static Route MapRouteArea(this AreaRegistrationContext context, string name, string url, ActionResult result, object defaults, object constraints, string[] namespaces) {
// Create and add the route
var route = CreateRoute(url, result, defaults, constraints, namespaces);
context.Routes.Add(name, route);
route.DataTokens["area"] = context.AreaName;
return route;
}
<#} #>
private static Route CreateRoute(string url, ActionResult result, object defaults, object constraints, string[] namespaces) {
// Start by adding the default values from the anonymous object (if any)
var routeValues = new RouteValueDictionary(defaults);
// Then add the Controller/Action names and the parameters from the call
foreach (var pair in result.GetRouteValueDictionary()) {
routeValues.Add(pair.Key, pair.Value);
}
var routeConstraints = new RouteValueDictionary(constraints);
// Create and add the route
var route = new Route(url, routeValues, routeConstraints, new MvcRouteHandler());
route.DataTokens = new RouteValueDictionary();
if (namespaces != null && namespaces.Length > 0) {
route.DataTokens["Namespaces"] = namespaces;
}
return route;
}
public static <#=ActionResultInterfaceName #> GetT4MVCResult(this ActionResult result) {
var t4MVCResult = result as <#=ActionResultInterfaceName #>;
if (t4MVCResult == null) {
throw new InvalidOperationException("T4MVC was called incorrectly. You may need to force it to regenerate by right clicking on T4MVC.tt and choosing Run Custom Tool");
}
return t4MVCResult;
}
public static RouteValueDictionary GetRouteValueDictionary(this ActionResult result) {
return result.GetT4MVCResult().RouteValueDictionary;
}
public static ActionResult AddRouteValues(this ActionResult result, object routeValues) {
return result.AddRouteValues(new RouteValueDictionary(routeValues));
}
public static ActionResult AddRouteValues(this ActionResult result, RouteValueDictionary routeValues) {
RouteValueDictionary currentRouteValues = result.GetRouteValueDictionary();
// Add all the extra values
foreach (var pair in routeValues) {
currentRouteValues.Add(pair.Key, pair.Value);
}
return result;
}
public static ActionResult AddRouteValues(this ActionResult result, System.Collections.Specialized.NameValueCollection nameValueCollection) {
// Copy all the values from the NameValueCollection into the route dictionary
nameValueCollection.CopyTo(result.GetRouteValueDictionary());
return result;
}
public static ActionResult AddRouteValue(this ActionResult result, string name, object value) {
RouteValueDictionary routeValues = result.GetRouteValueDictionary();
routeValues.Add(name, value);
return result;
}
public static void InitMVCT4Result(this <#=ActionResultInterfaceName #> result, string area, string controller, string action) {
result.Controller = controller;
result.Action = action;
result.RouteValueDictionary = new RouteValueDictionary();
<# if (Areas.Count > 1) { #>result.RouteValueDictionary.Add("Area", area ?? "");<# } #>
result.RouteValueDictionary.Add("Controller", controller);
result.RouteValueDictionary.Add("Action", action);
}
public static bool FileExists(string virtualPath) {
if (!HostingEnvironment.IsHosted) return false;
string filePath = HostingEnvironment.MapPath(virtualPath);
return System.IO.File.Exists(filePath);
}
static DateTime CenturyBegin=new DateTime(2001,1,1);
public static string TimestampString(string virtualPath) {
if (!HostingEnvironment.IsHosted) return string.Empty;
string filePath = HostingEnvironment.MapPath(virtualPath);
return Convert.ToString((System.IO.File.GetLastWriteTimeUtc(filePath).Ticks-CenturyBegin.Ticks)/1000000000,16);
}
}
}
<#if (GenerateActionResultInterface) { #>
[<#= GeneratedCode #>]
public interface <#=ActionResultInterfaceName #> {
string Action { get; set; }
string Controller { get; set; }
RouteValueDictionary RouteValueDictionary { get; set; }
}
<#} #>
<#foreach (var resultType in ResultTypes.Values) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class T4MVC_<#=resultType.Name #> : <#=resultType.FullName #>, <#=ActionResultInterfaceName #> {
public T4MVC_<#=resultType.Name #>(string area, string controller, string action): base(<#resultType.Constructor.WriteNonEmptyParameterValues(true); #>) {
this.InitMVCT4Result(area, controller, action);
}
<#foreach (var method in resultType.AbstractMethods) { #>
<#=method.IsPublic ? "public" : "protected" #> override void <#=method.Name #>(<#method.WriteFormalParameters(true); #>) { }
<#} #>
public string Controller { get; set; }
public string Action { get; set; }
public RouteValueDictionary RouteValueDictionary { get; set; }
}
<#} #>
namespace <#=LinksNamespace #> {
<#
foreach (string folder in StaticFilesFolders) {
ProcessStaticFiles(Project, folder);
}
#>
}
<#
RenderAdditionalCode();
#>
<#foreach (var controller in GetAbstractControllers().Where(c => !c.HasDefaultConstructor)) { #>
<#manager.StartNewFile(controller.GeneratedFileName); #>
namespace <#=controller.Namespace #> {
public partial class <#=controller.ClassName #> {
protected <#=controller.ClassName #>() { }
}
}
<#manager.EndBlock(); #>
<#} #>
<#foreach (var controller in GetControllers()) { #>
<#
// Don't generate the file at all if the existing one is up to date
// NOTE: disable this optimization since it doesn't catch view changes! It can be re-enabled later if smarter change detection is added
//if (controller.GeneratedCodeIsUpToDate) {
// manager.KeepGeneratedFile(controller.GeneratedFileName);
// continue;
//}
#>
<#manager.StartNewFile(controller.GeneratedFileName); #>
<#if (!String.IsNullOrEmpty(controller.Namespace)) { #>
namespace <#=controller.Namespace #> {
<#} #>
public <#if (!controller.NotRealController) { #>partial <#} #>class <#=controller.ClassName #> {
<#if (!controller.NotRealController) { #>
<#if (!controller.HasExplicitConstructor) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public <#=controller.ClassName #>() { }
<#} #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
protected <#=controller.ClassName #>(Dummy d) { }
[<#= GeneratedCode #>, DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToAction(ActionResult result) {
var callInfo = result.GetT4MVCResult();
return RedirectToRoute(callInfo.RouteValueDictionary);
}
<#foreach (var method in controller.ActionMethodsUniqueWithoutParameterlessOverload) { #>
[NonAction]
[<#= GeneratedCode #>, DebuggerNonUserCode]
public <#=method.ReturnTypeFullName #> <#=method.Name #>() {
return new T4MVC_<#=method.ReturnType #>(Area, Name, ActionNames.<#=method.ActionName #>);
}
<#} #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public <#=controller.ClassName #> Actions { get { return <#=controller.T4MVCControllerFullName #>; } }
[<#= GeneratedCode #>]
public readonly string Area = "<#=ProcessAreaOrControllerName(controller.AreaName) #>";
[<#= GeneratedCode #>]
public readonly string Name = "<#=ProcessAreaOrControllerName(controller.Name) #>";
static readonly ActionNamesClass s_actions = new ActionNamesClass();
[<#= GeneratedCode #>, DebuggerNonUserCode]
public ActionNamesClass ActionNames { get { return s_actions; } }
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class ActionNamesClass {
<#foreach (var method in controller.ActionMethodsWithUniqueNames) { #>
<# if (UseLowercaseRoutes) { #>
public readonly string <#=method.ActionName #> = (<#=method.ActionNameValueExpression #>).ToLowerInvariant();
<# } else { #>
public readonly string <#=method.ActionName #> = <#=method.ActionNameValueExpression #>;
<# }
} #>
}
<#} #>
static readonly ViewNames s_views = new ViewNames();
[<#= GeneratedCode #>, DebuggerNonUserCode]
public ViewNames Views { get { return s_views; } }
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class ViewNames {
<#RenderControllerViews(controller);#>
}
}
<#if (!controller.NotRealController) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class <#=controller.DerivedClassName #>: <#=controller.FullClassName #> {
public <#=controller.DerivedClassName #>() : base(Dummy.Instance) { }
<#foreach (var method in controller.ActionMethods) { #>
public override <#=method.ReturnTypeFullName #> <#=method.Name #>(<#method.WriteFormalParameters(true); #>) {
var callInfo = new T4MVC_<#=method.ReturnType #>(Area, Name, ActionNames.<#=method.ActionName #>);
<#if (method.Parameters.Count > 0) { #>
<#foreach (var p in method.Parameters) { #>
callInfo.RouteValueDictionary.Add(<#=p.RouteNameExpression #>, <#=p.Name #>);
<#} #>
<#}#>
return callInfo;
}
<#} #>
}
<#} #>
<#if (!String.IsNullOrEmpty(controller.Namespace)) { #>
}
<#} #>
<#manager.EndBlock(); #>
<#} #>
namespace <#=T4MVCNamespace #> {
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class Dummy {
private Dummy() { }
public static Dummy Instance = new Dummy();
}
}
<# if (ExplicitHtmlHelpersForPartials) {
manager.StartNewFile("T4MVC.ExplicitExtensions.cs"); #>
namespace System.Web.Mvc {
[<#= GeneratedCode #>]
public static class HtmlHelpersForExplicitPartials {
<#
foreach(var partial in GetPartials()) {
string partialName = partial.Key;
string partialPath = partial.Value;
string partialRenderMethod = string.Format(ExplicitHtmlHelpersForPartialsFormat, partialName);
#>
///<summary>
///Render the <b><#= partialName #></b> partial.
///</summary>
public static void <#= partialRenderMethod #>(this HtmlHelper html) {
html.RenderPartial("<#= partialPath #>");
}
///<summary>
///Render the <b><#= partialName #></b> partial.
///</summary>
public static void <#= partialRenderMethod #>(this HtmlHelper html, object model) {
html.RenderPartial("<#= partialPath #>", model);
}
<# } #>
}
}
<# manager.EndBlock(); #>
<# } #>
<#manager.StartFooter(); #>
#endregion T4MVC
#pragma warning restore 1591
<#manager.EndBlock(); #>
<#manager.Process(SplitIntoMultipleFiles); #>
<#@ Include File="T4MVC.settings.t4" #>
<#+
const string T4MVCNamespace = "T4MVC";
const string ControllerSuffix = "Controller";
static DTE Dte;
static Project Project;
static string AppRoot;
static HashSet<AreaInfo> Areas;
static AreaInfo DefaultArea;
static Dictionary<string, ResultTypeInfo> ResultTypes;
static TextTransformation TT;
static string T4FileName;
static string T4Folder;
static string GeneratedCode = @"GeneratedCode(""T4MVC"", ""2.0"")";
static float MvcVersion;
static string HtmlStringType;
static Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
IEnumerable<ControllerInfo> GetControllers() {
var controllers = new List<ControllerInfo>();
foreach (var area in Areas) {
controllers.AddRange(area.GetControllers());
}
return controllers;
}
IEnumerable<ControllerInfo> GetAbstractControllers() {
var controllers = new List<ControllerInfo>();
foreach (var area in Areas) {
controllers.AddRange(area.GetAbstractControllers());
}
return controllers;
}
IDictionary<string, string> GetPartials() {
var parts = GetControllers()
.Select(m => m.ViewsFolder)
.SelectMany(m => m.Views)
.Where(m => m.Value.EndsWith(".ascx"));
var partsDic = new Dictionary<string, KeyValuePair<string, string>>();
foreach(var part in parts) {
// Check if we already have a partial view by that name (e.g. if two Views folders have the same ascx)
int keyCollisionCount = partsDic.Where(m => m.Key == part.Key || m.Value.Key == part.Key).Count();
if (keyCollisionCount > 0) {
// Append a numbered suffix to avoid the conflict
partsDic.Add(part.Key + keyCollisionCount.ToString(), part);
}
else {
partsDic.Add(part.Key, part);
}
}
return partsDic.ToDictionary(k => k.Key, v => v.Value.Value);
}
void PrepareDataToRender(TextTransformation tt) {
TT = tt;
T4FileName = Path.GetFileName(Host.TemplateFile);
T4Folder = Path.GetDirectoryName(Host.TemplateFile);
Areas = new HashSet<AreaInfo>();
ResultTypes = new Dictionary<string, ResultTypeInfo>();
// Get the DTE service from the host
var serviceProvider = Host as IServiceProvider;
if (serviceProvider != null) {
Dte = serviceProvider.GetService(typeof(SDTE)) as DTE;
}
// Fail if we couldn't get the DTE. This can happen when trying to run in TextTransform.exe
if (Dte == null) {
throw new Exception("T4MVC can only execute through the Visual Studio host");
}
Project = GetProjectContainingT4File(Dte);
if (Project == null) {
Error("Could not find the VS Project containing the T4 file.");
return;
}
// Get the path of the root folder of the app
AppRoot = Path.GetDirectoryName(Project.FullName) + '\\';
MvcVersion = GetMvcVersion();
// Use the proper return type of render helpers
HtmlStringType = MvcVersion < 2 ? "string" : "MvcHtmlString";
ProcessAreas(Project);
}
float GetMvcVersion() {
var vsProject = (VSLangProj.VSProject)Project.Object;
foreach (VSLangProj.Reference r in vsProject.References) {
if (r.Name.Equals("System.Web.Mvc", StringComparison.OrdinalIgnoreCase)) {
return r.MajorVersion + (r.MinorVersion / 10);
}
}
// We should never get here, but default to v1 just in case
return 1;
}
Project GetProjectContainingT4File(DTE dte) {
// Find the .tt file's ProjectItem
ProjectItem projectItem = dte.Solution.FindProjectItem(Host.TemplateFile);
// If the .tt file is not opened, open it
if (projectItem.Document == null)
projectItem.Open(Constants.vsViewKindCode);
if (AlwaysKeepTemplateDirty) {
// Mark the .tt file as unsaved. This way it will be saved and update itself next time the
// project is built. Basically, it keeps marking itself as unsaved to make the next build work.
// Note: this is certainly hacky, but is the best I could come up with so far.
projectItem.Document.Saved = false;
}
return projectItem.ContainingProject;
}
void ProcessAreas(Project project) {
// Process the default area
ProcessArea(project.ProjectItems, null);
// Get the Areas folder
ProjectItem areaProjectItem = GetProjectItem(project, AreasFolder);
if (areaProjectItem == null)
return;
foreach (ProjectItem item in areaProjectItem.ProjectItems) {
if (IsFolder(item)) {
ProcessArea(item.ProjectItems, item.Name);
}
}
}
void ProcessArea(ProjectItems areaFolderItems, string name) {
var area = new AreaInfo() { Name = name };
ProcessAreaControllers(areaFolderItems, area);
ProcessAreaViews(areaFolderItems, area);
Areas.Add(area);
if (String.IsNullOrEmpty(name))
DefaultArea = area;
}
void ProcessAreaControllers(ProjectItems areaFolderItems, AreaInfo area) {
// Get area Controllers folder
ProjectItem controllerProjectItem = GetProjectItem(areaFolderItems, ControllersFolder);
if (controllerProjectItem == null)
return;
ProcessControllersRecursive(controllerProjectItem, area);
}
void ProcessAreaViews(ProjectItems areaFolderItems, AreaInfo area) {
// Get area Views folder
ProjectItem viewsProjectItem = GetProjectItem(areaFolderItems, ViewsRootFolder);
if (viewsProjectItem == null)
return;
ProcessAllViews(viewsProjectItem, area);
}
void ProcessControllersRecursive(ProjectItem projectItem, AreaInfo area) {
// Recurse into all the sub-items (both files and folder can have some - e.g. .tt files)
foreach (ProjectItem item in projectItem.ProjectItems) {
ProcessControllersRecursive(item, area);
}
if (projectItem.FileCodeModel != null) {
DateTime controllerLastWriteTime = File.GetLastWriteTime(projectItem.get_FileNames(0));
foreach (var type in projectItem.FileCodeModel.CodeElements.OfType<CodeClass2>()) {
ProcessControllerType(type, area, controllerLastWriteTime);
}
// Process all the elements that are namespaces
foreach (var ns in projectItem.FileCodeModel.CodeElements.OfType<CodeNamespace>()) {
foreach (var type in ns.Members.OfType<CodeClass2>()) {
ProcessControllerType(type, area, controllerLastWriteTime);
}
}
}
}
void ProcessControllerType(CodeClass2 type, AreaInfo area, DateTime controllerLastWriteTime) {
// Only process types that end with Controller
// REVIEW: this check is not super reliable. Should look at base class.
if (!type.Name.EndsWith(ControllerSuffix, StringComparison.OrdinalIgnoreCase))
return;
// Don't process generic classes (their concrete derived classes will be processed)
if (type.IsGeneric)
return;
// Make sure the class is partial
if (type.ClassKind != vsCMClassKind.vsCMClassKindPartialClass) {
try {
type.ClassKind = vsCMClassKind.vsCMClassKindPartialClass;
}
catch {
// If we couldn't make it partial, give a warning and skip it
Warning(String.Format("{0} was not able to make the class {1} partial. Please change it manually if possible", T4FileName, type.Name));
return;
}
Warning(String.Format("{0} changed the class {1} to be partial", T4FileName, type.Name));
}
// Collect misc info about the controller class and add it to the collection
var controllerInfo = new ControllerInfo {
Area = area,
Namespace = type.Namespace != null ? type.Namespace.Name : String.Empty,
ClassName = type.Name
};
// Check if the controller has changed since the generated file was last created
DateTime lastGenerationTime = File.GetLastWriteTime(controllerInfo.GeneratedFileFullPath);
if (lastGenerationTime > controllerLastWriteTime) {
controllerInfo.GeneratedCodeIsUpToDate = true;
}
// Either process new ControllerInfo or integrate results into existing object for partially defined controllers
var target = area.Controllers.Add(controllerInfo) ? controllerInfo : area.Controllers.First(c => c.Equals(controllerInfo));
target.HasExplicitConstructor |= HasExplicitConstructor(type);
target.HasExplicitDefaultConstructor |= HasExplicitDefaultConstructor(type);
if (type.IsAbstract) {
// If it's abstract, set a flag and don't process action methods (derived classes will)
target.IsAbstract = true;
}
else {
// Process all the action methods in the controller
ProcessControllerActionMethods(target, type);
}
}
void ProcessControllerActionMethods(ControllerInfo controllerInfo, CodeClass2 current) {
// We want to process not just the controller class itself, but also its parents, as they
// may themselves define actions
for (CodeClass2 type = current; type != null && type.FullName != "System.Web.Mvc.Controller"; type = (CodeClass2)type.Bases.Item(1)) {
// If the type doesn't come from this project, some actions on it will fail. Try to get a real project type if possible.
if (type.InfoLocation != vsCMInfoLocation.vsCMInfoLocationProject) {
// Go through all the projects in the solution
//foreach (Project prj in Dte.Solution.Projects) {
for (int i = 1; i <= Dte.Solution.Projects.Count; i++) {
Project prj = null;
try {
prj = Dte.Solution.Projects.Item(i);
}
catch (System.Runtime.Serialization.SerializationException) {
// Some project types (that we don't care about) cause a strange exception, so ingore it
continue;
}
// Skip it if it's the current project or doesn't have a code model
try {
if (prj == Project || prj.CodeModel == null)
continue;
}
catch (System.NotImplementedException) {
// Installer project does not implement CodeModel property
continue;
}
// If we can get a local project type, use it instead of the original
var codeType = prj.CodeModel.CodeTypeFromFullName(type.FullName);
if (codeType != null && codeType.InfoLocation == vsCMInfoLocation.vsCMInfoLocationProject) {
type = (CodeClass2)codeType;
break;
}
}
}
foreach (CodeFunction2 method in GetMethods(type)) {
// Ignore non-public methods
if (method.Access != vsCMAccess.vsCMAccessPublic)
continue;
// Ignore methods that are marked as not being actions
if (GetAttribute(method.Attributes, "System.Web.Mvc.NonActionAttribute") != null)
continue;
// This takes care of avoiding generic types which cause method.Type.CodeType to blow up
if (method.Type.TypeKind != vsCMTypeRef.vsCMTypeRefCodeType)
continue;
// We only support action methods that return an ActionResult derived type
if (!method.Type.CodeType.get_IsDerivedFrom("System.Web.Mvc.ActionResult")) {
Warning(String.Format("{0} doesn't support {1}.{2} because it doesn't return a supported ActionResult type", T4FileName, type.Name, method.Name));
continue;
}
// If we haven't yet seen this return type, keep track of it
if (!ResultTypes.ContainsKey(method.Type.CodeType.Name)) {
var resTypeInfo = new ResultTypeInfo(method.Type.CodeType);
ResultTypes[method.Type.CodeType.Name] = resTypeInfo;
}
// Make sure the method is virtual
if (!method.CanOverride && method.OverrideKind != vsCMOverrideKind.vsCMOverrideKindOverride) {
try {
method.CanOverride = true;
}
catch {
// If we couldn't make it virtual, give a warning and skip it
Warning(String.Format("{0} was not able to make the action method {1}.{2} virtual. Please change it manually if possible", T4FileName, type.Name, method.Name));
continue;
}
Warning(String.Format("{0} changed the action method {1}.{2} to be virtual", T4FileName, type.Name, method.Name));
}
// Collect misc info about the action method and add it to the collection
controllerInfo.ActionMethods.Add(new ActionMethodInfo(method));
}
}
}
void ProcessAllViews(ProjectItem viewsProjectItem, AreaInfo area) {
// Go through all the sub-folders in the Views folder
foreach (ProjectItem item in viewsProjectItem.ProjectItems) {
// We only care about sub-folders, not files
if (!IsFolder(item))
continue;
// Find the controller for this view folder
ControllerInfo controller = area.Controllers.SingleOrDefault(c => c.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase));
if (controller == null) {
// If it doesn't match a controller, treat as a pseudo-controller for consistency
controller = new ControllerInfo {
Area = area,
NotRealController = true,
Namespace = MakeClassName(T4MVCNamespace, area.Name),
ClassName = item.Name + ControllerSuffix
};
area.Controllers.Add(controller);
}
AddViewsRecursive(item.ProjectItems, controller.ViewsFolder);
}
}
void AddViewsRecursive(ProjectItems items, ViewsFolderInfo viewsFolder) {
AddViewsRecursive(items, viewsFolder, false);
}
void AddViewsRecursive(ProjectItems items, ViewsFolderInfo viewsFolder, bool useNonQualifiedViewNames) {
// Go through all the files in the subfolder to get the view names
foreach (ProjectItem item in items) {
if (item.Kind == Constants.vsProjectItemKindPhysicalFile) {
if (Path.GetExtension(item.Name).Equals(".master", StringComparison.OrdinalIgnoreCase))
continue; // ignore master files
viewsFolder.AddView(item, useNonQualifiedViewNames);
}
else if (item.Kind == Constants.vsProjectItemKindPhysicalFolder) {
string folderName = Path.GetFileName(item.Name);
if (folderName.Equals("App_LocalResources", StringComparison.OrdinalIgnoreCase))
continue;
// Use simple view names if we're already in that mode, or if the folder name is in the collection
bool folderShouldUseNonQualifiedViewNames = useNonQualifiedViewNames || NonQualifiedViewFolders.Contains(folderName, StringComparer.OrdinalIgnoreCase);
var subViewFolder = new ViewsFolderInfo() { Name = folderName };
viewsFolder.SubFolders.Add(subViewFolder);
AddViewsRecursive(item.ProjectItems, subViewFolder, folderShouldUseNonQualifiedViewNames);
}
}
}
void RenderControllerViews(ControllerInfo controller) {
PushIndent(" ");
RenderViewsRecursive(controller.ViewsFolder, controller);
PopIndent();
}
void RenderViewsRecursive(ViewsFolderInfo viewsFolder, ControllerInfo controller) {
// For each view, generate a readonly string
foreach (var viewPair in viewsFolder.Views) {
WriteLine("public readonly string " + EscapeID(Sanitize(viewPair.Key)) + " = \"" + viewPair.Value + "\";");
}
// For each sub folder, generate a class and recurse
foreach (var subFolder in viewsFolder.SubFolders) {
string newClassName = Sanitize(subFolder.Name);#>
static readonly _<#=newClassName#> s_<#=newClassName#> = new _<#=newClassName#>();
public _<#=newClassName#> <#=EscapeID(newClassName)#> { get { return s_<#=newClassName#>; } }
public partial class _<#=newClassName#>{
<#+
PushIndent(" ");
RenderViewsRecursive(subFolder, controller);
PopIndent();
WriteLine("}");
}
}
void ProcessStaticFiles(Project project, string folder) {
ProjectItem folderProjectItem = GetProjectItem(project, folder);
if (folderProjectItem != null) {
ProcessStaticFilesRecursive(folderProjectItem, "~");
}
}
void ProcessStaticFilesRecursive(ProjectItem projectItem, string path) {
if (IsFolder(projectItem)) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public static class <#=EscapeID(Sanitize(projectItem.Name)) #> {
private const string URLPATH = "<#=path#>/<#=projectItem.Name#>";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
<#+
PushIndent(" ");
// Recurse into all the items in the folder
foreach (ProjectItem item in projectItem.ProjectItems) {
ProcessStaticFilesRecursive(item, path + "/" + projectItem.Name);
}
PopIndent();
#>
}
<#+
}
else { #>
<#+
if (!ExcludedStaticFileExtensions.Any(extension => projectItem.Name.EndsWith(extension, StringComparison.OrdinalIgnoreCase))) {
// if it's a non-minified javascript file
if (projectItem.Name.EndsWith(".js") && !projectItem.Name.EndsWith(".min.js")) {
if (AddTimestampToStaticLinks) { #>
public static readonly string <#=Sanitize(projectItem.Name)#> = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/<#=projectItem.Name.Replace(".js", ".min.js")#>") ? Url("<#=projectItem.Name.Replace(".js", ".min.js")#>")+"?"+T4Extensions.TimestampString(URLPATH + "/<#=projectItem.Name#>") : Url("<#=projectItem.Name#>")+"?"+T4Extensions.TimestampString(URLPATH + "/<#=projectItem.Name#>");
<#+} else {#>
public static readonly string <#=Sanitize(projectItem.Name)#> = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/<#=projectItem.Name.Replace(".js", ".min.js")#>") ? Url("<#=projectItem.Name.Replace(".js", ".min.js")#>") : Url("<#=projectItem.Name#>");
<#+} #>
<#+}
else if (AddTimestampToStaticLinks) { #>
public static readonly string <#=Sanitize(projectItem.Name)#> = Url("<#=projectItem.Name#>")+"?"+T4Extensions.TimestampString(URLPATH + "/<#=projectItem.Name#>");
<#+}
else { #>
public static readonly string <#=Sanitize(projectItem.Name)#> = Url("<#=projectItem.Name#>");
<#+}
} #>
<#+
// Non folder items may also have children (virtual folders, Class.cs -> Class.Designer.cs, template output)
// Just register them on the same path as their parent item
foreach (ProjectItem item in projectItem.ProjectItems) {
ProcessStaticFilesRecursive(item, path);
}
}
}
ProjectItem GetProjectItem(Project project, string name) {
return GetProjectItem(project.ProjectItems, name);
}
ProjectItem GetProjectItem(ProjectItems items, string subPath) {
ProjectItem current = null;
foreach (string name in subPath.Split('\\')) {
try {
// ProjectItems.Item() throws when it doesn't exist, so catch the exception
// to return null instead.
current = items.Item(name);
}
catch {
// If any chunk couldn't be found, fail
return null;
}
items = current.ProjectItems;
}
return current;
}
static string GetVirtualPath(ProjectItem item) {
string fileFullPath = item.get_FileNames(0);
if (!fileFullPath.StartsWith(AppRoot, StringComparison.OrdinalIgnoreCase))
throw new Exception(string.Format("File {0} is not under app root {1}. Please report issue.", fileFullPath, AppRoot));
// Make a virtual path from the physical path
return "~/" + fileFullPath.Substring(AppRoot.Length).Replace('\\', '/');
}
static string ProcessAreaOrControllerName(string name) {
return UseLowercaseRoutes ? name.ToLowerInvariant() : name;
}
// Return all the CodeFunction2 in the CodeElements collection
static IEnumerable<CodeFunction2> GetMethods(CodeClass2 codeClass) {
// Only look at regular method (e.g. ignore things like contructors)
return codeClass.Members.OfType<CodeFunction2>()
.Where(f => f.FunctionKind == vsCMFunction.vsCMFunctionFunction);
}
// Check if the class has any explicit constructor
static bool HasExplicitConstructor(CodeClass2 codeClass) {
return codeClass.Members.OfType<CodeFunction2>().Any(
f => f.FunctionKind == vsCMFunction.vsCMFunctionConstructor);
}
// Check if the class has a default (i.e. no params) constructor
static bool HasExplicitDefaultConstructor(CodeClass2 codeClass) {
return codeClass.Members.OfType<CodeFunction2>().Any(