Пример #1
0
 public LibraryExporter(LibraryManager manager, CompilationEngine compilationEngine, FrameworkName targetFramework, string configuration)
 {
     _manager           = manager;
     _compilationEngine = compilationEngine;
     _targetFramework   = targetFramework;
     _configuration     = configuration;
 }
Пример #2
0
 public LibraryExporter(LibraryManager manager, IAssemblyLoadContext loadContext, CompilationEngine compilationEngine, string configuration)
 {
     LibraryManager = manager;
     _compilationEngine = compilationEngine;
     _configuration = configuration;
     _loadContext = loadContext;
 }
        public Assembly Load(AssemblyName assemblyName)
        {
            var projectPath = Path.Combine(_path, assemblyName.Name);
            if (!Project.HasProjectFile(projectPath)) {
                return null;
            }

            return _cache.Get<Assembly>(assemblyName.Name, cacheContext => {
                var moduleContext = new ModuleLoaderContext(
                    projectPath,
                    _applicationEnvironment.RuntimeFramework);

                foreach (var lib in moduleContext.LibraryManager.GetLibraries()) {
                    _libraryManager.AddLibrary(lib);
                }

                var engine = new CompilationEngine(new CompilationEngineContext(
                    _applicationEnvironment,
                    _assemblyLoadContextAccessor.Default,
                    new CompilationCache()));

                var exporter = engine.CreateProjectExporter(
                    moduleContext.Project, moduleContext.TargetFramework, _applicationEnvironment.Configuration);

                var exports = exporter.GetAllExports(moduleContext.Project.Name);
                foreach (var metadataReference in exports.MetadataReferences) {
                    _libraryManager.AddMetadataReference(metadataReference);
                }

                return engine.LoadProject(moduleContext.Project, null, _assemblyLoadContextAccessor.Default);
            });
        }
Пример #4
0
 public LibraryExporter(LibraryManager manager, IAssemblyLoadContext loadContext, CompilationEngine compilationEngine, string configuration)
 {
     LibraryManager     = manager;
     _compilationEngine = compilationEngine;
     _configuration     = configuration;
     _loadContext       = loadContext;
 }
Пример #5
0
 public LibraryExporter(LibraryManager manager, CompilationEngine compilationEngine, FrameworkName targetFramework, string configuration)
 {
     _manager = manager;
     _compilationEngine = compilationEngine;
     _targetFramework = targetFramework;
     _configuration = configuration;
 }
Пример #6
0
 public BuildLoadContext(Project project,
                         CompilationEngine compilationEngine,
                         CompilationEngineContext compilationEngineContext)
 {
     _project                  = project;
     _compilationEngine        = compilationEngine;
     _compilationEngineContext = compilationEngineContext;
 }
Пример #7
0
 public BuildLoadContext(Project project,
                         CompilationEngine compilationEngine,
                         CompilationEngineContext compilationEngineContext)
 {
     _project = project;
     _compilationEngine = compilationEngine;
     _compilationEngineContext = compilationEngineContext;
 }
Пример #8
0
 public ProjectStateResolver(CompilationEngine compilationEngine,
                             FrameworkReferenceResolver frameworkReferenceResolver,
                             Func<CacheContext, Project, FrameworkName, ApplicationHostContext> applicaitonHostContextCreator)
 {
     _compilationEngine = compilationEngine;
     _frameworkReferenceResolver = frameworkReferenceResolver;
     _applicationHostContextCreator = applicaitonHostContextCreator;
 }
