File: ResourceManager.cs

package info (click to toggle)
mono 2.6.7-5.1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 327,344 kB
  • ctags: 413,649
  • sloc: cs: 2,471,883; xml: 1,768,594; ansic: 350,665; sh: 13,644; makefile: 8,640; perl: 1,784; asm: 717; cpp: 209; python: 146; sql: 81; sed: 16
file content (568 lines) | stat: -rw-r--r-- 16,669 bytes parent folder | download | duplicates (2)
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
//	
// System.Resources.ResourceManager.cs
//
// Authors:
//	Duncan Mak (duncan@ximian.com)
//	Dick Porter (dick@ximian.com)
// 	Alexander Olk (alex.olk@googlemail.com)
//
// (C) 2001, 2002 Ximian, Inc. http://www.ximian.com
//

//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Collections;
using System.Reflection;
using System.Globalization;
using System.Runtime.InteropServices;
using System.IO;

namespace System.Resources
{
	[Serializable]
#if NET_2_0
	[ComVisible (true)]
#endif
	public class ResourceManager
	{
		static Hashtable ResourceCache = new Hashtable (); 
		static Hashtable NonExistent = Hashtable.Synchronized (new Hashtable ());
		public static readonly int HeaderVersionNumber = 1;
		public static readonly int MagicNumber = unchecked ((int) 0xBEEFCACE);

		protected string BaseNameField;
		protected Assembly MainAssembly;
		// Maps cultures to ResourceSet objects
		protected Hashtable ResourceSets;
		
		private bool ignoreCase;
		private Type resourceSource;
		private Type resourceSetType = typeof (RuntimeResourceSet);
		private String resourceDir;

		// Contains cultures which have no resource sets
		
		/* Recursing through culture parents stops here */
		private CultureInfo neutral_culture;

#if NET_2_0
		private UltimateResourceFallbackLocation fallbackLocation;
#endif
		
		static Hashtable GetResourceSets (Assembly assembly, string basename)
		{
			lock (ResourceCache) {
				string key = String.Empty;
				if (assembly != null) {
					key = assembly.FullName;
				} else {
					key = basename.GetHashCode ().ToString () + "@@";
				}
				if (basename != null && basename != String.Empty) {
					key += "!" + basename;
				} else {
					key += "!" + key.GetHashCode ();
				}
				Hashtable tbl = ResourceCache [key] as Hashtable;
				if (tbl == null) {
					tbl = Hashtable.Synchronized (new Hashtable ());
					ResourceCache [key] = tbl;
				}
				return tbl;
			}
		}

		// constructors
		protected ResourceManager ()
		{
		}
		
		public ResourceManager (Type resourceSource)
		{
			if (resourceSource == null)
				throw new ArgumentNullException ("resourceSource");

			this.resourceSource = resourceSource;
			BaseNameField = resourceSource.Name;
			MainAssembly = resourceSource.Assembly;
			ResourceSets = GetResourceSets (MainAssembly, BaseNameField);
			neutral_culture = GetNeutralResourcesLanguage (MainAssembly);
		}

		public ResourceManager (string baseName, Assembly assembly)
		{
			if (baseName == null)
				throw new ArgumentNullException ("baseName");
			if (assembly == null)
				throw new ArgumentNullException ("assembly");
			
			BaseNameField = baseName;
			MainAssembly = assembly;
			ResourceSets = GetResourceSets (MainAssembly, BaseNameField);
#if ONLY_1_1
			CheckBaseName ();
#endif
			neutral_culture = GetNeutralResourcesLanguage (MainAssembly);
		}

		private Type CheckResourceSetType (Type usingResourceSet, bool verifyType)
		{
			if (usingResourceSet == null)
				return resourceSetType;

			if (verifyType && !typeof (ResourceSet).IsAssignableFrom (usingResourceSet))
				throw new ArgumentException ("Type parameter"
					+ " must refer to a subclass of"
					+ " ResourceSet.", "usingResourceSet");
			return usingResourceSet;
		}

