Exemplo n.º 1
1
        public static CompilationResult GetAssemblyFromCompilation(
            IAssemblyLoadContext loader,
            Compilation compilation)
        {
            EmitResult result;
            using (var ms = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    if (PlatformHelper.IsMono)
                    {
                        result = compilation.Emit(ms, pdbStream: null);
                    }
                    else
                    {
                        result = compilation.Emit(ms, pdbStream: pdb);
                    }

                    if (!result.Success)
                    {
                        var formatter = new DiagnosticFormatter();
                        var errorMessages = result.Diagnostics
                                             .Where(IsError)
                                             .Select(d => formatter.Format(d));

                        return CompilationResult.FromErrorMessages(errorMessages);
                    }

                    ms.Seek(0, SeekOrigin.Begin);

                    Assembly assembly;
                    if (PlatformHelper.IsMono)
                    {
                        assembly = loader.LoadStream(ms, assemblySymbols: null);
                    }
                    else
                    {
                        pdb.Seek(0, SeekOrigin.Begin);
                        assembly = loader.LoadStream(ms, pdb);
                    }

                    return CompilationResult.FromAssembly(assembly);
                }
            }
        }
Exemplo n.º 2
0
 protected T InvokeProtectedMethodOnLoadContextAndGetResult <T>(IAssemblyLoadContext loadContext, string methodName, params object[] args)
 {
     return((T)loadContext
            .GetType()
            .GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(loadContext, args));
 }
Exemplo n.º 3
0
 public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                 IRuntimeEnvironment runtimeEnvironment,
                                 IAssemblyLoadContext defaultLoadContext,
                                 CompilationCache cache) :
     this(applicationEnvironment, runtimeEnvironment, defaultLoadContext, cache, NoopWatcher.Instance)
 {
 }
Exemplo n.º 4
0
 public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                 IRuntimeEnvironment runtimeEnvironment,
                                 IAssemblyLoadContext defaultLoadContext,
                                 CompilationCache cache)
     : this(applicationEnvironment, runtimeEnvironment, defaultLoadContext, cache, NoopWatcher.Instance)
 {
 }
Exemplo n.º 5
0
 public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                 IAssemblyLoadContext defaultLoadContext,
                                 CompilationCache cache,
                                 IProjectGraphProvider projectGraphProvider) :
     this(applicationEnvironment, defaultLoadContext, cache, NoopWatcher.Instance, projectGraphProvider)
 {
 }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InProcDataCollector"/> class.
        /// </summary>
        /// <param name="codeBase">
        /// </param>
        /// <param name="assemblyQualifiedName">
        /// </param>
        /// <param name="interfaceTypeInfo">
        /// </param>
        /// <param name="configXml">
        /// </param>
        /// <param name="assemblyLoadContext">
        /// </param>
        internal InProcDataCollector(string codeBase, string assemblyQualifiedName, TypeInfo interfaceTypeInfo, string configXml, IAssemblyLoadContext assemblyLoadContext, TestPluginCache testPluginCache)
        {
            this.configXml           = configXml;
            this.assemblyLoadContext = assemblyLoadContext;

            var assembly = this.LoadInProcDataCollectorExtension(codeBase);

            Func <Type, bool> filterPredicate;

            if (Path.GetFileName(codeBase) == Constants.CoverletDataCollectorCodebase)
            {
                // If we're loading coverlet collector we skip to check the version of assembly
                // to allow upgrade throught nuget package
                filterPredicate = (x) => x.FullName.Equals(Constants.CoverletDataCollectorTypeName) && interfaceTypeInfo.IsAssignableFrom(x.GetTypeInfo());

                // Coverlet collector is consumed as nuget package we need to add assemblies directory to resolver to correctly load references.
                Debug.Assert(Path.IsPathRooted(codeBase), "Absolute path expected");
                testPluginCache.AddResolverSearchDirectories(new string[] { Path.GetDirectoryName(codeBase) });
            }
            else
            {
                filterPredicate = (x) => x.AssemblyQualifiedName.Equals(assemblyQualifiedName) && interfaceTypeInfo.IsAssignableFrom(x.GetTypeInfo());
            }

            this.dataCollectorType     = assembly?.GetTypes().FirstOrDefault(filterPredicate);
            this.AssemblyQualifiedName = this.dataCollectorType?.AssemblyQualifiedName;
        }
Exemplo n.º 7
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            // An assembly name like "MyLibrary!alternate!more-text"
            // is parsed into:
            // name == "MyLibrary"
            // aspect == "alternate"
            // and the more-text may be used to force a recompilation of an aspect that would
            // otherwise have been cached by some layer within Assembly.Load

            var name = assemblyName.Name;
            string aspect = null;
            var parts = name.Split(new[] { '!' }, 3);
            if (parts.Length != 1)
            {
                name = parts[0];
                aspect = parts[1];
            }

            Project project;
            if (!_projectResolver.TryResolveProject(name, out project))
            {
                return null;
            }

            return _compilationEngine.LoadProject(
                project,
                aspect,
                loadContext);
        }
Exemplo n.º 8
0
        public AssemblyLoadContextFactory(IServiceProvider serviceProvider)
        {
            var accessor = serviceProvider.GetService(typeof(IAssemblyLoadContextAccessor)) as IAssemblyLoadContextAccessor;

            _serviceProvider = serviceProvider;
            _defaultContext  = accessor.Default;
        }