Пример #9
0
        private async Task OpenChannel(int port, string hostId)
        {
            var contexts = new Dictionary<int, ApplicationContext>();
            var protocolManager = new ProtocolManager(maxVersion: 3);

            // REVIEW: Should these be on a shared context object that flows?
            var applicationEnvironment = (IApplicationEnvironment)_services.GetService(typeof(IApplicationEnvironment));
            var runtimeEnvironment = (IRuntimeEnvironment)_services.GetService(typeof(IRuntimeEnvironment));
            var loadContextAccessor = (IAssemblyLoadContextAccessor)_services.GetService(typeof(IAssemblyLoadContextAccessor));
            var compilationEngine = new CompilationEngine(new CompilationEngineContext(applicationEnvironment, runtimeEnvironment, loadContextAccessor.Default, new CompilationCache()));
            var frameworkResolver = new FrameworkReferenceResolver();

            // This fixes the mono incompatibility but ties it to ipv4 connections
            var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, port));
            listenSocket.Listen(10);

            Console.WriteLine($"Process ID {Process.GetCurrentProcess().Id}");
            Console.WriteLine("Listening on port {0}", port);

            while (true)
            {
                var acceptSocket = await AcceptAsync(listenSocket);

                Console.WriteLine("Client accepted {0}", acceptSocket.LocalEndPoint);

                var stream = new NetworkStream(acceptSocket);
                var queue = new ProcessingQueue(stream);
                var connection = new ConnectionContext(
                    contexts,
                    _services,
                    applicationEnvironment,
                    runtimeEnvironment,
                    loadContextAccessor,
                    frameworkResolver,
                    queue,
                    protocolManager,
                    compilationEngine,
                    hostId);

                queue.OnReceive += message =>
                {
                    // Enumerates all project contexts and return them to the
                    // sender
                    if (message.MessageType == "EnumerateProjectContexts")
                    {
                        WriteProjectContexts(message, queue, contexts);
                    }
                    else
                    {
                        // Otherwise it's a context specific message
                        connection.OnReceive(message);
                    }
                };

                queue.Start();
            }
        }
Пример #10
0
 public BuildLoadContext(Project project,
                         CompilationEngine compilationEngine,
                         CompilationEngineContext compilationEngineContext,
                         string configuration)
 {
     _project = project;
     _compilationEngine = compilationEngine;
     _compilationEngineContext = compilationEngineContext;
     _configuration = configuration;
 }
Пример #11
0
 public BuildLoadContext(Project project,
                         CompilationEngine compilationEngine,
                         CompilationEngineContext compilationEngineContext,
                         string configuration)
 {
     _project                  = project;
     _compilationEngine        = compilationEngine;
     _compilationEngineContext = compilationEngineContext;
     _configuration            = configuration;
 }
Пример #12
0
        public BuildManager(IServiceProvider hostServices, BuildOptions buildOptions)
        {
            _hostServices = hostServices;
            _buildOptions = buildOptions;

            _applicationEnvironment = (IApplicationEnvironment)hostServices.GetService(typeof(IApplicationEnvironment));
            var loadContextAccessor = (IAssemblyLoadContextAccessor)hostServices.GetService(typeof(IAssemblyLoadContextAccessor));

            _compilationEngine = new CompilationEngine(new CompilationEngineContext(_applicationEnvironment, loadContextAccessor.Default, new CompilationCache()));

            ScriptExecutor = new ScriptExecutor(buildOptions.Reports.Information);
        }
Пример #13
0
        public BuildManager(BuildOptions buildOptions)
        {
            _buildOptions = buildOptions;

            _applicationEnvironment = PlatformServices.Default.Application;
            var runtimeEnvironment = PlatformServices.Default.Runtime;
            var loadContextAccessor = PlatformServices.Default.AssemblyLoadContextAccessor;

            _compilationEngine = new CompilationEngine(new CompilationEngineContext(
                _applicationEnvironment,
                runtimeEnvironment,
                loadContextAccessor.Default,
                new CompilationCache()));

            ScriptExecutor = new ScriptExecutor(buildOptions.Reports.Information);
        }
Пример #14
0
        public BuildContext(CompilationEngine compilationEngine,
                            Runtime.Project project,
                            FrameworkName targetFramework,
                            string configuration,
                            string outputPath)
        {
            _project = project;
            _targetFramework = targetFramework;
            _configuration = configuration;
            _targetFrameworkFolder = VersionUtility.GetShortFrameworkName(_targetFramework);
            _outputPath = Path.Combine(outputPath, _targetFrameworkFolder);

            _libraryExporter = compilationEngine.CreateProjectExporter(
                _project, _targetFramework, _configuration);

            _libraryManager = _libraryExporter.LibraryManager;
        }
