2 // System.Reflection.Assembly Test Cases
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 // Philippe Lavoie (philippe.lavoie@cactus.ca)
7 // Sebastien Pouliot (sebastien@ximian.com)
8 // Aleksey Kliger (aleksey@xamarin.com)
10 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
11 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
12 // Copyright (C) 2015 Xamarin, Inc. (http://www.xamarin.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using NUnit.Framework;
36 using System.Configuration.Assemblies;
37 using System.Globalization;
39 using System.Reflection;
40 #if !MONOTOUCH && !MOBILE_STATIC
41 using System.Reflection.Emit;
43 using System.Threading;
44 using System.Runtime.Serialization;
45 using System.Runtime.CompilerServices;
46 using System.Security;
48 using System.Resources;
50 // Used by GetType_TypeForwarder_Nested ()
51 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Globalization.CultureInfo))]
53 namespace MonoTests.System.Reflection
56 public class AssemblyTest
58 static string TempFolder = Path.Combine (Path.GetTempPath (),
59 "MonoTests.System.Reflection.AssemblyTest");
64 while (Directory.Exists (TempFolder))
65 TempFolder = Path.Combine (TempFolder, "2");
66 Directory.CreateDirectory (TempFolder);
70 public void TearDown ()
73 // This throws an exception under MS.NET, since the directory contains loaded
75 Directory.Delete (TempFolder, true);
81 public void CreateInstance()
83 Type type = typeof (AssemblyTest);
84 Object obj = type.Assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
85 Assert.IsNotNull (obj, "#01");
86 Assert.AreEqual (GetType (), obj.GetType (), "#02");
90 public void CreateInvalidInstance()
92 Type type = typeof (AssemblyTest);
93 Object obj = type.Assembly.CreateInstance("NunitTests.ThisTypeDoesNotExist");
94 Assert.IsNull (obj, "#03");
98 [ExpectedException (typeof (ArgumentException))]
99 public void GetType_TypeName_Invalid ()
101 typeof (int).Assembly.GetType ("&blabla", true, true);
105 [ExpectedException (typeof (ArgumentException))]
106 public void GetType_Invalid_RefPtr () {
107 typeof (int).Assembly.GetType ("System.Int32&*", true, true);
111 [ExpectedException (typeof (ArgumentException))]
112 public void GetType_Invalid_RefArray () {
113 typeof (int).Assembly.GetType ("System.Int32&[]", true, true);
117 [ExpectedException (typeof (ArgumentException))]
118 public void GetType_Invalid_RefGeneric () {
119 typeof (int).Assembly.GetType ("System.Tuple`1&[System.Int32]", true, true);
123 [ExpectedException (typeof (ArgumentException))]
124 public void GetType_Invalid_PtrGeneric () {
125 typeof (int).Assembly.GetType ("System.Tuple`1*[System.Int32]", true, true);
129 public void GetType_ComposeModifiers () {
130 var a = typeof(int).Assembly;
132 var e1 = typeof (Int32).MakePointerType().MakeByRefType();
133 var t1 = a.GetType ("System.Int32*&", true, true);
134 Assert.AreEqual (e1, t1, "#1");
136 var e2 = typeof (Int32).MakeArrayType(2).MakeByRefType();
137 var t2 = a.GetType ("System.Int32[,]&", true, true);
138 Assert.AreEqual (e2, t2, "#2");
140 var e3 = typeof (Int32).MakePointerType().MakeArrayType();
141 var t3 = a.GetType ("System.Int32*[]", true, true);
142 Assert.AreEqual (e3, t3, "#3");
144 var e4 = typeof (Int32).MakeArrayType().MakePointerType().MakePointerType().MakeArrayType().MakePointerType().MakeByRefType();
145 var t4 = a.GetType ("System.Int32[]**[]*&", true, true);
146 Assert.AreEqual (e4, t4, "#4");
150 [Test] // bug #334203
151 public void GetType_TypeName_AssemblyName ()
153 Assembly a = typeof (int).Assembly;
154 string typeName = typeof (string).AssemblyQualifiedName;
156 a.GetType (typeName, true, false);
158 } catch (ArgumentException ex) {
159 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
160 Assert.IsNull (ex.InnerException, "#A3");
161 Assert.IsNotNull (ex.Message, "#A4");
162 Assert.IsNull (ex.ParamName, "#A5");
165 Type type = a.GetType (typeName, false);
166 Assert.IsNull (type, "#B1");
167 type = a.GetType (typeName, false, true);
168 Assert.IsNull (type, "#B2");
172 public void GetType_TypeForwarder_Nested () {
173 // System.Globalization is a PCL assembly
174 Type t = typeof (AssemblyTest).Assembly.GetType ("System.Globalization.CultureInfo/Data");
175 Assert.IsNotNull (t);
176 Assert.AreEqual ("System.Globalization.CultureInfo+Data", t.FullName);
180 public void GetEntryAssembly ()
182 // note: only available in default appdomain
183 // http://weblogs.asp.net/asanto/archive/2003/09/08/26710.aspx
184 // Not sure we should emulate this behavior.
186 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
187 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
189 string fname = AppDomain.CurrentDomain.FriendlyName;
190 if (fname.EndsWith (".dll")) { // nunit-console
191 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
192 Assert.IsFalse (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
194 Assert.IsNotNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
195 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
198 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
199 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
203 #if !MONOTOUCH && !MOBILE_STATIC // Reflection.Emit is not supported.
205 [Category("AndroidNotWorking")] // Missing Mono.CompilerServices.SymbolWriter
206 public void GetModules_MissingFile ()
208 AssemblyName newName = new AssemblyName ();
209 newName.Name = "AssemblyTest";
211 AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly (newName, AssemblyBuilderAccess.RunAndSave, TempFolder);
213 ModuleBuilder mb = ab.DefineDynamicModule ("myDynamicModule1", "myDynamicModule.dll", true);
215 ab.Save ("test_assembly.dll");
217 File.Delete (Path.Combine (TempFolder, "myDynamicModule.dll"));
219 Assembly ass = Assembly.LoadFrom (Path.Combine (TempFolder, "test_assembly.dll"));
223 } catch (FileNotFoundException ex) {
224 Assert.AreEqual ("myDynamicModule.dll", ex.FileName);
229 [Category ("NotWorking")]
231 public void Corlib ()
233 Assembly corlib = typeof (int).Assembly;
234 Assert.IsTrue (corlib.CodeBase.EndsWith ("mscorlib.dll"), "CodeBase");
235 Assert.IsNull (corlib.EntryPoint, "EntryPoint");
236 Assert.IsTrue (corlib.EscapedCodeBase.EndsWith ("mscorlib.dll"), "EscapedCodeBase");
237 Assert.IsNotNull (corlib.Evidence, "Evidence");
238 Assert.IsTrue (corlib.Location.EndsWith ("mscorlib.dll"), "Location");
240 // corlib doesn't reference anything
241 Assert.AreEqual (0, corlib.GetReferencedAssemblies ().Length, "GetReferencedAssemblies");
242 Assert.AreEqual ("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", corlib.FullName, "FullName");
243 // not really "true" but it's even more trusted so...
244 Assert.IsTrue (corlib.GlobalAssemblyCache, "GlobalAssemblyCache");
245 Assert.AreEqual (0, corlib.HostContext, "HostContext");
246 Assert.AreEqual ("v2.0.50727", corlib.ImageRuntimeVersion, "ImageRuntimeVersion");
247 Assert.IsFalse (corlib.ReflectionOnly, "ReflectionOnly");
248 Assert.AreEqual (0x1, corlib.ManifestModule.MetadataToken);
252 public void Corlib_test ()
254 Assembly corlib_test = Assembly.GetExecutingAssembly ();
255 #if MONODROID || MOBILE_STATIC || __WATCHOS__
256 Assert.IsNull (corlib_test.EntryPoint, "EntryPoint");
257 Assert.IsNull (corlib_test.Evidence, "Evidence");
259 Assert.IsNotNull (corlib_test.EntryPoint, "EntryPoint");
260 Assert.IsNull (corlib_test.Evidence, "Evidence");
262 Assert.IsNull (corlib_test.EntryPoint, "EntryPoint");
263 Assert.IsNotNull (corlib_test.Evidence, "Evidence");
265 Assert.IsFalse (corlib_test.GlobalAssemblyCache, "GlobalAssemblyCache");
267 Assert.IsTrue (corlib_test.GetReferencedAssemblies ().Length > 0, "GetReferencedAssemblies");
268 Assert.AreEqual (0, corlib_test.HostContext, "HostContext");
269 Assert.AreEqual ("v4.0.30319", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
271 Assert.IsNotNull (corlib_test.ManifestModule, "ManifestModule");
272 Assert.IsFalse (corlib_test.ReflectionOnly, "ReflectionOnly");
276 public void GetAssembly ()
278 Assert.IsTrue (Assembly.GetAssembly (typeof (int)).FullName.StartsWith ("mscorlib"), "GetAssembly(int)");
279 Assert.AreEqual (this.GetType ().Assembly.FullName, Assembly.GetAssembly (this.GetType ()).FullName, "GetAssembly(this)");
283 public void GetFile_Null ()
286 Assembly.GetExecutingAssembly ().GetFile (null);
288 } catch (ArgumentNullException ex) {
289 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
290 Assert.IsNull (ex.InnerException, "#3");
291 Assert.IsNotNull (ex.Message, "#4");
292 Assert.IsNull (ex.ParamName, "#5");
297 public void GetFile_Empty ()
300 Assembly.GetExecutingAssembly ().GetFile (
303 } catch (ArgumentException ex) {
304 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
305 Assert.IsNull (ex.InnerException, "#3");
306 Assert.IsNotNull (ex.Message, "#4");
307 Assert.IsNull (ex.ParamName, "#5");
312 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be accessed as FileStream
313 public void GetFiles_False ()
315 Assembly corlib = typeof (int).Assembly;
316 FileStream[] fss = corlib.GetFiles ();
317 Assert.AreEqual (fss.Length, corlib.GetFiles (false).Length, "corlib.GetFiles (false)");
319 Assembly corlib_test = Assembly.GetExecutingAssembly ();
320 fss = corlib_test.GetFiles ();
321 Assert.AreEqual (fss.Length, corlib_test.GetFiles (false).Length, "test.GetFiles (false)");
325 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be accessed as FileStream
326 public void GetFiles_True ()
328 Assembly corlib = typeof (int).Assembly;
329 FileStream[] fss = corlib.GetFiles ();
330 Assert.IsTrue (fss.Length <= corlib.GetFiles (true).Length, "corlib.GetFiles (true)");
332 Assembly corlib_test = Assembly.GetExecutingAssembly ();
333 fss = corlib_test.GetFiles ();
334 Assert.IsTrue (fss.Length <= corlib_test.GetFiles (true).Length, "test.GetFiles (true)");
338 public void GetManifestResourceStream_Name_Empty ()
340 Assembly corlib = typeof (int).Assembly;
343 corlib.GetManifestResourceStream (string.Empty);
345 } catch (ArgumentException ex) {
346 // String cannot have zero length
347 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
348 Assert.IsNull (ex.InnerException, "#A3");
349 Assert.IsNotNull (ex.Message, "#A4");
352 corlib.GetManifestResourceStream (typeof (int), string.Empty);
355 corlib.GetManifestResourceStream ((Type) null, string.Empty);
357 } catch (ArgumentException ex) {
358 // String cannot have zero length
359 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
360 Assert.IsNull (ex.InnerException, "#B3");
361 Assert.IsNotNull (ex.Message, "#B4");
366 public void GetManifestResourceStream_Name_Null ()
368 Assembly corlib = typeof (int).Assembly;
371 corlib.GetManifestResourceStream ((string) null);
373 } catch (ArgumentNullException ex) {
374 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
375 Assert.IsNull (ex.InnerException, "#A3");
376 Assert.IsNotNull (ex.Message, "#A4");
379 corlib.GetManifestResourceStream (typeof (int), (string) null);
382 corlib.GetManifestResourceStream ((Type) null, (string) null);
384 } catch (ArgumentNullException ex) {
385 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2");
386 Assert.IsNull (ex.InnerException, "#B3");
387 Assert.IsNotNull (ex.Message, "#B4");
388 Assert.IsNotNull (ex.ParamName, "#B5");
389 Assert.AreEqual ("type", ex.ParamName, "#B6");
394 public void IsDefined_AttributeType_Null ()
396 Assembly corlib = typeof (int).Assembly;
399 corlib.IsDefined ((Type) null, false);
401 } catch (ArgumentNullException ex) {
402 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
403 Assert.IsNull (ex.InnerException, "#3");
404 Assert.IsNotNull (ex.Message, "#4");
405 Assert.IsNotNull (ex.ParamName, "#5");
406 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
411 public void LoadFrom_Empty_Assembly ()
413 string tempFile = Path.GetTempFileName ();
416 Assembly.LoadFrom (tempFile);
418 } catch (BadImageFormatException ex) {
419 Assert.IsNull (ex.InnerException, "#2");
421 File.Delete (tempFile);
426 public void LoadFrom_Invalid_Assembly ()
428 string tempFile = Path.GetTempFileName ();
429 using (StreamWriter sw = File.CreateText (tempFile)) {
430 sw.WriteLine ("foo");
435 Assembly.LoadFrom (tempFile);
437 } catch (BadImageFormatException ex) {
438 Assert.IsNull (ex.InnerException, "#2");
440 File.Delete (tempFile);
445 public void LoadFrom_NonExisting_Assembly ()
447 string tempFile = Path.GetTempFileName ();
448 File.Delete (tempFile);
451 Assembly.LoadFrom (tempFile);
453 } catch (FileNotFoundException ex) {
454 Assert.IsNull (ex.InnerException, "#2");
456 File.Delete (tempFile);
461 public void LoadWithPartialName ()
464 // So the problem here is that if we load an assembly
465 // in a fully aot mode and then cannot load the
466 // dylib, we will assert. This test is incompatible
467 // with the semantics of aot'ed assembly loading, as
468 // aot may assert when loading. This assumes that it's
469 // safe to greedly load everything.
471 string [] names = { "mobile_static_corlib_test" };
473 string [] names = { "corlib_test_net_1_1", "corlib_test_net_2_0", "corlib_test_net_4_0", "corlib_test_net_4_5", "net_4_x_corlib_test", "corlib_plattest", "mscorlibtests", "BclTests" };
476 foreach (string s in names)
477 if (Assembly.LoadWithPartialName (s) != null)
479 Assert.Fail ("Was not able to load any corlib test");
483 public void GetObjectData_Info_Null ()
485 Assembly corlib = typeof (int).Assembly;
487 corlib.GetObjectData (null, new StreamingContext (
488 StreamingContextStates.All));
490 } catch (ArgumentNullException ex) {
491 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
492 Assert.IsNull (ex.InnerException, "#3");
493 Assert.IsNotNull (ex.Message, "#4");
494 Assert.IsNotNull (ex.ParamName, "#5");
495 Assert.AreEqual ("info", ex.ParamName, "#6");
500 public void GetReferencedAssemblies ()
502 Assembly corlib_test = Assembly.GetExecutingAssembly ();
503 AssemblyName[] names = corlib_test.GetReferencedAssemblies ();
504 foreach (AssemblyName an in names) {
505 Assert.IsNull (an.CodeBase, "CodeBase");
506 Assert.IsNotNull (an.CultureInfo, "CultureInfo");
507 Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase");
508 Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags");
509 Assert.IsNotNull (an.FullName, "FullName");
510 Assert.AreEqual (AssemblyHashAlgorithm.SHA1, an.HashAlgorithm, "HashAlgorithm");
511 Assert.IsNull (an.KeyPair, "KeyPair");
512 Assert.IsNotNull (an.Name, "Name");
513 Assert.IsNotNull (an.Version, "Version");
514 Assert.AreEqual (AssemblyVersionCompatibility.SameMachine,
515 an.VersionCompatibility, "VersionCompatibility");
519 #if !MONOTOUCH && !MOBILE_STATIC // Reflection.Emit is not supported.
521 public void Location_Empty() {
522 string assemblyFileName = Path.Combine (
523 Path.GetTempPath (), "AssemblyLocation.dll");
526 AssemblyName assemblyName = new AssemblyName ();
527 assemblyName.Name = "AssemblyLocation";
529 AssemblyBuilder ab = AppDomain.CurrentDomain
530 .DefineDynamicAssembly (assemblyName,
531 AssemblyBuilderAccess.Save,
533 AppDomain.CurrentDomain.Evidence);
534 ab.Save (Path.GetFileName (assemblyFileName));
536 using (FileStream fs = File.OpenRead (assemblyFileName)) {
537 byte[] buffer = new byte[fs.Length];
538 fs.Read (buffer, 0, buffer.Length);
539 Assembly assembly = Assembly.Load (buffer);
540 Assert.AreEqual (string.Empty, assembly.Location);
544 File.Delete (assemblyFileName);
549 public void SateliteAssemblyForInMemoryAssembly ()
551 string assemblyFileName = Path.Combine (
552 Path.GetTempPath (), "AssemblyLocation1.dll");
555 AssemblyName assemblyName = new AssemblyName ();
556 assemblyName.Name = "AssemblyLocation1";
558 AssemblyBuilder ab = AppDomain.CurrentDomain
559 .DefineDynamicAssembly (assemblyName,
560 AssemblyBuilderAccess.Save,
561 Path.GetTempPath ());
563 ModuleBuilder moduleBuilder = ab.DefineDynamicModule (assemblyName.Name, assemblyName.Name + ".dll");
564 TypeBuilder typeBuilder = moduleBuilder.DefineType ("Program", TypeAttributes.Public);
566 MethodBuilder methodBuilder = typeBuilder.DefineMethod ("TestCall", MethodAttributes.Public | MethodAttributes.Static, typeof(void), Type.EmptyTypes);
567 ILGenerator gen = methodBuilder.GetILGenerator ();
570 // var resourceManager = new ResourceManager (typeof (Program));
571 // resourceManager.GetString ("test");
573 gen.Emit (OpCodes.Ldtoken, typeBuilder);
574 gen.Emit (OpCodes.Call, typeof(Type).GetMethod ("GetTypeFromHandle"));
575 gen.Emit (OpCodes.Newobj, typeof(ResourceManager).GetConstructor (new Type[] { typeof(Type) }));
576 gen.Emit (OpCodes.Ldstr, "test");
577 gen.Emit (OpCodes.Callvirt, typeof(ResourceManager).GetMethod ("GetString", new Type[] { typeof(string) }));
578 gen.Emit (OpCodes.Pop);
579 gen.Emit (OpCodes.Ret);
581 typeBuilder.CreateType ();
583 ab.Save (Path.GetFileName (assemblyFileName));
585 using (FileStream fs = File.OpenRead (assemblyFileName)) {
586 byte[] buffer = new byte[fs.Length];
587 fs.Read (buffer, 0, buffer.Length);
588 Assembly assembly = Assembly.Load (buffer);
590 var mm = assembly.GetType ("Program").GetMethod ("TestCall");
592 mm.Invoke (null, null);
594 } catch (TargetInvocationException e) {
595 Assert.IsTrue (e.InnerException is MissingManifestResourceException);
601 File.Delete (assemblyFileName);
606 [Category ("NotWorking")]
607 public void bug78464 ()
609 string assemblyFileName = Path.Combine (
610 Path.GetTempPath (), "bug78464.dll");
613 // execute test in separate appdomain to allow assembly to be unloaded
614 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
615 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
617 crossDomainTester.bug78464 (assemblyFileName);
619 AppDomain.Unload (testDomain);
622 File.Delete (assemblyFileName);
627 [Category("MobileNotWorking")]
628 public void bug78465 ()
630 string assemblyFileName = Path.Combine (
631 Path.GetTempPath (), "bug78465.dll");
634 AssemblyName assemblyName = new AssemblyName ();
635 assemblyName.Name = "bug78465";
637 AssemblyBuilder ab = AppDomain.CurrentDomain
638 .DefineDynamicAssembly (assemblyName,
639 AssemblyBuilderAccess.Save,
640 Path.GetDirectoryName (assemblyFileName),
641 AppDomain.CurrentDomain.Evidence);
642 ab.Save (Path.GetFileName (assemblyFileName));
644 using (FileStream fs = File.OpenRead (assemblyFileName)) {
645 byte[] buffer = new byte[fs.Length];
646 fs.Read (buffer, 0, buffer.Length);
647 Assembly assembly = Assembly.Load (buffer);
648 Assert.AreEqual (string.Empty, assembly.Location, "#1");
652 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
653 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
655 crossDomainTester.bug78465 (assemblyFileName);
657 AppDomain.Unload (testDomain);
660 File.Delete (assemblyFileName);
665 [Category("MobileNotWorking")]
666 public void bug78468 ()
668 string assemblyFileNameA = Path.Combine (Path.GetTempPath (),
670 string resourceFileName = Path.Combine (Path.GetTempPath (),
673 using (StreamWriter sw = File.CreateText (resourceFileName)) {
674 sw.WriteLine ("FOO");
679 AssemblyName assemblyName = new AssemblyName ();
680 assemblyName.Name = "bug78468a";
682 AssemblyBuilder ab = AppDomain.CurrentDomain
683 .DefineDynamicAssembly (assemblyName,
684 AssemblyBuilderAccess.Save,
686 AppDomain.CurrentDomain.Evidence);
687 ab.AddResourceFile ("read", "readme.txt");
688 ab.Save (Path.GetFileName (assemblyFileNameA));
692 using (FileStream fs = File.OpenRead (assemblyFileNameA)) {
693 byte[] buffer = new byte[fs.Length];
694 fs.Read (buffer, 0, buffer.Length);
695 assembly = Assembly.Load (buffer);
699 Assert.AreEqual (string.Empty, assembly.Location, "#A1");
700 string[] resNames = assembly.GetManifestResourceNames ();
701 Assert.IsNotNull (resNames, "#A2");
702 Assert.AreEqual (1, resNames.Length, "#A3");
703 Assert.AreEqual ("read", resNames[0], "#A4");
704 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
705 Assert.IsNotNull (resInfo, "#A5");
706 Assert.AreEqual ("readme.txt", resInfo.FileName, "#A6");
707 Assert.IsNull (resInfo.ReferencedAssembly, "#A7");
708 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#A8");
710 assembly.GetManifestResourceStream ("read");
712 } catch (FileNotFoundException) {
715 assembly.GetFile ("readme.txt");
716 Assert.Fail ("#A10");
717 } catch (FileNotFoundException) {
720 string assemblyFileNameB = Path.Combine (Path.GetTempPath (),
723 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
724 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
726 crossDomainTester.bug78468 (assemblyFileNameB);
728 AppDomain.Unload (testDomain);
729 File.Delete (assemblyFileNameB);
732 File.Delete (assemblyFileNameA);
733 File.Delete (resourceFileName);
738 [Category ("NotWorking")]
739 public void ReflectionOnlyLoad ()
741 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
743 Assert.IsNotNull (assembly);
744 Assert.IsTrue (assembly.ReflectionOnly);
748 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be directly as files
749 public void ReflectionOnlyLoadFrom ()
751 string loc = typeof (AssemblyTest).Assembly.Location;
752 string filename = Path.GetFileName (loc);
753 Assembly assembly = Assembly.ReflectionOnlyLoadFrom (filename);
755 Assert.IsNotNull (assembly);
756 Assert.IsTrue (assembly.ReflectionOnly);
760 [ExpectedException (typeof (ArgumentException))]
761 public void CreateInstanceOnRefOnly ()
763 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
764 assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
768 [Category ("NotWorking")] // patch for bug #79720 must be committed first
769 public void Load_Culture ()
771 string tempDir = Path.Combine (Path.GetTempPath (),
772 "MonoTests.System.Reflection.AssemblyTest");
773 string cultureTempDir = Path.Combine (tempDir, "nl-BE");
774 if (!Directory.Exists (cultureTempDir))
775 Directory.CreateDirectory (cultureTempDir);
776 cultureTempDir = Path.Combine (tempDir, "en-US");
777 if (!Directory.Exists (cultureTempDir))
778 Directory.CreateDirectory (cultureTempDir);
781 AppDomain ad = CreateTestDomain (tempDir, true);
783 CrossDomainTester cdt = CreateCrossDomainTester (ad);
787 AssemblyName aname = new AssemblyName ();
788 aname.Name = "culturea";
789 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "culturea.dll"));
791 aname = new AssemblyName ();
792 aname.Name = "culturea";
793 Assert.IsTrue (cdt.AssertLoad(aname), "#A1");
795 aname = new AssemblyName ();
796 aname.Name = "culturea";
797 aname.CultureInfo = new CultureInfo ("nl-BE");
798 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A2");
800 aname = new AssemblyName ();
801 aname.Name = "culturea";
802 aname.CultureInfo = CultureInfo.InvariantCulture;
803 Assert.IsTrue (cdt.AssertLoad(aname), "#A3");
807 aname = new AssemblyName ();
808 aname.Name = "cultureb";
809 aname.CultureInfo = new CultureInfo ("nl-BE");
810 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "cultureb.dll"));
812 aname = new AssemblyName ();
813 aname.Name = "cultureb";
814 aname.CultureInfo = new CultureInfo ("nl-BE");
815 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
817 aname = new AssemblyName ();
818 aname.Name = "cultureb";
819 Assert.IsTrue (cdt.AssertLoad (aname), "#B2");
821 aname = new AssemblyName ();
822 aname.Name = "cultureb";
823 aname.CultureInfo = new CultureInfo ("en-US");
824 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B3");
828 aname = new AssemblyName ();
829 aname.Name = "culturec";
830 aname.CultureInfo = new CultureInfo ("nl-BE");
831 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "nl-BE/culturec.dll"));
833 aname = new AssemblyName ();
834 aname.Name = "culturec";
835 aname.CultureInfo = new CultureInfo ("nl-BE");
836 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
838 aname = new AssemblyName ();
839 aname.Name = "culturec";
840 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C2");
842 aname = new AssemblyName ();
843 aname.Name = "culturec";
844 aname.CultureInfo = CultureInfo.InvariantCulture;
845 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C3");
849 aname = new AssemblyName ();
850 aname.Name = "cultured";
851 aname.CultureInfo = new CultureInfo ("nl-BE");
852 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/cultured.dll"));
854 aname = new AssemblyName ();
855 aname.Name = "cultured";
856 aname.CultureInfo = new CultureInfo ("nl-BE");
857 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D1");
859 aname = new AssemblyName ();
860 aname.Name = "cultured";
861 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D2");
863 aname = new AssemblyName ();
864 aname.Name = "cultured";
865 aname.CultureInfo = CultureInfo.InvariantCulture;
866 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D3");
868 AppDomain.Unload (ad);
869 if (Directory.Exists (tempDir))
870 Directory.Delete (tempDir, true);
875 [Category ("NotWorking")] // in non-default domain, MS throws FileNotFoundException
876 public void Load_Culture_Mismatch ()
878 string tempDir = Path.Combine (Path.GetTempPath (),
879 "MonoTests.System.Reflection.AssemblyTest");
880 string cultureTempDir = Path.Combine (tempDir, "en-US");
881 if (!Directory.Exists (cultureTempDir))
882 Directory.CreateDirectory (cultureTempDir);
884 AppDomain ad = CreateTestDomain (tempDir, true);
886 CrossDomainTester cdt = CreateCrossDomainTester (ad);
890 AssemblyName aname = new AssemblyName ();
891 aname.Name = "bug79712a";
892 aname.CultureInfo = new CultureInfo ("nl-BE");
893 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79712a.dll"));
895 aname = new AssemblyName ();
896 aname.Name = "bug79712a";
897 aname.CultureInfo = CultureInfo.InvariantCulture;
898 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A1");
902 aname = new AssemblyName ();
903 aname.Name = "bug79712b";
904 aname.CultureInfo = new CultureInfo ("nl-BE");
905 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/bug79712b.dll"));
907 aname = new AssemblyName ();
908 aname.Name = "bug79712b";
909 aname.CultureInfo = new CultureInfo ("en-US");
910 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
912 AppDomain.Unload (ad);
913 if (Directory.Exists (tempDir))
914 Directory.Delete (tempDir, true);
920 [Category("MobileNotWorking")]
921 public void Load_PartialVersion ()
923 string tempDir = Path.Combine (Path.GetTempPath (),
924 "MonoTests.System.Reflection.AssemblyTest");
925 if (!Directory.Exists (tempDir))
926 Directory.CreateDirectory (tempDir);
928 AppDomain ad = CreateTestDomain (tempDir, true);
930 CrossDomainTester cdt = CreateCrossDomainTester (ad);
932 AssemblyName aname = new AssemblyName ();
933 aname.Name = "bug79715";
934 aname.Version = new Version (1, 2, 3, 4);
935 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79715.dll"));
937 aname = new AssemblyName ();
938 aname.Name = "bug79715";
939 aname.Version = new Version (1, 2);
940 Assert.IsTrue (cdt.AssertLoad (aname), "#A1");
941 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#A2");
943 aname = new AssemblyName ();
944 aname.Name = "bug79715";
945 aname.Version = new Version (1, 2, 3);
946 Assert.IsTrue (cdt.AssertLoad (aname), "#B1");
947 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#B2");
949 aname = new AssemblyName ();
950 aname.Name = "bug79715";
951 aname.Version = new Version (1, 2, 3, 4);
952 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
953 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#C2");
955 AppDomain.Unload (ad);
956 if (Directory.Exists (tempDir))
957 Directory.Delete (tempDir, true);
961 private static AppDomain CreateTestDomain (string baseDirectory, bool assemblyResolver)
963 AppDomainSetup setup = new AppDomainSetup ();
964 setup.ApplicationBase = baseDirectory;
965 setup.ApplicationName = "testdomain";
967 AppDomain ad = AppDomain.CreateDomain ("testdomain",
968 AppDomain.CurrentDomain.Evidence, setup);
970 if (assemblyResolver) {
971 Assembly ea = Assembly.GetExecutingAssembly ();
972 ad.CreateInstanceFrom (ea.CodeBase,
973 typeof (AssemblyResolveHandler).FullName,
975 BindingFlags.Public | BindingFlags.Instance,
977 new object [] { ea.Location, ea.FullName },
978 CultureInfo.InvariantCulture,
986 private static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
988 Type testerType = typeof (CrossDomainTester);
989 return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
990 testerType.Assembly.FullName, testerType.FullName, false,
991 BindingFlags.Public | BindingFlags.Instance, null, new object[0],
992 CultureInfo.InvariantCulture, new object[0], null);
995 private class CrossDomainTester : MarshalByRefObject
997 public void GenerateAssembly (AssemblyName aname, string path)
999 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
1000 aname, AssemblyBuilderAccess.Save, Path.GetDirectoryName (path));
1001 ab.Save (Path.GetFileName (path));
1004 public void Load (AssemblyName assemblyRef)
1006 Assembly.Load (assemblyRef);
1009 public void LoadFrom (string assemblyFile)
1011 Assembly.LoadFrom (assemblyFile);
1014 public bool AssertLoad (AssemblyName assemblyRef)
1017 Assembly.Load (assemblyRef);
1024 public bool AssertLoad (string assemblyString)
1027 Assembly.Load (assemblyString);
1034 public bool AssertFileLoadException (AssemblyName assemblyRef)
1037 Assembly.Load (assemblyRef);
1039 } catch (FileLoadException) {
1044 public bool AssertFileNotFoundException (AssemblyName assemblyRef)
1047 Assembly.Load (assemblyRef);
1049 } catch (FileNotFoundException) {
1054 public void bug78464 (string assemblyFileName)
1056 AssemblyName assemblyName = new AssemblyName ();
1057 assemblyName.Name = "bug78464";
1059 AssemblyBuilder ab = AppDomain.CurrentDomain
1060 .DefineDynamicAssembly (assemblyName,
1061 AssemblyBuilderAccess.Save,
1062 Path.GetDirectoryName (assemblyFileName),
1063 AppDomain.CurrentDomain.Evidence);
1064 ab.Save (Path.GetFileName (assemblyFileName));
1068 using (FileStream fs = File.OpenRead (assemblyFileName)) {
1069 byte[] buffer = new byte[fs.Length];
1070 fs.Read (buffer, 0, buffer.Length);
1071 assembly = Assembly.Load (buffer);
1075 Assert.AreEqual (string.Empty, assembly.Location, "#1");
1077 assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1078 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1079 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName(assembly.Location), "#3");
1080 // note: we cannot check if directory names match, as MS.NET seems to
1081 // convert directory part of assembly location to lowercase
1082 Assert.IsFalse (Path.GetDirectoryName(assembly.Location) == string.Empty, "#4");
1085 public void bug78465 (string assemblyFileName)
1087 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1088 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1089 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName (assembly.Location), "#3");
1090 // note: we cannot check if directory names match, as MS.NET seems to
1091 // convert directory part of assembly location to lowercase
1092 Assert.IsFalse (Path.GetDirectoryName (assembly.Location) == string.Empty, "#4");
1095 public void bug78468 (string assemblyFileName)
1097 AssemblyName assemblyName = new AssemblyName ();
1098 assemblyName.Name = "bug78468b";
1100 AssemblyBuilder ab = AppDomain.CurrentDomain
1101 .DefineDynamicAssembly (assemblyName,
1102 AssemblyBuilderAccess.Save,
1103 Path.GetDirectoryName (assemblyFileName),
1104 AppDomain.CurrentDomain.Evidence);
1105 ab.AddResourceFile ("read", "readme.txt");
1106 ab.Save (Path.GetFileName (assemblyFileName));
1108 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1109 Assert.IsTrue (assembly.Location != string.Empty, "#B1");
1110 string[] resNames = assembly.GetManifestResourceNames ();
1111 Assert.IsNotNull (resNames, "#B2");
1112 Assert.AreEqual (1, resNames.Length, "#B3");
1113 Assert.AreEqual ("read", resNames[0], "#B4");
1114 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
1115 Assert.IsNotNull (resInfo, "#B5");
1116 Assert.AreEqual ("readme.txt", resInfo.FileName, "#B6");
1117 Assert.IsNull (resInfo.ReferencedAssembly, "#B7");
1118 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#B8");
1119 Stream s = assembly.GetManifestResourceStream ("read");
1120 Assert.IsNotNull (s, "#B9");
1122 s = assembly.GetFile ("readme.txt");
1123 Assert.IsNotNull (s, "#B10");
1129 public void bug79872 ()
1131 Random rnd = new Random ();
1136 outdir = Path.Combine (Path.GetTempPath (), "bug79872-" + rnd.Next (10000, 99999));
1137 if (Directory.Exists (outdir)) {
1139 Directory.Delete (outdir, true);
1146 Directory.CreateDirectory (outdir);
1148 AssemblyName an = new AssemblyName ();
1149 an.Name = "bug79872";
1150 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, outdir);
1151 string dllname = "bug79872.dll";
1152 ModuleBuilder mb1 = ab.DefineDynamicModule ("bug79872", dllname);
1153 string netmodule = "bug79872.netmodule";
1154 ModuleBuilder mb2 = ab.DefineDynamicModule (netmodule, netmodule);
1155 TypeBuilder a1 = mb2.DefineType ("A");
1161 Assembly.LoadFrom (Path.Combine (outdir, dllname));
1165 Assert.IsTrue (ok, "Should load a .NET metadata file with an assembly manifest");
1169 Assembly.LoadFrom (Path.Combine (outdir, netmodule));
1170 } catch (BadImageFormatException) {
1171 ok = true; // mono and .net 2.0 throw this
1172 } catch (FileLoadException) {
1173 ok = true; // .net 1.1 throws this
1177 Assert.IsTrue (ok, "Complain on loading a .NET metadata file without an assembly manifest");
1179 Directory.Delete (outdir, true);
1184 public void ManifestModule ()
1186 Assembly assembly = typeof (int).Assembly;
1187 Module module = assembly.ManifestModule;
1188 Assert.IsNotNull (module, "#1");
1190 Assert.AreEqual ("MonoModule", module.GetType ().Name, "#2");
1192 #if !MONOTOUCH && !MOBILE_STATIC
1193 Assert.AreEqual ("mscorlib.dll", module.Name, "#3");
1195 Assert.IsFalse (module.IsResource (), "#4");
1196 Assert.IsTrue (assembly.GetModules ().Length > 0, "#5");
1197 Assert.AreSame (module, assembly.GetModules () [0], "#6");
1198 Assert.AreSame (module, assembly.ManifestModule, "#7");
1203 private class AssemblyResolveHandler
1205 public AssemblyResolveHandler (string assemblyFile, string assemblyName)
1207 _assemblyFile = assemblyFile;
1208 _assemblyName = assemblyName;
1210 AppDomain.CurrentDomain.AssemblyResolve +=
1211 new ResolveEventHandler (ResolveAssembly);
1214 private Assembly ResolveAssembly (Object sender, ResolveEventArgs args)
1216 if (args.Name == _assemblyName)
1217 return Assembly.LoadFrom (_assemblyFile);
1222 private readonly string _assemblyFile;
1223 private readonly string _assemblyName;
1226 protected internal class Bug328812_NestedFamORAssem { };
1229 public void bug328812 ()
1231 Assembly corlib_test = Assembly.GetExecutingAssembly ();
1232 Assert.IsNull (corlib_test.GetType ("Bug328812_NestedFamORAssem"));
1233 // Just a sanity check, in case the above passed for some other reason
1234 Assert.IsNotNull (corlib_test.GetType ("MonoTests.System.Reflection.AssemblyTest+Bug328812_NestedFamORAssem"));
1238 public void GetCustomAttributes_AttributeType_Null ()
1240 Assembly a = typeof (int).Assembly;
1242 a.GetCustomAttributes (null, false);
1244 } catch (ArgumentNullException ex) {
1245 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
1246 Assert.IsNull (ex.InnerException, "#3");
1247 Assert.IsNotNull (ex.Message, "#4");
1248 Assert.IsNotNull (ex.ParamName, "#5");
1249 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
1254 public void GetTypeWithEmptyStringShouldThrow ()
1257 typeof (string).Assembly.GetType ("");
1259 } catch (ArgumentException) {}
1262 class GetCallingAssemblyCallee {
1265 static void sideEffect () {
1269 // GetCallingAssembly may see an unpredictable
1270 // view of the stack if it's called in tail
1271 // position, or if its caller or the caller's
1272 // caller is inlined. So we put in a side
1273 // effect to get out of tail position, and we
1274 // tag the methods NoInlining to discourage
1276 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1277 public static Assembly Leaf () {
1278 var a = Assembly.GetCallingAssembly ();
1283 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1284 public static Assembly DirectCall () {
1290 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1291 public static Assembly InvokeCall () {
1292 var ty = typeof (GetCallingAssemblyCallee);
1293 var mi = ty.GetMethod("Leaf");
1294 var o = mi.Invoke(null, null);
1301 public void GetCallingAssembly_Direct() {
1302 var a = GetCallingAssemblyCallee.DirectCall ();
1303 Assert.IsNotNull (a);
1305 Assert.AreEqual (GetType().Assembly, a);
1309 public void GetCallingAssembly_SkipsReflection () {
1310 // check that the calling assembly is this
1311 // one, not mscorlib (aka, the reflection
1313 var a = GetCallingAssemblyCallee.InvokeCall ();
1314 Assert.IsNotNull (a);
1316 var invokeAssembly =
1317 typeof (MethodInfo).Assembly;
1318 Assert.AreNotEqual (invokeAssembly, a);
1320 Assert.AreEqual (GetType().Assembly, a);
1325 public void DefinedTypes_Equality ()
1327 var x1 = Assembly.GetExecutingAssembly ().DefinedTypes.Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1328 var x2 = Assembly.GetExecutingAssembly ().GetTypes ().Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1330 Assert.AreSame (x1, x2, "#1");
1334 class MyAssembly : Assembly { }
1337 public void CustomAssemblyImplThrows ()
1339 var ma = new MyAssembly();
1342 Assert.Fail ("must throw");
1343 } catch (NotImplementedException){
1348 public class TestDefinedTypes