		public ResourceManager (string baseName, Assembly assembly, Type usingResourceSet)
		{
			if (baseName == null)
				throw new ArgumentNullException ("baseName");
			if (assembly == null)
				throw new ArgumentNullException ("assembly");

			BaseNameField = baseName;
			MainAssembly = assembly;
			ResourceSets = GetResourceSets (MainAssembly, BaseNameField);
#if ONLY_1_1
			CheckBaseName ();
#endif
			resourceSetType = CheckResourceSetType (usingResourceSet, true);
			neutral_culture = GetNeutralResourcesLanguage (MainAssembly);
		}

		/* Private constructor for CreateFileBasedResourceManager */
		private ResourceManager(String baseName, String resourceDir, Type usingResourceSet)
		{
			if (baseName == null)
				throw new ArgumentNullException ("baseName");
			if (resourceDir == null)
				throw new ArgumentNullException("resourceDir");

			BaseNameField = baseName;
			this.resourceDir = resourceDir;
#if ONLY_1_1
			CheckBaseName ();
#endif
			resourceSetType = CheckResourceSetType (usingResourceSet, false);
			ResourceSets = GetResourceSets (MainAssembly, BaseNameField);
		}
		
		public static ResourceManager CreateFileBasedResourceManager (string baseName,
						      string resourceDir, Type usingResourceSet)
		{
			return new ResourceManager (baseName, resourceDir, usingResourceSet);
		}

		public virtual string BaseName {
			get { return BaseNameField; }
		}

		public virtual bool IgnoreCase {
			get { return ignoreCase; }
			set { ignoreCase = value; }
		}

		public virtual Type ResourceSetType {
			get { return resourceSetType; }
		}

		public virtual object GetObject (string name)
		{
			return GetObject (name, null);
		}

		public virtual object GetObject (string name, CultureInfo culture)
		{
			if (name == null)
				throw new ArgumentNullException("name");

			if (culture == null)
				culture = CultureInfo.CurrentUICulture;

			lock (this) {
				ResourceSet set = InternalGetResourceSet(culture, true, true);
				object obj = null;
				
				if (set != null) {
					obj = set.GetObject(name, ignoreCase);
					if (obj != null)
						return obj;
				}
				
				/* Try parent cultures */

				do {
					culture = culture.Parent;

					set = InternalGetResourceSet (culture, true, true);
					if (set != null) {
						obj = set.GetObject (name, ignoreCase);
						if (obj != null)
							return obj;
					}
				} while (!culture.Equals (neutral_culture) &&
					!culture.Equals (CultureInfo.InvariantCulture));
			}

			return null;
		}

		public virtual ResourceSet GetResourceSet (CultureInfo culture,
					   bool createIfNotExists, bool tryParents)
			
		{
			if (culture == null)
				throw new ArgumentNullException ("culture");

			lock (this) {
				return InternalGetResourceSet (culture, createIfNotExists, tryParents);
			}
		}
		
		public virtual string GetString (string name)
		{
			return GetString (name, null);
		}

		public virtual string GetString (string name, CultureInfo culture)
		{
			if (name == null)
				throw new ArgumentNullException ("name");

			if (culture == null)
				culture = CultureInfo.CurrentUICulture;

			lock (this) {
				ResourceSet set = InternalGetResourceSet (culture, true, true);
				string str = null;

				if (set != null) {
					str = set.GetString (name, ignoreCase);
					if (str != null)
						return str;
				}

				/* Try parent cultures */

				do {
					culture = culture.Parent;
					set = InternalGetResourceSet (culture, true, true);
					if (set != null) {
						str = set.GetString(name, ignoreCase);
						if (str != null)
							return str;
					}
				} while (!culture.Equals (neutral_culture) &&
					!culture.Equals (CultureInfo.InvariantCulture));
			}
			
			return null;
		}

		protected virtual string GetResourceFileName (CultureInfo culture)
		{
			if (culture.Equals (CultureInfo.InvariantCulture))
				return BaseNameField + ".resources";
			else
				return BaseNameField + "." +  culture.Name + ".resources";
		}

		private string GetResourceFilePath (CultureInfo culture)
		{
#if !NET_2_1 || MONOTOUCH
			if (resourceDir != null)
				return Path.Combine (resourceDir, GetResourceFileName (culture));
			else
#endif
				return GetResourceFileName (culture);
		}
		
