public void MonoCannotResolveLegacyNetFrameworks(string shortFrameworkName)
        {
            var resolver = new FrameworkReferenceResolver();

            string path;
            Version version;
            Assert.False(resolver.TryGetAssembly("mscorlib", VersionUtility.ParseFrameworkName(shortFrameworkName), out path, out version));
        }
        // Microsoft.Build.Engine (in 2.0, but overridden in 3.5)
        //[InlineData("net20", "Microsoft.Build.Engine", @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727\Microsoft.Build.Engine.dll", "2.0.0.0")]
        //[InlineData("net30", "Microsoft.Build.Engine", @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727\Microsoft.Build.Engine.dll", "2.0.0.0")]
        //[InlineData("net35", "Microsoft.Build.Engine", @"REFASMSROOT\v3.5\Microsoft.Build.Engine.dll", "3.5.0.0")]

        public void FrameworkResolverResolvesCorrectPaths(string shortFrameworkName, string assemblyName, string expectedPath, string expectedVersion)
        {
            var resolver = new FrameworkReferenceResolver();

            string actualPath;
            Version actualVersion;
            Assert.True(resolver.TryGetAssembly(assemblyName, VersionUtility.ParseFrameworkName(shortFrameworkName), out actualPath, out actualVersion));
            Assert.Equal(Environment.ExpandEnvironmentVariables(expectedPath).Replace("REFASMSROOT", FrameworkReferenceResolver.GetReferenceAssembliesPath()), actualPath);

            // Having this be Version->Version equality caused some problems...
            Assert.Equal(Version.Parse(expectedVersion).ToString(), actualVersion.ToString());
        }
 public void FrameworkResolverReturnsCorrectAttemptedPaths(string shortFrameworkName, string attemptedPaths)
 {
     var resolver = new FrameworkReferenceResolver();
     var paths = resolver.GetAttemptedPaths(VersionUtility.ParseFrameworkName(shortFrameworkName));
     Assert.Equal(
         attemptedPaths.Split(',').Select(s => Environment.ExpandEnvironmentVariables(s).Replace("REFASMSROOT", FrameworkReferenceResolver.GetReferenceAssembliesPath())).ToArray(),
         paths.ToArray());
 }
