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
|
/*
T4Resx Version 0.1
Maintained by Kenneth Baltrinic
http://blog.baltrinic.com
Related blog posts: http://blog.baltrinic.com/software-development/dotnet/t4-template-replace-resxfilecodegenerator
The certain parts of this template were copied from the T4MVC template which is distributed under the MvcContrib license (http://mvccontrib.codeplex.com/license)
This template if free for redistribution in accordance with the same license.
*/
#>
<#@ template debug="true" hostspecific="true" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ 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="System.Xml" #>
<#@ import namespace="Microsoft.VisualStudio.Shell.Interop" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#
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"XX";
}
AppRoot = Path.GetDirectoryName(Project.FullName) + '\';
RootNamespace = Project.Properties.Item("RootNamespace").Value.ToString();
#>
using System.Threading;
using System.Web;
<#
try{
AllEntries = new List<ResourceEntry>();
FindResourceFilesRecursivlyAndRecordEntries(Project.ProjectItems, "");
AllEntries.Sort( new Comparison<ResourceEntry>( (e1, e2) => (e1.Path + e1.File + e1.Name).CompareTo(e2.Path + e2.File + e2.Name)));
var currentNamespace = "";
var currentClass = "";
var thisIsFirstEntryInClass = true;
var names = new List<string>();
foreach(var entry in AllEntries)
{
//WriteLine("//" + entry.Path + ":" + entry.File+ ":" + entry.Name);
var newNamespace = ("Resources." + entry.Path + ".").Replace(".Resources.", ".");
newNamespace = RootNamespace + "." + newNamespace.Substring(0, newNamespace.Length-1);
var newClass = entry.File;
bool namesapceIsChanging = newNamespace != currentNamespace;
bool classIsChanging = namesapceIsChanging || newClass != currentClass;
//Close out current class if class is changing and there is a current class
if(classIsChanging && currentClass != "")
{
EmitNamesInnerClass(names);
WriteLine("t}");
}
if(namesapceIsChanging)
{
//Close out current namespace if one exists
if( currentNamespace != "" )
WriteLine("}");
currentNamespace = newNamespace;
//open new namespace
WriteLine(string.Format("namespace {0}", currentNamespace));
WriteLine("{");
}
if(classIsChanging)
{
currentClass = newClass;
WriteLine(string.Format("tpublic class {0}", currentClass));
WriteLine("t{");
thisIsFirstEntryInClass = true;
//Emit code for the ResourceManager property and GetResourceString method for the current class
#>
private static global::System.Resources.ResourceManager resourceMan;
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager
{
get
{
if (object.ReferenceEquals(resourceMan, null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("<#=string.Format("{0}.{1}{2}", RootNamespace, entry.Path + "." + entry.File, entry.Type) #>", typeof(<#=entry.File#>).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Returns the formatted resource string.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static string GetResourceString(string key, params string[] tokens)
{
var culture = Thread.CurrentThread.CurrentCulture;
var str = ResourceManager.GetString(key, culture);
for(int i = 0; i < tokens.Length; i += 2)
str = str.Replace(tokens[i], tokens[i+1]);
return str;
}
/// <summary>
/// Returns the resource string.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static string GetString(string key)
{
return ResourceManager.GetString(key);
}
<#
}
//Emit the static resource string access method for the current entry
if(entry.Comment != null)
{
if(!thisIsFirstEntryInClass) WriteLine("");
WriteLine(string.Format("rntt///<summary>rntt///{0}rntt///</summary>", entry.Comment.Replace("rn", "rntt///")));
}
else
WriteLine("");
//Select all tokens between braces that constitute valid identifiers
var tokens = Regex.Matches(entry.Value, @"{(([A-Za-z]{1}w*?)|([A-Za-z_]{1}w+?))?}").Cast<Match>().Select(m => m.Value);
if(tokens.Any())
{
var inParams = tokens.Aggregate("", (list, value) => list += ", string " + value)
.Replace("{", "").Replace("}", "");
if(inParams.Length > 0 ) inParams = inParams.Substring(1);
var outParams = tokens.Aggregate("", (list, value) => list += ", "" + value +"", " + value.Replace("{", "").Replace("}", "") );
if(entry.Value.StartsWith("HTML:"))
WriteLine(string.Format("ttpublic static HtmlString {0}({1}) {{ return GetResourceHtmlString("{0}"{2}); }}", entry.Name, inParams, outParams));
else
WriteLine(string.Format("ttpublic static string {0}({1}) {{ return GetResourceString("{0}"{2}); }}", entry.Name, inParams, outParams));
}
else
{
if(entry.Value.StartsWith("HTML:"))
WriteLine(string.Format("ttpublic static HtmlString {0} {{ get {{ return GetResourceHtmlString("{0}"); }} }}", entry.Name));
else
{
WriteLine(string.Format("ttpublic static string {0} {{ get {{ return GetResourceString("{0}"); }} }}", entry.Name));
//WriteLine(string.Format("ttinternal static string V{0} {{ get {{ return GetResourceString("{0}"); }} }}", entry.Name));
}
}
names.Add(entry.Name);
thisIsFirstEntryInClass = false;
} // foreach(var entry in AllEntries)
//close out the current class when done
if(currentClass != "")
{
EmitNamesInnerClass(names);
WriteLine("t}");
}
}
catch(Exception ex)
{
Error(ex.ToString());
}
#>
}
<#+
const string Kind_PhysicalFolder = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}";
bool AlwaysKeepTemplateDirty = true;
static DTE Dte;
static Project Project;
static string AppRoot;
static string RootNamespace;
static List<ResourceEntry> AllEntries;
void FindResourceFilesRecursivlyAndRecordEntries(ProjectItems items, string path)
{
foreach(ProjectItem item in items)
{
if(Path.GetExtension(item.Name) == ".resx")
RecordEntriesInResourceFile(item, path);
if(item.Kind == Kind_PhysicalFolder)
FindResourceFilesRecursivlyAndRecordEntries(item.ProjectItems, path+"."+item.Name);
}
}
void RecordEntriesInResourceFile(ProjectItem item, string path)
{
//skip resource files except those for the default culture
if(Regex.IsMatch(item.Name, @".*.[a-zA-z]{2}(-[a-zA-z]{2})?.resx"))
return;
var filePath = (string)item.Properties.Item("FullPath").Value;
var xml = new XmlDocument();
xml.Load(filePath);
var entries = xml.DocumentElement.SelectNodes("//data");
var parentFile = item.Name.Replace(".resx", "");
var fileType = Path.GetExtension(parentFile);
if(fileType != null && fileType != "")
parentFile = parentFile.Replace(fileType, "");
foreach (XmlElement entryElement in entries)
{
var entry = new ResourceEntry
{
Path = path.Substring(1),
File = MakeIntoValidIdentifier(parentFile),
Type = fileType,
Name = MakeIntoValidIdentifier(entryElement.Attributes["name"].Value)
};
var valueElement = entryElement.SelectSingleNode("value");
if(valueElement != null)
entry.Value = valueElement.InnerText;
var commentElement = entryElement.SelectSingleNode("comment");
if(commentElement != null)
entry.Comment = commentElement.InnerText;
AllEntries.Add(entry);
}
}
string MakeIntoValidIdentifier(string arbitraryString)
{
var validIdentifier = Regex.Replace(arbitraryString, @"[^A-Za-z0-9-._]", " ");
validIdentifier = ConvertToPascalCase(validIdentifier);
if (Regex.IsMatch(validIdentifier, @"^d")) validIdentifier = "_" + validIdentifier;
return validIdentifier;
}
string ConvertToPascalCase(string phrase)
{
string[] splittedPhrase = phrase.Split(' ', '-', '.');
var sb = new StringBuilder();
sb = new StringBuilder();
foreach (String s in splittedPhrase)
{
char[] splittedPhraseChars = s.ToCharArray();
if (splittedPhraseChars.Length > 0)
{
splittedPhraseChars[0] = ((new String(splittedPhraseChars[0], 1)).ToUpper().ToCharArray())[0];
}
sb.Append(new String(splittedPhraseChars));
}
return sb.ToString();
}
void EmitNamesInnerClass(List<string> names)
{
if(names.Any())
{
WriteLine("rnttpublic static class Names");
WriteLine("tt{");
foreach(var name in names)
WriteLine(string.Format("tttpublic const string {0} = "{0}";", name));
WriteLine("tt}");
names.Clear();
}
}
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;
}
struct ResourceEntry
{
public string Path { get; set; }
public string File { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public string Comment { get; set; }
}
#>
|