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(); } }
public ProjectStateResolver(CompilationEngine compilationEngine, FrameworkReferenceResolver frameworkReferenceResolver, Func <CacheContext, Project, FrameworkName, ApplicationHostContext> applicaitonHostContextCreator) { _compilationEngine = compilationEngine; _frameworkReferenceResolver = frameworkReferenceResolver; _applicationHostContextCreator = applicaitonHostContextCreator; }
/// <summary> /// this will call our top level module that will set up and invoke the other modules. /// </summary> private void AnalyzeFile() { //creating a compilationEngine class for this file. //the CompilationEngine will then take care of creating the JackTokenizer and compiling the given class var compileEngine = new CompilationEngine(_fileName, _fileName.Replace(".jack", ".xml")); rtbDestination.Text = compileEngine.Xml; //check for errors if (compileEngine.HasErrors) { var errorTokens = from t in compileEngine.Tokens where !string.IsNullOrEmpty(t.Error) select t; foreach (var error in errorTokens) { //Select the line from it's number var errorLine = error.LineNo - 1; var startIndex = rtbSource.GetFirstCharIndexFromLine(errorLine) + error.CharNo; var currentChar = rtbSource.GetCharFromPosition(rtbSource.GetPositionFromCharIndex(startIndex)).ToString(); var length = 0; var currentIndex = startIndex; while (currentChar != "\n") { currentIndex++; length++; currentChar = rtbSource.GetCharFromPosition(rtbSource.GetPositionFromCharIndex(currentIndex)).ToString(); } //rtbSource.Select(rtbSource.GetFirstCharIndexFromLine(errorLine), currentIndex - rtbSource.GetFirstCharIndexFromLine(errorLine)); //rtbSource.SelectedText += " error: " + error.Error; rtbSource.Select(startIndex, 1); //Set the selected text fore and background color rtbSource.SelectionColor = System.Drawing.Color.Black; rtbSource.SelectionBackColor = System.Drawing.Color.Red; //rtbSource.Select(currentIndex, error.Error.Length + 8); ////Set the selected text fore and background color //rtbSource.SelectionColor = System.Drawing.Color.Black; //rtbSource.SelectionBackColor = System.Drawing.Color.Orange; rtbSource.DeselectAll(); } lblStatus.Text = "Compilation failed! Error count = " + errorTokens.Count() + "; line: " + errorTokens.First().LineNo + "; char: " + errorTokens.First().CharNo + "; Error Message: " + errorTokens.First().Error; rtbErrors.Text = "Compilation failed! Error count = " + errorTokens.Count() + "; line: " + errorTokens.First().LineNo + "; char: " + errorTokens.First().CharNo + "; Error Message: " + errorTokens.First().Error; rtbErrors.Text += Environment.NewLine + "Stack Trace: " + errorTokens.First().StackTrace; frmStatus.Refresh(); } }
/// <summary> /// Starts the P# compilation process. /// </summary> public void Start() { foreach (var target in this.CompilationContext.Configuration.CompilationTargets) { Output.PrintLine(". Compiling for " + target); this.CompilationContext.ActiveCompilationTarget = target; // Creates and runs a P# compilation engine. CompilationEngine.Create(this.CompilationContext).Run(); } }
/// <summary> /// Starts the P# compiler. /// </summary> public static void Run() { if (Configuration.NoCompilation) { return; } Output.Print(". Compiling"); // Runs the P# compilation engine. CompilationEngine.Run(); }
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); }
/// <summary> /// Starts the P# compilation process. /// </summary> public void Start() { if (this.CompilationContext.Configuration.CompilationTarget == CompilationTarget.Testing) { Output.WriteLine($". Compiling ({this.CompilationContext.Configuration.CompilationTarget})"); } else { Output.WriteLine($". Compiling ({this.CompilationContext.Configuration.CompilationTarget}::" + $"{this.CompilationContext.Configuration.OptimizationTarget})"); } // Creates and runs a P# compilation engine. CompilationEngine.Create(this.CompilationContext, this.Logger).Run(); }
/// <summary> /// Starts the P# compilation process. /// </summary> public void Start() { if (this.CompilationContext.Configuration.CompilationTarget == CompilationTarget.Testing) { IO.PrintLine($". Compiling ({this.CompilationContext.Configuration.CompilationTarget})"); } else { IO.PrintLine($". Compiling ({this.CompilationContext.Configuration.CompilationTarget}::" + $"{this.CompilationContext.Configuration.OptimizationTarget})"); } // Creates and runs a P# compilation engine. CompilationEngine.Create(this.CompilationContext).Run(); }
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); }
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; }
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"); }
/// <summary> /// Create a new proxy type. /// </summary> /// <param name="interfaceType">Type</param> /// <param name="actorMachineType">Actor machine type</param> /// <param name="assemblyPath">Assembly path</param> /// <returns>Type</returns> private Type CreateProxyType(Type interfaceType, Type actorMachineType, string assemblyPath) { if (!interfaceType.IsInterface) { throw new InvalidOperationException(); } var actorType = this.GetActorType(interfaceType, assemblyPath); var references = new HashSet <MetadataReference>(); references.Add(MetadataReference.CreateFromFile(actorType.Assembly.Location)); references.Add(MetadataReference.CreateFromFile(typeof(ActorMachine).Assembly.Location)); foreach (var referencedAssembly in actorType.Assembly.GetReferencedAssemblies()) { references.Add(MetadataReference.CreateFromFile(Assembly.Load(referencedAssembly).Location)); } SyntaxTree syntaxTree = this.CreateProxySyntaxTree(interfaceType, actorType, actorMachineType); //Console.WriteLine(syntaxTree); var context = CompilationContext.Create().LoadSolution(syntaxTree.ToString(), references, "cs"); var compilation = context.GetSolution().Projects.First().GetCompilationAsync().Result; syntaxTree = context.GetSolution().Projects.First().Documents.First().GetSyntaxTreeAsync().Result; SemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree); var typeSymbol = semanticModel.GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes() .OfType <ClassDeclarationSyntax>().First()); compilation = compilation.WithAssemblyName(interfaceType.Name + "_PSharpProxy"); compilation = compilation.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); string proxyAssemblyPath = CompilationEngine.Create(context).ToFile(compilation, OutputKind.DynamicallyLinkedLibrary, Assembly.GetExecutingAssembly().Location, false, false); Assembly proxyAssembly = Assembly.LoadFrom(proxyAssemblyPath); Type proxyType = proxyAssembly.GetType(typeSymbol.ContainingNamespace.ToString() + "." + typeSymbol.MetadataName); return(proxyType); }
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); foreach (LibraryDescription libraryDescription in libraries.Where(l => l.Type == LibraryTypes.Package)) { PackageDescription packageDescription = (PackageDescription)libraryDescription; if (packageDescription.Target.CompileTimeAssemblies != null && packageDescription.Target.CompileTimeAssemblies.Count > 0) { CompileAssemblies[libraryDescription.Identity.Name] = Path.Combine(packageDescription.Path, packageDescription.Target.CompileTimeAssemblies[0].Path); } else { CompileAssemblies[libraryDescription.Identity.Name] = Path.Combine(packageDescription.Path, packageDescription.Target.RuntimeAssemblies[0].Path); } } _loaders.Add(new ProjectAssemblyLoader(_loadContextAccessor, compilationEngine, projects.Values)); _loaders.Add(new PackageAssemblyLoader(_loadContextAccessor, assemblies, libraries)); } else { _noProjectJsonFile = true; } DebugMessage("EdgeAssemblyLoadContext::ctor (CLR) - Created the dependency providers for the application"); }
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; }
public ApplicationContext(IServiceProvider services, IApplicationEnvironment applicationEnvironment, IRuntimeEnvironment runtimeEnvironment, IAssemblyLoadContextAccessor loadContextAccessor, ProtocolManager protocolManager, CompilationEngine compilationEngine, FrameworkReferenceResolver frameworkResolver, int id) { _applicationEnvironment = applicationEnvironment; _runtimeEnvironment = runtimeEnvironment; _defaultLoadContext = loadContextAccessor.Default; _pluginHandler = new PluginHandler(services, SendPluginMessage); _protocolManager = protocolManager; _compilationEngine = compilationEngine; _frameworkResolver = frameworkResolver; Id = id; _projectStateResolver = new ProjectStateResolver( _compilationEngine, _frameworkResolver, (ctx, project, frameworkName) => CreateApplicationHostContext(ctx, project, frameworkName, Enumerable.Empty <string>())); }
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); })); }
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); }
private void Initialize(RuntimeOptions options, IServiceProvider hostServices, IAssemblyLoadContextAccessor loadContextAccessor, IFileWatcher fileWatcher) { 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; ValidateMinRuntimeVersion(libraries); 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, _runtimeEnvironment, loadContextAccessor.Default, new CompilationCache(), fileWatcher); // 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), new RuntimeLibraryManager(applicationHostContext)); _serviceProvider.Add(typeof(ILibraryExporter), new RuntimeLibraryExporter(() => compilationEngine.CreateProjectExporter(Project, _targetFramework, options.Configuration))); _serviceProvider.Add(typeof(IApplicationShutdown), _shutdown); if (options.CompilationServerPort.HasValue) { // Change the project reference provider Project.DefaultCompiler = Project.DefaultDesignTimeCompiler; } CallContextServiceLocator.Locator.ServiceProvider = ServiceProvider; // TODO: Dedupe this logic in the RuntimeLoadContext var projects = libraries.Where(p => p.Type == 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)); _loaders.Add(new PackageAssemblyLoader(loadContextAccessor, assemblies)); _serviceProvider.Add(typeof(ICompilerOptionsProvider), new CompilerOptionsProvider(projects)); AddBreadcrumbs(libraries); }
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)); }
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); }
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, _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 == LibraryTypes.Package) .Distinct() .ToList(); foreach (var dependency in flattenedList) { foreach (var assemblyToLoad in dependency.Library.Assemblies) { Assembly.Load(new AssemblyName(assemblyToLoad)); } } return(loadedProjectAssembly); }