forked from JeremyDurnell/locbaml
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBamlLocalizabilityByReflection.cs
More file actions
469 lines (408 loc) · 17.8 KB
/
BamlLocalizabilityByReflection.cs
File metadata and controls
469 lines (408 loc) · 17.8 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
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Description: BamlLocalizabilityResolver class
// It resolves localizabilities of a class/element
//
//---------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Markup.Localizer;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Collections.Generic;
using System.Security.Permissions;
namespace BamlLocalization
{
/// <summary>
/// </summary>
public class BamlLocalizabilityByReflection : BamlLocalizabilityResolver
{
/// Take in an optional list of assemblies in addition to the
/// default well-known WPF assemblies. The assemblies will be searched first
/// in order before the well-known WPF assemblies.
/// </summary>
/// <param name="assemblies">additinal list of assemblies to search for Type information</param>
public BamlLocalizabilityByReflection(params Assembly[] assemblies)
{
if (assemblies != null)
{
// create the table
_assemblies = new Dictionary<string, Assembly>(assemblies.Length);
try{
// Assert security permissions
FileIOPermission permobj = new FileIOPermission(PermissionState.None);
permobj.AllFiles = FileIOPermissionAccess.PathDiscovery;
//CASRemoval:permobj.Assert();
for (int i = 0; i < assemblies.Length; i++)
{
// skip the null ones.
if (assemblies[i] != null)
{
// index it by the name;
_assemblies[assemblies[i].GetName().FullName] = assemblies[i];
}
}
}
finally
{
// revert assert permission
//CASRemoval:FileIOPermission.RevertAssert();
}
}
// create the cache for Type here
_typeCache = new Dictionary<string, Type>(32);
}
/// <summary>
/// Return the localizability of an element to the BamlLocalizer
/// </summary>
public override ElementLocalizability GetElementLocalizability(
string assembly,
string className
)
{
ElementLocalizability loc = new ElementLocalizability();
Type type = GetType(assembly, className);
if (type != null)
{
// We found the type, now try to get the localizability attribte from the type
loc.Attribute = GetLocalizabilityFromType(type);
}
// fill in the formatting tag
int index = Array.IndexOf(FormattedElements, className);
if (index >= 0)
{
loc.FormattingTag = FormattingTag[index];
}
return loc;
}
/// <summary>
/// return localizability of a property to the BamlLocalizer
/// </summary>
public override LocalizabilityAttribute GetPropertyLocalizability(
string assembly,
string className,
string property
)
{
LocalizabilityAttribute attribute = null;
Type type = GetType(assembly, className);
if (type != null)
{
// type of the property. The type can be retrieved from CLR property, or Attached property.
Type clrPropertyType = null, attachedPropertyType = null;
// we found the type. try to get to the property as Clr property
GetLocalizabilityForClrProperty(
property,
type,
out attribute,
out clrPropertyType
);
if (attribute == null)
{
// we didn't find localizability as a Clr property on the type,
// try to get the property as attached property
GetLocalizabilityForAttachedProperty(
property,
type,
out attribute,
out attachedPropertyType
);
}
if (attribute == null)
{
// if attached property doesn't have [LocalizabilityAttribute] defined,
// we get it from the type of the property.
attribute =(clrPropertyType != null) ?
GetLocalizabilityFromType(clrPropertyType)
: GetLocalizabilityFromType(attachedPropertyType);
}
}
return attribute;
}
/// <summary>
/// Resolve a formatting tag back to the actual class name
/// </summary>
public override string ResolveFormattingTagToClass(
string formattingTag
)
{
int index = Array.IndexOf(FormattingTag, formattingTag);
if (index >= 0)
return FormattedElements[index];
else
return null;
}
/// <summary>
/// Resolve a class name back to its containing assembly
/// </summary>
public override string ResolveAssemblyFromClass(
string className
)
{
// search through the well-known assemblies
for (int i = 0; i < _wellKnownAssemblies.Length; i++)
{
if (_wellKnownAssemblies[i] == null)
{
_wellKnownAssemblies[i] = Assembly.Load(
GetCompatibleAssemblyName(_wellKnownAssemblyNames[i])
);
}
if (_wellKnownAssemblies[i] != null && _wellKnownAssemblies[i].GetType(className) != null)
{
return _wellKnownAssemblies[i].GetName().FullName;
}
}
// search through the custom assemblies
if (_assemblies != null)
{
foreach (KeyValuePair<string, Assembly> pair in _assemblies)
{
if (pair.Value.GetType(className) != null)
{
return pair.Value.GetName().FullName;
}
}
}
return null;
}
//-----------------------------------------------
// Private methods
//-----------------------------------------------
// get the type in a specified assembly
private Type GetType(string assemblyName, string className)
{
Debug.Assert(className != null, "classname can't be null");
Debug.Assert(assemblyName != null, "Assembly name can't be null");
// combine assembly name and class name for unique indexing
string fullName = assemblyName + ":" + className;
Type type;
if (_typeCache.ContainsKey(fullName))
{
// we found it in the cache, so just return
return _typeCache[fullName];
}
// we didn't find it in the table. So let's get to the assembly first
Assembly assembly = null;
if (_assemblies != null && _assemblies.ContainsKey(assemblyName))
{
// find the assembly in the hash table first
assembly = _assemblies[assemblyName];
}
if (assembly == null)
{
// we don't find the assembly in the hashtable
// try to use the default well known assemblies
int index;
if ( (index = Array.BinarySearch(
_wellKnownAssemblyNames,
GetAssemblyShortName(assemblyName).ToLower(CultureInfo.InvariantCulture)
)
) >= 0
)
{
// see if we already loaded the assembly
if (_wellKnownAssemblies[index] == null)
{
// it is a well known name, load it from the gac
_wellKnownAssemblies[index] = Assembly.Load(assemblyName);
}
assembly = _wellKnownAssemblies[index];
}
}
if (assembly != null)
{
// So, we found the assembly. Now get the type from the assembly
type = assembly.GetType(className);
}
else
{
// Couldn't find the assembly. We will try to load it
type = null;
}
// remember what we found out.
_typeCache[fullName] = type;
return type; // return
}
// returns the short name for the assembly
private static string GetAssemblyShortName(string assemblyFullName)
{
int commaIndex = assemblyFullName.IndexOf(',');
if (commaIndex > 0)
{
return assemblyFullName.Substring(0, commaIndex);
}
return assemblyFullName;
}
private static string GetCompatibleAssemblyName(string shortName)
{
AssemblyName asmName = null;
for (int i = 0; i < _wellKnownAssemblies.Length; i++)
{
if (_wellKnownAssemblies[i] != null)
{
// create an assembly name with the same version and token info
// as the WPF assembilies
asmName = _wellKnownAssemblies[i].GetName();
asmName.Name = shortName;
break;
}
}
if (asmName == null)
{
// there is no WPF assembly loaded yet. We will just get the compatible version
// of the current PresentationFramework
Assembly presentationFramework = typeof(BamlLocalizer).Assembly;
asmName = presentationFramework.GetName();
asmName.Name = shortName;
}
return asmName.ToString();
}
/// <summary>
/// gets the localizabiity attribute of a given the type
/// </summary>
private LocalizabilityAttribute GetLocalizabilityFromType(Type type)
{
if (type == null) return null;
// let's get to its localizability attribute.
object[] locAttributes = type.GetCustomAttributes(
TypeOfLocalizabilityAttribute, // type of localizability
true // search for inherited value
);
if (locAttributes.Length == 0)
{
return DefaultAttributes.GetDefaultAttribute(type);
}
else
{
Debug.Assert(locAttributes.Length == 1, "Should have only 1 localizability attribute");
// use the one defined on the class
return (LocalizabilityAttribute) locAttributes[0];
}
}
/// <summary>
/// Get the localizability of a CLR property
/// </summary>
private void GetLocalizabilityForClrProperty(
string propertyName,
Type owner,
out LocalizabilityAttribute localizability,
out Type propertyType
)
{
localizability = null;
propertyType = null;
PropertyInfo info = owner.GetProperty(propertyName);
if (info == null)
{
return; // couldn't find the Clr property
}
// we found the CLR property, set the type of the property
propertyType = info.PropertyType;
object[] locAttributes = info.GetCustomAttributes(
TypeOfLocalizabilityAttribute, // type of the attribute
true // search in base class
);
if (locAttributes.Length == 0)
{
return;
}
else
{
Debug.Assert(locAttributes.Length == 1, "Should have only 1 localizability attribute");
// we found the attribute defined on the property
localizability = (LocalizabilityAttribute) locAttributes[0];
}
}
/// <summary>
/// Get localizability for attached property
/// </summary>
/// <param name="propertyName">property name</param>
/// <param name="owner">owner type</param>
/// <param name="localizability">out: localizability attribute</param>
/// <param name="propertyType">out: type of the property</param>
private void GetLocalizabilityForAttachedProperty(
string propertyName,
Type owner,
out LocalizabilityAttribute localizability,
out Type propertyType
)
{
localizability = null;
propertyType = null;
// if it is an attached property, it should have a dependency property with the name
// <attached proeprty's name> + "Property"
DependencyProperty attachedDp = DependencyPropertyFromName(
propertyName, // property name
owner
); // owner type
if (attachedDp == null)
return; // couldn't find the dp.
// we found the Dp, set the type of the property
propertyType = attachedDp.PropertyType;
FieldInfo fieldInfo = attachedDp.OwnerType.GetField(
attachedDp.Name + "Property",
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.FlattenHierarchy);
Debug.Assert(fieldInfo != null);
object[] attributes = fieldInfo.GetCustomAttributes(
TypeOfLocalizabilityAttribute, // type of localizability
true
); // inherit
if (attributes.Length == 0)
{
// didn't find it.
return;
}
else
{
Debug.Assert(attributes.Length == 1, "Should have only 1 localizability attribute");
localizability = (LocalizabilityAttribute) attributes[0];
}
}
private DependencyProperty DependencyPropertyFromName(string propertyName, Type propertyType)
{
FieldInfo fi = propertyType.GetField(propertyName + "Property", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
return (fi != null)?fi.GetValue(null) as DependencyProperty:null;
}
//---------------------------
// private members
//---------------------------
private Dictionary<string, Assembly> _assemblies; // the _assemblies table
private Dictionary<string, Type> _typeCache; // the types cache
// well know assembly names, keep them sorted.
private static readonly string[] _wellKnownAssemblyNames = new string[] {
"presentationcore",
"presentationframework",
"windowsbase"
};
// the well known assemblies
private static Assembly[] _wellKnownAssemblies = new Assembly[_wellKnownAssemblyNames.Length];
private static Type TypeOfLocalizabilityAttribute= typeof(LocalizabilityAttribute);
// supported elements that are formatted inline
private static string[] FormattedElements = new string[]{
"System.Windows.Documents.Bold",
"System.Windows.Documents.Hyperlink",
"System.Windows.Documents.Inline",
"System.Windows.Documents.Italic",
"System.Windows.Documents.SmallCaps",
"System.Windows.Documents.Subscript",
"System.Windows.Documents.Superscript",
"System.Windows.Documents.Underline"
};
// corresponding tag
private static string[] FormattingTag = new string[] {
"b",
"a",
"in",
"i",
"small",
"sub",
"sup",
"u"
};
}
}