Beispiel #1
0
        private void CalculateDefaultsForNonAssigned()
        {
            if (string.IsNullOrWhiteSpace(Project))
            {
                Project = Directory.GetCurrentDirectory();
            }

            if (string.IsNullOrWhiteSpace(Configuration))
            {
                Configuration = Constants.DefaultConfiguration;
            }

            var contexts = ProjectContext.CreateContextForEachFramework(Project);

            if (Framework == null)
            {
                _context = contexts.First();
            }
            else
            {
                var fx = NuGetFramework.Parse(Framework);
                _context = contexts.FirstOrDefault(c => c.TargetFramework.Equals(fx));
            }

            if (Args == null)
            {
                _args = new List <string>();
            }
            else
            {
                _args = new List <string>(Args);
            }
        }
        private ProjectContext GetRuntimeContext()
        {
            var            workspace       = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());
            var            projectContexts = ProjectContext.CreateContextForEachFramework(ProjectPath).ToArray();
            ProjectContext projectContext;

            if (TargetFramework != null)
            {
                projectContext = projectContexts.FirstOrDefault(context => context.TargetFramework.Equals(TargetFramework));
                if (projectContext == null)
                {
                    throw new InvalidOperationException($"Project '{ProjectPath}' does not support framework: {FrameworkOption.Value()}");
                }
            }
            else if (projectContexts.Length == 1)
            {
                projectContext = projectContexts[0];
            }
            else
            {
                throw new InvalidOperationException($"Project '{ProjectPath}' targets multiple frameworks. Specify one using '{FrameworkOption.Template}.");
            }

            return(workspace.GetRuntimeContext(
                       projectContext,
                       RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers()));
        }
        public OperationsFactory([CanBeNull] string startupProject, [CanBeNull] string environment)
        {
            var project = Directory.GetCurrentDirectory();

            startupProject = startupProject ?? project;

            var startupProjectContext = ProjectContext.CreateContextForEachFramework(startupProject).First();
            var projectContext        = ProjectContext.CreateContextForEachFramework(project).First();
            var startupAssemblyName   = new AssemblyName(startupProjectContext.ProjectFile.Name);
            var assemblyName          = new AssemblyName(projectContext.ProjectFile.Name);
            var assemblyLoadContext   = startupProjectContext.CreateLoadContext();

            _startupAssembly = assemblyLoadContext.LoadFromAssemblyName(startupAssemblyName);

            try
            {
                _assembly = assemblyLoadContext.LoadFromAssemblyName(assemblyName);
            }
            catch (Exception ex)
            {
                throw new OperationException(
                          CommandsStrings.UnreferencedAssembly(
                              projectContext.ProjectFile.Name,
                              startupProjectContext.ProjectFile.Name),
                          ex);
            }
            _environment   = environment;
            _projectDir    = projectContext.ProjectDirectory;
            _rootNamespace = projectContext.ProjectFile.Name;
        }
        public IEnumerable <ProjectDependency> ResolveAllProjectDependenciesForFramework(
            ProjectDependency projectToResolve,
            NuGetFramework framework,
            IEnumerable <string> preResolvedProjects = null)
        {
            var projects = new List <ProjectDependency> {
                projectToResolve
            };
            var allDependencies = new List <ProjectDependency>();

            while (projects.Count > 0)
            {
                var project = projects.First();
                projects.Remove(project);
                var projectContext =
                    ProjectContext.CreateContextForEachFramework(project.ProjectFilePath).FirstOrDefault();
                if (projectContext == null)
                {
                    continue;
                }

                var dependencies = ResolveDirectProjectDependenciesForFramework(
                    projectContext.ProjectFile,
                    framework,
                    preResolvedProjects
                    );
                projects.AddRange(dependencies);
                allDependencies.AddRange(dependencies);
            }

            return(allDependencies);
        }
Beispiel #5
0
 internal ProjectContext GetProjectContextFromPath(string projectPath)
 {
     return(File.Exists(Path.Combine(projectPath, Project.FileName)) &&
            File.Exists(Path.Combine(projectPath, LockFile.FileName))
         ? ProjectContext.CreateContextForEachFramework(projectPath).FirstOrDefault()
         : null);
 }