Exemplo n.º 9
0
        private void PluginMessage(PluginMessage message, IAssemblyLoadContext assemblyLoadContext)
        {
            IPlugin plugin;

            if (_registeredPlugins.TryGetValue(message.PluginId, out plugin))
            {
                try
                {
                    plugin.ProcessMessage(message.Data, assemblyLoadContext);
                }
                catch (Exception exception)
                {
                    OnError(
                        message.PluginId,
                        PluginMessageMessageName,
                        errorMessage: Resources.FormatPlugin_EncounteredExceptionWhenProcessingPluginMessage(
                            message.PluginId,
                            exception.Message));
                }
            }
            else
            {
                OnError(
                    message.PluginId,
                    PluginMessageMessageName,
                    errorMessage: Resources.FormatPlugin_UnregisteredPluginIdCannotReceiveMessages(message.PluginId));
            }
        }
Exemplo n.º 10
0
        public void ProcessMessages(IAssemblyLoadContext assemblyLoadContext)
        {
            if (assemblyLoadContext == null)
            {
                throw new ArgumentNullException(nameof(assemblyLoadContext));
            }

            while (_messageQueue.Count > 0)
            {
                var message = _messageQueue.Dequeue();

                switch (message.MessageName)
                {
                case RegisterPluginMessageName:
                    RegisterMessage(message, assemblyLoadContext);
                    break;

                case UnregisterPluginMessageName:
                    UnregisterMessage(message);
                    break;

                case PluginMessageMessageName:
                    PluginMessage(message, assemblyLoadContext);
                    break;

                default:
                    OnNoop(
                        message,
                        Resources.FormatPlugin_PluginHandlerCouldNotHandleMessage(
                            message.MessageName,
                            message.PluginId));
                    break;
                }
            }
        }
Exemplo n.º 11
0
        public void TryRegisterFaultedPlugins(IAssemblyLoadContext assemblyLoadContext)
        {
            if (assemblyLoadContext == null)
            {
                throw new ArgumentNullException(nameof(assemblyLoadContext));
            }

            // Capture the messages here so we can clear the original list to potentially re-add messages if they
            // fail to recover.
            var faultedRegistrations = _faultedRegisterPluginMessages.ToArray();
            _faultedRegisterPluginMessages.Clear();

            foreach (var faultedRegisterPluginMessage in faultedRegistrations)
            {
                var response = RegisterPlugin(faultedRegisterPluginMessage, assemblyLoadContext);

                if (response.Success)
                {
                    SendMessage(faultedRegisterPluginMessage.PluginId, response);
                }
                else
                {
                    // We were unable to recover, re-add the faulted register plugin message.
                    _faultedRegisterPluginMessages.Add(faultedRegisterPluginMessage);
                }
            }
        }
Exemplo n.º 12
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            // An assembly name like "MyLibrary!alternate!more-text"
            // is parsed into:
            // name == "MyLibrary"
            // aspect == "alternate"
            // and the more-text may be used to force a recompilation of an aspect that would
            // otherwise have been cached by some layer within Assembly.Load

            var name = assemblyName.Name;
            string aspect = null;
            var parts = name.Split(new[] { '!' }, 3);
            if (parts.Length != 1)
            {
                name = parts[0];
                aspect = parts[1];
            }

            var library = _libraryManager.GetLibraryDescription(name) as ProjectDescription;

            if (library == null)
            {
                return null;
            }

            return _compilationEngine.LoadProject(
                library.Project, 
                aspect, 
                loadContext);
        }
Exemplo n.º 13
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            // An assembly name like "MyLibrary!alternate!more-text"
            // is parsed into:
            // name == "MyLibrary"
            // aspect == "alternate"
            // and the more-text may be used to force a recompilation of an aspect that would
            // otherwise have been cached by some layer within Assembly.Load

            var    name   = assemblyName.Name;
            string aspect = null;
            var    parts  = name.Split(new[] { '!' }, 3);

            if (parts.Length != 1)
            {
                name   = parts[0];
                aspect = parts[1];
            }

            Project project;

            if (!_projectResolver.TryResolveProject(name, out project))
            {
                return(null);
            }

            return(_compilationEngine.LoadProject(
                       project,
                       aspect,
                       loadContext));
        }
Exemplo n.º 14
0
        public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                        IAssemblyLoadContext defaultLoadContext,
                                        CompilationCache cache) :
            this(applicationEnvironment, defaultLoadContext, cache, NoopWatcher.Instance, new ProjectGraphProvider())
        {

        }