		Stream GetManifestResourceStreamNoCase (Assembly ass, string fn)
		{
			string resourceName = GetManifestResourceName (fn);

			foreach (string s in ass.GetManifestResourceNames ())
				if (String.Compare (resourceName, s, true, CultureInfo.InvariantCulture) == 0)
					return ass.GetManifestResourceStream (s);
			return null;
		}

#if NET_2_0
		[CLSCompliant (false)]
		[ComVisible (false)]
		public UnmanagedMemoryStream GetStream (string name)
		{
			return GetStream (name, (CultureInfo) null);
		}

		[CLSCompliant (false)]
		[ComVisible (false)]
		public UnmanagedMemoryStream GetStream (string name, CultureInfo culture)
		{
			if (name == null)
				throw new ArgumentNullException ("name");
			if (culture == null)
				culture = CultureInfo.CurrentUICulture;
			ResourceSet set = InternalGetResourceSet (culture, true, true);
			return set.GetStream (name, ignoreCase);
		}
#endif
		protected virtual ResourceSet InternalGetResourceSet (CultureInfo culture, bool createIfNotExists, bool tryParents)
		{
			if (culture == null)
				throw new ArgumentNullException ("key"); // 'key' instead of 'culture' to make a test pass

			ResourceSet set;
			
			/* if we already have this resource set, return it */
			set = (ResourceSet) ResourceSets [culture];
			if (set != null)
				return set;

			if (NonExistent.Contains (culture))
				return null;

			if (MainAssembly != null) {
				/* Assembly resources */
				CultureInfo resourceCulture = culture;

				// when the specified culture matches the neutral culture,
				// then use the invariant resources
				if (culture.Equals (neutral_culture))
					resourceCulture = CultureInfo.InvariantCulture;

				Stream stream = null;

				string filename = GetResourceFileName (resourceCulture);
				if (!resourceCulture.Equals (CultureInfo.InvariantCulture)) {
					/* Try a satellite assembly */
					Version sat_version = GetSatelliteContractVersion (MainAssembly);
					try {
						Assembly a = MainAssembly.GetSatelliteAssemblyNoThrow (
							resourceCulture, sat_version);
						if (a != null){
							stream = a.GetManifestResourceStream (filename);
							if (stream == null)
								stream = GetManifestResourceStreamNoCase (a, filename);
						}
					} catch (Exception) {
						// Ignored
					}
				} else {
					stream = MainAssembly.GetManifestResourceStream (
						resourceSource, filename);
					if (stream == null)
						stream = GetManifestResourceStreamNoCase (
							MainAssembly, filename);
				}

				if (stream != null && createIfNotExists) {
					object [] args = new Object [1] { stream };
					
					/* should we catch
					 * MissingMethodException, or
					 * just let someone else deal
					 * with it?
					 */
					set = (ResourceSet) Activator.CreateInstance (resourceSetType, args);
				} else if (resourceCulture.Equals (CultureInfo.InvariantCulture)) {
					throw AssemblyResourceMissing (filename);
				}
			} else if (resourceDir != null || BaseNameField != null) {
				/* File resources */
				string filename = GetResourceFilePath (culture);
				if (createIfNotExists && File.Exists (filename)) {
					object [] args = new Object [1] { filename };

					/* should we catch
					 * MissingMethodException, or
					 * just let someone else deal
					 * with it?
					 */
					set = (ResourceSet) Activator.CreateInstance(
						resourceSetType, args);
				} else if (culture.Equals (CultureInfo.InvariantCulture)) {
					string msg = string.Format ("Could not find any " +
						"resources appropriate for the specified culture " +
						"(or the neutral culture) on disk.{0}" +
						"baseName: {1}  locationInfo: {2}  fileName: {3}",
						Environment.NewLine, BaseNameField, "<null>",
						GetResourceFileName (culture));
					throw new MissingManifestResourceException (msg);
				}
			}

			if (set == null && tryParents) {
				// avoid endless recursion
				if (!culture.Equals (CultureInfo.InvariantCulture))
					set = InternalGetResourceSet (culture.Parent,
						createIfNotExists, tryParents);
			}

			if (set != null)
				ResourceSets [culture] = set;
			else
				NonExistent [culture] = culture;

			return set;
		}