Пример #15
0
 public ConnectionContext(IDictionary<int, ApplicationContext> contexts,
                          IServiceProvider services,
                          IApplicationEnvironment applicationEnvironment,
                          IAssemblyLoadContextAccessor loadContextAccessor,
                          FrameworkReferenceResolver frameworkResolver,
                          ProcessingQueue queue,
                          ProtocolManager protocolManager,
                          CompilationEngine compilationEngine,
                          string hostId)
 {
     _contexts = contexts;
     _services = services;
     _applicationEnvironment = applicationEnvironment;
     _loadContextAccessor = loadContextAccessor;
     _frameworkResolver = frameworkResolver;
     _queue = queue;
     _compilationEngine = compilationEngine;
     _protocolManager = protocolManager;
     _compilationEngine = compilationEngine;
     _hostId = hostId;
 }
Пример #16
0
 public LibraryExporter(LibraryManager manager, CompilationEngine compilationEngine, string configuration)
 {
     LibraryManager = manager;
     _compilationEngine = compilationEngine;
     _configuration = configuration;
 }
Пример #17
0
 private static LibraryExport ExportProjectDependencies(Project project, FrameworkName targetFramework, string configuration, string aspect, CompilationEngine compilationEngine)
 {
     return(compilationEngine
            .CreateProjectExporter(project, targetFramework, configuration)
            .GetAllDependencies(project.Name, aspect));
 }
Пример #18
0
        public Assembly Load(AssemblyName assemblyName)
        {
            var reference = _libraryManager.GetMetadataReference(assemblyName.Name);

            if (reference != null && reference is MetadataFileReference)
            {
                var fileReference = (MetadataFileReference)reference;

                var assembly = _assemblyLoadContextAccessor
                    .Default
                    .LoadFile(fileReference.Path);

                return assembly;
            }

            var projectPath = Path.Combine(_path, assemblyName.Name);
            if (!Project.HasProjectFile(projectPath))
            {
                return null;
            }

            var moduleContext = new ModuleLoaderContext(
                projectPath,
                _applicationEnvironment.RuntimeFramework);

            foreach (var lib in moduleContext.LibraryManager.GetLibraries())
            {
                _libraryManager.AddLibrary(lib);
            }

            var engine = new CompilationEngine(new CompilationEngineContext(
                _applicationEnvironment,
                _runtimeEnvironment,
                _assemblyLoadContextAccessor.Default,
                new CompilationCache()));

            var exporter = engine.CreateProjectExporter(
                moduleContext.Project, moduleContext.TargetFramework, _applicationEnvironment.Configuration);

            var exports = exporter.GetAllExports(moduleContext.Project.Name);
            foreach (var metadataReference in exports.MetadataReferences)
            {
                _libraryManager.AddMetadataReference(metadataReference);
            }

            var loadedProjectAssembly = engine.LoadProject(
                moduleContext.Project,
                _applicationEnvironment.RuntimeFramework,
                null,
                _assemblyLoadContextAccessor.Default,
                assemblyName);

            IList<LibraryDependency> flattenedList = moduleContext
                .Project
                .Dependencies
                .SelectMany(x => Flatten(x))
                .Where(x => x.Library.Type == "Package")
                .Distinct()
                .ToList();

            foreach (var dependency in flattenedList)
            {
                foreach (var assemblyToLoad in dependency.Library.Assemblies)
                {
                    Assembly.Load(new AssemblyName(assemblyToLoad));
                }
            }

            return loadedProjectAssembly;
        }
        private List<MetadataReference> GetApplicationReferences()
        {
            var references = new List<MetadataReference>();

            ILibraryExporter libraryExporter;
            if (_hostingEnvironment.IsDevelopment())
            {
                Project project;
                if (!Project.TryGetProject(_environment.ApplicationBasePath, out project))
                    return references;

                var engine = new CompilationEngine(
                    new CompilationEngineContext(
                        _environment,
                        _runtimeEnvironment,
                        _loader,
                        new CompilationCache()));

                libraryExporter = engine.CreateProjectExporter(
                    project, _environment.RuntimeFramework, _environment.Configuration);
            }
            else
            {
                libraryExporter = _libraryExporter;
            }

            // Get the MetadataReference for the executing application. If it's a Roslyn reference,
            // we can copy the references created when compiling the application to the Razor page being compiled.
            // This avoids performing expensive calls to MetadataReference.CreateFromImage.
            var libraryExport = libraryExporter.GetExport(_environment.ApplicationName);
            if (libraryExport?.MetadataReferences != null && libraryExport.MetadataReferences.Count > 0)
            {
                Debug.Assert(libraryExport.MetadataReferences.Count == 1,
                             "Expected 1 MetadataReferences, found " + libraryExport.MetadataReferences.Count);
                var roslynReference = libraryExport.MetadataReferences[0] as IRoslynMetadataReference;
                var compilationReference = roslynReference?.MetadataReference as CompilationReference;
                if (compilationReference != null)
                {
                    references.AddRange(compilationReference.Compilation.References);
                    references.Add(roslynReference.MetadataReference);

                    references.AddRange(_libraryManager
                            .GetAllMetadataReferences()
                            .OfType<IRoslynMetadataReference>()
                            .Select(x => x.MetadataReference));

                    return references;
                }
            }

            var export = libraryExporter.GetAllExports(_environment.ApplicationName);
            foreach (var metadataReference in export.MetadataReferences)
            {
                // Taken from https://github.com/aspnet/KRuntime/blob/757ba9bfdf80bd6277e715d6375969a7f44370ee/src/...
                // Microsoft.Framework.Runtime.Roslyn/RoslynCompiler.cs#L164
                // We don't want to take a dependency on the Roslyn bit directly since it pulls in more dependencies
                // than the view engine needs (Microsoft.Framework.Runtime) for example
                references.Add(ConvertMetadataReference(metadataReference));
            }

            return references;
        }
