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;
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 // 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 ();
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 ()
460 string [] names = { "corlib_test_net_1_1", "corlib_test_net_2_0", "corlib_test_net_4_0", "corlib_test_net_4_5", "corlib_test_net_4_x", "corlib_plattest", "mscorlibtests", "BclTests" };
462 foreach (string s in names)
463 if (Assembly.LoadWithPartialName (s) != null)
465 Assert.Fail ("Was not able to load any corlib test");
469 public void GetObjectData_Info_Null ()
471 Assembly corlib = typeof (int).Assembly;
473 corlib.GetObjectData (null, new StreamingContext (
474 StreamingContextStates.All));
476 } catch (ArgumentNullException ex) {
477 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
478 Assert.IsNull (ex.InnerException, "#3");
479 Assert.IsNotNull (ex.Message, "#4");
480 Assert.IsNotNull (ex.ParamName, "#5");
481 Assert.AreEqual ("info", ex.ParamName, "#6");
486 public void GetReferencedAssemblies ()
488 Assembly corlib_test = Assembly.GetExecutingAssembly ();
489 AssemblyName[] names = corlib_test.GetReferencedAssemblies ();
490 foreach (AssemblyName an in names) {
491 Assert.IsNull (an.CodeBase, "CodeBase");
492 Assert.IsNotNull (an.CultureInfo, "CultureInfo");
493 Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase");
494 Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags");
495 Assert.IsNotNull (an.FullName, "FullName");
496 Assert.AreEqual (AssemblyHashAlgorithm.SHA1, an.HashAlgorithm, "HashAlgorithm");
497 Assert.IsNull (an.KeyPair, "KeyPair");
498 Assert.IsNotNull (an.Name, "Name");
499 Assert.IsNotNull (an.Version, "Version");
500 Assert.AreEqual (AssemblyVersionCompatibility.SameMachine,
501 an.VersionCompatibility, "VersionCompatibility");
505 #if !MONOTOUCH // Reflection.Emit is not supported.
507 public void Location_Empty() {
508 string assemblyFileName = Path.Combine (
509 Path.GetTempPath (), "AssemblyLocation.dll");
512 AssemblyName assemblyName = new AssemblyName ();
513 assemblyName.Name = "AssemblyLocation";
515 AssemblyBuilder ab = AppDomain.CurrentDomain
516 .DefineDynamicAssembly (assemblyName,
517 AssemblyBuilderAccess.Save,
519 AppDomain.CurrentDomain.Evidence);
520 ab.Save (Path.GetFileName (assemblyFileName));
522 using (FileStream fs = File.OpenRead (assemblyFileName)) {
523 byte[] buffer = new byte[fs.Length];
524 fs.Read (buffer, 0, buffer.Length);
525 Assembly assembly = Assembly.Load (buffer);
526 Assert.AreEqual (string.Empty, assembly.Location);
530 File.Delete (assemblyFileName);
535 public void SateliteAssemblyForInMemoryAssembly ()
537 string assemblyFileName = Path.Combine (
538 Path.GetTempPath (), "AssemblyLocation1.dll");
541 AssemblyName assemblyName = new AssemblyName ();
542 assemblyName.Name = "AssemblyLocation1";
544 AssemblyBuilder ab = AppDomain.CurrentDomain
545 .DefineDynamicAssembly (assemblyName,
546 AssemblyBuilderAccess.Save,
547 Path.GetTempPath ());
549 ModuleBuilder moduleBuilder = ab.DefineDynamicModule (assemblyName.Name, assemblyName.Name + ".dll");
550 TypeBuilder typeBuilder = moduleBuilder.DefineType ("Program", TypeAttributes.Public);
552 MethodBuilder methodBuilder = typeBuilder.DefineMethod ("TestCall", MethodAttributes.Public | MethodAttributes.Static, typeof(void), Type.EmptyTypes);
553 ILGenerator gen = methodBuilder.GetILGenerator ();
556 // var resourceManager = new ResourceManager (typeof (Program));
557 // resourceManager.GetString ("test");
559 gen.Emit (OpCodes.Ldtoken, typeBuilder);
560 gen.Emit (OpCodes.Call, typeof(Type).GetMethod ("GetTypeFromHandle"));
561 gen.Emit (OpCodes.Newobj, typeof(ResourceManager).GetConstructor (new Type[] { typeof(Type) }));
562 gen.Emit (OpCodes.Ldstr, "test");
563 gen.Emit (OpCodes.Callvirt, typeof(ResourceManager).GetMethod ("GetString", new Type[] { typeof(string) }));
564 gen.Emit (OpCodes.Pop);
565 gen.Emit (OpCodes.Ret);
567 typeBuilder.CreateType ();
569 ab.Save (Path.GetFileName (assemblyFileName));
571 using (FileStream fs = File.OpenRead (assemblyFileName)) {
572 byte[] buffer = new byte[fs.Length];
573 fs.Read (buffer, 0, buffer.Length);
574 Assembly assembly = Assembly.Load (buffer);
576 var mm = assembly.GetType ("Program").GetMethod ("TestCall");
578 mm.Invoke (null, null);
580 } catch (TargetInvocationException e) {
581 Assert.IsTrue (e.InnerException is MissingManifestResourceException);
587 File.Delete (assemblyFileName);
592 [Category ("NotWorking")]
593 public void bug78464 ()
595 string assemblyFileName = Path.Combine (
596 Path.GetTempPath (), "bug78464.dll");
599 // execute test in separate appdomain to allow assembly to be unloaded
600 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
601 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
603 crossDomainTester.bug78464 (assemblyFileName);
605 AppDomain.Unload (testDomain);
608 File.Delete (assemblyFileName);
613 [Category("MobileNotWorking")]
614 public void bug78465 ()
616 string assemblyFileName = Path.Combine (
617 Path.GetTempPath (), "bug78465.dll");
620 AssemblyName assemblyName = new AssemblyName ();
621 assemblyName.Name = "bug78465";
623 AssemblyBuilder ab = AppDomain.CurrentDomain
624 .DefineDynamicAssembly (assemblyName,
625 AssemblyBuilderAccess.Save,
626 Path.GetDirectoryName (assemblyFileName),
627 AppDomain.CurrentDomain.Evidence);
628 ab.Save (Path.GetFileName (assemblyFileName));
630 using (FileStream fs = File.OpenRead (assemblyFileName)) {
631 byte[] buffer = new byte[fs.Length];
632 fs.Read (buffer, 0, buffer.Length);
633 Assembly assembly = Assembly.Load (buffer);
634 Assert.AreEqual (string.Empty, assembly.Location, "#1");
638 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
639 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
641 crossDomainTester.bug78465 (assemblyFileName);
643 AppDomain.Unload (testDomain);
646 File.Delete (assemblyFileName);
651 [Category("MobileNotWorking")]
652 public void bug78468 ()
654 string assemblyFileNameA = Path.Combine (Path.GetTempPath (),
656 string resourceFileName = Path.Combine (Path.GetTempPath (),
659 using (StreamWriter sw = File.CreateText (resourceFileName)) {
660 sw.WriteLine ("FOO");
665 AssemblyName assemblyName = new AssemblyName ();
666 assemblyName.Name = "bug78468a";
668 AssemblyBuilder ab = AppDomain.CurrentDomain
669 .DefineDynamicAssembly (assemblyName,
670 AssemblyBuilderAccess.Save,
672 AppDomain.CurrentDomain.Evidence);
673 ab.AddResourceFile ("read", "readme.txt");
674 ab.Save (Path.GetFileName (assemblyFileNameA));
678 using (FileStream fs = File.OpenRead (assemblyFileNameA)) {
679 byte[] buffer = new byte[fs.Length];
680 fs.Read (buffer, 0, buffer.Length);
681 assembly = Assembly.Load (buffer);
685 Assert.AreEqual (string.Empty, assembly.Location, "#A1");
686 string[] resNames = assembly.GetManifestResourceNames ();
687 Assert.IsNotNull (resNames, "#A2");
688 Assert.AreEqual (1, resNames.Length, "#A3");
689 Assert.AreEqual ("read", resNames[0], "#A4");
690 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
691 Assert.IsNotNull (resInfo, "#A5");
692 Assert.AreEqual ("readme.txt", resInfo.FileName, "#A6");
693 Assert.IsNull (resInfo.ReferencedAssembly, "#A7");
694 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#A8");
696 assembly.GetManifestResourceStream ("read");
698 } catch (FileNotFoundException) {
701 assembly.GetFile ("readme.txt");
702 Assert.Fail ("#A10");
703 } catch (FileNotFoundException) {
706 string assemblyFileNameB = Path.Combine (Path.GetTempPath (),
709 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
710 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
712 crossDomainTester.bug78468 (assemblyFileNameB);
714 AppDomain.Unload (testDomain);
715 File.Delete (assemblyFileNameB);
718 File.Delete (assemblyFileNameA);
719 File.Delete (resourceFileName);
724 [Category ("NotWorking")]
725 public void ReflectionOnlyLoad ()
727 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
729 Assert.IsNotNull (assembly);
730 Assert.IsTrue (assembly.ReflectionOnly);
734 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be directly as files
735 public void ReflectionOnlyLoadFrom ()
737 string loc = typeof (AssemblyTest).Assembly.Location;
738 string filename = Path.GetFileName (loc);
739 Assembly assembly = Assembly.ReflectionOnlyLoadFrom (filename);
741 Assert.IsNotNull (assembly);
742 Assert.IsTrue (assembly.ReflectionOnly);
746 [ExpectedException (typeof (ArgumentException))]
747 public void CreateInstanceOnRefOnly ()
749 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
750 assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
754 [Category ("NotWorking")] // patch for bug #79720 must be committed first
755 public void Load_Culture ()
757 string tempDir = Path.Combine (Path.GetTempPath (),
758 "MonoTests.System.Reflection.AssemblyTest");
759 string cultureTempDir = Path.Combine (tempDir, "nl-BE");
760 if (!Directory.Exists (cultureTempDir))
761 Directory.CreateDirectory (cultureTempDir);
762 cultureTempDir = Path.Combine (tempDir, "en-US");
763 if (!Directory.Exists (cultureTempDir))
764 Directory.CreateDirectory (cultureTempDir);
767 AppDomain ad = CreateTestDomain (tempDir, true);
769 CrossDomainTester cdt = CreateCrossDomainTester (ad);
773 AssemblyName aname = new AssemblyName ();
774 aname.Name = "culturea";
775 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "culturea.dll"));
777 aname = new AssemblyName ();
778 aname.Name = "culturea";
779 Assert.IsTrue (cdt.AssertLoad(aname), "#A1");
781 aname = new AssemblyName ();
782 aname.Name = "culturea";
783 aname.CultureInfo = new CultureInfo ("nl-BE");
784 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A2");
786 aname = new AssemblyName ();
787 aname.Name = "culturea";
788 aname.CultureInfo = CultureInfo.InvariantCulture;
789 Assert.IsTrue (cdt.AssertLoad(aname), "#A3");
793 aname = new AssemblyName ();
794 aname.Name = "cultureb";
795 aname.CultureInfo = new CultureInfo ("nl-BE");
796 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "cultureb.dll"));
798 aname = new AssemblyName ();
799 aname.Name = "cultureb";
800 aname.CultureInfo = new CultureInfo ("nl-BE");
801 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
803 aname = new AssemblyName ();
804 aname.Name = "cultureb";
805 Assert.IsTrue (cdt.AssertLoad (aname), "#B2");
807 aname = new AssemblyName ();
808 aname.Name = "cultureb";
809 aname.CultureInfo = new CultureInfo ("en-US");
810 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B3");
814 aname = new AssemblyName ();
815 aname.Name = "culturec";
816 aname.CultureInfo = new CultureInfo ("nl-BE");
817 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "nl-BE/culturec.dll"));
819 aname = new AssemblyName ();
820 aname.Name = "culturec";
821 aname.CultureInfo = new CultureInfo ("nl-BE");
822 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
824 aname = new AssemblyName ();
825 aname.Name = "culturec";
826 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C2");
828 aname = new AssemblyName ();
829 aname.Name = "culturec";
830 aname.CultureInfo = CultureInfo.InvariantCulture;
831 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C3");
835 aname = new AssemblyName ();
836 aname.Name = "cultured";
837 aname.CultureInfo = new CultureInfo ("nl-BE");
838 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/cultured.dll"));
840 aname = new AssemblyName ();
841 aname.Name = "cultured";
842 aname.CultureInfo = new CultureInfo ("nl-BE");
843 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D1");
845 aname = new AssemblyName ();
846 aname.Name = "cultured";
847 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D2");
849 aname = new AssemblyName ();
850 aname.Name = "cultured";
851 aname.CultureInfo = CultureInfo.InvariantCulture;
852 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D3");
854 AppDomain.Unload (ad);
855 if (Directory.Exists (tempDir))
856 Directory.Delete (tempDir, true);
861 [Category ("NotWorking")] // in non-default domain, MS throws FileNotFoundException
862 public void Load_Culture_Mismatch ()
864 string tempDir = Path.Combine (Path.GetTempPath (),
865 "MonoTests.System.Reflection.AssemblyTest");
866 string cultureTempDir = Path.Combine (tempDir, "en-US");
867 if (!Directory.Exists (cultureTempDir))
868 Directory.CreateDirectory (cultureTempDir);
870 AppDomain ad = CreateTestDomain (tempDir, true);
872 CrossDomainTester cdt = CreateCrossDomainTester (ad);
876 AssemblyName aname = new AssemblyName ();
877 aname.Name = "bug79712a";
878 aname.CultureInfo = new CultureInfo ("nl-BE");
879 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79712a.dll"));
881 aname = new AssemblyName ();
882 aname.Name = "bug79712a";
883 aname.CultureInfo = CultureInfo.InvariantCulture;
884 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A1");
888 aname = new AssemblyName ();
889 aname.Name = "bug79712b";
890 aname.CultureInfo = new CultureInfo ("nl-BE");
891 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/bug79712b.dll"));
893 aname = new AssemblyName ();
894 aname.Name = "bug79712b";
895 aname.CultureInfo = new CultureInfo ("en-US");
896 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
898 AppDomain.Unload (ad);
899 if (Directory.Exists (tempDir))
900 Directory.Delete (tempDir, true);
906 [Category("MobileNotWorking")]
907 public void Load_PartialVersion ()
909 string tempDir = Path.Combine (Path.GetTempPath (),
910 "MonoTests.System.Reflection.AssemblyTest");
911 if (!Directory.Exists (tempDir))
912 Directory.CreateDirectory (tempDir);
914 AppDomain ad = CreateTestDomain (tempDir, true);
916 CrossDomainTester cdt = CreateCrossDomainTester (ad);
918 AssemblyName aname = new AssemblyName ();
919 aname.Name = "bug79715";
920 aname.Version = new Version (1, 2, 3, 4);
921 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79715.dll"));
923 aname = new AssemblyName ();
924 aname.Name = "bug79715";
925 aname.Version = new Version (1, 2);
926 Assert.IsTrue (cdt.AssertLoad (aname), "#A1");
927 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#A2");
929 aname = new AssemblyName ();
930 aname.Name = "bug79715";
931 aname.Version = new Version (1, 2, 3);
932 Assert.IsTrue (cdt.AssertLoad (aname), "#B1");
933 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#B2");
935 aname = new AssemblyName ();
936 aname.Name = "bug79715";
937 aname.Version = new Version (1, 2, 3, 4);
938 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
939 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#C2");
941 AppDomain.Unload (ad);
942 if (Directory.Exists (tempDir))
943 Directory.Delete (tempDir, true);
947 private static AppDomain CreateTestDomain (string baseDirectory, bool assemblyResolver)
949 AppDomainSetup setup = new AppDomainSetup ();
950 setup.ApplicationBase = baseDirectory;
951 setup.ApplicationName = "testdomain";
953 AppDomain ad = AppDomain.CreateDomain ("testdomain",
954 AppDomain.CurrentDomain.Evidence, setup);
956 if (assemblyResolver) {
957 Assembly ea = Assembly.GetExecutingAssembly ();
958 ad.CreateInstanceFrom (ea.CodeBase,
959 typeof (AssemblyResolveHandler).FullName,
961 BindingFlags.Public | BindingFlags.Instance,
963 new object [] { ea.Location, ea.FullName },
964 CultureInfo.InvariantCulture,
972 private static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
974 Type testerType = typeof (CrossDomainTester);
975 return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
976 testerType.Assembly.FullName, testerType.FullName, false,
977 BindingFlags.Public | BindingFlags.Instance, null, new object[0],
978 CultureInfo.InvariantCulture, new object[0], null);
981 private class CrossDomainTester : MarshalByRefObject
983 public void GenerateAssembly (AssemblyName aname, string path)
985 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
986 aname, AssemblyBuilderAccess.Save, Path.GetDirectoryName (path));
987 ab.Save (Path.GetFileName (path));
990 public void Load (AssemblyName assemblyRef)
992 Assembly.Load (assemblyRef);
995 public void LoadFrom (string assemblyFile)
997 Assembly.LoadFrom (assemblyFile);
1000 public bool AssertLoad (AssemblyName assemblyRef)
1003 Assembly.Load (assemblyRef);
1010 public bool AssertLoad (string assemblyString)
1013 Assembly.Load (assemblyString);
1020 public bool AssertFileLoadException (AssemblyName assemblyRef)
1023 Assembly.Load (assemblyRef);
1025 } catch (FileLoadException) {
1030 public bool AssertFileNotFoundException (AssemblyName assemblyRef)
1033 Assembly.Load (assemblyRef);
1035 } catch (FileNotFoundException) {
1040 public void bug78464 (string assemblyFileName)
1042 AssemblyName assemblyName = new AssemblyName ();
1043 assemblyName.Name = "bug78464";
1045 AssemblyBuilder ab = AppDomain.CurrentDomain
1046 .DefineDynamicAssembly (assemblyName,
1047 AssemblyBuilderAccess.Save,
1048 Path.GetDirectoryName (assemblyFileName),
1049 AppDomain.CurrentDomain.Evidence);
1050 ab.Save (Path.GetFileName (assemblyFileName));
1054 using (FileStream fs = File.OpenRead (assemblyFileName)) {
1055 byte[] buffer = new byte[fs.Length];
1056 fs.Read (buffer, 0, buffer.Length);
1057 assembly = Assembly.Load (buffer);
1061 Assert.AreEqual (string.Empty, assembly.Location, "#1");
1063 assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1064 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1065 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName(assembly.Location), "#3");
1066 // note: we cannot check if directory names match, as MS.NET seems to
1067 // convert directory part of assembly location to lowercase
1068 Assert.IsFalse (Path.GetDirectoryName(assembly.Location) == string.Empty, "#4");
1071 public void bug78465 (string assemblyFileName)
1073 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1074 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1075 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName (assembly.Location), "#3");
1076 // note: we cannot check if directory names match, as MS.NET seems to
1077 // convert directory part of assembly location to lowercase
1078 Assert.IsFalse (Path.GetDirectoryName (assembly.Location) == string.Empty, "#4");
1081 public void bug78468 (string assemblyFileName)
1083 AssemblyName assemblyName = new AssemblyName ();
1084 assemblyName.Name = "bug78468b";
1086 AssemblyBuilder ab = AppDomain.CurrentDomain
1087 .DefineDynamicAssembly (assemblyName,
1088 AssemblyBuilderAccess.Save,
1089 Path.GetDirectoryName (assemblyFileName),
1090 AppDomain.CurrentDomain.Evidence);
1091 ab.AddResourceFile ("read", "readme.txt");
1092 ab.Save (Path.GetFileName (assemblyFileName));
1094 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1095 Assert.IsTrue (assembly.Location != string.Empty, "#B1");
1096 string[] resNames = assembly.GetManifestResourceNames ();
1097 Assert.IsNotNull (resNames, "#B2");
1098 Assert.AreEqual (1, resNames.Length, "#B3");
1099 Assert.AreEqual ("read", resNames[0], "#B4");
1100 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
1101 Assert.IsNotNull (resInfo, "#B5");
1102 Assert.AreEqual ("readme.txt", resInfo.FileName, "#B6");
1103 Assert.IsNull (resInfo.ReferencedAssembly, "#B7");
1104 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#B8");
1105 Stream s = assembly.GetManifestResourceStream ("read");
1106 Assert.IsNotNull (s, "#B9");
1108 s = assembly.GetFile ("readme.txt");
1109 Assert.IsNotNull (s, "#B10");
1115 public void bug79872 ()
1117 Random rnd = new Random ();
1122 outdir = Path.Combine (Path.GetTempPath (), "bug79872-" + rnd.Next (10000, 99999));
1123 if (Directory.Exists (outdir)) {
1125 Directory.Delete (outdir, true);
1132 Directory.CreateDirectory (outdir);
1134 AssemblyName an = new AssemblyName ();
1135 an.Name = "bug79872";
1136 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, outdir);
1137 string dllname = "bug79872.dll";
1138 ModuleBuilder mb1 = ab.DefineDynamicModule ("bug79872", dllname);
1139 string netmodule = "bug79872.netmodule";
1140 ModuleBuilder mb2 = ab.DefineDynamicModule (netmodule, netmodule);
1141 TypeBuilder a1 = mb2.DefineType ("A");
1147 Assembly.LoadFrom (Path.Combine (outdir, dllname));
1151 Assert.IsTrue (ok, "Should load a .NET metadata file with an assembly manifest");
1155 Assembly.LoadFrom (Path.Combine (outdir, netmodule));
1156 } catch (BadImageFormatException) {
1157 ok = true; // mono and .net 2.0 throw this
1158 } catch (FileLoadException) {
1159 ok = true; // .net 1.1 throws this
1163 Assert.IsTrue (ok, "Complain on loading a .NET metadata file without an assembly manifest");
1165 Directory.Delete (outdir, true);
1170 public void ManifestModule ()
1172 Assembly assembly = typeof (int).Assembly;
1173 Module module = assembly.ManifestModule;
1174 Assert.IsNotNull (module, "#1");
1176 Assert.AreEqual ("MonoModule", module.GetType ().Name, "#2");
1179 Assert.AreEqual ("mscorlib.dll", module.Name, "#3");
1181 Assert.IsFalse (module.IsResource (), "#4");
1182 Assert.IsTrue (assembly.GetModules ().Length > 0, "#5");
1183 Assert.AreSame (module, assembly.GetModules () [0], "#6");
1184 Assert.AreSame (module, assembly.ManifestModule, "#7");
1189 private class AssemblyResolveHandler
1191 public AssemblyResolveHandler (string assemblyFile, string assemblyName)
1193 _assemblyFile = assemblyFile;
1194 _assemblyName = assemblyName;
1196 AppDomain.CurrentDomain.AssemblyResolve +=
1197 new ResolveEventHandler (ResolveAssembly);
1200 private Assembly ResolveAssembly (Object sender, ResolveEventArgs args)
1202 if (args.Name == _assemblyName)
1203 return Assembly.LoadFrom (_assemblyFile);
1208 private readonly string _assemblyFile;
1209 private readonly string _assemblyName;
1212 protected internal class Bug328812_NestedFamORAssem { };
1215 public void bug328812 ()
1217 Assembly corlib_test = Assembly.GetExecutingAssembly ();
1218 Assert.IsNull (corlib_test.GetType ("Bug328812_NestedFamORAssem"));
1219 // Just a sanity check, in case the above passed for some other reason
1220 Assert.IsNotNull (corlib_test.GetType ("MonoTests.System.Reflection.AssemblyTest+Bug328812_NestedFamORAssem"));
1224 public void GetCustomAttributes_AttributeType_Null ()
1226 Assembly a = typeof (int).Assembly;
1228 a.GetCustomAttributes (null, false);
1230 } catch (ArgumentNullException ex) {
1231 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
1232 Assert.IsNull (ex.InnerException, "#3");
1233 Assert.IsNotNull (ex.Message, "#4");
1234 Assert.IsNotNull (ex.ParamName, "#5");
1235 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
1240 public void GetTypeWithEmptyStringShouldThrow ()
1243 typeof (string).Assembly.GetType ("");
1245 } catch (ArgumentException) {}
1248 class GetCallingAssemblyCallee {
1251 static void sideEffect () {
1255 // GetCallingAssembly may see an unpredictable
1256 // view of the stack if it's called in tail
1257 // position, or if its caller or the caller's
1258 // caller is inlined. So we put in a side
1259 // effect to get out of tail position, and we
1260 // tag the methods NoInlining to discourage
1262 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1263 public static Assembly Leaf () {
1264 var a = Assembly.GetCallingAssembly ();
1269 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1270 public static Assembly DirectCall () {
1276 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1277 public static Assembly InvokeCall () {
1278 var ty = typeof (GetCallingAssemblyCallee);
1279 var mi = ty.GetMethod("Leaf");
1280 var o = mi.Invoke(null, null);
1287 public void GetCallingAssembly_Direct() {
1288 var a = GetCallingAssemblyCallee.DirectCall ();
1289 Assert.IsNotNull (a);
1291 Assert.AreEqual (GetType().Assembly, a);
1295 public void GetCallingAssembly_SkipsReflection () {
1296 // check that the calling assembly is this
1297 // one, not mscorlib (aka, the reflection
1299 var a = GetCallingAssemblyCallee.InvokeCall ();
1300 Assert.IsNotNull (a);
1302 var invokeAssembly =
1303 typeof (MethodInfo).Assembly;
1304 Assert.AreNotEqual (invokeAssembly, a);
1306 Assert.AreEqual (GetType().Assembly, a);
1311 public void DefinedTypes_Equality ()
1313 var x1 = Assembly.GetExecutingAssembly ().DefinedTypes.Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1314 var x2 = Assembly.GetExecutingAssembly ().GetTypes ().Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1316 Assert.AreSame (x1, x2, "#1");
1321 public class TestDefinedTypes