internal override void LoadCompileTimeReferencedAssemblies(AssemblyLoader/*!*/ loader) { base.LoadCompileTimeReferencedAssemblies(loader); foreach (string full_name in GetAttribute().ReferencedAssemblies) loader.Load(full_name, null, null); }
internal AssemblyLog(AssemblyLoader.LoadedAssembly assembly) { name = assembly.assembly.GetName().Name; version = assembly.assembly.GetName().Version.ToString(); infoVersion = FileVersionInfo.GetVersionInfo(assembly.assembly.Location).ProductVersion; location = assembly.url.ToString(); }
/// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public DesignTimeServicesBuilder( [NotNull] AssemblyLoader assemblyLoader, [NotNull] StartupInvoker startupInvoker) { _assemblyLoader = assemblyLoader; _startup = startupInvoker; }
public void Can_load_external_dlls_from_outside_bin_directory() { string libDir = GetLibDirectory(); string graphSharpFullPath = Path.Combine(libDir, "GraphSharp.dll"); _graphBuilder.AddAssemblyAndAllDependencies(graphSharpFullPath); AssemblyDependencyGraph graph = _graphBuilder.BuildAssemblyDependencyGraph(); Assembly graphSharpAssembly = new AssemblyLoader().LoadAssembly(graphSharpFullPath); IEnumerable<Assembly> dependencies = graph.GetDependantAssemblies(graphSharpAssembly); dependencies.Single(o => o.GetName().Name == "QuickGraph"); }
public static void InitializeDatabase( AssemblyLoader assemblyLoader, string contextAssemblyPath, string contextName, string serverName, string databaseName) { assemblyLoader.Load(MigrationsSource.Deployed, contextAssemblyPath); using ( var context = Assembly.LoadFile(contextAssemblyPath).CreateInstance(contextName) as DbContext) { context.Database.Connection.ConnectionString= string.Format( "Server={0};Initial Catalog={1};Integrated Security=true;Application Name=Galen.Ci.EntityFramework.Tests;", serverName, databaseName); context.Database.Initialize(false); } }
internal AssemblyLog(AssemblyLoader.LoadedAssembly Assembly) { assemblyLoaded = Assembly.assembly; var ainfoV = Attribute.GetCustomAttribute(Assembly.assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; var afileV = Attribute.GetCustomAttribute(Assembly.assembly, typeof(AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute; switch (afileV == null) { case true: fileVersion = ""; break; default: fileVersion = afileV.Version; break; } switch (ainfoV == null) { case true: infoVersion = ""; break; default: infoVersion = ainfoV.InformationalVersion; break; } name = Assembly.assembly.GetName().Name; version = Assembly.assembly.GetName().Version.ToString(); location = Assembly.url.ToString(); }
internal AssemblyClassLoader(Assembly assembly, string[] fixedReferences) : base(CodeGenOptions.None, null) { this.assemblyLoader = new AssemblyLoader(assembly); this.references = fixedReferences; #if STATIC_COMPILER if (assembly.GetManifestResourceInfo("ikvm.exports") != null) { using (Stream stream = assembly.GetManifestResourceStream("ikvm.exports")) { BinaryReader rdr = new BinaryReader(stream); int assemblyCount = rdr.ReadInt32(); for (int i = 0; i < assemblyCount; i++) { string assemblyName = rdr.ReadString(); int typeCount = rdr.ReadInt32(); for (int j = 0; j < typeCount; j++) { rdr.ReadInt32(); } if (typeCount != 0) { IkvmcCompiler.resolver.AddHintPath(assemblyName, Path.GetDirectoryName(assembly.Location)); } } } } #endif }
private AssemblyLoader GetLoaderForExportedAssembly(Assembly assembly) { LazyInitExports(); AssemblyLoader loader; lock (exportedLoaders) { exportedLoaders.TryGetValue(assembly, out loader); } if (loader == null) { loader = new AssemblyLoader(assembly); lock (exportedLoaders) { AssemblyLoader existing; if (exportedLoaders.TryGetValue(assembly, out existing)) { // another thread beat us to it loader = existing; } else { exportedLoaders.Add(assembly, loader); } } } return loader; }
private void DiscoverAssemblies(AssemblyLoader loader, List<string> exclusionList, bool validate = true) { var result = loader.DiscoverAssemblies(); var text = new StringBuilder(); text.Append("\nFound assemblies:"); foreach (var i in result) text.Append(String.Format("\n\t* {0}", i)); logger.Info(text.ToString()); if (validate) { var found = false; foreach (var i in result) { var fileName = Path.GetFileName(i); // we shouldn't have any blacklisted assemblies in the list. Assert.IsFalse(exclusionList.Contains(fileName), "Assemblies on an exclusion list should be ignored."); if (fileName == ExpectedFileName) found = true; } Assert.IsTrue( found, String.Format( "{0} should have been found by the assembly loader", ExpectedFileName)); } }
/// <summary> /// Emits the compilation into given <see cref="ModuleBuilder"/> using Reflection.Emit APIs. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="moduleBuilder"> /// The module builder to add the types into. Can be reused for multiple compilation units. /// </param> /// <param name="assemblyLoader"> /// Loads an assembly given an <see cref="AssemblyIdentity"/>. /// This callback is used for loading assemblies referenced by the compilation. /// <see cref="System.Reflection.Assembly.Load(AssemblyName)"/> is used if not specified. /// </param> /// <param name="assemblySymbolMapper"> /// Applied when converting assembly symbols to assembly references. /// <see cref="IAssemblySymbol"/> is mapped to its <see cref="IAssemblySymbol.Identity"/> by default. /// </param> /// <param name="cancellationToken">Can be used to cancel the emit process.</param> /// <param name="recoverOnError">If false the method returns an unsuccessful result instead of falling back to CCI writer.</param> /// <param name="compiledAssemblyImage">Assembly image, returned only if we fallback to CCI writer.</param> /// <param name="entryPoint">An entry point or null if not applicable or on failure.</param> /// <param name="diagnostics">Diagnostics.</param> /// <returns>True on success, false if a compilation error occurred or the compilation doesn't contain any code or declarations.</returns> /// <remarks> /// Reflection.Emit doesn't support all metadata constructs. If an unsupported construct is /// encountered a metadata writer that procudes uncollectible code is used instead. This is /// indicated by /// <see cref="ReflectionEmitResult.IsUncollectible"/> flag on the result. /// /// Reusing <see cref="System.Reflection.Emit.ModuleBuilder"/> may be beneficial in certain /// scenarios. For example, when emitting a sequence of code snippets one at a time (like in /// REPL). All the snippets can be compiled into a single module as long as the types being /// emitted have unique names. Reusing a single module/assembly reduces memory overhead. On /// the other hand, collectible assemblies are units of collection. Defining too many /// unrelated types in a single assemly might prevent the unused types to be collected. /// /// No need to provide a name override when using Reflection.Emit, since the assembly already /// exists. /// </remarks> /// <exception cref="InvalidOperationException">Referenced assembly can't be resolved.</exception> internal static bool Emit( this Compilation compilation, ModuleBuilder moduleBuilder, AssemblyLoader assemblyLoader, Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper, bool recoverOnError, DiagnosticBag diagnostics, CancellationToken cancellationToken, out MethodInfo entryPoint, out byte[] compiledAssemblyImage) { compiledAssemblyImage = default(byte[]); var moduleBeingBuilt = compilation.CreateModuleBuilder( emitOptions: EmitOptions.Default, manifestResources: null, assemblySymbolMapper: assemblySymbolMapper, testData: null, diagnostics: diagnostics, cancellationToken: cancellationToken); if (moduleBeingBuilt == null) { entryPoint = null; return false; } if (!compilation.Compile( moduleBeingBuilt, win32Resources: null, xmlDocStream: null, generateDebugInfo: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: cancellationToken)) { entryPoint = null; return false; } Cci.IMethodReference cciEntryPoint = moduleBeingBuilt.EntryPoint; cancellationToken.ThrowIfCancellationRequested(); DiagnosticBag metadataDiagnostics = DiagnosticBag.GetInstance(); var context = new EmitContext((Cci.IModule)moduleBeingBuilt, null, metadataDiagnostics); // try emit via Reflection.Emit try { var referencedAssemblies = from referencedAssembly in compilation.GetBoundReferenceManager().GetReferencedAssemblies() let peReference = referencedAssembly.Key as PortableExecutableReference select KeyValuePair.Create( moduleBeingBuilt.Translate(referencedAssembly.Value, metadataDiagnostics), (peReference != null) ? peReference.FilePath : null); entryPoint = ReflectionEmitter.Emit( context, referencedAssemblies, moduleBuilder, assemblyLoader ?? AssemblyLoader.Default, cciEntryPoint, cancellationToken); // translate metadata errors. return compilation.FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics); } catch (TypeLoadException) { // attempted to emit reference to a type that can't be loaded (has invalid metadata) } catch (NotSupportedException) { // nop } // TODO (tomat): // // Another possible approach would be to just return an error, that we can't emit via // Ref.Emit and let the user choose another method of emitting. For that we would want // to preserve the state of the Emit.Assembly object with all the compiled methods so // that the subsequent emit doesn't need to compile method bodies again. // TODO (tomat): // // If Ref.Emit fails to emit the code the type builders already created will stay // defined on the module builder. Ideally we would clean them up but Ref.Emit doesn't // provide any API to do so. In fact it also keeps baked TypeBuilders alive as well. if (!recoverOnError) { metadataDiagnostics.Free(); entryPoint = null; return false; } using (var stream = new System.IO.MemoryStream()) { Cci.PeWriter.WritePeToStream( context, compilation.MessageProvider, () => stream, nativePdbWriterOpt: null, pdbPathOpt: null, allowMissingMethodBodies: false, deterministic: false, cancellationToken: cancellationToken); compiledAssemblyImage = stream.ToArray(); } var compiledAssembly = Assembly.Load(compiledAssemblyImage); entryPoint = (cciEntryPoint != null) ? ReflectionEmitter.ResolveEntryPoint(compiledAssembly, cciEntryPoint, context) : null; // translate metadata errors. return compilation.FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics); }
private ReflectionEmitter( EmitContext context, IEnumerable<KeyValuePair<Cci.IAssemblyReference, string>> referencedAssemblies, ModuleBuilder builder, AssemblyLoader assemblyLoader) { Debug.Assert(context.Module != null); Debug.Assert(referencedAssemblies != null); Debug.Assert(builder != null); Debug.Assert(assemblyLoader != null); _module = context.Module; _context = context; _builder = builder; _tokenResolver = (ITokenDeferral)context.Module; _assemblyLoader = assemblyLoader; _referencedAssemblies = LoadReferencedAssemblies(referencedAssemblies); }
public static MethodInfo Emit( EmitContext context, IEnumerable<KeyValuePair<Cci.IAssemblyReference, string>> referencedAssemblies, ModuleBuilder builder, AssemblyLoader assemblyLoader, Cci.IMethodReference entryPoint, CancellationToken cancellationToken) { var emitter = new ReflectionEmitter(context, referencedAssemblies, builder, assemblyLoader); return emitter.EmitWorker(entryPoint, cancellationToken); }
/// <summary> /// Constructs a new instance of the <code>DefaultAddInTree</code> object. /// </summary> internal DefaultAddInTree(AssemblyLoader loader) { this.loader = loader; // load codons and conditions from the current assembly. LoadCodonsAndConditions(Assembly.GetExecutingAssembly()); }
internal AssemblyClassLoader(Assembly assembly, string[] fixedReferences) : base(CodeGenOptions.None, null) { this.assemblyLoader = new AssemblyLoader(assembly); this.references = fixedReferences; }
public static AddinError[] InitializeAddins() { AssemblyLoader loader = new AssemblyLoader(); try { loader.CheckAssembly (Assembly.GetEntryAssembly ()); } catch (Exception ex) { AddinError err = new AddinError (Assembly.GetEntryAssembly ().Location, ex, true); return new AddinError[] { err }; } AddinError[] errors = null; addInTree = new DefaultAddInTree (loader); FileUtilityService fileUtilityService = (FileUtilityService)ServiceManager.GetService(typeof(FileUtilityService)); StringCollection addInFiles = null; StringCollection retryList = null; if (ignoreDefaultCoreDirectory == false) { addInFiles = fileUtilityService.SearchDirectory(defaultCoreDirectory, "*.addin.xml"); retryList = InsertAddIns (addInFiles, out errors); } else retryList = new StringCollection(); if (addInDirectories != null) { foreach(string path in addInDirectories) { addInFiles = fileUtilityService.SearchDirectory(path, "*.addin.xml"); StringCollection partialRetryList = InsertAddIns (addInFiles, out errors); if (partialRetryList.Count != 0) { string [] retryListArray = new string[partialRetryList.Count]; partialRetryList.CopyTo(retryListArray, 0); retryList.AddRange(retryListArray); } } } while (retryList.Count > 0) { StringCollection newRetryList = InsertAddIns (retryList, out errors); // break if no add-in could be inserted. if (newRetryList.Count == retryList.Count) { break; } retryList = newRetryList; } return errors; }
public OperationExecutor( [NotNull] CommonOptions options, [CanBeNull] string environment) { if (!string.IsNullOrEmpty(options.DataDirectory)) { Environment.SetEnvironmentVariable(DataDirEnvName, options.DataDirectory); #if NET451 AppDomain.CurrentDomain.SetData("DataDirectory", options.DataDirectory); #endif } if (!File.Exists(options.Assembly)) { throw new OperationException($"Could not find assembly '{options.Assembly}'."); } var assemblyFileName = Path.GetFileNameWithoutExtension(options.Assembly); // TODO add hooks into Assembly.Load to allow loading from other locations var assemblyLoader = new AssemblyLoader(Assembly.Load); var projectAssembly = assemblyLoader.Load(assemblyFileName); // optional var startupAssembly = string.IsNullOrWhiteSpace(options.StartupAssembly) ? projectAssembly : assemblyLoader.Load(Path.GetFileNameWithoutExtension(options.StartupAssembly)); var projectDir = string.IsNullOrEmpty(options.ProjectDirectory) ? Directory.GetCurrentDirectory() : options.ProjectDirectory; var contentRootPath = string.IsNullOrEmpty(options.ContentRootPath) #if NET451 ? AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") as string ?? AppDomain.CurrentDomain.BaseDirectory #else ? AppContext.BaseDirectory #endif : options.ContentRootPath; var rootNamespace = string.IsNullOrEmpty(options.RootNamespace) ? assemblyFileName : options.RootNamespace; _contextOperations = new LazyRef<DbContextOperations>( () => new DbContextOperations( new LoggerProvider(name => new ConsoleCommandLogger(name)), assembly: projectAssembly, startupAssembly: startupAssembly, environment: environment, contentRootPath: contentRootPath)); _databaseOperations = new LazyRef<DatabaseOperations>( () => new DatabaseOperations( new LoggerProvider(name => new ConsoleCommandLogger(name)), startupAssemblyLoader: assemblyLoader, startupAssembly: startupAssembly, environment: environment, projectDir: projectDir, contentRootPath: contentRootPath, rootNamespace: rootNamespace)); _migrationsOperations = new LazyRef<MigrationsOperations>( () => new MigrationsOperations( new LoggerProvider(name => new ConsoleCommandLogger(name)), assembly: projectAssembly, startupAssemblyLoader: assemblyLoader, startupAssembly: startupAssembly, environment: environment, projectDir: projectDir, contentRootPath: contentRootPath, rootNamespace: rootNamespace)); }