Пример #20
0
        private void Initialize(DefaultHostOptions options, IAssemblyLoadContextAccessor loadContextAccessor)
        {
            var applicationHostContext = new ApplicationHostContext
            {
                ProjectDirectory = _projectDirectory,
                RuntimeIdentifiers = _runtimeEnvironment.GetAllRuntimeIdentifiers(),
                TargetFramework = _targetFramework
            };

            var libraries = ApplicationHostContext.GetRuntimeLibraries(applicationHostContext, throwOnInvalidLockFile: true);

            Logger.TraceInformation("[{0}]: Project path: {1}", GetType().Name, applicationHostContext.ProjectDirectory);
            Logger.TraceInformation("[{0}]: Project root: {1}", GetType().Name, applicationHostContext.RootDirectory);
            Logger.TraceInformation("[{0}]: Project configuration: {1}", GetType().Name, options.Configuration);
            Logger.TraceInformation("[{0}]: Packages path: {1}", GetType().Name, applicationHostContext.PackagesDirectory);

            _applicationHostContext = applicationHostContext;

            _project = applicationHostContext.Project;

#if FEATURE_DNX_MIN_VERSION_CHECK
            ValidateMinRuntimeVersion(libraries);
#endif

            // Create a new Application Environment for running the app. It needs a reference to the Host's application environment
            // (if any), which we can get from the service provider we were given.
            // If this is null (i.e. there is no Host Application Environment), that's OK, the Application Environment we are creating
            // will just have it's own independent set of global data.
            var hostEnvironment = PlatformServices.Default.Application;
            var applicationEnvironment = new ApplicationEnvironment(Project, _targetFramework, hostEnvironment);

            var compilationContext = new CompilationEngineContext(
                applicationEnvironment,
                _runtimeEnvironment,
                loadContextAccessor.Default,
                new CompilationCache());

            var compilationEngine = new CompilationEngine(compilationContext);
            var runtimeLibraryExporter = new RuntimeLibraryExporter(() => compilationEngine.CreateProjectExporter(Project, _targetFramework, options.Configuration));

            var runtimeLibraryManager = new RuntimeLibraryManager(applicationHostContext);

            // Default services
            _serviceProvider.Add(typeof(ILibraryExporter), runtimeLibraryExporter);
            _serviceProvider.Add(typeof(IApplicationEnvironment), applicationEnvironment);
            _serviceProvider.Add(typeof(IRuntimeEnvironment), PlatformServices.Default.Runtime);
            _serviceProvider.Add(typeof(ILibraryManager), runtimeLibraryManager);
            _serviceProvider.Add(typeof(IAssemblyLoadContextAccessor), PlatformServices.Default.AssemblyLoadContextAccessor);
            _serviceProvider.Add(typeof(IAssemblyLoaderContainer), PlatformServices.Default.AssemblyLoaderContainer);
            
            PlatformServices.SetDefault(new ApplicationHostPlatformServices(PlatformServices.Default, applicationEnvironment, runtimeLibraryManager));

            if (options.CompilationServerPort.HasValue)
            {
                // Change the project reference provider
                Project.DefaultCompiler = Project.DefaultDesignTimeCompiler;
                Project.DesignTimeCompilerPort = options.CompilationServerPort.Value;
            }

            // TODO: Dedupe this logic in the RuntimeLoadContext
            var projects = libraries.Where(p => p.Type == Runtime.LibraryTypes.Project)
                                    .ToDictionary(p => p.Identity.Name, p => (ProjectDescription)p);

            var assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries);

            // Configure Assembly loaders
            _loaders.Add(new ProjectAssemblyLoader(loadContextAccessor, compilationEngine, projects.Values, options.Configuration));
            _loaders.Add(new PackageAssemblyLoader(loadContextAccessor, assemblies, libraries));

            var compilerOptionsProvider = new CompilerOptionsProvider(projects);

            _serviceProvider.Add(typeof(ICompilerOptionsProvider), compilerOptionsProvider);

            CompilationServices.SetDefault(
                    CompilationServices.Create(
                            libraryExporter: runtimeLibraryExporter,
                            compilerOptionsProvider: compilerOptionsProvider
                        )
                );