Beispiel #6
0
        private void Setup([CallerMemberName] string callingMethod = "")
        {
            var testInstance = TestAssetsManager.CreateTestInstance(Path.Combine("ProjectsWithTests", "MultipleFrameworkProject"), callingMethod);

            _projectFilePath = Path.Combine(testInstance.TestRoot, "project.json");
            var contexts = ProjectContext.CreateContextForEachFramework(
                _projectFilePath,
                null,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            // Restore the project again in the destination to resolve projects
            // Since the lock file has project relative paths in it, those will be broken
            // unless we re-restore
            new RestoreCommand()
            {
                WorkingDirectory = testInstance.TestRoot
            }.Execute().Should().Pass();

            _netCoreAppOutputPath = Path.Combine(testInstance.TestRoot, "bin", "Debug", "netcoreapp1.0");
            var buildCommand = new BuildCommand(_projectFilePath);
            var result       = buildCommand.Execute($"-f netcoreapp1.0 -o {_netCoreAppOutputPath}");

            result.Should().Pass();

            if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows)
            {
                var rid = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers().First();
                _net46OutputPath = Path.Combine(testInstance.TestRoot, "bin", "Debug", "net46", rid);
                result           = buildCommand.Execute($"-f net46 -r {rid} -o {_net46OutputPath}");
                result.Should().Pass();
            }
        }
Beispiel #7
0
        public void MigratingLibWithMultipleTFMsDoesNotAddRuntimes()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssets)
                                .FromTestAssetBase("PJLibWithMultipleFrameworks")
                                .SaveToDisk(testDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory);
            var mockProj        = ProjectRootElement.Create();

            var migrationSettings =
                MigrationSettings.CreateMigrationSettingsTestHook(testDirectory, testDirectory, mockProj);
            var migrationInputs = new MigrationRuleInputs(
                projectContexts,
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            var reason = "Should not add runtime identifiers for libraries";

            mockProj.Properties.Count(p => p.Name == "RuntimeIdentifiers").Should().Be(0, reason);
            mockProj.Properties.Count(p => p.Name == "RuntimeIdentifier").Should().Be(0, reason);
        }
Beispiel #8
0
        public void MigratingCoreAndDesktopTFMsAddsRuntimeIdentifierWithWin7x86ConditionOnAllFullFrameworksWhenNoRuntimesExistAlready()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssets)
                                .FromTestAssetBase("PJAppWithMultipleFrameworks")
                                .SaveToDisk(testDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory);
            var mockProj        = ProjectRootElement.Create();

            var migrationSettings = MigrationSettings.CreateMigrationSettingsTestHook(testDirectory, testDirectory, mockProj);
            var migrationInputs   = new MigrationRuleInputs(
                projectContexts,
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            mockProj.Properties.Count(p => p.Name == "RuntimeIdentifier").Should().Be(1);
            var runtimeIdentifier = mockProj.Properties.First(p => p.Name == "RuntimeIdentifier");

            runtimeIdentifier.Value.Should().Be("win7-x86");
            runtimeIdentifier.Condition.Should().Be(" '$(TargetFramework)' == 'net20' OR '$(TargetFramework)' == 'net35' OR '$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net461' ");
        }
        public void Migrating_Single_TFM_project_Populates_TargetFramework()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssetsManager)
                                .FromTestAssetBase("TestAppWithRuntimeOptions")
                                .WithCustomProperty("buildOptions", new Dictionary <string, string>
            {
                { "emitEntryPoint", "false" }
            })
                                .SaveToDisk(testDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory);
            var mockProj        = ProjectRootElement.Create();

            // Run BuildOptionsRule
            var migrationSettings = new MigrationSettings(testDirectory, testDirectory, mockProj);
            var migrationInputs   = new MigrationRuleInputs(
                projectContexts,
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);
            Console.WriteLine(mockProj.RawXml);

            mockProj.Properties.Count(p => p.Name == "TargetFramework").Should().Be(1);
        }