Esempio n. 4
0
        public ProjectContext Build()
        {
            var diagnostics = new List <DiagnosticMessage>();

            ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;

            GlobalSettings globalSettings = null;

            if (ProjectDirectory != null)
            {
                RootDirectory = ProjectRootResolver.ResolveRootDirectory(ProjectDirectory);
                GlobalSettings.TryGetGlobalSettings(RootDirectory, out globalSettings);
            }

            RootDirectory     = globalSettings?.DirectoryPath ?? RootDirectory;
            PackagesDirectory = PackagesDirectory ?? PackageDependencyProvider.ResolvePackagesPath(RootDirectory, globalSettings);

            FrameworkReferenceResolver frameworkReferenceResolver;

            if (string.IsNullOrEmpty(ReferenceAssembliesPath))
            {
                // Use the default static resolver
                frameworkReferenceResolver = FrameworkReferenceResolver.Default;
            }
            else
            {
                frameworkReferenceResolver = new FrameworkReferenceResolver(ReferenceAssembliesPath);
            }

            LockFileLookup lockFileLookup = null;

            EnsureProjectLoaded();

            ReadLockFile(diagnostics);

            var    validLockFile             = true;
            string lockFileValidationMessage = null;

            if (LockFile != null)
            {
                if (Project != null)
                {
                    validLockFile = LockFile.IsValidForProject(Project, out lockFileValidationMessage);
                }

                lockFileLookup = new LockFileLookup(LockFile);
            }

            var libraries       = new Dictionary <LibraryKey, LibraryDescription>();
            var projectResolver = new ProjectDependencyProvider(ProjectResolver);

            ProjectDescription mainProject = null;

            if (Project != null)
            {
                mainProject = projectResolver.GetDescription(TargetFramework, Project, targetLibrary: null);

                // Add the main project
                libraries.Add(new LibraryKey(mainProject.Identity.Name), mainProject);
            }

            LibraryRange?platformDependency = null;

            if (mainProject != null)
            {
                platformDependency = mainProject.Dependencies
                                     .Where(d => d.Type.Equals(LibraryDependencyType.Platform))
                                     .Cast <LibraryRange?>()
                                     .FirstOrDefault();
            }
            bool isPortable = platformDependency != null;

            LockFileTarget     target          = null;
            LibraryDescription platformLibrary = null;

            if (lockFileLookup != null)
            {
                target = SelectTarget(LockFile, isPortable);
                if (target != null)
                {
                    var nugetPackageResolver   = new PackageDependencyProvider(PackagesDirectory, frameworkReferenceResolver);
                    var msbuildProjectResolver = new MSBuildDependencyProvider(Project, ProjectResolver);
                    ScanLibraries(target, lockFileLookup, libraries, msbuildProjectResolver, nugetPackageResolver, projectResolver);

                    if (platformDependency != null)
                    {
                        libraries.TryGetValue(new LibraryKey(platformDependency.Value.Name), out platformLibrary);
                    }
                }
            }

            string runtime = target?.RuntimeIdentifier;

            if (string.IsNullOrEmpty(runtime) && TargetFramework.IsDesktop())
            {
                // we got a ridless target for desktop so turning portable mode on
                isPortable = true;
                var legacyRuntime = RuntimeEnvironmentRidExtensions.GetLegacyRestoreRuntimeIdentifier();
                if (RuntimeIdentifiers.Contains(legacyRuntime))
                {
                    runtime = legacyRuntime;
                }
                else
                {
                    runtime = RuntimeIdentifiers.FirstOrDefault();
                }
            }

            var  referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(frameworkReferenceResolver);
            bool requiresFrameworkAssemblies;

            // Resolve the dependencies
            ResolveDependencies(libraries, referenceAssemblyDependencyResolver, out requiresFrameworkAssemblies);

            // REVIEW: Should this be in NuGet (possibly stored in the lock file?)
            if (LockFile == null)
            {
                diagnostics.Add(new DiagnosticMessage(
                                    ErrorCodes.NU1009,
                                    $"The expected lock file doesn't exist. Please run \"dotnet restore\" to generate a new lock file.",
                                    Path.Combine(Project.ProjectDirectory, LockFile.FileName),
                                    DiagnosticMessageSeverity.Error));
            }

            if (!validLockFile)
            {
                diagnostics.Add(new DiagnosticMessage(
                                    ErrorCodes.NU1006,
                                    $"{lockFileValidationMessage}. Please run \"dotnet restore\" to generate a new lock file.",
                                    Path.Combine(Project.ProjectDirectory, LockFile.FileName),
                                    DiagnosticMessageSeverity.Warning));
            }

            if (requiresFrameworkAssemblies)
            {
                var frameworkInfo = Project.GetTargetFramework(TargetFramework);

                if (frameworkReferenceResolver == null || string.IsNullOrEmpty(frameworkReferenceResolver.ReferenceAssembliesPath))
                {
                    // If there was an attempt to use reference assemblies but they were not installed
                    // report an error
                    diagnostics.Add(new DiagnosticMessage(
                                        ErrorCodes.DOTNET1012,
                                        $"The reference assemblies directory was not specified. You can set the location using the DOTNET_REFERENCE_ASSEMBLIES_PATH environment variable.",
                                        filePath: Project.ProjectFilePath,
                                        severity: DiagnosticMessageSeverity.Error,
                                        startLine: frameworkInfo.Line,
                                        startColumn: frameworkInfo.Column
                                        ));
                }
                else if (!frameworkReferenceResolver.IsInstalled(TargetFramework))
                {
                    // If there was an attempt to use reference assemblies but they were not installed
                    // report an error
                    diagnostics.Add(new DiagnosticMessage(
                                        ErrorCodes.DOTNET1011,
                                        $"Framework not installed: {TargetFramework.DotNetFrameworkName} in {ReferenceAssembliesPath}",
                                        filePath: Project.ProjectFilePath,
                                        severity: DiagnosticMessageSeverity.Error,
                                        startLine: frameworkInfo.Line,
                                        startColumn: frameworkInfo.Column
                                        ));
                }
            }

            List <DiagnosticMessage> allDiagnostics = new List <DiagnosticMessage>(diagnostics);

            if (Project != null)
            {
                allDiagnostics.AddRange(Project.Diagnostics);
            }

            // Create a library manager
            var libraryManager = new LibraryManager(libraries.Values.ToList(), allDiagnostics, Project?.ProjectFilePath);

            return(new ProjectContext(
                       globalSettings,
                       mainProject,
                       platformLibrary,
                       TargetFramework,
                       isPortable,
                       runtime,
                       PackagesDirectory,
                       libraryManager,
                       LockFile,
                       diagnostics));
        }
        public ProjectContext Build()
        {
            ProjectDirectory = Project?.ProjectDirectory ?? ProjectDirectory;

            if (GlobalSettings == null)
            {
                RootDirectory = ProjectRootResolver.ResolveRootDirectory(ProjectDirectory);

                GlobalSettings globalSettings;
                if (GlobalSettings.TryGetGlobalSettings(RootDirectory, out globalSettings))
                {
                    GlobalSettings = globalSettings;
                }
            }

            RootDirectory           = GlobalSettings?.DirectoryPath ?? RootDirectory;
            PackagesDirectory       = PackagesDirectory ?? PackageDependencyProvider.ResolvePackagesPath(RootDirectory, GlobalSettings);
            ReferenceAssembliesPath = ReferenceAssembliesPath ?? GetDefaultReferenceAssembliesPath();

            LockFileLookup lockFileLookup = null;

            EnsureProjectLoaded();

            var projectLockJsonPath = Path.Combine(ProjectDirectory, LockFile.FileName);

            if (LockFile == null && File.Exists(projectLockJsonPath))
            {
                LockFile = LockFileReader.Read(projectLockJsonPath);
            }

            var    validLockFile             = true;
            string lockFileValidationMessage = null;

            if (LockFile != null)
            {
                validLockFile = LockFile.IsValidForProject(Project, out lockFileValidationMessage);

                lockFileLookup = new LockFileLookup(LockFile);
            }

            var libraries       = new Dictionary <LibraryKey, LibraryDescription>();
            var projectResolver = new ProjectDependencyProvider();

            var mainProject = projectResolver.GetDescription(TargetFramework, Project);

            // Add the main project
            libraries.Add(new LibraryKey(mainProject.Identity.Name), mainProject);

            LockFileTarget target = null;

            if (lockFileLookup != null)
            {
                target = SelectTarget(LockFile);
                if (target != null)
                {
                    var packageResolver = new PackageDependencyProvider(PackagesDirectory);
                    ScanLibraries(target, lockFileLookup, libraries, packageResolver, projectResolver);
                }
            }

            var  frameworkReferenceResolver          = new FrameworkReferenceResolver(ReferenceAssembliesPath);
            var  referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(frameworkReferenceResolver);
            bool requiresFrameworkAssemblies;

            // Resolve the dependencies
            ResolveDependencies(libraries, referenceAssemblyDependencyResolver, out requiresFrameworkAssemblies);

            var diagnostics = new List <DiagnosticMessage>();

            // REVIEW: Should this be in NuGet (possibly stored in the lock file?)
            if (LockFile == null)
            {
                diagnostics.Add(new DiagnosticMessage(
                                    ErrorCodes.NU1009,
                                    $"The expected lock file doesn't exist. Please run \"dotnet restore\" to generate a new lock file.",
                                    Path.Combine(Project.ProjectDirectory, LockFile.FileName),
                                    DiagnosticMessageSeverity.Error));
            }

            if (!validLockFile)
            {
                diagnostics.Add(new DiagnosticMessage(
                                    ErrorCodes.NU1006,
                                    $"{lockFileValidationMessage}. Please run \"dotnet restore\" to generate a new lock file.",
                                    Path.Combine(Project.ProjectDirectory, LockFile.FileName),
                                    DiagnosticMessageSeverity.Warning));
            }

            if (requiresFrameworkAssemblies)
            {
                var frameworkInfo = Project.GetTargetFramework(TargetFramework);

                if (string.IsNullOrEmpty(ReferenceAssembliesPath))
                {
                    // If there was an attempt to use reference assemblies but they were not installed
                    // report an error
                    diagnostics.Add(new DiagnosticMessage(
                                        ErrorCodes.DOTNET1012,
                                        $"The reference assemblies directory was not specified. You can set the location using the DOTNET_REFERENCE_ASSEMBLIES_PATH environment variable.",
                                        filePath: Project.ProjectFilePath,
                                        severity: DiagnosticMessageSeverity.Error,
                                        startLine: frameworkInfo.Line,
                                        startColumn: frameworkInfo.Column
                                        ));
                }
                else if (!frameworkReferenceResolver.IsInstalled(TargetFramework))
                {
                    // If there was an attempt to use reference assemblies but they were not installed
                    // report an error
                    diagnostics.Add(new DiagnosticMessage(
                                        ErrorCodes.DOTNET1011,
                                        $"Framework not installed: {TargetFramework.DotNetFrameworkName} in {ReferenceAssembliesPath}",
                                        filePath: Project.ProjectFilePath,
                                        severity: DiagnosticMessageSeverity.Error,
                                        startLine: frameworkInfo.Line,
                                        startColumn: frameworkInfo.Column
                                        ));
                }
            }

            // Create a library manager
            var libraryManager = new LibraryManager(libraries.Values.ToList(), diagnostics, Project.ProjectFilePath);

            return(new ProjectContext(
                       GlobalSettings,
                       mainProject,
                       TargetFramework,
                       target?.RuntimeIdentifier,
                       PackagesDirectory,
                       libraryManager));
        }