#if DNX451
            PackageDependencyProvider.EnableLoadingNativeLibraries(libraries);
#endif
            AddBreadcrumbs(libraries);
        }
Пример #21
0
        public void Main(string[] args)
        {
            var applicationEnvironment = _serviceProvider.GetService<IApplicationEnvironment>();
            var runtimeEnvironment = _serviceProvider.GetService<IRuntimeEnvironment>();
            var assemblyLoadContextAccessor = _serviceProvider.GetService<IAssemblyLoadContextAccessor>();

            var moduleContext = new ModuleLoaderContext(
                @"d:\TIEBug\ConsoleApp1\src\ClassLibrary1",
                applicationEnvironment.RuntimeFramework);

            var engine = new CompilationEngine(new CompilationEngineContext(
                applicationEnvironment,
                runtimeEnvironment,
                assemblyLoadContextAccessor.Default,
                new CompilationCache()));

            var exporter = engine.CreateProjectExporter(
                moduleContext.Project,
                moduleContext.TargetFramework,
                applicationEnvironment.Configuration);

            // Throws Target Invocation Exception here.
            var exports = exporter.GetExport(moduleContext.Project.Name);
        }
Пример #22
0
        public static LibraryExport ExportProject(Project project, CompilationEngine compilationEngine, string aspect, FrameworkName targetFramework, string configuration)
        {
            Logger.TraceInformation($"[{nameof(ProjectExporter)}]: {nameof(ExportProject)}({project.Name}, {aspect}, {targetFramework}, {configuration})");

            var targetFrameworkInformation = project.GetTargetFramework(targetFramework);

            // This is the target framework defined in the project. If there were no target frameworks
            // defined then this is the targetFramework specified
            if (targetFrameworkInformation.FrameworkName != null)
            {
                targetFramework = targetFrameworkInformation.FrameworkName;
            }

            var key = Tuple.Create(project.Name, targetFramework, configuration, aspect);

            return compilationEngine.CompilationCache.Cache.Get<LibraryExport>(key, ctx =>
            {
                var metadataReferences = new List<IMetadataReference>();
                var sourceReferences = new List<ISourceReference>();

                if (!string.IsNullOrEmpty(targetFrameworkInformation.AssemblyPath))
                {
                    // Project specifies a pre-compiled binary. We're done!

                    var assemblyPath = ResolvePath(project, configuration, targetFrameworkInformation.AssemblyPath);
                    var pdbPath = ResolvePath(project, configuration, targetFrameworkInformation.PdbPath);

                    metadataReferences.Add(new CompiledProjectMetadataReference(project.ToCompilationContext(targetFramework, configuration, aspect), assemblyPath, pdbPath));
                }
                else
                {
                    // We need to compile the project.

                    var provider = project.CompilerServices?.ProjectCompiler ?? Project.DefaultCompiler;

                    // Find the project compiler
                    var projectCompiler = compilationEngine.GetCompiler(provider);

                    Logger.TraceInformation("[{0}]: GetProjectReference({1}, {2}, {3}, {4})", provider.TypeName, project.Name, targetFramework, configuration, aspect);

                    // Get the exports for the project dependencies
                    var projectExport = new Lazy<LibraryExport>(() => ExportProjectDependencies(project, targetFramework, configuration, aspect, compilationEngine));

                    // Resolve the project export
                    IMetadataProjectReference projectReference = projectCompiler.CompileProject(
                        project.ToCompilationContext(targetFramework, configuration, aspect),
                        () => projectExport.Value,
                        () => CompositeResourceProvider.Default.GetResources(project));

                    metadataReferences.Add(projectReference);

                    // Shared sources
                    foreach (var sharedFile in project.Files.SharedFiles)
                    {
                        sourceReferences.Add(new SourceFileReference(sharedFile));
                    }
                }

                return new LibraryExport(metadataReferences, sourceReferences);
            });
        }