Beispiel #10
0
        private static IEnumerable <ProjectContext> GenerateProjectContextsFromString(
            string projectDirectory,
            string json)
        {
            var globalJson = Path.Combine(new DirectoryInfo(projectDirectory).Parent.FullName, "global.json");

            if (!File.Exists(globalJson))
            {
                var file = new FileInfo(globalJson);
                try
                {
                    File.WriteAllText(file.FullName, @"{}");
                }
                catch (IOException)
                {
                    //this means there is someone else writing to the file already. So, just ignore it.
                }
            }

            var testPj = new ProjectJsonBuilder(null)
                         .FromStringBase(json)
                         .SaveToDisk(projectDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(projectDirectory);

            if (projectContexts.Count() == 0)
            {
                projectContexts = new []
                {
                    ProjectContext.Create(testPj, FrameworkConstants.CommonFrameworks.NetCoreApp10)
                };
            }

            return(projectContexts);
        }
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            if (!ExtensionsSearchPaths.Contains(descriptor.Location))
            {
                return(null);
            }

            var extensionPath = Path.Combine(descriptor.Location, descriptor.Id);

            var projectContext = ProjectContext.CreateContextForEachFramework(extensionPath).FirstOrDefault();

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

            var loadContext = projectContext.CreateLoadContext();

            var assembly = loadContext.LoadFromAssemblyName(new AssemblyName(descriptor.Id));

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Loaded referenced extension \"{0}\": assembly name=\"{1}\"", descriptor.Name, assembly.FullName);
            }

            return(new ExtensionEntry
            {
                Descriptor = descriptor,
                Assembly = assembly,
                ExportedTypes = assembly.ExportedTypes
            });
        }
Beispiel #12
0
        public static IServiceProvider CreateServices(string testAppName)
        {
#if RELEASE
            var applicationInfo = new ApplicationInfo("TestApp", Directory.GetCurrentDirectory(), "Release");
#else
            var applicationInfo = new ApplicationInfo("TestApp", Directory.GetCurrentDirectory(), "Debug");
#endif
            // When the tests are run the applicationInfo points to test project.
            // Change the app applicationInfo to point to the test application to be used
            // by test.
            var originalAppBase = applicationInfo.ApplicationBasePath; ////Microsoft.VisualStudio.Web.CodeGeneration.Core.FunctionalTest
#if NET451
            var testAppPath = Path.GetFullPath(Path.Combine(originalAppBase, "..", "..", "..", "..", "..", "TestApps", testAppName));
#else
            var testAppPath = Path.GetFullPath(Path.Combine(originalAppBase, "..", "TestApps", testAppName));
#endif
            var testEnvironment = new TestApplicationInfo(applicationInfo, testAppPath, testAppName);
            var context         = ProjectContext.CreateContextForEachFramework(testAppPath).First();
            var exporter        = new LibraryExporter(context, testEnvironment);
            var workspace       = new ProjectJsonWorkspace(context);
            return(new WebHostBuilder()
                   .UseServer(new DummyServer())
                   .UseStartup <ModelTypesLocatorTestWebApp.Startup>()
                   .ConfigureServices(services =>
            {
                services.AddSingleton <IApplicationInfo>(testEnvironment);
                services.AddSingleton <ILibraryExporter>(exporter);
                services.AddSingleton <CodeAnalysis.Workspace>(workspace);
            })
                   .Build()
                   .Services);
        }
Beispiel #13
0
 private void AddProject(string projectPath)
 {
     // Get all of the specific projects (there is a project per framework)
     foreach (var p in ProjectContext.CreateContextForEachFramework(projectPath))
     {
         AddProject(p);
     }
 }