Exemplo n.º 15
0
        public void ProcessMessages([NotNull] IAssemblyLoadContext assemblyLoadContext)
        {
            while (_messageQueue.Count > 0)
            {
                var message = _messageQueue.Dequeue();

                switch (message.MessageName)
                {
                case RegisterPluginMessageName:
                    RegisterMessage(message, assemblyLoadContext);
                    break;

                case UnregisterPluginMessageName:
                    UnregisterMessage(message);
                    break;

                case PluginMessageMessageName:
                    PluginMessage(message, assemblyLoadContext);
                    break;

                default:
                    OnNoop(
                        message,
                        Resources.FormatPlugin_PluginHandlerCouldNotHandleMessage(
                            message.MessageName,
                            message.PluginId));
                    break;
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Loads the assembly containing precompiled views. 
        /// </summary>
        /// <param name="loadContext">The <see cref="IAssemblyLoadContext"/>.</param>
        /// <returns>The <see cref="Assembly"/> containing precompiled views.</returns>
        public virtual Assembly LoadAssembly(IAssemblyLoadContext loadContext)
        {
            var viewCollectionAssembly = GetType().GetTypeInfo().Assembly;

            using (var assemblyStream = viewCollectionAssembly.GetManifestResourceStream(AssemblyResourceName))
            {
                if (assemblyStream == null)
                {
                    var message = Resources.FormatRazorFileInfoCollection_ResourceCouldNotBeFound(AssemblyResourceName,
                                                                                                  GetType().FullName);
                    throw new InvalidOperationException(message);
                }

                Stream symbolsStream = null;
                if (!string.IsNullOrEmpty(SymbolsResourceName))
                {
                    symbolsStream = viewCollectionAssembly.GetManifestResourceStream(SymbolsResourceName);
                }

                using (symbolsStream)
                {
                    return loadContext.LoadStream(assemblyStream, symbolsStream);
                }
            }
        }
Exemplo n.º 17
0
        private void PluginMessage(PluginMessage message, IAssemblyLoadContext assemblyLoadContext)
        {
            IPlugin plugin;

            if (_registeredPlugins.TryGetValue(message.PluginId, out plugin))
            {
                try
                {
                    if (!plugin.ProcessMessage(message.Data, assemblyLoadContext))
                    {
                        // Plugin didn't handle the message. Notify the client that we no-oped so it can respond
                        // accordingly.
                        OnNoop(
                            message,
                            Resources.FormatPlugin_PluginCouldNotHandleMessage(message.PluginId, message.MessageName));
                    }
                }
                catch (Exception exception)
                {
                    OnError(
                        message,
                        errorMessage: Resources.FormatPlugin_EncounteredExceptionWhenProcessingPluginMessage(
                            message.PluginId,
                            exception.Message));
                }
            }
            else
            {
                OnError(
                    message,
                    errorMessage: Resources.FormatPlugin_UnregisteredPluginIdCannotReceiveMessages(message.PluginId));
            }
        }
Exemplo n.º 18
0
        public static IEnumerable <Assembly> GetAssemblies(string path, IAssemblyLoaderContainer assemblyLoaderContainer, IAssemblyLoadContextAccessor assemblyLoadContextAccessor, ILibraryManager libraryManager)
        {
            List <Assembly> assemblies = new List <Assembly>();

            IAssemblyLoadContext assemblyLoadContext = assemblyLoadContextAccessor.Default;

            using (assemblyLoaderContainer.AddLoader(new DirectoryAssemblyLoader(path, assemblyLoadContext)))
            {
                foreach (string extensionPath in Directory.EnumerateFiles(path, "*.dll"))
                {
                    string extensionFilename = Path.GetFileNameWithoutExtension(extensionPath);

                    assemblies.Add(assemblyLoadContext.Load(extensionFilename));
                }
            }

            // We must not load all of the assemblies
            foreach (Library library in libraryManager.GetLibraries())
            {
                if (AssemblyManager.IsCandidateLibrary(libraryManager, library))
                {
                    assemblies.AddRange(library.Assemblies.Select(an => assemblyLoadContext.Load(an)));
                }
            }

            return(assemblies);
        }
Exemplo n.º 19
0
 public LibraryExporter(LibraryManager manager, IAssemblyLoadContext loadContext, CompilationEngine compilationEngine, string configuration)
 {
     LibraryManager     = manager;
     _compilationEngine = compilationEngine;
     _configuration     = configuration;
     _loadContext       = loadContext;
 }
        /// <summary>
        /// Loads the assembly containing precompiled views.
        /// </summary>
        /// <param name="loadContext">The <see cref="IAssemblyLoadContext"/>.</param>
        /// <returns>The <see cref="Assembly"/> containing precompiled views.</returns>
        public virtual Assembly LoadAssembly(IAssemblyLoadContext loadContext)
        {
            var viewCollectionAssembly = GetType().GetTypeInfo().Assembly;

            using (var assemblyStream = viewCollectionAssembly.GetManifestResourceStream(AssemblyResourceName))
            {
                if (assemblyStream == null)
                {
                    var message = Resources.FormatRazorFileInfoCollection_ResourceCouldNotBeFound(AssemblyResourceName,
                                                                                                  GetType().FullName);
                    throw new InvalidOperationException(message);
                }

                Stream symbolsStream = null;
                if (!string.IsNullOrEmpty(SymbolsResourceName))
                {
                    symbolsStream = viewCollectionAssembly.GetManifestResourceStream(SymbolsResourceName);
                }

                using (symbolsStream)
                {
                    return(loadContext.LoadStream(assemblyStream, symbolsStream));
                }
            }
        }
Exemplo n.º 21
0
 public LibraryExporter(LibraryManager manager, IAssemblyLoadContext loadContext, CompilationEngine compilationEngine, string configuration)
 {
     LibraryManager = manager;
     _compilationEngine = compilationEngine;
     _configuration = configuration;
     _loadContext = loadContext;
 }
Exemplo n.º 22
0
        public void TryRegisterFaultedPlugins(IAssemblyLoadContext assemblyLoadContext)
        {
            if (assemblyLoadContext == null)
            {
                throw new ArgumentNullException(nameof(assemblyLoadContext));
            }

            // Capture the messages here so we can clear the original list to potentially re-add messages if they
            // fail to recover.
            var faultedRegistrations = _faultedRegisterPluginMessages.ToArray();

            _faultedRegisterPluginMessages.Clear();

            foreach (var faultedRegisterPluginMessage in faultedRegistrations)
            {
                var response = RegisterPlugin(faultedRegisterPluginMessage, assemblyLoadContext);

                if (response.Success)
                {
                    SendMessage(faultedRegisterPluginMessage.PluginId, response);
                }
                else
                {
                    // We were unable to recover, re-add the faulted register plugin message.
                    _faultedRegisterPluginMessages.Add(faultedRegisterPluginMessage);
                }
            }
        }
Exemplo n.º 23
0
        public static T CreateService <T>(IServiceProvider sp, IAssemblyLoadContext loadContext, TypeInformation typeInfo)
        {
            var assembly = loadContext.Load(typeInfo.AssemblyName);

            var type = assembly.GetType(typeInfo.TypeName);

            return((T)ActivatorUtilities.CreateInstance(sp, type));
        }
Exemplo n.º 24
0
 public LibraryAssemblyLoadContext(ProjectAssemblyLoader projectAssemblyLoader,
                                   NuGetAssemblyLoader nugetAssemblyLoader,
                                   IAssemblyLoadContext defaultContext)
 {
     _projectAssemblyLoader = projectAssemblyLoader;
     _nugetAssemblyLoader = nugetAssemblyLoader;
     _defaultContext = defaultContext;
 }
 public RoslynCompilationService(IApplicationEnvironment environment,
                                 IAssemblyLoadContextAccessor accessor,
                                 ILibraryExporter libraryExporter)
 {
     _environment     = environment;
     _loader          = accessor.GetLoadContext(typeof(RoslynCompilationService).GetTypeInfo().Assembly);
     _libraryExporter = libraryExporter;
 }
Exemplo n.º 26
0
 public RuntimeLoadContext(LibraryManager libraryManager,
                           ICompilationEngine compilationEngine,
                           IAssemblyLoadContext defaultContext)
 {
     _projectAssemblyLoader = new ProjectAssemblyLoader(loadContextAccessor: null, compilationEngine: compilationEngine, libraryManager: libraryManager);
     _packageAssemblyLoader = new PackageAssemblyLoader(loadContextAccessor: null, libraryManager: libraryManager);
     _defaultContext        = defaultContext;
 }
Exemplo n.º 27
0
 public RuntimeLoadContext(LibraryManager libraryManager,
                           ICompilationEngine compilationEngine,
                           IAssemblyLoadContext defaultContext)
 {
     _projectAssemblyLoader = new ProjectAssemblyLoader(loadContextAccessor: null, compilationEngine: compilationEngine, libraryManager: libraryManager);
     _packageAssemblyLoader = new PackageAssemblyLoader(loadContextAccessor: null, libraryManager: libraryManager);
     _defaultContext = defaultContext;
 }
Exemplo n.º 28
0
 public LibraryAssemblyLoadContext(ProjectAssemblyLoader projectAssemblyLoader,
                                   NuGetAssemblyLoader nugetAssemblyLoader,
                                   IAssemblyLoadContext defaultContext) : base(defaultContext)
 {
     _projectAssemblyLoader = projectAssemblyLoader;
     _nugetAssemblyLoader   = nugetAssemblyLoader;
     _defaultContext        = defaultContext;
 }
 public RoslynCompilationService(IApplicationEnvironment environment,
                                 IAssemblyLoadContextAccessor accessor,
                                 ILibraryExporter libraryExporter)
 {
     _environment = environment;
     _loader = accessor.GetLoadContext(typeof(RoslynCompilationService).GetTypeInfo().Assembly);
     _libraryExporter = libraryExporter;
 }
Exemplo n.º 30
0
 /// <summary>
 /// Test logger manager.
 /// </summary>
 /// <param name="requestData"></param>
 /// <param name="messageLogger"></param>
 /// <param name="loggerEvents"></param>
 /// <param name="assemblyLoadContext"></param>
 internal TestLoggerManager(IRequestData requestData, IMessageLogger messageLogger,
                            InternalTestLoggerEvents loggerEvents, IAssemblyLoadContext assemblyLoadContext)
 {
     this.requestData   = requestData;
     this.messageLogger = messageLogger;
     this.testLoggerExtensionManager = null;
     this.loggerEvents        = loggerEvents;
     this.assemblyLoadContext = assemblyLoadContext;
 }
        public AssemblyLoader(
            IAssemblyDataProvider assemblyDataProvider,
            IAssemblyLoadContext assemblyLoadContext)
        {
            _assemblyDataProvider = assemblyDataProvider;
            _assemblyLoadContext  = assemblyLoadContext;

            _loadingAssemblies = new ConcurrentDictionary <AssemblyName, Task <Assembly?> >(
                AssemblyByNameAndVersionComparer.Default);
        }
Exemplo n.º 32
0
        public Assembly Load(string name, IAssemblyLoadContext loadContext)
        {
            PackageAssembly assemblyInfo;
            if (_dependencyResolver.PackageAssemblyLookup.TryGetValue(name, out assemblyInfo))
            {
                return loadContext.LoadFile(assemblyInfo.Path);
            }

            return null;
        }
Exemplo n.º 33
0
 public AssemblyCache(ILibraryManager manager,
     IAssemblyLoadContextAccessor accessor,
     IAssemblyLoaderContainer container,
     IApplicationEnvironment environment)
 {
     _libraryManager = manager;
     _environment = environment;
     _loadContext = accessor.GetLoadContext(typeof (Program).GetTypeInfo().Assembly);
     Loader = new DirectoryLookupAssemblyLoader(_loadContext);
     _loaderRegistration = container.AddLoader(Loader);
 }
Exemplo n.º 34
0
        public Assembly Load(string name, IAssemblyLoadContext loadContext)
        {
            PackageAssembly assemblyInfo;

            if (_dependencyResolver.PackageAssemblyLookup.TryGetValue(name, out assemblyInfo))
            {
                return(loadContext.LoadFile(assemblyInfo.Path));
            }

            return(null);
        }
Exemplo n.º 35
0
 /// <summary>
 /// Initalizes a new instance of the <see cref="RoslynCompilationService"/> class.
 /// </summary>
 /// <param name="environment">The environment for the executing application.</param>
 /// <param name="loaderEngine">The loader used to load compiled assemblies.</param>
 /// <param name="libraryManager">The library manager that provides export and reference information.</param>
 /// <param name="host">The <see cref="IMvcRazorHost"/> that was used to generate the code.</param>
 public RoslynCompilationService(IApplicationEnvironment environment,
                                 IAssemblyLoadContextAccessor loaderAccessor,
                                 ILibraryManager libraryManager,
                                 IMvcRazorHost host)
 {
     _environment           = environment;
     _loader                = loaderAccessor.GetLoadContext(typeof(RoslynCompilationService).GetTypeInfo().Assembly);
     _libraryManager        = libraryManager;
     _applicationReferences = new Lazy <List <MetadataReference> >(GetApplicationReferences);
     _classPrefix           = host.MainClassNamePrefix;
 }
Exemplo n.º 36
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            // TODO: preserve name and culture info (we don't need to look at any other information)
            string path;
            if (_assemblies.TryGetValue(new AssemblyName(assemblyName.Name), out path))
            {
                return loadContext.LoadFile(path);
            }

            return null;
        }
Exemplo n.º 37
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            // TODO: preserve name and culture info (we don't need to look at any other information)
            PackageAssembly assemblyInfo;
            if (_dependencyResolver.PackageAssemblyLookup.TryGetValue(new AssemblyName(assemblyName.Name), out assemblyInfo))
            {
                return loadContext.LoadFile(assemblyInfo.Path);
            }

            return null;
        }
Exemplo n.º 38
0
        private void RegisterMessage(PluginMessage message, IAssemblyLoadContext assemblyLoadContext)
        {
            var response = RegisterPlugin(message, assemblyLoadContext);

            if (!response.Success)
            {
                _faultedRegisterPluginMessages.Add(message);
            }

            SendMessage(message.PluginId, response);
        }
Exemplo n.º 39
0
        public Assembly Load(IAssemblyLoadContext loadContext)
        {
            using (var pdbStream = new MemoryStream())
                using (var assemblyStream = new MemoryStream())
                {
                    IList <ResourceDescription> resources = CompilationContext.Resources;

                    Trace.TraceInformation("[{0}]: Emitting assembly for {1}", GetType().Name, Name);

                    var sw = Stopwatch.StartNew();

                    EmitResult emitResult = null;

                    if (_supportsPdbGeneration.Value)
                    {
                        emitResult = CompilationContext.Compilation.Emit(assemblyStream, pdbStream: pdbStream, manifestResources: resources);
                    }
                    else
                    {
                        Trace.TraceWarning("PDB generation is not supported on this platform");
                        emitResult = CompilationContext.Compilation.Emit(assemblyStream, manifestResources: resources);
                    }

                    sw.Stop();

                    Trace.TraceInformation("[{0}]: Emitted {1} in {2}ms", GetType().Name, Name, sw.ElapsedMilliseconds);

                    var diagnostics = CompilationContext.Diagnostics.Concat(
                        emitResult.Diagnostics);

                    if (!emitResult.Success ||
                        diagnostics.Any(RoslynDiagnosticUtilities.IsError))
                    {
                        throw new RoslynCompilationException(diagnostics);
                    }

                    Assembly assembly = null;

                    // Rewind the stream
                    assemblyStream.Seek(0, SeekOrigin.Begin);
                    pdbStream.Seek(0, SeekOrigin.Begin);

                    if (pdbStream.Length == 0)
                    {
                        assembly = loadContext.LoadStream(assemblyStream, assemblySymbols: null);
                    }
                    else
                    {
                        assembly = loadContext.LoadStream(assemblyStream, pdbStream);
                    }

                    return(assembly);
                }
        }
Exemplo n.º 40
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            // TODO: preserve name and culture info (we don't need to look at any other information)
            string path;

            if (_assemblies.TryGetValue(new AssemblyName(assemblyName.Name), out path))
            {
                return(loadContext.LoadFile(path));
            }

            return(null);
        }