Пример #23
0
 private static LibraryExport ExportProjectDependencies(Project project, FrameworkName targetFramework, string configuration, string aspect, CompilationEngine compilationEngine)
 {
     return compilationEngine
         .CreateProjectExporter(project, targetFramework, configuration)
         .GetAllDependencies(project.Name, aspect);
 }
Пример #24
0
        private void Initialize(RuntimeOptions options, IServiceProvider hostServices, IAssemblyLoadContextAccessor loadContextAccessor, IFileWatcher fileWatcher)
        {
            var applicationHostContext = new ApplicationHostContext
            {
                ProjectDirectory = _projectDirectory,
                TargetFramework = _targetFramework
            };

            ApplicationHostContext.Initialize(applicationHostContext);

            Logger.TraceInformation("[{0}]: Project path: {1}", GetType().Name, applicationHostContext.ProjectDirectory);
            Logger.TraceInformation("[{0}]: Project root: {1}", GetType().Name, applicationHostContext.RootDirectory);
            Logger.TraceInformation("[{0}]: Project configuration: {1}", GetType().Name, options.Configuration);
            Logger.TraceInformation("[{0}]: Packages path: {1}", GetType().Name, applicationHostContext.PackagesDirectory);

            _libraryManager = applicationHostContext.LibraryManager;

            _project = applicationHostContext.Project;

            if (options.WatchFiles)
            {
                fileWatcher.OnChanged += _ =>
                {
                    _shutdown.RequestShutdownWaitForDebugger();
                };
            }

            // Create a new Application Environment for running the app. It needs a reference to the Host's application environment
            // (if any), which we can get from the service provider we were given.
            // If this is null (i.e. there is no Host Application Environment), that's OK, the Application Environment we are creating
            // will just have it's own independent set of global data.
            var hostEnvironment = (IApplicationEnvironment)hostServices.GetService(typeof(IApplicationEnvironment));
            var applicationEnvironment = new ApplicationEnvironment(Project, _targetFramework, options.Configuration, hostEnvironment);

            var compilationContext = new CompilationEngineContext(applicationEnvironment, loadContextAccessor.Default, new CompilationCache(), fileWatcher, new ProjectGraphProvider());

            // Compilation services available only for runtime compilation
            compilationContext.AddCompilationService(typeof(RuntimeOptions), options);
            compilationContext.AddCompilationService(typeof(IApplicationShutdown), _shutdown);

            var compilationEngine = new CompilationEngine(compilationContext);

            // Default services
            _serviceProvider.Add(typeof(IApplicationEnvironment), applicationEnvironment);
            _serviceProvider.Add(typeof(ILibraryManager), _libraryManager);

            // TODO: Make this lazy
            _serviceProvider.Add(typeof(ILibraryExporter), compilationEngine.CreateProjectExporter(Project, _targetFramework, options.Configuration));
            _serviceProvider.Add(typeof(IApplicationShutdown), _shutdown);
            _serviceProvider.Add(typeof(ICompilerOptionsProvider), new CompilerOptionsProvider(_libraryManager));

            if (options.CompilationServerPort.HasValue)
            {
                // Change the project reference provider
                Project.DefaultCompiler = Project.DefaultDesignTimeCompiler;
            }

            CallContextServiceLocator.Locator.ServiceProvider = ServiceProvider;

            // Configure Assembly loaders
            _loaders.Add(new ProjectAssemblyLoader(
                loadContextAccessor,
                compilationEngine,
                _libraryManager));

            _loaders.Add(new PackageAssemblyLoader(loadContextAccessor, _libraryManager));
        }