Beispiel #14
0
        private void CalculateDefaultsForNonAssigned()
        {
            if (string.IsNullOrWhiteSpace(Project))
            {
                Project = Directory.GetCurrentDirectory();
            }

            if (string.IsNullOrWhiteSpace(Configuration))
            {
                Configuration = Constants.DefaultConfiguration;
            }

            var rids = PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers();

            if (Framework == null)
            {
                var defaultFrameworks = new[]
                {
                    FrameworkConstants.FrameworkIdentifiers.DnxCore,
                    FrameworkConstants.FrameworkIdentifiers.NetStandardApp,
                };

                var contexts = ProjectContext.CreateContextForEachFramework(Project, null);

                ProjectContext context;
                if (contexts.Count() == 1)
                {
                    context = contexts.Single();
                }
                else
                {
                    context = contexts.FirstOrDefault(c => defaultFrameworks.Contains(c.TargetFramework.Framework));
                    if (context == null)
                    {
                        throw new InvalidOperationException($"Couldn't find target to run. Possible causes:" + Environment.NewLine +
                                                            "1. No project.lock.json file or restore failed - run `dotnet restore`" + Environment.NewLine +
                                                            $"2. project.lock.json has multiple targets none of which is in default list ({string.Join(", ", defaultFrameworks)})");
                    }
                }

                _context = context.CreateRuntimeContext(rids);
            }
            else
            {
                _context = ProjectContext.Create(Project, NuGetFramework.Parse(Framework), rids);
            }

            if (Args == null)
            {
                _args = new List <string>();
            }
            else
            {
                _args = new List <string>(Args);
            }
        }
        public Assembly LoadExternalAssembly(ExtensionDescriptor descriptor)
        {
            var projectContext = ProjectContext.CreateContextForEachFramework(Path.Combine(descriptor.Location, descriptor.Id)).FirstOrDefault();

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

            var assemblyNames = new HashSet <string>(ApplicationAssemblyNames(), StringComparer.OrdinalIgnoreCase);

            // TODO: find a way to select the right configuration
            var libraryExporter = projectContext.CreateExporter("Debug");

            Assembly assembly = null;

            foreach (var libraryExport in libraryExporter.GetAllExports())
            {
                foreach (var asset in libraryExport.RuntimeAssemblyGroups.GetDefaultAssets())
                {
                    if (assemblyNames.Add(asset.Name))
                    {
                        try
                        {
                            if (asset.Name == descriptor.Id)
                            {
                                if (!File.Exists(asset.ResolvedPath))
                                {
                                    var location = Path.Combine(descriptor.Location, descriptor.Id);


                                    // We can do this but it relies on the dotnet cli sdk
                                    //Command.CreateDotNet("build", new [] { location }).Execute();


                                    // With an adapted compiler we only need to embed "csc.dll" and "csc.runtimeconfig.json"
                                    var success = new CSharpExtensionCompiler().Compile(projectContext, "Debug", projectContext.RootDirectory);
                                }
                            }

                            var loadedAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(asset.ResolvedPath);
                            if (loadedAssembly.GetName().Name == projectContext.ProjectFile.Name)
                            {
                                assembly = loadedAssembly;
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }

            return(assembly);
        }
Beispiel #16
0
        private void CalculateDefaultsForNonAssigned()
        {
            if (string.IsNullOrWhiteSpace(Project))
            {
                Project = Directory.GetCurrentDirectory();
            }

            if (string.IsNullOrWhiteSpace(Configuration))
            {
                Configuration = Constants.DefaultConfiguration;
            }

            var rids = PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers();

            if (Framework == null)
            {
                var defaultFrameworks = new[]
                {
                    FrameworkConstants.FrameworkIdentifiers.DnxCore,
                    FrameworkConstants.FrameworkIdentifiers.NetStandardApp,
                };

                var contexts = ProjectContext.CreateContextForEachFramework(Project, null);

                ProjectContext context;
                if (contexts.Count() == 1)
                {
                    context = contexts.Single();
                }
                else
                {
                    context = contexts.FirstOrDefault(c => defaultFrameworks.Contains(c.TargetFramework.Framework));
                    if (context == null)
                    {
                        throw new InvalidOperationException($"Couldn't find target to run. Defaults: {string.Join(", ", defaultFrameworks)}");
                    }
                }

                _context = context.CreateRuntimeContext(rids);
            }
            else
            {
                _context = ProjectContext.Create(Project, NuGetFramework.Parse(Framework), rids);
            }

            if (Args == null)
            {
                _args = new List <string>();
            }
            else
            {
                _args = new List <string>(Args);
            }
        }
Beispiel #17
0
        private IEnumerable <Feature> BuiltinFeatures()
        {
            var projectContext = ProjectContext.CreateContextForEachFramework("").FirstOrDefault();

            var additionalLibraries = projectContext.LibraryManager
                                      .GetLibraries()
                                      .Where(x => x.Identity.Name.StartsWith("Orchard"));

            var features = new List <Feature>();

            foreach (var additonalLib in additionalLibraries)
            {
                var assembly = Assembly.Load(new AssemblyName(additonalLib.Identity.Name));

                var feature = new Feature
                {
                    Descriptor = new FeatureDescriptor
                    {
                        Id        = additonalLib.Identity.Name,
                        Extension = new ExtensionDescriptor
                        {
                            Id = additonalLib.Identity.Name
                        }
                    },
                    ExportedTypes =
                        assembly.ExportedTypes
                        .Where(t => t.GetTypeInfo().IsClass&& !t.GetTypeInfo().IsAbstract)
                        //.Except(new[] { typeof(DefaultOrchardHost) })
                        .ToArray()
                };

                features.Add(feature);

                // Register built-in features in the type provider

                // TODO: Prevent this code from adding the services from modules as it's already added
                // by the extension loader.

                if (!_builtinFeatureRegistered)
                {
                    foreach (var type in feature.ExportedTypes)
                    {
                        _typeFeatureProvider.TryAdd(type, feature);
                    }
                }
            }

            _builtinFeatureRegistered = true;

            return(features);
        }
        public IProjectContext Create(string filePath,
                                      NuGetFramework framework,
                                      string configuration = null,
                                      string outputDir     = null)
        {
            var project = SelectCompatibleFramework(
                framework,
                ProjectContext.CreateContextForEachFramework(filePath,
                                                             runtimeIdentifiers: RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers()));

            return(new DotNetProjectContext(project,
                                            configuration ?? Constants.DefaultConfiguration,
                                            outputDir));
        }
Beispiel #19
0
        private void GetProjectInfo(string testRoot)
        {
            _testProjectsRoot  = testRoot;
            _rootDirInfo       = new DirectoryInfo(_testProjectsRoot);
            _testAppDirDirInfo = new DirectoryInfo(Path.Combine(_testProjectsRoot, "TestApp"));
            _testLibDirInfo    = new DirectoryInfo(Path.Combine(_testProjectsRoot, "TestLibrary"));

            var contexts = ProjectContext.CreateContextForEachFramework(
                _testAppDirDirInfo.FullName,
                null,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            _runtime = contexts.FirstOrDefault(c => !string.IsNullOrEmpty(c.RuntimeIdentifier))?.RuntimeIdentifier;
        }
Beispiel #20
0
        public GivenThatWeWantToRunTestsInTheConsole()
        {
            var testInstance =
                TestAssetsManager.CreateTestInstance("ProjectWithTests", identifier: "ConsoleTests").WithLockFiles();

            _projectFilePath = Path.Combine(testInstance.TestRoot, "project.json");
            var contexts = ProjectContext.CreateContextForEachFramework(
                _projectFilePath,
                null,
                PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers());

            var runtime = contexts.FirstOrDefault(c => !string.IsNullOrEmpty(c.RuntimeIdentifier))?.RuntimeIdentifier;

            _defaultOutputPath = Path.Combine(testInstance.TestRoot, "bin", "Debug", DefaultFramework, runtime);
        }
        public IEnumerable <ProjectDependency> ResolveProjectDependencies(string projectDir, string xprojFile = null)
        {
            var projectContexts = ProjectContext.CreateContextForEachFramework(projectDir);

            xprojFile = xprojFile ?? FindXprojFile(projectDir);

            ProjectRootElement xproj = null;

            if (xprojFile != null)
            {
                xproj = ProjectRootElement.Open(xprojFile);
            }

            return(ResolveProjectDependencies(projectContexts, ResolveXProjProjectDependencyNames(xproj)));
        }
Beispiel #22
0
        private MigrationRuleInputs ComputeMigrationRuleInputs(MigrationSettings migrationSettings)
        {
            var projectContexts = ProjectContext.CreateContextForEachFramework(migrationSettings.ProjectDirectory);

            var templateMSBuildProject = migrationSettings.MSBuildProjectTemplate;

            if (templateMSBuildProject == null)
            {
                throw new Exception("Expected non-null MSBuildProjectTemplate in MigrationSettings");
            }

            var propertyGroup = templateMSBuildProject.AddPropertyGroup();
            var itemGroup     = templateMSBuildProject.AddItemGroup();

            return(new MigrationRuleInputs(projectContexts, templateMSBuildProject, itemGroup, propertyGroup));
        }
Beispiel #23
0
        private static ProjectContext CreateProjectContext(string projectPath)
        {
            projectPath = projectPath ?? Directory.GetCurrentDirectory();
            var framework = NuGet.Frameworks.FrameworkConstants.CommonFrameworks.NetCoreApp10.GetShortFolderName();

            if (!projectPath.EndsWith(Microsoft.DotNet.ProjectModel.Project.FileName))
            {
                projectPath = Path.Combine(projectPath, Microsoft.DotNet.ProjectModel.Project.FileName);
            }

            if (!File.Exists(projectPath))
            {
                throw new InvalidOperationException($"{projectPath} does not exist.");
            }
            return(ProjectContext.CreateContextForEachFramework(projectPath).FirstOrDefault(c => c.TargetFramework.GetShortFolderName() == framework));
        }
Beispiel #24
0
        private static IEnumerable <ProjectContext> CreateProjectContexts(string projectPath)
        {
            projectPath = projectPath ?? Directory.GetCurrentDirectory();

            if (!projectPath.EndsWith(Project.FileName))
            {
                projectPath = Path.Combine(projectPath, Project.FileName);
            }

            if (!File.Exists(projectPath))
            {
                throw new InvalidOperationException($"{projectPath} does not exist.");
            }

            return(ProjectContext.CreateContextForEachFramework(projectPath));
        }
Beispiel #25
0
        private static IEnumerable <ProjectContext> CreateProjectContexts(string projectPath = null)
        {
            projectPath = projectPath ?? Directory.GetCurrentDirectory();

            if (!projectPath.EndsWith(Project.FileName))
            {
                projectPath = Path.Combine(projectPath, Project.FileName);
            }

            if (!File.Exists(projectPath))
            {
                return(Enumerable.Empty <ProjectContext>());
            }

            return(ProjectContext.CreateContextForEachFramework(projectPath));
        }
Beispiel #26
0
        private static ProjectContext GetProjectContext(string targetFramework, string projectPath)
        {
            // Selecting the target framework for the project is done in the same manner as dotnet run. If a target framework
            // was specified, we attempt to create a context for that framework (and error out if the framework is unsupported).
            // Otherwise, we pick the first context supported by the project.

            var contexts = ProjectContext.CreateContextForEachFramework(Path.GetFullPath(projectPath));
            var context  = contexts.First();

            if (targetFramework != null)
            {
                var framework = NuGetFramework.Parse(targetFramework);
                context = contexts.FirstOrDefault(c => c.TargetFramework.Equals(framework));
            }

            return(context);
        }
Beispiel #27
0
        public GivenThatWeWantToUseDotnetTestE2EInDesignTime()
        {
            var testInstance = TestAssetsManager.CreateTestInstance("ProjectWithTests").WithLockFiles();

            _projectFilePath = Path.Combine(testInstance.TestRoot, "project.json");
            var contexts = ProjectContext.CreateContextForEachFramework(
                _projectFilePath,
                null,
                PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers());
            var runtime = contexts.FirstOrDefault(c => !string.IsNullOrEmpty(c.RuntimeIdentifier))?.RuntimeIdentifier;

            _outputPath = Path.Combine(testInstance.TestRoot, "bin", "Debug", DefaultFramework, runtime);
            var buildCommand = new BuildCommand(_projectFilePath);
            var result       = buildCommand.Execute();

            result.Should().Pass();
        }
        static GenFuTagHelper()
        {
            //TODO: Review with James. This stuff used to be wired up via DI but is not anymore.
            //      It was also very slow so I had to put it in a static constructor. Doing this for every tag helper instance was too slow.
            var              projectContext = ProjectContext.CreateContextForEachFramework(Directory.GetCurrentDirectory(), null, new[] { PlatformServices.Default.Application.RuntimeFramework.FullName }).First();
            ApplicationInfo  appInfo        = new ApplicationInfo("TagHelperSamples.GenFu", PlatformServices.Default.Application.ApplicationBasePath);
            ILibraryExporter exporter       = new LibraryExporter(projectContext, appInfo);

            _references = new List <MetadataReference>();
            var exports      = exporter.GetAllExports();
            var metaDataRefs = exports.SelectMany(x => x.GetMetadataReferences()).ToList();

            foreach (var reference in metaDataRefs)
            {
                _references.Add(reference);
            }
        }
        private List <string> GetApplicationAssemblyNames()
        {
            var assemblyNames  = new HashSet <string>(System.StringComparer.OrdinalIgnoreCase);
            var projectContext = ProjectContext.CreateContextForEachFramework("").FirstOrDefault();

            // TODO: find a way to select the right configuration
            var libraryExporter = projectContext.CreateExporter("Debug");

            foreach (var libraryExport in libraryExporter.GetAllExports())
            {
                foreach (var asset in libraryExport.RuntimeAssemblyGroups.GetDefaultAssets())
                {
                    assemblyNames.Add(asset.Name);
                }
            }

            return(assemblyNames.ToList());
        }
        private static IEnumerable <ProjectContext> GenerateProjectContextsFromString(
            string projectDirectory,
            string json)
        {
            var testPj = new ProjectJsonBuilder(null)
                         .FromStringBase(json)
                         .SaveToDisk(projectDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(projectDirectory);

            if (projectContexts.Count() == 0)
            {
                projectContexts = new []
                {
                    ProjectContext.Create(testPj, FrameworkConstants.CommonFrameworks.NetCoreApp10)
                };
            }

            return(projectContexts);
        }