public static void MetadataLoadContextApisAfterDispose() { MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()); lc.Dispose(); Assert.Throws <ObjectDisposedException>(() => lc.LoadFromAssemblyName(new AssemblyName("Foo"))); Assert.Throws <ObjectDisposedException>(() => lc.LoadFromAssemblyName("Foo")); Assert.Throws <ObjectDisposedException>(() => lc.LoadFromAssemblyPath("Foo")); Assert.Throws <ObjectDisposedException>(() => lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage)); Assert.Throws <ObjectDisposedException>(() => lc.LoadFromStream(new MemoryStream(TestData.s_SimpleAssemblyImage))); Assert.Throws <ObjectDisposedException>(() => lc.CoreAssembly); Assert.Throws <ObjectDisposedException>(() => lc.GetAssemblies()); }
public static void LoadFromAssemblyName() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Stream peStream = new MemoryStream(TestData.s_SimpleAssemblyImage); Assembly a = lc.LoadFromStream(peStream); Assert.NotNull(a); Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleAssemblyName); Assert.Equal(a, a1); Assembly a2 = lc.LoadFromAssemblyName(new AssemblyName(TestData.s_SimpleAssemblyName)); Assert.Equal(a, a2); } }
public static void LoadExternalAssembly1() { Assembly runtimeAssembly = typeof(object).Assembly; // Intentionally not projected. using (MetadataLoadContext lc = new MetadataLoadContext( new FuncMetadataAssemblyResolver( delegate(MetadataLoadContext context, AssemblyName assemblyName) { if (assemblyName.Name == "SomeAssembly") { return(runtimeAssembly); } else if (assemblyName.Name == "mscorlib") { return(context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage)); } return(null); } ))) { string location = runtimeAssembly.Location; Assert.Throws <FileLoadException>(() => lc.LoadFromAssemblyName("SomeAssembly")); } }
private List <Assembly> LoadReferencedAssembliesMetadata() { var explorationContext = new MetadataLoadContext(_resolver); var knownAssemblies = explorationContext.GetAssemblies().Union(new[] { ImplementingAssembly }).ToList(); var recursions = 0; List <string> newAssemblyNames; do { recursions++; var knownNames = knownAssemblies.Select(a => a.GetName().FullName).Distinct().ToList(); var referencedNames = knownAssemblies.SelectMany( a => a.GetReferencedAssemblies().Where(n => n.FullName.StartsWith("Trakx"))) .Select(a => a.FullName); newAssemblyNames = referencedNames.Except(knownNames).ToList(); foreach (var name in newAssemblyNames) { try { knownAssemblies.Add(explorationContext.LoadFromAssemblyName(name)); } catch (Exception e) { _output.WriteLine("Failed to load assembly {0} with exception {1}", name, e); } } } while (newAssemblyNames.Any() && recursions <= _maxRecursions); return(knownAssemblies); }
public static void LoadFromAssemblyName() { // Note this is using SimpleAssemblyResolver in order to resolve LoadFromAssemblyName. using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Stream peStream = new MemoryStream(TestData.s_SimpleAssemblyImage); Assembly a = lc.LoadFromStream(peStream); Assert.NotNull(a); Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleAssemblyFullName); Assert.Equal(a, a1); Assembly a2 = lc.LoadFromAssemblyName(new AssemblyName(TestData.s_SimpleAssemblyFullName)); Assert.Equal(a, a2); } }
public static void AssemblyName_GetName_SimpleNameOnly() { using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleNameOnlyImage); AssemblyName an = a.GetName(copiedName: false); Assert.Equal("SimpleNameOnly", an.Name); Assert.Equal(AssemblyNameFlags.PublicKey, an.Flags); Version v = an.Version; Assert.NotNull(v); Assert.Equal(0, v.Major); Assert.Equal(0, v.Minor); Assert.Equal(0, v.Build); Assert.Equal(0, v.Revision); string cultureName = an.CultureName; Assert.Equal(string.Empty, cultureName); byte[] publicKey = an.GetPublicKey(); Assert.Equal(0, publicKey.Length); Assert.Equal(AssemblyContentType.Default, an.ContentType); Assert.Equal(AssemblyHashAlgorithm.SHA1, an.HashAlgorithm); Assembly aAgain = lc.LoadFromAssemblyName(an); Assert.Equal(a, aAgain); } }
public static void PathAssemblyResolverBasicPathWithRunningAssemblies() { string coreAssemblyPath = TestUtils.GetPathToCoreAssembly(); // Obtain this test class string thisAssemblyPath = typeof(MetadataLoadContextTests).Assembly.Location; if (PlatformDetection.IsBrowser) { // prepends slash as Assembly.Location only contains the file name on browser (https://github.com/dotnet/runtime/issues/39650) thisAssemblyPath = "/" + thisAssemblyPath; } var resolver = new PathAssemblyResolver(new string[] { coreAssemblyPath, thisAssemblyPath }); using (MetadataLoadContext lc = new MetadataLoadContext(resolver, TestUtils.GetNameOfCoreAssembly())) { AssemblyName thisAssemblyName = typeof(MetadataLoadContextTests).Assembly.GetName(); Assembly assembly = lc.LoadFromAssemblyName(thisAssemblyName); Type t = assembly.GetType(typeof(MetadataLoadContextTests).FullName, throwOnError: true); Assert.Equal(t.FullName, typeof(MetadataLoadContextTests).FullName); Assert.Equal(t.Assembly.Location, thisAssemblyPath); } }
public static void LoadFromAssemblyNameNullAssemblyName() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assert.Throws <ArgumentNullException>(() => lc.LoadFromAssemblyName((AssemblyName)null)); } }
public static void LoadFromAssemblyNameNeverLoadedAssembly() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assert.Throws <FileNotFoundException>(() => lc.LoadFromAssemblyName("NeverSawThis")); } }
public static void DuplicateAssembliesPickHigherVersion() { using (TempDirectory dir = new TempDirectory()) using (TempDirectory dir2 = new TempDirectory()) using (TempFile core = new TempFile(Path.Combine(dir.Path, TestData.s_PhonyCoreAssemblySimpleName), TestData.s_PhonyCoreAssemblyImage)) using (TempFile tf1 = new TempFile(Path.Combine(dir.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleUnsignedVersioned100Image)) using (TempFile tf2 = new TempFile(Path.Combine(dir2.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleUnsignedVersioned200Image)) { // tf1 first, then tf2. { var resolver = new PathAssemblyResolver(new string[] { core.Path, tf1.Path, tf2.Path }); using (var lc = new MetadataLoadContext(resolver, TestData.s_PhonyCoreAssemblyFullName)) { Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleUnsignedVersioned100FullName); Assert.Equal("2.0.0.0", a1.GetName().Version.ToString()); } } // Reverse the order. { var resolver = new PathAssemblyResolver(new string[] { core.Path, tf2.Path, tf1.Path }); using (var lc = new MetadataLoadContext(resolver, TestData.s_PhonyCoreAssemblyFullName)) { Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleUnsignedVersioned100FullName); Assert.Equal("2.0.0.0", a1.GetName().Version.ToString()); } } } }
// // For a given assembly name and its full path, Reflection-Only load the assembly directly // from the file in disk or load the file to memory and then create assembly instance from // memory buffer data. // private static Assembly ReflectionOnlyLoadAssembly(string assemblyName, string fullPathToAssembly) { Assembly assembly = null; // If the assembly path is empty, try to load assembly by name. LoadFromAssemblyName // will result in a MetadataLoadContext.Resolve event that will contain more information about the // requested assembly. if (String.IsNullOrEmpty(fullPathToAssembly)) { return(_metadataLoadContext.LoadFromAssemblyName(assemblyName)); } else if (_cachedMetadataLoadContextAssemblies.TryGetValue(fullPathToAssembly, out assembly)) { return(assembly); } else if (!String.IsNullOrEmpty(assemblyName) && _cachedMetadataLoadContextAssemblies.TryGetValue(assemblyName, out assembly)) { return(assembly); } else { assembly = _metadataLoadContext.LoadFromAssemblyPath(fullPathToAssembly); } // Add the assembly to the cache. ReflectionHelper.ReflectionOnlyLoadAssembly // receives frequent calls requesting the same assembly. if (assembly != null && fullPathToAssembly != null) { _cachedMetadataLoadContextAssemblies.Add(fullPathToAssembly, assembly); _cachedMetadataLoadContextAssembliesByNameNoExtension.Add(Path.GetFileNameWithoutExtension(fullPathToAssembly), assembly); } return(assembly); }
public static void RelocatableAssembly() { string coreAssemblyPath = TestUtils.GetPathToCoreAssembly(); string coreAssemblyName = Path.GetFileNameWithoutExtension(coreAssemblyPath); // Ensure mscorlib is specified since we want to relocate an older mscorlib later. string coreDirectory = Path.GetDirectoryName(coreAssemblyPath); string mscorLibPath = Path.Combine(coreDirectory, "mscorlib.dll"); using (TempDirectory dir = new TempDirectory()) using (TempFile relocatableAsmFile = new TempFile(Path.Combine(dir.Path, TestData.s_RetargetableAssemblySimpleName), TestData.s_RetargetableImage)) { var resolver = new PathAssemblyResolver(new string[] { coreAssemblyPath, mscorLibPath, relocatableAsmFile.Path }); using (MetadataLoadContext lc = new MetadataLoadContext(resolver, coreAssemblyName)) { Assembly retargetableAssembly = lc.LoadFromAssemblyName(TestData.s_RetargetableAssemblySimpleName); Assert.NotNull(retargetableAssembly); // The assembly only contains a reference to an older, retargetable mscorlib. AssemblyName[] assemblyNames = retargetableAssembly.GetReferencedAssemblies(); AssemblyName retargetableAssemblyName = assemblyNames[0]; Assert.Equal(AssemblyNameFlags.Retargetable, retargetableAssemblyName.Flags); Assert.Equal(new Version(2, 0, 5, 0), retargetableAssemblyName.Version); // Trigger PathAssemblyResolver.Resolve for the older mscorlib. Type myType = retargetableAssembly.GetType("Relocate.MyClass"); FieldInfo[] fields = myType.GetFields(); Assert.Equal(1, fields.Length); FieldInfo field = fields[0]; Assert.Equal("MyObj", field.Name); // Verify that LoadFromAssemblyName also finds the newer mscorlib. Assembly mscorlib = lc.LoadFromAssemblyName(retargetableAssemblyName); Assert.True(mscorlib.GetName().Version > retargetableAssemblyName.Version); // The older reference has a different public key token, which requires AssemblyNameFlags.Retargetable to find the newer assembly. byte[] newerPKT = mscorlib.GetName().GetPublicKeyToken(); Assert.NotEmpty(newerPKT); byte[] olderPKT = retargetableAssemblyName.GetPublicKeyToken(); Assert.NotEmpty(olderPKT); Assert.False(Enumerable.SequenceEqual(newerPKT, olderPKT)); } } }
// Resolve the type in the current metadata load context private Type T(Type type) { if (type.Assembly.GetName().Name == "System.Private.CoreLib") { return(_metadataLoadContext.CoreAssembly.GetType(type.FullName)); } return(_metadataLoadContext.LoadFromAssemblyName(type.Assembly.FullName).GetType(type.FullName)); }
public static void DuplicateUnsignedAssembliesSameVersions() { using (TempDirectory dir = new TempDirectory()) using (TempDirectory dir2 = new TempDirectory()) using (TempFile core = new TempFile(Path.Combine(dir.Path, TestData.s_PhonyCoreAssemblySimpleName), TestData.s_PhonyCoreAssemblyImage)) using (TempFile tf1 = new TempFile(Path.Combine(dir.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleUnsignedVersioned100Image)) using (TempFile tf2 = new TempFile(Path.Combine(dir2.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleUnsignedVersioned100Image)) { var resolver = new PathAssemblyResolver(new string[] { core.Path, tf1.Path, tf2.Path }); using (var lc = new MetadataLoadContext(resolver, TestData.s_PhonyCoreAssemblyFullName)) { Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleVersionedShortName); Assembly a2 = lc.LoadFromAssemblyName(TestData.s_SimpleUnsignedVersioned100FullName); Assert.Same(a1, a2); } } }
public static RoType LoadTypeFromAssemblyQualifiedName(string name, RoAssembly defaultAssembly, bool ignoreCase, bool throwOnError) { if (!name.TypeNameContainsTypeParserMetacharacters()) { // Fast-path: the type contains none of the parser metacharacters nor the escape character. Just treat as plain old type name. name.SplitTypeName(out string ns, out string simpleName); RoType type = defaultAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase, out Exception e); if (type != null) { return(type); } if (throwOnError) { throw e; } } MetadataLoadContext loader = defaultAssembly.Loader; Func <AssemblyName, Assembly> assemblyResolver = delegate(AssemblyName assemblyName) { return(loader.LoadFromAssemblyName(assemblyName)); }; Func <Assembly, string, bool, Type> typeResolver = delegate(Assembly assembly, string fullName, bool ignoreCase2) { if (assembly == null) { assembly = defaultAssembly; } Debug.Assert(assembly is RoAssembly); RoAssembly roAssembly = (RoAssembly)assembly; fullName = fullName.UnescapeTypeNameIdentifier(); fullName.SplitTypeName(out string ns, out string simpleName); Type type = roAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase2, out Exception e); if (type != null) { return(type); } if (throwOnError) { throw e; } return(null); }; return((RoType)Type.GetType(name, assemblyResolver: assemblyResolver, typeResolver: typeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase)); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Required path to dll"); return; } // input.dll outputDir references.txt var path = args[0]; var outputPath = args.Length > 1 ? args[1] : null; var directory = Path.GetDirectoryName(path); var referencePaths = args.Length > 2 ? File.ReadAllLines(args[2]) : new string[0]; var resolver = new PathAssemblyResolver(referencePaths); var corAssembly = referencePaths.Where(m => m.Contains("mscorlib")).Select(a => AssemblyName.GetAssemblyName(a).FullName).FirstOrDefault(); var metadataLoadContext = new MetadataLoadContext(resolver, corAssembly); var uControllerAssembly = metadataLoadContext.LoadFromAssemblyName(typeof(HttpHandler).Assembly.FullName); var handler = uControllerAssembly.GetType(typeof(HttpHandler).FullName); var assembly = metadataLoadContext.LoadFromAssemblyPath(path); var models = new List <HttpModel>(); foreach (var type in assembly.GetExportedTypes()) { if (handler.IsAssignableFrom(type)) { var model = HttpModel.FromType(type); models.Add(model); } } if (models.Count > 0 && outputPath != null) { Directory.CreateDirectory(outputPath); } foreach (var model in models) { var gen = new CodeGenerator(model, metadataLoadContext); if (outputPath != null) { var fileName = Path.Combine(outputPath, model.HandlerType.Name + ".RouteProvider.cs"); File.WriteAllText(fileName, gen.Generate()); } else { Console.WriteLine(gen.Generate()); } } }
private IEnumerable <Type> GetImplementationsOfTypeFromAssembly(string assemblyFullPath) { var context = new MetadataLoadContext(new DefaultAssemblyResolver(assemblyFullPath)); var assembly = context.LoadFromAssemblyName(Path.GetFileNameWithoutExtension(assemblyFullPath)); this.metadataLoadContexts.Add(context); return(assembly.GetTypes() .Where(t => t.CustomAttributes .Any(c => c.AttributeType.Name == typeof(Prise.Plugin.PluginAttribute).Name && (c.NamedArguments.First(a => a.MemberName == "PluginType").TypedValue.Value as Type).Name == typeof(T).Name)) .OrderBy(t => t.Name) .ToList()); }
public static void AssemblyName_GetName_HashWithSha256() { using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_HashWithSha256Image); AssemblyName an = a.GetName(copiedName: false); Assert.Equal("HashWithSha256", an.Name); Assert.Equal(AssemblyHashAlgorithm.SHA256, an.HashAlgorithm); Assembly aAgain = lc.LoadFromAssemblyName(an); Assert.Equal(a, aAgain); } }
public static void DuplicateSignedAndUnsignedAssemblies() { using (TempDirectory dir = new TempDirectory()) using (TempDirectory dir2 = new TempDirectory()) using (TempFile core = new TempFile(Path.Combine(dir.Path, TestData.s_PhonyCoreAssemblySimpleName), TestData.s_PhonyCoreAssemblyImage)) using (TempFile tf1 = new TempFile(Path.Combine(dir.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleSignedVersioned100Image)) using (TempFile tf2 = new TempFile(Path.Combine(dir2.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleUnsignedVersioned100Image)) { var resolver = new PathAssemblyResolver(new string[] { core.Path, tf1.Path, tf2.Path }); using (var lc = new MetadataLoadContext(resolver, TestData.s_PhonyCoreAssemblyFullName)) { Assert.Equal(1, lc.GetAssemblies().Count()); // These are treated as different since one contains a PublicKeyToken and one does not. Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleUnsignedVersioned100FullName); Assembly a2 = lc.LoadFromAssemblyName(TestData.s_SimpleSignedVersioned100FullName); Assert.NotSame(a1, a2); Assert.Equal(3, lc.GetAssemblies().Count()); } } }
public static void AssemblyName_GetName_CultureFrCh() { using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_CultureFrChImage); AssemblyName an = a.GetName(copiedName: false); Assert.Equal("CultureFrCh", an.Name); string cultureName = an.CultureName; Assert.Equal("fr-CH", cultureName); Assembly aAgain = lc.LoadFromAssemblyName(an); Assert.Equal(a, aAgain); } }
public static void DuplicateSignedAssembliesDifferentVersions() { using (TempDirectory dir = new TempDirectory()) using (TempDirectory dir2 = new TempDirectory()) using (TempFile core = new TempFile(Path.Combine(dir.Path, TestData.s_PhonyCoreAssemblySimpleName), TestData.s_PhonyCoreAssemblyImage)) using (TempFile tf1 = new TempFile(Path.Combine(dir.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleSignedVersioned100Image)) using (TempFile tf2 = new TempFile(Path.Combine(dir2.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleSignedVersioned200Image)) { var resolver = new PathAssemblyResolver(new string[] { core.Path, tf1.Path, tf2.Path }); using (var lc = new MetadataLoadContext(resolver, TestData.s_PhonyCoreAssemblyFullName)) { Assert.Equal(1, lc.GetAssemblies().Count()); // Using simple name will find first assembly that matches. Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleVersionedShortName); Assembly a2 = lc.LoadFromAssemblyName(TestData.s_SimpleSignedVersioned100FullName); Assembly a3 = lc.LoadFromAssemblyName(TestData.s_SimpleSignedVersioned200FullName); Assert.True(object.ReferenceEquals(a1, a2) || object.ReferenceEquals(a1, a3)); Assert.Equal(3, lc.GetAssemblies().Count()); } } }
public static void AssemblyName_GetName_PublicKeyToken1ee753223f71263d() { using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_PublicKeyToken1ee753223f71263dImage); AssemblyName an = a.GetName(copiedName: false); Assert.Equal("PublicKeyToken1ee753223f71263d", an.Name); Assert.Equal(AssemblyNameFlags.PublicKey, an.Flags); byte[] publicKey = an.GetPublicKey(); Assert.Equal <byte>(TestData.s_PublicKeyToken1ee753223f71263d_Pk, publicKey); Assembly aAgain = lc.LoadFromAssemblyName(an); Assert.Equal(a, aAgain); } }
public static void PathAssemblyResolverBasicPathWithRunningAssemblies() { string coreAssemblyPath = TestUtils.GetPathToCoreAssembly(); // Obtain this test class string thisAssemblyPath = AssemblyPathHelper.GetAssemblyLocation(typeof(MetadataLoadContextTests).Assembly); var resolver = new PathAssemblyResolver(new string[] { coreAssemblyPath, thisAssemblyPath }); using (MetadataLoadContext lc = new MetadataLoadContext(resolver, TestUtils.GetNameOfCoreAssembly())) { AssemblyName thisAssemblyName = typeof(MetadataLoadContextTests).Assembly.GetName(); Assembly assembly = lc.LoadFromAssemblyName(thisAssemblyName); Type t = assembly.GetType(typeof(MetadataLoadContextTests).FullName, throwOnError: true); Assert.Equal(t.FullName, typeof(MetadataLoadContextTests).FullName); Assert.Equal(t.Assembly.Location, thisAssemblyPath); } }
public static void AssemblyName_GetName_Version1_2_65535_65535() { using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_Version1_2_65535_65535Image); AssemblyName an = a.GetName(copiedName: false); Assert.Equal("Version1_2_65535_65535", an.Name); Version v = an.Version; Assert.NotNull(v); Assert.Equal(1, v.Major); Assert.Equal(2, v.Minor); Assert.Equal(65535, v.Build); Assert.Equal(65535, v.Revision); Assembly aAgain = lc.LoadFromAssemblyName(an); Assert.Equal(a, aAgain); } }
public static void CoreAssemblyCanBeAFacade() { Assembly actualCoreAssembly = null; Assembly testAssembly = null; var resolver = new FuncMetadataAssemblyResolver( delegate(MetadataLoadContext context, AssemblyName refName) { if (refName.Name.Equals("mscorlib", StringComparison.OrdinalIgnoreCase)) { return(actualCoreAssembly = context.LoadFromStream(TestUtils.CreateStreamForCoreAssembly())); } //else if (refName.Equals(new AssemblyName(TestData.s_PhonyCoreAssemblyName))) else if (refName.Name == new AssemblyName(TestData.s_PhonyCoreAssemblyName).Name) { return(testAssembly = context.LoadFromByteArray(TestData.s_PhonyCoreAssemblyImage)); } return(null); }); using (MetadataLoadContext lc = new MetadataLoadContext(resolver, coreAssemblyName: TestData.s_PhonyCoreAssemblyName)) { // This is a sanity check to ensure that "TestData.s_PhonyCoreAssemblyName" is actually the def-name of this // assembly. It better be since we told our MetadataLoadContext to use it as our core assembly. Assembly aAgain = lc.LoadFromAssemblyName(TestData.s_PhonyCoreAssemblyName); Type derived = testAssembly.GetType("Derived", throwOnError: true, ignoreCase: false); // Calling BaseType causes the MetadataLoadContext to parse the typespec "Base<object>". Since "object" is a primitive // type, it should be encoded using the short-form "ELEMENT_TYPE_OBJECT." Hence, the MetadataLoadContext is forced // to look up "System.Object" in the core assembly we assigned to it, which in this case is "PhonyCoreAssembly" // which type-forwards System.Object to "mscorlib". Type baseType = derived.BaseType; Assert.NotNull(actualCoreAssembly); // Ensure our resolve handler actually ran. Assert.NotEqual(testAssembly, actualCoreAssembly); Assert.True(baseType.IsConstructedGenericType); Type retrievedObjectType = baseType.GenericTypeArguments[0]; Assert.Equal("System.Object", retrievedObjectType.FullName); Assert.Equal(actualCoreAssembly, retrievedObjectType.Assembly); } }
public void Execute(SourceGeneratorContext context) { // For debugging // System.Diagnostics.Debugger.Launch(); var metadataLoadContext = new MetadataLoadContext(context.Compilation); var uControllerAssembly = metadataLoadContext.LoadFromAssemblyName("uController"); var handler = uControllerAssembly.GetType(typeof(HttpHandler).FullName); var assembly = metadataLoadContext.MainAssembly; var models = new List <HttpModel>(); foreach (var type in assembly.GetExportedTypes()) { if (handler.IsAssignableFrom(type)) { var model = HttpModel.FromType(type); models.Add(model); } } foreach (var model in models) { var gen = new CodeGenerator(model, metadataLoadContext); var rawSource = gen.Generate(); var sourceText = SourceText.From(rawSource, Encoding.UTF8); // For debugging //var comp = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(sourceText)); //var diagnosrics = comp.GetDiagnostics(); context.AddSource(model.HandlerType.Name + "RouteExtensions", sourceText); //if (gen.FromBodyTypes.Any()) //{ // var jsonGenerator = new JsonCodeGenerator(metadataLoadContext, model.HandlerType.Namespace); // var generatedConverters = jsonGenerator.Generate(gen.FromBodyTypes, out var helperSource); //} } }
public static void LoadFromDifferentLocations() { using (TempFile tf1 = TempFile.Create(TestData.s_SimpleAssemblyImage)) using (TempFile tf2 = TempFile.Create(TestData.s_SimpleAssemblyImage)) using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { // As long as the MVID matches, you can load the same assembly from multiple locations. Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.NotNull(a); Assembly a1 = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.Equal(a, a1); Assembly a2 = lc.LoadFromAssemblyName(new AssemblyName(TestData.s_SimpleAssemblyName)); Assert.Equal(a, a2); Assembly a3 = lc.LoadFromAssemblyPath(tf1.Path); Assert.Equal(a, a3); Assembly a4 = lc.LoadFromAssemblyPath(tf2.Path); Assert.Equal(a, a4); } }
public static void LoadFromDifferentLocations() { using (TempFile tf1 = TempFile.Create(TestData.s_SimpleAssemblyImage)) using (TempFile tf2 = TempFile.Create(TestData.s_SimpleAssemblyImage)) // Note this is using SimpleAssemblyResolver in order to resolve LoadFromAssemblyName. using (MetadataLoadContext lc = new MetadataLoadContext(new SimpleAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.NotNull(a); Assembly a1 = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.Equal(a, a1); Assembly a2 = lc.LoadFromAssemblyName(new AssemblyName(TestData.s_SimpleAssemblyFullName)); Assert.Equal(a, a2); Assembly a3 = lc.LoadFromAssemblyPath(tf1.Path); Assert.Equal(a, a3); Assembly a4 = lc.LoadFromAssemblyPath(tf2.Path); Assert.Equal(a, a4); } }
private static async Task <IModuleMetadata> GetMetadataAsync(string inputAssemblyPath, CancellationToken cancellation) { // We take our core assembly for now. var coreAssembly = typeof(object).Assembly; // TODO: Support specifying a different core assembly to support additional workloads. var assemblyResolver = new PathAssemblyResolver(new string[] { inputAssemblyPath, coreAssembly.Location }); using (var loadContext = new MetadataLoadContext(assemblyResolver, coreAssembly.FullName)) { var assemblyName = Path.GetFileNameWithoutExtension(inputAssemblyPath); var assembly = loadContext.LoadFromAssemblyName(assemblyName); var metadata = await _metadataAccessor.GetMetadataAsync(assembly, cancellation); if (metadata.ReleaseDate == default) { var editableMetadata = metadata as ModuleMetadata ?? new ModuleMetadata(metadata); editableMetadata.ReleaseDate = DateTime.Now; metadata = editableMetadata; } return(metadata); } }
private static async Task Main(string[] arguments) { if (arguments.Length != 2 || arguments[0].AsSpan().Trim().Length == 0 || arguments[1].AsSpan().Trim().Length == 0) { Program.Usage(); return; } string assemblyPath; string xmlFilePath; try { assemblyPath = Path.GetFullPath(arguments[0]); xmlFilePath = Path.ChangeExtension(assemblyPath, "xml"); } catch { Console.WriteLine("assembly-path \"" + arguments[0] + "\" is not valid."); Console.WriteLine(); Program.Usage(); return; } var assemblyDirectoryName = Path.GetDirectoryName(assemblyPath); if (string.IsNullOrEmpty(assemblyDirectoryName)) { Console.WriteLine("assembly-path \"" + arguments[0] + "\" is not valid."); Console.WriteLine(); Program.Usage(); return; } string outputPath; try { outputPath = Path.GetFullPath(arguments[1]); } catch { Console.WriteLine("output-path \"" + arguments[1] + "\" is not valid."); Console.WriteLine(); Program.Usage(); return; } var assemblies = new List <string>(); assemblies.AddRange(Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll")); assemblies.AddRange(Directory.GetFiles(assemblyDirectoryName, "*.dll")); using (var context = new MetadataLoadContext(new PathAssemblyResolver(assemblies))) { Assembly assembly; try { assembly = context.LoadFromAssemblyPath(assemblyPath); foreach (var childAssembly in assembly.GetReferencedAssemblies()) { context.LoadFromAssemblyName(childAssembly); } } catch { Console.WriteLine($"Unable to load assembly \"{assemblyPath}\"."); return; } XDocument xmlComments; try { using (var file = File.OpenText(xmlFilePath)) { xmlComments = await XDocument.LoadAsync( file, LoadOptions.PreserveWhitespace, CancellationToken.None); } } catch { xmlComments = new XDocument(); } try { Directory.CreateDirectory(outputPath); } catch { Console.WriteLine($"Unable to create output directory \"{outputPath}\"."); return; } await DocumentBuilder.Build(assembly, xmlComments, outputPath); } }