Esempio n. 6
0
        private static void 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 = PlatformServices.Default.Application;
            var runtimeEnvironment     = PlatformServices.Default.Runtime;
            var loadContextAccessor    = PlatformServices.Default.AssemblyLoadContextAccessor;
            var compilationEngine      = new CompilationEngine(new CompilationEngineContext(applicationEnvironment, runtimeEnvironment, loadContextAccessor.Default, new CompilationCache()));
            var frameworkResolver      = new FrameworkReferenceResolver();

            var services = new ServiceProvider();

            services.Add(typeof(IApplicationEnvironment), PlatformServices.Default.Application);
            services.Add(typeof(IRuntimeEnvironment), PlatformServices.Default.Runtime);
            services.Add(typeof(IAssemblyLoadContextAccessor), PlatformServices.Default.AssemblyLoadContextAccessor);
            services.Add(typeof(IAssemblyLoaderContainer), PlatformServices.Default.AssemblyLoaderContainer);
            services.Add(typeof(ILibraryManager), PlatformServices.Default.LibraryManager);

            // 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 = listenSocket.Accept();

                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();
            }
        }
Esempio n. 7
0
        public void FrameworkResolverReturnsCorrectAttemptedPaths(string shortFrameworkName, string attemptedPaths)
        {
            var resolver = new FrameworkReferenceResolver();
            var paths    = resolver.GetAttemptedPaths(VersionUtility.ParseFrameworkName(shortFrameworkName));

            Assert.Equal(
                attemptedPaths.Split(',').Select(s => Environment.ExpandEnvironmentVariables(s).Replace("REFASMSROOT", FrameworkReferenceResolver.GetReferenceAssembliesPath())).ToArray(),
                paths.ToArray());
        }