		public virtual void ReleaseAllResources ()
		{
			lock(this) {
				foreach (ResourceSet r in ResourceSets.Values)
					r.Close();
				ResourceSets.Clear();
			}
		}

		protected static CultureInfo GetNeutralResourcesLanguage (Assembly a)
		{
			object [] attrs = a.GetCustomAttributes (
				typeof (NeutralResourcesLanguageAttribute),
				false);

			if (attrs.Length == 0) {
				return CultureInfo.InvariantCulture;
			} else {
				NeutralResourcesLanguageAttribute res_attr = (NeutralResourcesLanguageAttribute) attrs [0];
				return new CultureInfo (res_attr.CultureName);
			}
		}

		protected static Version GetSatelliteContractVersion (Assembly a)
		{
			object [] attrs = a.GetCustomAttributes (
				typeof (SatelliteContractVersionAttribute),
				false);
			if (attrs.Length == 0) {
				return null;
			} else {
				SatelliteContractVersionAttribute sat_attr =
					(SatelliteContractVersionAttribute) attrs[0];

				/* Version(string) can throw
				 * ArgumentException if the version is
				 * invalid, but the spec for
				 * GetSatelliteContractVersion says we
				 * can throw the same exception for
				 * the same reason, so dont bother to
				 * catch it.
				 */
				return new Version (sat_attr.Version);
			}
		}

#if NET_2_0
		[MonoTODO ("the property exists but is not respected")]
		protected UltimateResourceFallbackLocation FallbackLocation {
			get { return fallbackLocation; }
			set { fallbackLocation = value; }
		}
#endif

#if ONLY_1_1
		void CheckBaseName ()
		{
			if (BaseNameField.Length <= 10)
				return;

			CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
			if (!c.IsSuffix (BaseNameField, ".resources", CompareOptions.IgnoreCase))
				return;

			if (MainAssembly != null) {
				string resourceFileName = GetResourceFileName (
					CultureInfo.InvariantCulture);
				Stream s = GetManifestResourceStreamNoCase (
					MainAssembly, resourceFileName);
				if (s != null)
					return;
			} else {
				string resourceFile = GetResourceFilePath (
					CultureInfo.InvariantCulture);
				if (File.Exists (resourceFile))
					return;
			}

			throw new ArgumentException ("ResourceManager base"
				+ " name should not end in .resources. It"
				+ " should be similar to MyResources,"
				+ " which the ResourceManager can convert"
				+ " into MyResources.<culture>.resources;"
				+ " for example, MyResources.en-US.resources.");
		}
#endif

		MissingManifestResourceException AssemblyResourceMissing (string fileName)
		{
			AssemblyName aname = MainAssembly != null ? MainAssembly.GetName ()
				: null;

#if NET_2_0
			string manifestName = GetManifestResourceName (fileName);
			string msg = string.Format ("Could not find any resources " +
				"appropriate for the specified culture or the " +
				"neutral culture.  Make sure \"{0}\" was correctly " +
				"embedded or linked into assembly \"{1}\" at " +
				"compile time, or that all the satellite assemblies " +
				"required are loadable and fully signed.",
				manifestName, aname != null ? aname.Name : string.Empty);
#else
			string location = resourceSource != null ? resourceSource.FullName
				: "<null>";
			string msg = String.Format ("Could not find any resources " +
				"appropriate for the specified culture (or " +
				"the neutral culture) in the given assembly.  " +
				"Make sure \"{0}\" was correctly embedded or " +
				"linked into assembly \"{1}\".{2}" +
				"baseName: {3}  locationInfo: {4}  resource " +
				"file name: {0}  assembly: {5}", fileName,
				aname != null ? aname.Name : "", Environment.NewLine,
				BaseNameField, location, aname != null ? aname.FullName :
				"");
#endif
			throw new MissingManifestResourceException (msg);
		}

		string GetManifestResourceName (string fn)
		{
			string resourceName = null;
			if (resourceSource != null) {
				if (resourceSource.Namespace != null && resourceSource.Namespace.Length > 0)
					resourceName = string.Concat (resourceSource.Namespace,
						".", fn);
				else
					resourceName = fn;
			} else {
				resourceName = fn;
			}
			return resourceName;
		}
	}
}