Exemplo n.º 41
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            // TODO: preserve name and culture info (we don't need to look at any other information)
            PackageAssembly assemblyInfo;

            if (_dependencyResolver.PackageAssemblyLookup.TryGetValue(new AssemblyName(assemblyName.Name), out assemblyInfo))
            {
                return(loadContext.LoadFile(assemblyInfo.Path));
            }

            return(null);
        }
        public static void Register(CommandLineApplication app, IAssemblyLoadContext assemblyLoadContext)
        {
            app.Command("resolve-taghelpers", config =>
            {
                config.Description = "Resolves TagHelperDescriptors in the specified assembly(s).";
                config.HelpOption("-?|-h|--help");
                var clientProtocol = config.Option(
                    "-p|--protocol",
                    "Provide client protocol version.",
                    CommandOptionType.SingleValue);
                var assemblyNames = config.Argument(
                    "[name]",
                    "Assembly name to resolve TagHelperDescriptors in.",
                    multipleValues: true);

                config.OnExecute(() =>
                {
                    var messageBroker = new CommandMessageBroker();
                    var plugin = new RazorPlugin(messageBroker);
                    var resolvedProtocol = ResolveProtocolCommand.ResolveProtocol(clientProtocol, plugin.Protocol);

                    plugin.Protocol = resolvedProtocol;

                    var success = true;
                    foreach (var assemblyName in assemblyNames.Values)
                    {
                        var messageData = new ResolveTagHelperDescriptorsRequestData
                        {
                            AssemblyName = assemblyName,
                            SourceLocation = SourceLocation.Zero
                        };
                        var message = new RazorPluginRequestMessage(
                            RazorPluginMessageTypes.ResolveTagHelperDescriptors,
                            JObject.FromObject(messageData));

                        success &= plugin.ProcessMessage(JObject.FromObject(message), assemblyLoadContext);
                    }

                    var resolvedDescriptors = messageBroker.Results.SelectMany(result => result.Data.Descriptors);
                    var resolvedErrors = messageBroker.Results.SelectMany(result => result.Data.Errors);
                    var resolvedResult = new ResolvedTagHelperDescriptorsResult
                    {
                        Descriptors = resolvedDescriptors,
                        Errors = resolvedErrors
                    };
                    var serializedResult = JsonConvert.SerializeObject(resolvedResult, Formatting.Indented);

                    Console.WriteLine(serializedResult);

                    return success ? 0 : 1;
                });
            });
        }