Пример #25
0
        public static LibraryExport ExportProject(Project project, CompilationEngine compilationEngine, string aspect, FrameworkName targetFramework, string configuration)
        {
            Logger.TraceInformation($"[{nameof(ProjectExporter)}]: {nameof(ExportProject)}({project.Name}, {aspect}, {targetFramework}, {configuration})");

            var targetFrameworkInformation = project.GetTargetFramework(targetFramework);

            // This is the target framework defined in the project. If there were no target frameworks
            // defined then this is the targetFramework specified
            if (targetFrameworkInformation.FrameworkName != null)
            {
                targetFramework = targetFrameworkInformation.FrameworkName;
            }

            var key = Tuple.Create(project.Name, targetFramework, configuration, aspect);

            return(compilationEngine.CompilationCache.Cache.Get <LibraryExport>(key, ctx =>
            {
                var metadataReferences = new List <IMetadataReference>();
                var sourceReferences = new List <ISourceReference>();

                if (!string.IsNullOrEmpty(targetFrameworkInformation.AssemblyPath))
                {
                    // Project specifies a pre-compiled binary. We're done!

                    var assemblyPath = ResolvePath(project, configuration, targetFrameworkInformation.AssemblyPath);
                    var pdbPath = ResolvePath(project, configuration, targetFrameworkInformation.PdbPath);

                    metadataReferences.Add(new CompiledProjectMetadataReference(project.ToCompilationContext(targetFramework, configuration, aspect), assemblyPath, pdbPath));
                }
                else
                {
                    // We need to compile the project.

                    var provider = project.CompilerServices?.ProjectCompiler ?? Project.DefaultCompiler;

                    // Find the project compiler
                    var projectCompiler = compilationEngine.GetCompiler(provider);

                    Logger.TraceInformation("[{0}]: GetProjectReference({1}, {2}, {3}, {4})", provider.TypeName, project.Name, targetFramework, configuration, aspect);

                    // Get the exports for the project dependencies
                    var projectExport = new Lazy <LibraryExport>(() => ExportProjectDependencies(project, targetFramework, configuration, aspect, compilationEngine));

                    // Resolve the project export
                    IMetadataProjectReference projectReference = projectCompiler.CompileProject(
                        project.ToCompilationContext(targetFramework, configuration, aspect),
                        () => projectExport.Value,
                        () => CompositeResourceProvider.Default.GetResources(project));

                    metadataReferences.Add(projectReference);

                    // Shared sources
                    foreach (var sharedFile in project.Files.SharedFiles)
                    {
                        sourceReferences.Add(new SourceFileReference(sharedFile));
                    }
                }

                return new LibraryExport(metadataReferences, sourceReferences);
            }));
        }
Пример #26
0
 public LibraryExporter(LibraryManager manager, CompilationEngine compilationEngine, string configuration)
 {
     LibraryManager     = manager;
     _compilationEngine = compilationEngine;
     _configuration     = configuration;
 }