Esempio n. 8
0
        // Microsoft.Build.Engine (in 2.0, but overridden in 3.5)
        //[InlineData("net20", "Microsoft.Build.Engine", @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727\Microsoft.Build.Engine.dll", "2.0.0.0")]
        //[InlineData("net30", "Microsoft.Build.Engine", @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727\Microsoft.Build.Engine.dll", "2.0.0.0")]
        //[InlineData("net35", "Microsoft.Build.Engine", @"REFASMSROOT\v3.5\Microsoft.Build.Engine.dll", "3.5.0.0")]

        public void FrameworkResolverResolvesCorrectPaths(string shortFrameworkName, string assemblyName, string expectedPath, string expectedVersion)
        {
            var resolver = new FrameworkReferenceResolver();

            string  actualPath;
            Version actualVersion;

            Assert.True(resolver.TryGetAssembly(assemblyName, VersionUtility.ParseFrameworkName(shortFrameworkName), out actualPath, out actualVersion));
            Assert.Equal(Environment.ExpandEnvironmentVariables(expectedPath).Replace("REFASMSROOT", FrameworkReferenceResolver.GetReferenceAssembliesPath()), actualPath);

            // Having this be Version->Version equality caused some problems...
            Assert.Equal(Version.Parse(expectedVersion).ToString(), actualVersion.ToString());
        }