Exemplo n.º 43
0
        private static object GetCalculator()
        {
            IAssemblyLoadContext loadContext = PlatformServices.Default.AssemblyLoadContextAccessor.Default;

            using (PlatformServices.Default.AssemblyLoaderContainer.AddLoader(new DirectoryLoader(CalculatorLibPath, loadContext)))
            {
                Assembly assembly = Assembly.Load(new AssemblyName(CalculatorLibName));
                Type     type     = assembly.GetType(CalculatorTypeName);

                return(Activator.CreateInstance(type));
            }
        }
        public static void Register(CommandLineApplication app, IAssemblyLoadContext assemblyLoadContext)
        {
            app.Command("resolve-taghelpers", config =>
            {
                config.Description = "Resolves TagHelperDescriptors in the specified assembly(s).";
                config.HelpOption("-?|-h|--help");
                var clientProtocol = config.Option(
                    "-p|--protocol",
                    "Provide client protocol version.",
                    CommandOptionType.SingleValue);
                var assemblyNames = config.Argument(
                    "[name]",
                    "Assembly name to resolve TagHelperDescriptors in.",
                    multipleValues: true);

                config.OnExecute(() =>
                {
                    var messageBroker    = new CommandMessageBroker();
                    var plugin           = new RazorPlugin(messageBroker);
                    var resolvedProtocol = ResolveProtocolCommand.ResolveProtocol(clientProtocol, plugin.Protocol);

                    plugin.Protocol = resolvedProtocol;

                    var success = true;
                    foreach (var assemblyName in assemblyNames.Values)
                    {
                        var messageData = new ResolveTagHelperDescriptorsRequestData
                        {
                            AssemblyName   = assemblyName,
                            SourceLocation = SourceLocation.Zero
                        };
                        var message = new RazorPluginRequestMessage(
                            RazorPluginMessageTypes.ResolveTagHelperDescriptors,
                            JObject.FromObject(messageData));

                        success &= plugin.ProcessMessage(JObject.FromObject(message), assemblyLoadContext);
                    }

                    var resolvedDescriptors = messageBroker.Results.SelectMany(result => result.Data.Descriptors);
                    var resolvedErrors      = messageBroker.Results.SelectMany(result => result.Data.Errors);
                    var resolvedResult      = new ResolvedTagHelperDescriptorsResult
                    {
                        Descriptors = resolvedDescriptors,
                        Errors      = resolvedErrors
                    };
                    var serializedResult = JsonConvert.SerializeObject(resolvedResult, Formatting.Indented);

                    Console.WriteLine(serializedResult);

                    return(success ? 0 : 1);
                });
            });
        }
        Assembly IMetadataProjectReference.Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            Console.WriteLine("*** PostSharpProjectReference.Load {0}.dll", _underlyingReference.Name);

            string referencePath = Path.Combine(_workingDirectory, assemblyName.Name + ".dll");

            if (File.Exists(referencePath))
            {
                return(loadContext.LoadFile(referencePath));
            }

            return(_underlyingReference.Load(assemblyName, loadContext));
        }
 /// <summary>
 /// Initalizes a new instance of the <see cref="RoslynCompilationService"/> class.
 /// </summary>
 /// <param name="environment">The environment for the executing application.</param>
 /// <param name="loaderEngine">The loader used to load compiled assemblies.</param>
 /// <param name="libraryManager">The library manager that provides export and reference information.</param>
 /// <param name="host">The <see cref="IMvcRazorHost"/> that was used to generate the code.</param>
 public RoslynCompilationService(IApplicationEnvironment environment,
                                 IAssemblyLoadContextAccessor loaderAccessor,
                                 ILibraryManager libraryManager,
                                 ICompilerOptionsProvider compilerOptionsProvider,
                                 IMvcRazorHost host)
 {
     _environment = environment;
     _loader = loaderAccessor.GetLoadContext(typeof(RoslynCompilationService).GetTypeInfo().Assembly);
     _libraryManager = libraryManager;
     _applicationReferences = new Lazy<List<MetadataReference>>(GetApplicationReferences);
     _compilerOptionsProvider = compilerOptionsProvider;
     _classPrefix = host.MainClassNamePrefix;
 }