Пример #27
0
        public EdgeAssemblyLoadContext(EdgeAssemblyLoadContextAccessor loadContextAccessor)
        {
            DebugMessage("EdgeAssemblyLoadContext::ctor (CLR) - Starting");
            DebugMessage("EdgeAssemblyLoadContext::ctor (CLR) - Application root is {0}", RuntimeEnvironment.ApplicationDirectory);

            _loadContextAccessor = loadContextAccessor;

            if (File.Exists(Path.Combine(RuntimeEnvironment.ApplicationDirectory, "project.lock.json")))
            {
                IList<LibraryDescription> libraries = ApplicationHostContext.GetRuntimeLibraries(ApplicationHostContext);
                Dictionary<string, ProjectDescription> projects = libraries.Where(p => p.Type == LibraryTypes.Project).ToDictionary(p => p.Identity.Name, p => (ProjectDescription)p);
                Dictionary<AssemblyName, string> assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries);
                
                CompilationEngineContext compilationContext = new CompilationEngineContext(ApplicationEnvironment, RuntimeEnvironment, this, new CompilationCache());
                CompilationEngine compilationEngine = new CompilationEngine(compilationContext);

                AddCompileAssemblies(libraries);

                _loaders.Add(new ProjectAssemblyLoader(_loadContextAccessor, compilationEngine, projects.Values));
                _loaders.Add(new PackageAssemblyLoader(_loadContextAccessor, assemblies, libraries));
            }

            else
            {
                _noProjectJsonFile = true;

                if (File.Exists(Path.Combine(RuntimeEnvironment.EdgeNodePath, "project.lock.json")))
                {
                    ApplicationHostContext stockHostContext = new ApplicationHostContext
                    {
                        ProjectDirectory = RuntimeEnvironment.EdgeNodePath,
                        TargetFramework = TargetFrameworkName
                    };

                    IList<LibraryDescription> libraries = ApplicationHostContext.GetRuntimeLibraries(stockHostContext);
                    Dictionary<AssemblyName, string> assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries);

                    AddCompileAssemblies(libraries);

                    _loaders.Add(new PackageAssemblyLoader(_loadContextAccessor, assemblies, libraries));
                }
            }

            DebugMessage("EdgeAssemblyLoadContext::ctor (CLR) - Created the dependency providers for the application");
        }
Пример #28
0
        public Assembly Load(AssemblyName assemblyName)
        {
            return _cache.Get<Assembly>(assemblyName.Name, cacheContext =>
            {
                var reference = _libraryManager.GetMetadataReference(assemblyName.Name);

                if (reference is MetadataFileReference)
                {
                    var fileReference = (MetadataFileReference)reference;

                    var assembly = _assemblyLoadContextAccessor
                        .Default
                        .LoadFile(fileReference.Path);

                    return assembly;
                }

                var projectPath = Path.Combine(_path, assemblyName.Name);

                if (!Project.HasProjectFile(projectPath))
                {
                    return null;
                }

                var moduleContext = new ModuleLoaderContext(
                    projectPath,
                    _applicationEnvironment.RuntimeFramework);

                foreach (var lib in moduleContext.LibraryManager.GetLibraries())
                {
                    _libraryManager.AddLibrary(lib);
                }

                var ctx = new CompilationEngineContext(
                    _applicationEnvironment,
                    _runtimeEnvironment,
                    _assemblyLoadContextAccessor.Default,
                    new CompilationCache());

                var engine = new CompilationEngine(ctx);

                var exporter = engine.CreateProjectExporter(
                    moduleContext.Project, moduleContext.TargetFramework, _applicationEnvironment.Configuration);

                var exports = exporter.GetAllExports(moduleContext.Project.Name);

                foreach (var metadataReference in exports.MetadataReferences)
                {
                    _libraryManager.AddMetadataReference(metadataReference);
                }

                //LibraryExport projectExport = exporter.GetExport(moduleContext.Project.Name);
                //IMetadataProjectReference projectRef = (IMetadataProjectReference)projectExport.MetadataReferences.First();

                //string exportDir = Path.Combine(moduleContext.Project.ProjectDirectory, "export");
                //projectRef.EmitAssembly(exportDir);

                //string assemblyPath = Path.Combine(exportDir, moduleContext.Project.Name + ".dll");

                Assembly pluginAssm = engine.LoadProject(
                    moduleContext.Project, moduleContext.FrameworkName, null, _assemblyLoadContextAccessor.Default,
                    new AssemblyName(moduleContext.Project.Name));

                IList<LibraryDependency> flattenedList = moduleContext
                    .Project
                    .Dependencies
                    .SelectMany(Flatten)
                    .Where(x => x.Library.Type == "Package")
                    .Distinct()
                    .ToList();

                //foreach (var dependency in flattenedList)
                //{
                //    foreach (var assemblyToLoad in dependency.Library.Assemblies)
                //    {
                //        Assembly.Load(new AssemblyName(assemblyToLoad));
                //    }
                //}

                return pluginAssm;
            });
        }