Esempio n. 9
0
        /// <summary>
        /// Create a <see cref="RuntimeHostBuilder"/> for the project in the specified
        /// <paramref name="projectDirectory"/>, using the default configuration.
        /// </summary>
        /// <remarks>
        /// This method will throw if the project.json file cannot be found in the
        /// specified folder. If a project.lock.json file is present in the directory
        /// it will be loaded.
        /// </remarks>
        /// <param name="projectDirectory">The directory of the project to host</param>
        public static RuntimeHostBuilder ForProjectDirectory(string projectDirectory, NuGetFramework runtimeFramework, IServiceProvider services)
        {
            if (string.IsNullOrEmpty(projectDirectory))
            {
                throw new ArgumentNullException(nameof(projectDirectory));
            }
            if (runtimeFramework == null)
            {
                throw new ArgumentNullException(nameof(runtimeFramework));
            }

            var log = RuntimeLogging.Logger<RuntimeHostBuilder>();
            var hostBuilder = new RuntimeHostBuilder();

            // Load the Project
            var projectResolver = new PackageSpecResolver(projectDirectory);
            PackageSpec packageSpec;
            if (projectResolver.TryResolvePackageSpec(GetProjectName(projectDirectory), out packageSpec))
            {
                log.LogVerbose($"Loaded project {packageSpec.Name}");
                hostBuilder.Project = new Project(packageSpec);
            }
            hostBuilder.GlobalSettings = projectResolver.GlobalSettings;

            // Load the Lock File if present
            LockFile lockFile;
            if (TryReadLockFile(projectDirectory, out lockFile))
            {
                log.LogVerbose($"Loaded lock file");
                hostBuilder.LockFile = lockFile;
            }

            // Set the framework and other components
            hostBuilder.TargetFramework = runtimeFramework;
            hostBuilder.Services = services;
            hostBuilder.PackagePathResolver = new PackagePathResolver(
                ResolveRepositoryPath(hostBuilder.GlobalSettings),
                GetCachePaths());

            log.LogVerbose("Registering PackageSpecReferenceDependencyProvider");
            hostBuilder.DependencyProviders.Add(new PackageSpecReferenceDependencyProvider(projectResolver));

            if (hostBuilder.LockFile != null)
            {
                log.LogVerbose("Registering LockFileDependencyProvider");
                hostBuilder.DependencyProviders.Add(new LockFileDependencyProvider(hostBuilder.LockFile));
            }

            log.LogVerbose("Registering ReferenceAssemblyDependencyProvider");
            var referenceResolver = new FrameworkReferenceResolver();
            hostBuilder.DependencyProviders.Add(new ReferenceAssemblyDependencyProvider(referenceResolver));

            // GAC resolver goes here! :)

            return hostBuilder;
        }