Exemplo n.º 47
0
        public IProjectCompiler GetCompiler(TypeInformation provider, IAssemblyLoadContext loadContext)
        {
            // TODO: Optimize the default compiler case by using the default load context directly

            var services = new ServiceProvider(_context.Services);
            services.Add(typeof(IAssemblyLoadContext), loadContext);

            var assembly = loadContext.Load(provider.AssemblyName);

            var type = assembly.GetType(provider.TypeName);

            return (IProjectCompiler)ActivatorUtilities.CreateInstance(services, type);
        }
Exemplo n.º 48
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InProcDataCollector"/> class.
        /// </summary>
        /// <param name="codeBase">
        /// </param>
        /// <param name="assemblyQualifiedName">
        /// </param>
        /// <param name="interfaceTypeInfo">
        /// </param>
        /// <param name="configXml">
        /// </param>
        /// <param name="assemblyLoadContext">
        /// </param>
        internal InProcDataCollector(string codeBase, string assemblyQualifiedName, TypeInfo interfaceTypeInfo, string configXml, IAssemblyLoadContext assemblyLoadContext)
        {
            this.configXml           = configXml;
            this.assemblyLoadContext = assemblyLoadContext;

            var assembly = this.LoadInProcDataCollectorExtension(codeBase);

            this.dataCollectorType =
                assembly?.GetTypes()
                .FirstOrDefault(x => x.AssemblyQualifiedName.Equals(assemblyQualifiedName) && interfaceTypeInfo.IsAssignableFrom(x.GetTypeInfo()));

            this.AssemblyQualifiedName = this.dataCollectorType?.AssemblyQualifiedName;
        }
 /// <summary>
 /// Initalizes a new instance of the <see cref="RoslynCompilationService"/> class.
 /// </summary>
 /// <param name="environment">The environment for the executing application.</param>
 /// <param name="loaderAccessor">
 /// The accessor for the <see cref="IAssemblyLoadContext"/> used to load compiled assemblies.
 /// </param>
 /// <param name="libraryExporter">The library manager that provides export and reference information.</param>
 /// <param name="compilerOptionsProvider">
 /// The <see cref="ICompilerOptionsProvider"/> that provides Roslyn compilation settings.
 /// </param>
 /// <param name="host">The <see cref="IMvcRazorHost"/> that was used to generate the code.</param>
 public DefaultRoslynCompilationService(IApplicationEnvironment environment,
                                 IAssemblyLoadContextAccessor loaderAccessor,
                                 IOrchardLibraryManager libraryExporter,
                                 ICompilerOptionsProvider compilerOptionsProvider,
                                 IMvcRazorHost host,
                                 IOptions<RazorViewEngineOptions> optionsAccessor)
 {
     _environment = environment;
     _loader = loaderAccessor.GetLoadContext(typeof(DefaultRoslynCompilationService).GetTypeInfo().Assembly);
     _libraryExporter = libraryExporter;
     _applicationReferences = new Lazy<List<MetadataReference>>(GetApplicationReferences);
     _compilerOptionsProvider = compilerOptionsProvider;
     _fileProvider = optionsAccessor.Options.FileProvider;
     _classPrefix = host.MainClassNamePrefix;
 }
