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 string fname = AppDomain.CurrentDomain.FriendlyName;
187 if (fname.EndsWith (".dll")) { // nunit-console
188 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
189 Assert.IsFalse (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
191 Assert.IsNotNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
192 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
195 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
196 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
200 #if !MONOTOUCH && !MOBILE_STATIC // Reflection.Emit is not supported.
202 [Category("AndroidNotWorking")] // Missing Mono.CompilerServices.SymbolWriter
203 public void GetModules_MissingFile ()
205 AssemblyName newName = new AssemblyName ();
206 newName.Name = "AssemblyTest";
208 AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly (newName, AssemblyBuilderAccess.RunAndSave, TempFolder);
210 ModuleBuilder mb = ab.DefineDynamicModule ("myDynamicModule1", "myDynamicModule.dll", true);
212 ab.Save ("test_assembly.dll");
214 File.Delete (Path.Combine (TempFolder, "myDynamicModule.dll"));
216 Assembly ass = Assembly.LoadFrom (Path.Combine (TempFolder, "test_assembly.dll"));
220 } catch (FileNotFoundException ex) {
221 Assert.AreEqual ("myDynamicModule.dll", ex.FileName);
226 [Category ("NotWorking")]
228 public void Corlib ()
230 Assembly corlib = typeof (int).Assembly;
231 Assert.IsTrue (corlib.CodeBase.EndsWith ("mscorlib.dll"), "CodeBase");
232 Assert.IsNull (corlib.EntryPoint, "EntryPoint");
233 Assert.IsTrue (corlib.EscapedCodeBase.EndsWith ("mscorlib.dll"), "EscapedCodeBase");
234 Assert.IsNotNull (corlib.Evidence, "Evidence");
235 Assert.IsTrue (corlib.Location.EndsWith ("mscorlib.dll"), "Location");
237 // corlib doesn't reference anything
238 Assert.AreEqual (0, corlib.GetReferencedAssemblies ().Length, "GetReferencedAssemblies");
239 Assert.AreEqual ("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", corlib.FullName, "FullName");
240 // not really "true" but it's even more trusted so...
241 Assert.IsTrue (corlib.GlobalAssemblyCache, "GlobalAssemblyCache");
242 Assert.AreEqual (0, corlib.HostContext, "HostContext");
243 Assert.AreEqual ("v2.0.50727", corlib.ImageRuntimeVersion, "ImageRuntimeVersion");
244 Assert.IsFalse (corlib.ReflectionOnly, "ReflectionOnly");
245 Assert.AreEqual (0x1, corlib.ManifestModule.MetadataToken);
249 public void Corlib_test ()
251 Assembly corlib_test = Assembly.GetExecutingAssembly ();
252 #if MONODROID || MOBILE_STATIC
253 Assert.IsNull (corlib_test.EntryPoint, "EntryPoint");
254 Assert.IsNull (corlib_test.Evidence, "Evidence");
256 Assert.IsNotNull (corlib_test.EntryPoint, "EntryPoint");
257 Assert.IsNull (corlib_test.Evidence, "Evidence");
259 Assert.IsNull (corlib_test.EntryPoint, "EntryPoint");
260 Assert.IsNotNull (corlib_test.Evidence, "Evidence");
262 Assert.IsFalse (corlib_test.GlobalAssemblyCache, "GlobalAssemblyCache");
264 Assert.IsTrue (corlib_test.GetReferencedAssemblies ().Length > 0, "GetReferencedAssemblies");
265 Assert.AreEqual (0, corlib_test.HostContext, "HostContext");
266 Assert.AreEqual ("v4.0.30319", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
268 Assert.IsNotNull (corlib_test.ManifestModule, "ManifestModule");
269 Assert.IsFalse (corlib_test.ReflectionOnly, "ReflectionOnly");
273 public void GetAssembly ()
275 Assert.IsTrue (Assembly.GetAssembly (typeof (int)).FullName.StartsWith ("mscorlib"), "GetAssembly(int)");
276 Assert.AreEqual (this.GetType ().Assembly.FullName, Assembly.GetAssembly (this.GetType ()).FullName, "GetAssembly(this)");
280 public void GetFile_Null ()
283 Assembly.GetExecutingAssembly ().GetFile (null);
285 } catch (ArgumentNullException ex) {
286 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
287 Assert.IsNull (ex.InnerException, "#3");
288 Assert.IsNotNull (ex.Message, "#4");
289 Assert.IsNull (ex.ParamName, "#5");
294 public void GetFile_Empty ()
297 Assembly.GetExecutingAssembly ().GetFile (
300 } catch (ArgumentException ex) {
301 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
302 Assert.IsNull (ex.InnerException, "#3");
303 Assert.IsNotNull (ex.Message, "#4");
304 Assert.IsNull (ex.ParamName, "#5");
309 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be accessed as FileStream
310 public void GetFiles_False ()
312 Assembly corlib = typeof (int).Assembly;
313 FileStream[] fss = corlib.GetFiles ();
314 Assert.AreEqual (fss.Length, corlib.GetFiles (false).Length, "corlib.GetFiles (false)");
316 Assembly corlib_test = Assembly.GetExecutingAssembly ();
317 fss = corlib_test.GetFiles ();
318 Assert.AreEqual (fss.Length, corlib_test.GetFiles (false).Length, "test.GetFiles (false)");
322 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be accessed as FileStream
323 public void GetFiles_True ()
325 Assembly corlib = typeof (int).Assembly;
326 FileStream[] fss = corlib.GetFiles ();
327 Assert.IsTrue (fss.Length <= corlib.GetFiles (true).Length, "corlib.GetFiles (true)");
329 Assembly corlib_test = Assembly.GetExecutingAssembly ();
330 fss = corlib_test.GetFiles ();
331 Assert.IsTrue (fss.Length <= corlib_test.GetFiles (true).Length, "test.GetFiles (true)");
335 public void GetManifestResourceStream_Name_Empty ()
337 Assembly corlib = typeof (int).Assembly;
340 corlib.GetManifestResourceStream (string.Empty);
342 } catch (ArgumentException ex) {
343 // String cannot have zero length
344 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
345 Assert.IsNull (ex.InnerException, "#A3");
346 Assert.IsNotNull (ex.Message, "#A4");
349 corlib.GetManifestResourceStream (typeof (int), string.Empty);
352 corlib.GetManifestResourceStream ((Type) null, string.Empty);
354 } catch (ArgumentException ex) {
355 // String cannot have zero length
356 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
357 Assert.IsNull (ex.InnerException, "#B3");
358 Assert.IsNotNull (ex.Message, "#B4");
363 public void GetManifestResourceStream_Name_Null ()
365 Assembly corlib = typeof (int).Assembly;
368 corlib.GetManifestResourceStream ((string) null);
370 } catch (ArgumentNullException ex) {
371 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
372 Assert.IsNull (ex.InnerException, "#A3");
373 Assert.IsNotNull (ex.Message, "#A4");
376 corlib.GetManifestResourceStream (typeof (int), (string) null);
379 corlib.GetManifestResourceStream ((Type) null, (string) null);
381 } catch (ArgumentNullException ex) {
382 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2");
383 Assert.IsNull (ex.InnerException, "#B3");
384 Assert.IsNotNull (ex.Message, "#B4");
385 Assert.IsNotNull (ex.ParamName, "#B5");
386 Assert.AreEqual ("type", ex.ParamName, "#B6");
391 public void IsDefined_AttributeType_Null ()
393 Assembly corlib = typeof (int).Assembly;
396 corlib.IsDefined ((Type) null, false);
398 } catch (ArgumentNullException ex) {
399 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
400 Assert.IsNull (ex.InnerException, "#3");
401 Assert.IsNotNull (ex.Message, "#4");
402 Assert.IsNotNull (ex.ParamName, "#5");
403 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
408 public void LoadFrom_Empty_Assembly ()
410 string tempFile = Path.GetTempFileName ();
413 Assembly.LoadFrom (tempFile);
415 } catch (BadImageFormatException ex) {
416 Assert.IsNull (ex.InnerException, "#2");
418 File.Delete (tempFile);
423 public void LoadFrom_Invalid_Assembly ()
425 string tempFile = Path.GetTempFileName ();
426 using (StreamWriter sw = File.CreateText (tempFile)) {
427 sw.WriteLine ("foo");
432 Assembly.LoadFrom (tempFile);
434 } catch (BadImageFormatException ex) {
435 Assert.IsNull (ex.InnerException, "#2");
437 File.Delete (tempFile);
442 public void LoadFrom_NonExisting_Assembly ()
444 string tempFile = Path.GetTempFileName ();
445 File.Delete (tempFile);
448 Assembly.LoadFrom (tempFile);
450 } catch (FileNotFoundException ex) {
451 Assert.IsNull (ex.InnerException, "#2");
453 File.Delete (tempFile);
458 public void LoadWithPartialName ()
461 // So the problem here is that if we load an assembly
462 // in a fully aot mode and then cannot load the
463 // dylib, we will assert. This test is incompatible
464 // with the semantics of aot'ed assembly loading, as
465 // aot may assert when loading. This assumes that it's
466 // safe to greedly load everything.
468 string [] names = { "mobile_static_corlib_test" };
470 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" };
473 foreach (string s in names)
474 if (Assembly.LoadWithPartialName (s) != null)
476 Assert.Fail ("Was not able to load any corlib test");
480 public void GetObjectData_Info_Null ()
482 Assembly corlib = typeof (int).Assembly;
484 corlib.GetObjectData (null, new StreamingContext (
485 StreamingContextStates.All));
487 } catch (ArgumentNullException ex) {
488 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
489 Assert.IsNull (ex.InnerException, "#3");
490 Assert.IsNotNull (ex.Message, "#4");
491 Assert.IsNotNull (ex.ParamName, "#5");
492 Assert.AreEqual ("info", ex.ParamName, "#6");
497 public void GetReferencedAssemblies ()
499 Assembly corlib_test = Assembly.GetExecutingAssembly ();
500 AssemblyName[] names = corlib_test.GetReferencedAssemblies ();
501 foreach (AssemblyName an in names) {
502 Assert.IsNull (an.CodeBase, "CodeBase");
503 Assert.IsNotNull (an.CultureInfo, "CultureInfo");
504 Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase");
505 Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags");
506 Assert.IsNotNull (an.FullName, "FullName");
507 Assert.AreEqual (AssemblyHashAlgorithm.SHA1, an.HashAlgorithm, "HashAlgorithm");
508 Assert.IsNull (an.KeyPair, "KeyPair");
509 Assert.IsNotNull (an.Name, "Name");
510 Assert.IsNotNull (an.Version, "Version");
511 Assert.AreEqual (AssemblyVersionCompatibility.SameMachine,
512 an.VersionCompatibility, "VersionCompatibility");
516 #if !MONOTOUCH && !MOBILE_STATIC // Reflection.Emit is not supported.
518 public void Location_Empty() {
519 string assemblyFileName = Path.Combine (
520 Path.GetTempPath (), "AssemblyLocation.dll");
523 AssemblyName assemblyName = new AssemblyName ();
524 assemblyName.Name = "AssemblyLocation";
526 AssemblyBuilder ab = AppDomain.CurrentDomain
527 .DefineDynamicAssembly (assemblyName,
528 AssemblyBuilderAccess.Save,
530 AppDomain.CurrentDomain.Evidence);
531 ab.Save (Path.GetFileName (assemblyFileName));
533 using (FileStream fs = File.OpenRead (assemblyFileName)) {
534 byte[] buffer = new byte[fs.Length];
535 fs.Read (buffer, 0, buffer.Length);
536 Assembly assembly = Assembly.Load (buffer);
537 Assert.AreEqual (string.Empty, assembly.Location);
541 File.Delete (assemblyFileName);
546 public void SateliteAssemblyForInMemoryAssembly ()
548 string assemblyFileName = Path.Combine (
549 Path.GetTempPath (), "AssemblyLocation1.dll");
552 AssemblyName assemblyName = new AssemblyName ();
553 assemblyName.Name = "AssemblyLocation1";
555 AssemblyBuilder ab = AppDomain.CurrentDomain
556 .DefineDynamicAssembly (assemblyName,
557 AssemblyBuilderAccess.Save,
558 Path.GetTempPath ());
560 ModuleBuilder moduleBuilder = ab.DefineDynamicModule (assemblyName.Name, assemblyName.Name + ".dll");
561 TypeBuilder typeBuilder = moduleBuilder.DefineType ("Program", TypeAttributes.Public);
563 MethodBuilder methodBuilder = typeBuilder.DefineMethod ("TestCall", MethodAttributes.Public | MethodAttributes.Static, typeof(void), Type.EmptyTypes);
564 ILGenerator gen = methodBuilder.GetILGenerator ();
567 // var resourceManager = new ResourceManager (typeof (Program));
568 // resourceManager.GetString ("test");
570 gen.Emit (OpCodes.Ldtoken, typeBuilder);
571 gen.Emit (OpCodes.Call, typeof(Type).GetMethod ("GetTypeFromHandle"));
572 gen.Emit (OpCodes.Newobj, typeof(ResourceManager).GetConstructor (new Type[] { typeof(Type) }));
573 gen.Emit (OpCodes.Ldstr, "test");
574 gen.Emit (OpCodes.Callvirt, typeof(ResourceManager).GetMethod ("GetString", new Type[] { typeof(string) }));
575 gen.Emit (OpCodes.Pop);
576 gen.Emit (OpCodes.Ret);
578 typeBuilder.CreateType ();
580 ab.Save (Path.GetFileName (assemblyFileName));
582 using (FileStream fs = File.OpenRead (assemblyFileName)) {
583 byte[] buffer = new byte[fs.Length];
584 fs.Read (buffer, 0, buffer.Length);
585 Assembly assembly = Assembly.Load (buffer);
587 var mm = assembly.GetType ("Program").GetMethod ("TestCall");
589 mm.Invoke (null, null);
591 } catch (TargetInvocationException e) {
592 Assert.IsTrue (e.InnerException is MissingManifestResourceException);
598 File.Delete (assemblyFileName);
603 [Category ("NotWorking")]
604 public void bug78464 ()
606 string assemblyFileName = Path.Combine (
607 Path.GetTempPath (), "bug78464.dll");
610 // execute test in separate appdomain to allow assembly to be unloaded
611 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
612 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
614 crossDomainTester.bug78464 (assemblyFileName);
616 AppDomain.Unload (testDomain);
619 File.Delete (assemblyFileName);
624 [Category("MobileNotWorking")]
625 public void bug78465 ()
627 string assemblyFileName = Path.Combine (
628 Path.GetTempPath (), "bug78465.dll");
631 AssemblyName assemblyName = new AssemblyName ();
632 assemblyName.Name = "bug78465";
634 AssemblyBuilder ab = AppDomain.CurrentDomain
635 .DefineDynamicAssembly (assemblyName,
636 AssemblyBuilderAccess.Save,
637 Path.GetDirectoryName (assemblyFileName),
638 AppDomain.CurrentDomain.Evidence);
639 ab.Save (Path.GetFileName (assemblyFileName));
641 using (FileStream fs = File.OpenRead (assemblyFileName)) {
642 byte[] buffer = new byte[fs.Length];
643 fs.Read (buffer, 0, buffer.Length);
644 Assembly assembly = Assembly.Load (buffer);
645 Assert.AreEqual (string.Empty, assembly.Location, "#1");
649 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
650 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
652 crossDomainTester.bug78465 (assemblyFileName);
654 AppDomain.Unload (testDomain);
657 File.Delete (assemblyFileName);
662 [Category("MobileNotWorking")]
663 public void bug78468 ()
665 string assemblyFileNameA = Path.Combine (Path.GetTempPath (),
667 string resourceFileName = Path.Combine (Path.GetTempPath (),
670 using (StreamWriter sw = File.CreateText (resourceFileName)) {
671 sw.WriteLine ("FOO");
676 AssemblyName assemblyName = new AssemblyName ();
677 assemblyName.Name = "bug78468a";
679 AssemblyBuilder ab = AppDomain.CurrentDomain
680 .DefineDynamicAssembly (assemblyName,
681 AssemblyBuilderAccess.Save,
683 AppDomain.CurrentDomain.Evidence);
684 ab.AddResourceFile ("read", "readme.txt");
685 ab.Save (Path.GetFileName (assemblyFileNameA));
689 using (FileStream fs = File.OpenRead (assemblyFileNameA)) {
690 byte[] buffer = new byte[fs.Length];
691 fs.Read (buffer, 0, buffer.Length);
692 assembly = Assembly.Load (buffer);
696 Assert.AreEqual (string.Empty, assembly.Location, "#A1");
697 string[] resNames = assembly.GetManifestResourceNames ();
698 Assert.IsNotNull (resNames, "#A2");
699 Assert.AreEqual (1, resNames.Length, "#A3");
700 Assert.AreEqual ("read", resNames[0], "#A4");
701 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
702 Assert.IsNotNull (resInfo, "#A5");
703 Assert.AreEqual ("readme.txt", resInfo.FileName, "#A6");
704 Assert.IsNull (resInfo.ReferencedAssembly, "#A7");
705 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#A8");
707 assembly.GetManifestResourceStream ("read");
709 } catch (FileNotFoundException) {
712 assembly.GetFile ("readme.txt");
713 Assert.Fail ("#A10");
714 } catch (FileNotFoundException) {
717 string assemblyFileNameB = Path.Combine (Path.GetTempPath (),
720 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
721 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
723 crossDomainTester.bug78468 (assemblyFileNameB);
725 AppDomain.Unload (testDomain);
726 File.Delete (assemblyFileNameB);
729 File.Delete (assemblyFileNameA);
730 File.Delete (resourceFileName);
735 [Category ("NotWorking")]
736 public void ReflectionOnlyLoad ()
738 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
740 Assert.IsNotNull (assembly);
741 Assert.IsTrue (assembly.ReflectionOnly);
745 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be directly as files
746 public void ReflectionOnlyLoadFrom ()
748 string loc = typeof (AssemblyTest).Assembly.Location;
749 string filename = Path.GetFileName (loc);
750 Assembly assembly = Assembly.ReflectionOnlyLoadFrom (filename);
752 Assert.IsNotNull (assembly);
753 Assert.IsTrue (assembly.ReflectionOnly);
757 [ExpectedException (typeof (ArgumentException))]
758 public void CreateInstanceOnRefOnly ()
760 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
761 assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
765 [Category ("NotWorking")] // patch for bug #79720 must be committed first
766 public void Load_Culture ()
768 string tempDir = Path.Combine (Path.GetTempPath (),
769 "MonoTests.System.Reflection.AssemblyTest");
770 string cultureTempDir = Path.Combine (tempDir, "nl-BE");
771 if (!Directory.Exists (cultureTempDir))
772 Directory.CreateDirectory (cultureTempDir);
773 cultureTempDir = Path.Combine (tempDir, "en-US");
774 if (!Directory.Exists (cultureTempDir))
775 Directory.CreateDirectory (cultureTempDir);
778 AppDomain ad = CreateTestDomain (tempDir, true);
780 CrossDomainTester cdt = CreateCrossDomainTester (ad);
784 AssemblyName aname = new AssemblyName ();
785 aname.Name = "culturea";
786 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "culturea.dll"));
788 aname = new AssemblyName ();
789 aname.Name = "culturea";
790 Assert.IsTrue (cdt.AssertLoad(aname), "#A1");
792 aname = new AssemblyName ();
793 aname.Name = "culturea";
794 aname.CultureInfo = new CultureInfo ("nl-BE");
795 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A2");
797 aname = new AssemblyName ();
798 aname.Name = "culturea";
799 aname.CultureInfo = CultureInfo.InvariantCulture;
800 Assert.IsTrue (cdt.AssertLoad(aname), "#A3");
804 aname = new AssemblyName ();
805 aname.Name = "cultureb";
806 aname.CultureInfo = new CultureInfo ("nl-BE");
807 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "cultureb.dll"));
809 aname = new AssemblyName ();
810 aname.Name = "cultureb";
811 aname.CultureInfo = new CultureInfo ("nl-BE");
812 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
814 aname = new AssemblyName ();
815 aname.Name = "cultureb";
816 Assert.IsTrue (cdt.AssertLoad (aname), "#B2");
818 aname = new AssemblyName ();
819 aname.Name = "cultureb";
820 aname.CultureInfo = new CultureInfo ("en-US");
821 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B3");
825 aname = new AssemblyName ();
826 aname.Name = "culturec";
827 aname.CultureInfo = new CultureInfo ("nl-BE");
828 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "nl-BE/culturec.dll"));
830 aname = new AssemblyName ();
831 aname.Name = "culturec";
832 aname.CultureInfo = new CultureInfo ("nl-BE");
833 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
835 aname = new AssemblyName ();
836 aname.Name = "culturec";
837 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C2");
839 aname = new AssemblyName ();
840 aname.Name = "culturec";
841 aname.CultureInfo = CultureInfo.InvariantCulture;
842 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C3");
846 aname = new AssemblyName ();
847 aname.Name = "cultured";
848 aname.CultureInfo = new CultureInfo ("nl-BE");
849 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/cultured.dll"));
851 aname = new AssemblyName ();
852 aname.Name = "cultured";
853 aname.CultureInfo = new CultureInfo ("nl-BE");
854 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D1");
856 aname = new AssemblyName ();
857 aname.Name = "cultured";
858 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D2");
860 aname = new AssemblyName ();
861 aname.Name = "cultured";
862 aname.CultureInfo = CultureInfo.InvariantCulture;
863 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D3");
865 AppDomain.Unload (ad);
866 if (Directory.Exists (tempDir))
867 Directory.Delete (tempDir, true);
872 [Category ("NotWorking")] // in non-default domain, MS throws FileNotFoundException
873 public void Load_Culture_Mismatch ()
875 string tempDir = Path.Combine (Path.GetTempPath (),
876 "MonoTests.System.Reflection.AssemblyTest");
877 string cultureTempDir = Path.Combine (tempDir, "en-US");
878 if (!Directory.Exists (cultureTempDir))
879 Directory.CreateDirectory (cultureTempDir);
881 AppDomain ad = CreateTestDomain (tempDir, true);
883 CrossDomainTester cdt = CreateCrossDomainTester (ad);
887 AssemblyName aname = new AssemblyName ();
888 aname.Name = "bug79712a";
889 aname.CultureInfo = new CultureInfo ("nl-BE");
890 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79712a.dll"));
892 aname = new AssemblyName ();
893 aname.Name = "bug79712a";
894 aname.CultureInfo = CultureInfo.InvariantCulture;
895 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A1");
899 aname = new AssemblyName ();
900 aname.Name = "bug79712b";
901 aname.CultureInfo = new CultureInfo ("nl-BE");
902 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/bug79712b.dll"));
904 aname = new AssemblyName ();
905 aname.Name = "bug79712b";
906 aname.CultureInfo = new CultureInfo ("en-US");
907 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
909 AppDomain.Unload (ad);
910 if (Directory.Exists (tempDir))
911 Directory.Delete (tempDir, true);
917 [Category("MobileNotWorking")]
918 public void Load_PartialVersion ()
920 string tempDir = Path.Combine (Path.GetTempPath (),
921 "MonoTests.System.Reflection.AssemblyTest");
922 if (!Directory.Exists (tempDir))
923 Directory.CreateDirectory (tempDir);
925 AppDomain ad = CreateTestDomain (tempDir, true);
927 CrossDomainTester cdt = CreateCrossDomainTester (ad);
929 AssemblyName aname = new AssemblyName ();
930 aname.Name = "bug79715";
931 aname.Version = new Version (1, 2, 3, 4);
932 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79715.dll"));
934 aname = new AssemblyName ();
935 aname.Name = "bug79715";
936 aname.Version = new Version (1, 2);
937 Assert.IsTrue (cdt.AssertLoad (aname), "#A1");
938 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#A2");
940 aname = new AssemblyName ();
941 aname.Name = "bug79715";
942 aname.Version = new Version (1, 2, 3);
943 Assert.IsTrue (cdt.AssertLoad (aname), "#B1");
944 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#B2");
946 aname = new AssemblyName ();
947 aname.Name = "bug79715";
948 aname.Version = new Version (1, 2, 3, 4);
949 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
950 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#C2");
952 AppDomain.Unload (ad);
953 if (Directory.Exists (tempDir))
954 Directory.Delete (tempDir, true);
958 private static AppDomain CreateTestDomain (string baseDirectory, bool assemblyResolver)
960 AppDomainSetup setup = new AppDomainSetup ();
961 setup.ApplicationBase = baseDirectory;
962 setup.ApplicationName = "testdomain";
964 AppDomain ad = AppDomain.CreateDomain ("testdomain",
965 AppDomain.CurrentDomain.Evidence, setup);
967 if (assemblyResolver) {
968 Assembly ea = Assembly.GetExecutingAssembly ();
969 ad.CreateInstanceFrom (ea.CodeBase,
970 typeof (AssemblyResolveHandler).FullName,
972 BindingFlags.Public | BindingFlags.Instance,
974 new object [] { ea.Location, ea.FullName },
975 CultureInfo.InvariantCulture,
983 private static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
985 Type testerType = typeof (CrossDomainTester);
986 return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
987 testerType.Assembly.FullName, testerType.FullName, false,
988 BindingFlags.Public | BindingFlags.Instance, null, new object[0],
989 CultureInfo.InvariantCulture, new object[0], null);
992 private class CrossDomainTester : MarshalByRefObject
994 public void GenerateAssembly (AssemblyName aname, string path)
996 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
997 aname, AssemblyBuilderAccess.Save, Path.GetDirectoryName (path));
998 ab.Save (Path.GetFileName (path));
1001 public void Load (AssemblyName assemblyRef)
1003 Assembly.Load (assemblyRef);
1006 public void LoadFrom (string assemblyFile)
1008 Assembly.LoadFrom (assemblyFile);
1011 public bool AssertLoad (AssemblyName assemblyRef)
1014 Assembly.Load (assemblyRef);
1021 public bool AssertLoad (string assemblyString)
1024 Assembly.Load (assemblyString);
1031 public bool AssertFileLoadException (AssemblyName assemblyRef)
1034 Assembly.Load (assemblyRef);
1036 } catch (FileLoadException) {
1041 public bool AssertFileNotFoundException (AssemblyName assemblyRef)
1044 Assembly.Load (assemblyRef);
1046 } catch (FileNotFoundException) {
1051 public void bug78464 (string assemblyFileName)
1053 AssemblyName assemblyName = new AssemblyName ();
1054 assemblyName.Name = "bug78464";
1056 AssemblyBuilder ab = AppDomain.CurrentDomain
1057 .DefineDynamicAssembly (assemblyName,
1058 AssemblyBuilderAccess.Save,
1059 Path.GetDirectoryName (assemblyFileName),
1060 AppDomain.CurrentDomain.Evidence);
1061 ab.Save (Path.GetFileName (assemblyFileName));
1065 using (FileStream fs = File.OpenRead (assemblyFileName)) {
1066 byte[] buffer = new byte[fs.Length];
1067 fs.Read (buffer, 0, buffer.Length);
1068 assembly = Assembly.Load (buffer);
1072 Assert.AreEqual (string.Empty, assembly.Location, "#1");
1074 assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1075 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1076 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName(assembly.Location), "#3");
1077 // note: we cannot check if directory names match, as MS.NET seems to
1078 // convert directory part of assembly location to lowercase
1079 Assert.IsFalse (Path.GetDirectoryName(assembly.Location) == string.Empty, "#4");
1082 public void bug78465 (string assemblyFileName)
1084 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1085 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1086 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName (assembly.Location), "#3");
1087 // note: we cannot check if directory names match, as MS.NET seems to
1088 // convert directory part of assembly location to lowercase
1089 Assert.IsFalse (Path.GetDirectoryName (assembly.Location) == string.Empty, "#4");
1092 public void bug78468 (string assemblyFileName)
1094 AssemblyName assemblyName = new AssemblyName ();
1095 assemblyName.Name = "bug78468b";
1097 AssemblyBuilder ab = AppDomain.CurrentDomain
1098 .DefineDynamicAssembly (assemblyName,
1099 AssemblyBuilderAccess.Save,
1100 Path.GetDirectoryName (assemblyFileName),
1101 AppDomain.CurrentDomain.Evidence);
1102 ab.AddResourceFile ("read", "readme.txt");
1103 ab.Save (Path.GetFileName (assemblyFileName));
1105 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1106 Assert.IsTrue (assembly.Location != string.Empty, "#B1");
1107 string[] resNames = assembly.GetManifestResourceNames ();
1108 Assert.IsNotNull (resNames, "#B2");
1109 Assert.AreEqual (1, resNames.Length, "#B3");
1110 Assert.AreEqual ("read", resNames[0], "#B4");
1111 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
1112 Assert.IsNotNull (resInfo, "#B5");
1113 Assert.AreEqual ("readme.txt", resInfo.FileName, "#B6");
1114 Assert.IsNull (resInfo.ReferencedAssembly, "#B7");
1115 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#B8");
1116 Stream s = assembly.GetManifestResourceStream ("read");
1117 Assert.IsNotNull (s, "#B9");
1119 s = assembly.GetFile ("readme.txt");
1120 Assert.IsNotNull (s, "#B10");
1126 public void bug79872 ()
1128 Random rnd = new Random ();
1133 outdir = Path.Combine (Path.GetTempPath (), "bug79872-" + rnd.Next (10000, 99999));
1134 if (Directory.Exists (outdir)) {
1136 Directory.Delete (outdir, true);
1143 Directory.CreateDirectory (outdir);
1145 AssemblyName an = new AssemblyName ();
1146 an.Name = "bug79872";
1147 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, outdir);
1148 string dllname = "bug79872.dll";
1149 ModuleBuilder mb1 = ab.DefineDynamicModule ("bug79872", dllname);
1150 string netmodule = "bug79872.netmodule";
1151 ModuleBuilder mb2 = ab.DefineDynamicModule (netmodule, netmodule);
1152 TypeBuilder a1 = mb2.DefineType ("A");
1158 Assembly.LoadFrom (Path.Combine (outdir, dllname));
1162 Assert.IsTrue (ok, "Should load a .NET metadata file with an assembly manifest");
1166 Assembly.LoadFrom (Path.Combine (outdir, netmodule));
1167 } catch (BadImageFormatException) {
1168 ok = true; // mono and .net 2.0 throw this
1169 } catch (FileLoadException) {
1170 ok = true; // .net 1.1 throws this
1174 Assert.IsTrue (ok, "Complain on loading a .NET metadata file without an assembly manifest");
1176 Directory.Delete (outdir, true);
1181 public void ManifestModule ()
1183 Assembly assembly = typeof (int).Assembly;
1184 Module module = assembly.ManifestModule;
1185 Assert.IsNotNull (module, "#1");
1187 Assert.AreEqual ("MonoModule", module.GetType ().Name, "#2");
1189 #if !MONOTOUCH && !MOBILE_STATIC
1190 Assert.AreEqual ("mscorlib.dll", module.Name, "#3");
1192 Assert.IsFalse (module.IsResource (), "#4");
1193 Assert.IsTrue (assembly.GetModules ().Length > 0, "#5");
1194 Assert.AreSame (module, assembly.GetModules () [0], "#6");
1195 Assert.AreSame (module, assembly.ManifestModule, "#7");
1200 private class AssemblyResolveHandler
1202 public AssemblyResolveHandler (string assemblyFile, string assemblyName)
1204 _assemblyFile = assemblyFile;
1205 _assemblyName = assemblyName;
1207 AppDomain.CurrentDomain.AssemblyResolve +=
1208 new ResolveEventHandler (ResolveAssembly);
1211 private Assembly ResolveAssembly (Object sender, ResolveEventArgs args)
1213 if (args.Name == _assemblyName)
1214 return Assembly.LoadFrom (_assemblyFile);
1219 private readonly string _assemblyFile;
1220 private readonly string _assemblyName;
1223 protected internal class Bug328812_NestedFamORAssem { };
1226 public void bug328812 ()
1228 Assembly corlib_test = Assembly.GetExecutingAssembly ();
1229 Assert.IsNull (corlib_test.GetType ("Bug328812_NestedFamORAssem"));
1230 // Just a sanity check, in case the above passed for some other reason
1231 Assert.IsNotNull (corlib_test.GetType ("MonoTests.System.Reflection.AssemblyTest+Bug328812_NestedFamORAssem"));
1235 public void GetCustomAttributes_AttributeType_Null ()
1237 Assembly a = typeof (int).Assembly;
1239 a.GetCustomAttributes (null, false);
1241 } catch (ArgumentNullException ex) {
1242 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
1243 Assert.IsNull (ex.InnerException, "#3");
1244 Assert.IsNotNull (ex.Message, "#4");
1245 Assert.IsNotNull (ex.ParamName, "#5");
1246 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
1251 public void GetTypeWithEmptyStringShouldThrow ()
1254 typeof (string).Assembly.GetType ("");
1256 } catch (ArgumentException) {}
1259 class GetCallingAssemblyCallee {
1262 static void sideEffect () {
1266 // GetCallingAssembly may see an unpredictable
1267 // view of the stack if it's called in tail
1268 // position, or if its caller or the caller's
1269 // caller is inlined. So we put in a side
1270 // effect to get out of tail position, and we
1271 // tag the methods NoInlining to discourage
1273 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1274 public static Assembly Leaf () {
1275 var a = Assembly.GetCallingAssembly ();
1280 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1281 public static Assembly DirectCall () {
1287 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1288 public static Assembly InvokeCall () {
1289 var ty = typeof (GetCallingAssemblyCallee);
1290 var mi = ty.GetMethod("Leaf");
1291 var o = mi.Invoke(null, null);
1298 public void GetCallingAssembly_Direct() {
1299 var a = GetCallingAssemblyCallee.DirectCall ();
1300 Assert.IsNotNull (a);
1302 Assert.AreEqual (GetType().Assembly, a);
1306 public void GetCallingAssembly_SkipsReflection () {
1307 // check that the calling assembly is this
1308 // one, not mscorlib (aka, the reflection
1310 var a = GetCallingAssemblyCallee.InvokeCall ();
1311 Assert.IsNotNull (a);
1313 var invokeAssembly =
1314 typeof (MethodInfo).Assembly;
1315 Assert.AreNotEqual (invokeAssembly, a);
1317 Assert.AreEqual (GetType().Assembly, a);
1322 public void DefinedTypes_Equality ()
1324 var x1 = Assembly.GetExecutingAssembly ().DefinedTypes.Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1325 var x2 = Assembly.GetExecutingAssembly ().GetTypes ().Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1327 Assert.AreSame (x1, x2, "#1");
1332 public class TestDefinedTypes