/
T4MVC.tt
2886 lines (2479 loc) · 98.2 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 3.17.1
Find latest version and documentation at https://github.com/T4MVC/T4MVC/wiki/Documentation
Discuss on StackOverflow or on GitHub (https://github.com/T4MVC/T4MVC/issues)
T4MVC is part of the MvcContrib project, but in a different GitHub site (https://github.com/T4MVC/T4MVC)
Maintained by David Ebbo, with much feedback from the MVC community (thanks all!)
david.ebbo@microsoft.com
http://twitter.com/davidebbo
http://blog.davidebbo.com/ (previously: http://blogs.msdn.com/davidebb)
Related blog posts: http://blogs.msdn.com/davidebb/archive/tags/T4MVC/default.aspx
Please use in accordance to the license (https://github.com/T4MVC/T4MVC/blob/master/License.txt)
*/
#>
<#@ template language="C#" debug="true" hostspecific="true" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="Microsoft.VisualStudio.Shell.Interop" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="EnvDTE80" #>
<#@ assembly name="VSLangProj" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ 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" #>
<# // To debug, uncomment the next two lines !!
// System.Diagnostics.Debugger.Launch();
// System.Diagnostics.Debugger.Break();
#>
<#settings=MvcSettings.Load(Host);#>
<#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 and CLS compliance
// 0108: suppress "Foo hides inherited member Foo. Use the new keyword if hiding was intended." when a controller and its abstract parent are both processed
// 0114: suppress "Foo.BarController.Baz()' hides inherited member 'Qux.BarController.Baz()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." when an action (with an argument) overrides an action in a parent controller
#pragma warning disable 1591, 3008, 3009, 0108, 0114
#region T4MVC
using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
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 <#=settings.T4MVCNamespace #>;
<#foreach (var referencedNamespace in settings.ReferencedNamespaces) { #>
using <#=referencedNamespace #>;
<#} #>
<#manager.EndBlock(); #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public static partial class <#=settings.HelpersPrefix #>
{
<#if (settings.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 (settings.IncludeAreasToken) { #>
}
<#} #>
<#foreach (var controller in DefaultArea.GetControllers()) { #>
public static <#=controller.FullClassName #> <#=controller.Name #> = new <#=controller.FullDerivedClassName #>();
<#} #>
}
namespace <#=settings.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 <#=settings.T4MVCNamespace #>
{
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class Dummy
{
private Dummy() { }
public static Dummy Instance = new Dummy();
}
}
<#foreach (var resultType in ResultTypes.Values) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
internal partial class T4MVC_<#=resultType.UniqueName #> : <#=resultType.FullName #>, IT4MVCActionResult
{
public T4MVC_<#=resultType.UniqueName #>(string area, string controller, string action, string protocol = null): base(<#resultType.Constructor.WriteNonEmptyParameterValues(true); #>)
{
this.InitMVCT4Result(area, controller, action, protocol);
}
<#foreach (var method in resultType.AbstractMethods) { #>
<#=method.IsPublic ? "public" : "protected" #> override <#=method.ReturnType#> <#=method.Name #>(<#method.WriteFormalParameters(true); #>) {<# if(method.ReturnType != "void") {#> return default(<#=method.ReturnType#>); <#} #> }
<#} #>
public string Controller { get; set; }
public string Action { get; set; }
public string Protocol { get; set; }
public RouteValueDictionary RouteValueDictionary { get; set; }
}
<#} #>
namespace <#=settings.LinksNamespace #>
{
<#
var inAreas = Areas
.Where(a => !string.IsNullOrEmpty(a.Name))
.SelectMany(a => settings.StaticFilesFolders.Select(b => settings.AreasFolder + "\\" + a.Name + "\\" + b));
foreach (string folder in settings.StaticFilesFolders
.Concat(GetStaticFilesViewFolders())
.Concat(inAreas)
) {
ProcessStaticFiles(Project, folder);
}
PushIndent(" ");
#>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public static partial class Bundles
{
<#
foreach (string folder in settings.StaticFilesFolders.Concat(GetStaticFilesViewFolders())) {
ProcessBundles(Project, folder);
}
PopIndent();
#>
}
}
<#
RenderAdditionalCode();
#>
<#foreach (var controller in GetAbstractControllers().Where(c => !c.HasDefaultConstructor)) { #>
<#manager.StartNewFile(controller.GeneratedFileName); #>
namespace <#=controller.Namespace #>
{
[<#= GeneratedCode #>, DebuggerNonUserCode]
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);
}
[<#= GeneratedCode #>, DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToAction(Task<ActionResult> taskResult)
{
return RedirectToAction(taskResult.Result);
}
[<#= GeneratedCode #>, DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToActionPermanent(ActionResult result)
{
var callInfo = result.GetT4MVCResult();
return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
}
[<#= GeneratedCode #>, DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToActionPermanent(Task<ActionResult> taskResult)
{
return RedirectToActionPermanent(taskResult.Result);
}
<#foreach (var method in controller.ActionMethodsUniqueWithoutParameterlessOverload) { #>
[NonAction]
[<#= GeneratedCode #>, DebuggerNonUserCode]
public virtual <#=method.ReturnTypeFullName #> <#=method.Name #>()
{
<#if (method.IsTaskBased) { #>
var callInfo = new T4MVC_<#=method.ReturnTypeUniqueName #>(Area, Name, ActionNames.<#=method.ActionName #><# if (method.ActionUrlHttps) {#>, "https"<#}#>);
return System.Threading.Tasks.Task.FromResult(callInfo as <#=method.TaskActionTypeFullName #>);
<#} else { #>
return new T4MVC_<#=method.ReturnTypeUniqueName #>(Area, Name, ActionNames.<#=method.ActionName #><# if (method.ActionUrlHttps) {#>, "https"<#}#>);
<#} #>
}
<#} #>
<#foreach (var method in controller.CustomActionMethodsUniqueWithoutParameterlessOverload) { #>
[NonAction]
[<#= GeneratedCode #>, DebuggerNonUserCode]
public virtual <#=method.ReturnTypeFullName #> <#=method.ActionName #>()
{
return new T4MVC_<#=method.ReturnTypeUniqueName #>(Area, Name, ActionNames.<#=method.ActionName #><# if (method.ActionUrlHttps) {#>, "https"<#}#>);
}
<#} #>
<#foreach (var method in controller.CustomActionMethods) { #>
[NonAction]
[<#= GeneratedCode #>, DebuggerNonUserCode]
public virtual <#=method.ReturnTypeFullName #> <#=method.ActionName #>(<#method.WriteFormalParameters(true, true); #>)
{
var callInfo = new T4MVC_<#=method.ReturnTypeUniqueName #>(Area, Name, ActionNames.<#=method.ActionName #><# if (method.ActionUrlHttps) {#>, "https"<#}#>);
<#if (method.Parameters.Count > 0) { #>
<#foreach (var p in method.Parameters) { #>
ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, <#=p.RouteNameExpression #>, <#=p.Name #>);
<#} #>
<#}#>
<#if (method.IsTaskBased) { #>
return System.Threading.Tasks.Task.FromResult(callInfo as <#=method.TaskActionTypeFullName #>);
<#} else { #>
return callInfo;
<#} #>
}
<#} #>
[<#= 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) #>";
[<#= GeneratedCode #>]
public const string NameConst = "<#=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 (settings.UseLowercaseRoutes) { #>
public readonly string <#=method.ActionName #> = (<#=method.ActionNameValueExpression #>).ToLowerInvariant();
<# } else { #>
public readonly string <#=method.ActionName #> = <#=method.ActionNameValueExpression #>;
<# }
} #>
}
<#
// Issue: we can't honor UseLowercaseRoutes here because ToLowerInvariant() is not valid in constants!
if (!settings.UseLowercaseRoutes) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class ActionNameConstants
{
<#foreach (var method in controller.ActionMethodsWithUniqueNames) { #>
public const string <#=method.ActionName #> = <#=method.ActionNameValueExpression #>;
<#
} #>
}
<#}
} #>
<#if (settings.GenerateParamsForActionMethods && !settings.GenerateParamsAsConstantsForActionMethods){
foreach (var group in controller.UniqueParameterNamesGroupedByActionName) if (group.Any()) { #>
static readonly ActionParamsClass_<#=group.Key #> s_params_<#=group.Key #> = new ActionParamsClass_<#=group.Key #>();
[<#= GeneratedCode #>, DebuggerNonUserCode]
public ActionParamsClass_<#=group.Key #> <#=group.Key + settings.ParamsPropertySuffix #> { get { return s_params_<#=group.Key #>; } }
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class ActionParamsClass_<#=group.Key #>
{
<#foreach (var param in group) { #>
<# if (settings.UseLowercaseRoutes) { #>
public readonly string <#=param.Name #> = (<#=param.RouteNameExpression #>).ToLowerInvariant();
<# } else { #>
public readonly string <#=param.Name #> = <#=param.RouteNameExpression #>;
<# }
} #>
}
<# } #>
<#} #>
<#if (settings.GenerateParamsAsConstantsForActionMethods){
foreach (var group in controller.UniqueParameterNamesGroupedByActionName) if (group.Any()) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class <#=group.Key + settings.ParamsPropertySuffix#>
{
<#foreach (var param in group) { #>
<# if (settings.UseLowercaseRoutes) { #>
public const string <#=param.Name #> = (<#=param.RouteNameExpression #>).ToLowerInvariant();
<# } else { #>
public const string <#=param.Name #> = <#=param.RouteNameExpression #>;
<# }
} #>
}
<# } #>
<#} #>
static readonly ViewsClass s_views = new ViewsClass();
[<#= GeneratedCode #>, DebuggerNonUserCode]
public ViewsClass Views { get { return s_views; } }
[<#= GeneratedCode #>, DebuggerNonUserCode]
public class ViewsClass
{
<#RenderControllerViews(controller);#>
}
}
<#if (!controller.NotRealController) { #>
[<#= GeneratedCode #>, DebuggerNonUserCode]
public partial class <#=controller.DerivedClassName #> : <#=controller.FullClassName #>
{
public <#=controller.DerivedClassName #>() : base(Dummy.Instance) { }
<#foreach (var method in controller.ActionMethods.Where(m => !m.IsCustomReturnType)) { #>
[NonAction]
partial void <#=method.Name #>Override(T4MVC_<#=method.ReturnTypeUniqueName #> callInfo<#if (method.Parameters.Count > 0) { #>, <#method.WriteFormalParameters(true); #><#}#>);
[NonAction]
public override <#=method.ReturnTypeFullName #> <#=method.Name #>(<#method.WriteFormalParameters(true); #>)
{
var callInfo = new T4MVC_<#=method.ReturnTypeUniqueName #>(Area, Name, ActionNames.<#=method.ActionName #><# if (method.ActionUrlHttps) {#>, "https"<#}#>);
<#if (method.Parameters.Count > 0) { #>
<#foreach (var p in method.Parameters) { #>
ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, <#=p.RouteNameExpression #>, <#=p.Name #>);
<#} #>
<#}#>
<#=method.Name #>Override(callInfo<#if (method.Parameters.Count > 0) { #><#foreach (var p in method.Parameters) { #>, <#=p.Name #><#}}#>);
<#if (method.IsTaskBased) { #>
return System.Threading.Tasks.Task.FromResult(callInfo as <#=method.TaskActionTypeFullName #>);
<#} else { #>
return callInfo;
<#} #>
}
<#} #>
}
<#} #>
<#if (!String.IsNullOrEmpty(controller.Namespace)) { #>
}
<#} #>
<#manager.EndBlock(); #>
<#} #>
<# if (settings.ExplicitHtmlHelpersForPartials) {
manager.StartNewFile("T4MVC.ExplicitExtensions.cs"); #>
namespace System.Web.Mvc {
[<#= GeneratedCode #>]
public static class HtmlHelpersForExplicitPartials
{
<#
foreach(var partialView in GetPartials()) {
string partialName = partialView.Key;
string partialPath = partialView.Value;
string partialRenderMethod = string.Format(settings.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, 3008, 3009, 0108, 0114
<#manager.EndBlock(); #>
<#settings.SaveChanges(manager); #>
<#manager.Process(settings.SplitIntoMultipleFiles); #>
<#@ Include File="T4MVC.tt.hooks.t4" #>
<#+
static MvcSettings settings;
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 Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
List<string> virtualPathesForStaticFiles = new List<string>();
static CodeTypeRef TryCreateActionResultDerivedCodeTypeRef(CodeType codeType) {
return codeType.get_IsDerivedFrom("System.Web.Mvc.ActionResult")
? Project.CodeModel.CreateCodeTypeRef(codeType.FullName)
: null;
}
enum ActionTypeMatch {
None = 0,
Direct = 1,
TaskBased = 2
}
static ActionTypeMatch TryGetActionType(CodeType codeType, out CodeTypeRef actionTypeRef) {
// check for task based
Match match = Regex.Match(codeType.FullName, "^System.Threading.Tasks.Task<(.+)>$");
if (match == null || !match.Success) {
actionTypeRef = TryCreateActionResultDerivedCodeTypeRef(codeType);
return actionTypeRef != null
? ActionTypeMatch.Direct
: ActionTypeMatch.None;
} else {
CodeTypeRef typeRef = Project.CodeModel.CreateCodeTypeRef(match.Groups[1].Value);
if (typeRef.CodeType.get_IsDerivedFrom("System.Web.Mvc.ActionResult"))
actionTypeRef = typeRef;
else
actionTypeRef = null;
return actionTypeRef != null
? ActionTypeMatch.TaskBased
: ActionTypeMatch.None;
}
}
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 => IsPartialView(m.Value));
var partsDic = new Dictionary<string, KeyValuePair<string, string>>();
foreach(var part in parts)
{
string viewName = Sanitize(part.Key);
// 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 == viewName || m.Value.Key == viewName).Count();
if (keyCollisionCount > 0)
{
// Append a numbered suffix to avoid the conflict
partsDic.Add(viewName + keyCollisionCount.ToString(), part);
}
else
{
partsDic.Add(viewName, part);
}
}
return partsDic.ToDictionary(k => k.Key, v => v.Value.Value);
}
bool IsPartialView(string viewFilePath)
{
string viewFileName = Path.GetFileName(viewFilePath);
if (viewFileName.EndsWith(".ascx")) return true;
if ((viewFileName.EndsWith(".cshtml") || viewFileName.EndsWith(".vbhtml")) && viewFileName.StartsWith("_"))
{
return true;
}
return false;
}
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 = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.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) + '\\';
// Process controllers and views from project root
ProcessProjectRoot(Project);
// Process controllers and views from areas.
ProcessAreas(Project);
}
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(EnvDTE.Constants.vsViewKindCode);
return projectItem.ContainingProject;
}
void ProcessProjectRoot(Project project)
{
var area = new AreaInfo() { Name = null };
// process controllers and views from their folders
ProcessAreaControllers(project.ProjectItems, area, null);
ProcessAreaViews(project.ProjectItems, area, null);
// does the project root contain a folder which follows the "feature folder" convention?
// If yes, controllers and views from there are added to the existing default area.
// this means, if you use both conventions, you cannot have two controllers with the same name!
if (!String.IsNullOrEmpty(settings.FeatureFolderRootArea))
{
ProjectItem featureFolderItem = GetProjectItem(project, settings.FeatureFolderRootArea);
if (featureFolderItem != null)
{
ProcessArea(featureFolderItem, area);
}
}
Areas.Add(area);
DefaultArea = area;
}
void ProcessAreas(Project project)
{
// Get the Areas folder
ProjectItem areaProjectItem = GetProjectItem(project, settings.AreasFolder);
// Process areas folder
if (areaProjectItem != null)
{
foreach (ProjectItem item in areaProjectItem.ProjectItems)
{
if (IsFolder(item))
{
ProcessArea(item, null);
}
}
}
// Process portable areas
foreach (string portableArea in settings.PortableAreas)
{
ProjectItem portableAreaProjectItem = GetProjectItem(project, portableArea);
if (portableAreaProjectItem == null)
return;
if (IsFolder(portableAreaProjectItem))
{
ProcessArea(portableAreaProjectItem, null);
}
}
}
void ProcessArea(ProjectItem areaFolder, AreaInfo existingArea)
{
var area = existingArea ?? new AreaInfo() { Name = areaFolder.Name };
area.IsFeatureFolderArea = IsFeatureFolderArea(area.Name, areaFolder);
ProcessAreaControllers(areaFolder.ProjectItems, area, areaFolder);
ProcessAreaViews(areaFolder.ProjectItems, area, areaFolder);
if (existingArea == null)
Areas.Add(area);
}
void ProcessAreaControllers(ProjectItems areaFolderItems, AreaInfo area, ProjectItem areaFolder)
{
if (area.IsFeatureFolderArea)
{
// Every folder within the area might contain controllers when using "FeatureFolders".
ProcessControllersRecursive(areaFolder, area);
}
else
{
// Get area Controllers folder
ProjectItem controllerProjectItem = GetProjectItem(areaFolderItems, settings.ControllersFolder);
if (controllerProjectItem == null)
return;
ProcessControllersRecursive(controllerProjectItem, area);
}
}
void ProcessAreaViews(ProjectItems areaFolderItems, AreaInfo area, ProjectItem areaFolder)
{
ProjectItem viewsProjectItem;
if (area.IsFeatureFolderArea)
{
// For "FeatureFolders", we don't have to search for a "Views"-folder since the area directly contains the feature-folders holding the views.
viewsProjectItem = areaFolder;
}
else
{
// Get area Views folder
viewsProjectItem = GetProjectItem(areaFolderItems, settings.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 controllers
if (!IsController(type))
return;
// Only process "processable" controllers
if (!IsProcessableController(type))
return;
//Ignore references to controllers we create
if(area.Controllers.Any(c => c.DerivedClassName == type.Name))
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
};
//Filter references to controllers we create
foreach(var derived in area.Controllers.Where(c => c.ClassName == controllerInfo.DerivedClassName).ToArray())
area.Controllers.Remove(derived);
// 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)
if (!HasControllerAttribute(type))
target.IsAbstract = true;
// ...unless it has the [T4MVC] attribute, then process all the action methods in the controller
else
ProcessControllerActionMethods(target, type);
}
else
{
// Process all the action methods in the controller
ProcessControllerActionMethods(target, type);
}
}
void ProcessControllerActionMethods(ControllerInfo controllerInfo, CodeClass2 current)
{
bool isAsyncController = IsAsyncController(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
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;
}
try
{
// 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;
}
}
catch (System.ArgumentException)
{
// CodeTypeFromFullName throws when called on VB projects with a type it doesn't know
// (instead of returning null), so ignore those exceptions (See http://t4mvc.codeplex.com/workitem/7)
}
}
}
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;
// Ignore methods that are marked as Obsolete
if (GetAttribute(method.Attributes, "System.ObsoleteAttribute") != null)
continue;
// Ignore generic methods
if (method.IsGeneric)
continue;
if(isAsyncController && settings.SupportAsyncActions && (method.Type.TypeKind == vsCMTypeRef.vsCMTypeRefVoid) && method.Name.EndsWith("Async"))
{
//Async methods return void and there could be multiple matching Completed methods, so we will use
//the generic ActionResult as the return type for the method.
var resultType = Project.CodeModel.CreateCodeTypeRef("System.Web.Mvc.ActionResult");
// If we haven't yet seen this return type, keep track of it
if (!ResultTypes.ContainsKey(resultType.AsFullName))
{
var resTypeInfo = new ResultTypeInfo(resultType);
ResultTypes[resultType.AsFullName] = resTypeInfo;
}
// Collect misc info about the action method and add it to the collection
controllerInfo.ActionMethods.Add(new ActionMethodInfo(method, current, resultType));
continue;
}
// This takes care of avoiding generic types which cause method.Type.CodeType to blow up
if (method.Type.TypeKind != vsCMTypeRef.vsCMTypeRefCodeType || !(method.Type.CodeType is CodeClass2))
continue;
// We only support action methods that return an ActionResult and Task<ActionResult> derived types
CodeTypeRef methodType;
ActionTypeMatch match = TryGetActionType(method.Type.CodeType, out methodType);
if (match == ActionTypeMatch.None)
{
// Comment out warning, as it's more annoying than helpful
//Warning(String.Format("{0} doesn't support {1}.{2} because it doesn't return a supported {3} type", T4FileName, type.Name, method.Name, method.Type.CodeType.FullName));
continue;
}
// Ignore async completion methods as they can't really be used in T4MVC, and can cause issues.
// See http://stackoverflow.com/questions/5419173/t4mvc-asynccontroller
if (isAsyncController && method.Name.EndsWith("Completed", StringComparison.OrdinalIgnoreCase))
continue;
// If we haven't yet seen this return type, keep track of it
var resTypeInfo2 = new ResultTypeInfo(methodType);
if (!ResultTypes.ContainsKey(resTypeInfo2.FullName))
{
ResultTypes[resTypeInfo2.FullName] = resTypeInfo2;
}
// 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, current, null, match == ActionTypeMatch.TaskBased ? methodType : null));
}
}
}
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(settings.T4MVCNamespace, area.Name),
ClassName = Sanitize(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 == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
{
// Ignore some extensions that are normally not views
if (settings.ExcludedViewExtensions.Any(extension => Path.GetExtension(item.Name).Equals(extension, StringComparison.OrdinalIgnoreCase)))
continue;
viewsFolder.AddView(item, useNonQualifiedViewNames);
}
else if (item.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)
{
string folderName = Path.GetFileName(item.Name);