Exemplo n.º 50
0
 public RoslynCompiler(ICache cache,
                       ICacheContextAccessor cacheContextAccessor,
                       INamedCacheDependencyProvider namedDependencyProvider,
                       IAssemblyLoadContext loadContext,
                       IFileWatcher watcher,
                       IApplicationEnvironment environment,
                       IServiceProvider services)
 {
     _cache = cache;
     _cacheContextAccessor = cacheContextAccessor;
     _namedDependencyProvider = namedDependencyProvider;
     _loadContext = loadContext;
     _watcher = watcher;
     _environment = environment;
     _services = services;
 }
Exemplo n.º 51
0
        public Assembly LoadProject(Project project, string aspect, IAssemblyLoadContext loadContext)
        {
            // Export the project
            var export = ProjectExporter.ExportProject(project, this, aspect, _context.TargetFramework, _context.Configuration);

            // Load the metadata reference
            foreach (var projectReference in export.MetadataReferences.OfType<IMetadataProjectReference>())
            {
                if (string.Equals(projectReference.Name, project.Name, StringComparison.OrdinalIgnoreCase))
                {
                    return projectReference.Load(loadContext);
                }
            }

            return null;
        }
Exemplo n.º 52
0
        public RuntimeLoadContext(string friendlyName,
                                  IEnumerable<LibraryDescription> libraries,
                                  ICompilationEngine compilationEngine,
                                  IAssemblyLoadContext defaultContext) : base(friendlyName)
        {
            // TODO: Make this all lazy
            // TODO: Unify this logic with default host
            var projects = libraries.Where(p => p.Type == LibraryTypes.Project)
                                    .OfType<ProjectDescription>();

            var assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries);

            _projectAssemblyLoader = new ProjectAssemblyLoader(loadContextAccessor: null, compilationEngine: compilationEngine, projects: projects);
            _packageAssemblyLoader = new PackageAssemblyLoader(loadContextAccessor: null, assemblies: assemblies, libraryDescriptions: libraries);
            _defaultContext = defaultContext;
        }
Exemplo n.º 53
0
        public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                        IRuntimeEnvironment runtimeEnvironment,
                                        IAssemblyLoadContext defaultLoadContext,
                                        CompilationCache cache)
        {
            ApplicationEnvironment = applicationEnvironment;
            RuntimeEnvironment = runtimeEnvironment;
            DefaultLoadContext = defaultLoadContext;
            CompilationCache = cache;

            // Register compiler services
            AddCompilationService(typeof(IApplicationEnvironment), ApplicationEnvironment);
            AddCompilationService(typeof(ICache), CompilationCache.Cache);
            AddCompilationService(typeof(ICacheContextAccessor), CompilationCache.CacheContextAccessor);
            AddCompilationService(typeof(INamedCacheDependencyProvider), CompilationCache.NamedCacheDependencyProvider);
        }
Exemplo n.º 54
0
 public RoslynProjectCompiler(
     ICache cache,
     ICacheContextAccessor cacheContextAccessor,
     INamedCacheDependencyProvider namedCacheProvider,
     IAssemblyLoadContext loadContext,
     IApplicationEnvironment environment,
     IServiceProvider services)
 {
     _compiler = new RoslynCompiler(
         cache,
         cacheContextAccessor,
         namedCacheProvider,
         loadContext,
         environment,
         services);
 }
Exemplo n.º 55
0
 public EntityFrameworkServices(
     [NotNull]ILibraryManager libraryManager,
     [NotNull]IApplicationEnvironment environment,
     [NotNull]IAssemblyLoadContextAccessor loader,
     [NotNull]IModelTypesLocator modelTypesLocator,
     [NotNull]IDbContextEditorServices dbContextEditorServices,
     [NotNull]IPackageInstaller packageInstaller,
     [NotNull]ILogger logger)
 {
     _libraryManager = libraryManager;
     _environment = environment;
     _loader = loader.GetLoadContext(typeof(EntityFrameworkServices).GetTypeInfo().Assembly);
     _modelTypesLocator = modelTypesLocator;
     _dbContextEditorServices = dbContextEditorServices;
     _packageInstaller = packageInstaller;
     _logger = logger;
 }
Exemplo n.º 56
0
        public Assembly LoadProject(Project project, string aspect, IAssemblyLoadContext loadContext)
        {
            var exporter = CreateProjectExporter(project, _context.ApplicationEnvironment.RuntimeFramework, _context.ApplicationEnvironment.Configuration);

            // Export the project
            var export = exporter.GetExport(project.Name, aspect);

            // Load the metadata reference
            foreach (var projectReference in export.MetadataReferences.OfType<IMetadataProjectReference>())
            {
                if (string.Equals(projectReference.Name, project.Name, StringComparison.OrdinalIgnoreCase))
                {
                    return projectReference.Load(loadContext);
                }
            }

            return null;
        }
        // Internal for unit testing
        internal static Dictionary<string, Type> GetPrecompiledViews(
            IEnumerable<RazorFileInfoCollection> razorFileInfoCollections, 
            IAssemblyLoadContext loadContext)
        {
            var precompiledViews = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);

            foreach (var viewCollection in razorFileInfoCollections)
            {
                var containingAssembly = viewCollection.LoadAssembly(loadContext);
                foreach (var fileInfo in viewCollection.FileInfos)
                {
                    var viewType = containingAssembly.GetType(fileInfo.FullTypeName);
                    precompiledViews[fileInfo.RelativePath] = viewType;
                }
            }

            return precompiledViews;
        }
Exemplo n.º 58
0
        internal CompilerCache(IEnumerable<RazorFileInfoCollection> razorFileInfoCollections,
                               IAssemblyLoadContext loadContext,
                               IFileProvider fileProvider)
        {
            _fileProvider = fileProvider;
            _cache = new MemoryCache(new MemoryCacheOptions { CompactOnMemoryPressure = false });

            var cacheEntries = new List<CompilerCacheEntry>();
            foreach (var viewCollection in razorFileInfoCollections)
            {
                var containingAssembly = viewCollection.LoadAssembly(loadContext);
                foreach (var fileInfo in viewCollection.FileInfos)
                {
                    var viewType = containingAssembly.GetType(fileInfo.FullTypeName);
                    var cacheEntry = new CompilerCacheEntry(fileInfo, viewType);

                    // There shouldn't be any duplicates and if there are any the first will win.
                    // If the result doesn't match the one on disk its going to recompile anyways.
                    var normalizedPath = NormalizePath(fileInfo.RelativePath);
                    _cache.Set(
                        normalizedPath,
                        cacheEntry,
                        GetMemoryCacheEntryOptions(fileInfo.RelativePath));

                    cacheEntries.Add(cacheEntry);
                }
            }

            // Set up _ViewImports
            foreach (var entry in cacheEntries)
            {
                var globalFileLocations = ViewHierarchyUtility.GetViewImportsLocations(entry.RelativePath);
                foreach (var location in globalFileLocations)
                {
                    var globalFileEntry = _cache.Get<CompilerCacheEntry>(location);
                    if (globalFileEntry != null)
                    {
                        // Add the composite _ViewImports entry as a dependency.
                        entry.AssociatedGlobalFileEntry = globalFileEntry;
                        break;
                    }
                }
            }
        }
Exemplo n.º 59
0
        public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                        IAssemblyLoadContext defaultLoadContext,
                                        CompilationCache cache,
                                        IFileWatcher fileWatcher,
                                        IProjectGraphProvider projectGraphProvider)
        {
            ApplicationEnvironment = applicationEnvironment;
            DefaultLoadContext = defaultLoadContext;
            ProjectGraphProvider = projectGraphProvider;
            CompilationCache = cache;
            FileWatcher = fileWatcher;

            // Register compiler services
            AddCompilationService(typeof(IFileWatcher), FileWatcher);
            AddCompilationService(typeof(IApplicationEnvironment), ApplicationEnvironment);
            AddCompilationService(typeof(ICache), CompilationCache.Cache);
            AddCompilationService(typeof(ICacheContextAccessor), CompilationCache.CacheContextAccessor);
            AddCompilationService(typeof(INamedCacheDependencyProvider), CompilationCache.NamedCacheDependencyProvider);
        }
Exemplo n.º 60
0
        public Assembly Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
        {
            if (_response.Diagnostics.HasErrors())
            {
                throw new DesignTimeCompilationException(_response.Diagnostics);
            }

            if (_response.AssemblyPath != null)
            {
                return loadContext.LoadFile(_response.AssemblyPath);
            }

            if (_response.PdbBytes == null)
            {
                return loadContext.LoadStream(new MemoryStream(_response.AssemblyBytes), assemblySymbols: null);
            }

            return loadContext.LoadStream(new MemoryStream(_response.AssemblyBytes),
                                           new MemoryStream(_response.PdbBytes));
        }