コード例 #1
0
        public void GetSubToolsetVersion()
        {
            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", null);

                ProjectInstance p = GetSampleProjectInstance(null, null, new ProjectCollection());

                Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
                Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.SubToolsetVersion);

                if (p.Toolset.DefaultSubToolsetVersion == null)
                {
                    Assert.Equal(MSBuildConstants.CurrentVisualStudioVersion, p.GetPropertyValue("VisualStudioVersion"));
                }
                else
                {
                    Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.GetPropertyValue("VisualStudioVersion"));
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
コード例 #2
0
        public void PropertiesAccessors()
        {
            ProjectInstance p = GetSampleProjectInstance();

            Assert.Equal("v1", p.GetPropertyValue("p1"));
            Assert.Equal("v2X", p.GetPropertyValue("p2"));
        }
コード例 #3
0
        // Internal for testing
        internal static bool TryResolveConfigurationOutputPath(ProjectInstance projectInstance, out string path)
        {
            var intermediateOutputPath = projectInstance.GetPropertyValue(IntermediateOutputPathPropertyName);

            if (string.IsNullOrEmpty(intermediateOutputPath))
            {
                path = null;
                return(false);
            }

            if (!Path.IsPathRooted(intermediateOutputPath))
            {
                // Relative path, need to convert to absolute.
                var projectDirectory = projectInstance.GetPropertyValue(MSBuildProjectDirectoryPropertyName);
                if (string.IsNullOrEmpty(projectDirectory))
                {
                    // This should never be true but we're beign extra careful.
                    path = null;
                    return(false);
                }

                intermediateOutputPath = Path.Combine(projectDirectory, intermediateOutputPath);
            }

            intermediateOutputPath = intermediateOutputPath
                                     .Replace('\\', Path.DirectorySeparatorChar)
                                     .Replace('/', Path.DirectorySeparatorChar);
            path = Path.Combine(intermediateOutputPath, LanguageServerConstants.ProjectConfigurationFile);
            return(true);
        }
コード例 #4
0
        private bool IsApplication(ProjectInstance projectInstance)
        {
            var isAndroidApp = projectInstance.GetPropertyValue("AndroidApplication")?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false;
            var isiOSApp     = projectInstance.GetPropertyValue("ProjectTypeGuids")?.Equals("{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", StringComparison.OrdinalIgnoreCase) ?? false;
            var isExe        = projectInstance.GetPropertyValue("OutputType")?.Equals("Exe", StringComparison.OrdinalIgnoreCase) ?? false;
            var isWasm       = projectInstance.GetPropertyValue("WasmHead")?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false;

            return(isAndroidApp || (isiOSApp && isExe) || isWasm);
        }
コード例 #5
0
        public IEnumerable <ReferenceInfo> GetReferences(ProjectInstance requesterInstance)
        {
            IEnumerable <ProjectItemInstance>      projectReferenceItems;
            IEnumerable <GlobalPropertiesModifier> globalPropertiesModifiers = null;

            switch (GetProjectType(requesterInstance))
            {
            case ProjectType.OuterBuild:
                projectReferenceItems = ConstructInnerBuildReferences(requesterInstance);
                break;

            case ProjectType.InnerBuild:
                globalPropertiesModifiers = ModifierForNonMultitargetingNodes.Add((parts, reference) => parts.AddPropertyToUndefine(GetInnerBuildPropertyName(requesterInstance)));
                projectReferenceItems     = requesterInstance.GetItems(ItemTypeNames.ProjectReference);
                break;

            case ProjectType.NonMultitargeting:
                globalPropertiesModifiers = ModifierForNonMultitargetingNodes;
                projectReferenceItems     = requesterInstance.GetItems(ItemTypeNames.ProjectReference);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            foreach (var projectReferenceItem in projectReferenceItems)
            {
                if (!String.IsNullOrEmpty(projectReferenceItem.GetMetadataValue(ToolsVersionMetadataName)))
                {
                    throw new InvalidOperationException(
                              String.Format(
                                  CultureInfo.InvariantCulture,
                                  ResourceUtilities.GetResourceString(
                                      "ProjectGraphDoesNotSupportProjectReferenceWithToolset"),
                                  projectReferenceItem.EvaluatedInclude,
                                  requesterInstance.FullPath));
                }

                var projectReferenceFullPath = projectReferenceItem.GetMetadataValue(FullPathMetadataName);

                var referenceGlobalProperties = GetGlobalPropertiesForItem(projectReferenceItem, requesterInstance.GlobalPropertiesDictionary, globalPropertiesModifiers);

                var requesterPlatform            = "";
                var requesterPlatformLookupTable = "";

                if (ConversionUtilities.ValidBooleanTrue(requesterInstance.GetPropertyValue("EnableDynamicPlatformResolution")))
                {
                    requesterPlatform            = requesterInstance.GetPropertyValue("Platform");
                    requesterPlatformLookupTable = requesterInstance.GetPropertyValue("PlatformLookupTable");
                }

                var referenceConfig = new ConfigurationMetadata(projectReferenceFullPath, referenceGlobalProperties, requesterPlatform, requesterPlatformLookupTable, projectReferenceItem.HasMetadata("SetPlatform"));

                yield return(new ReferenceInfo(referenceConfig, projectReferenceItem));
            }
        }
コード例 #6
0
        private ICommand GetTargetCommand()
        {
            var globalProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                // This property disables default item globbing to improve performance
                // This should be safe because we are not evaluating items, only properties
                { Constants.EnableDefaultItems, "false" },
                { Constants.MSBuildExtensionsPath, AppContext.BaseDirectory }
            };

            if (!string.IsNullOrWhiteSpace(Configuration))
            {
                globalProperties.Add("Configuration", Configuration);
            }

            if (!string.IsNullOrWhiteSpace(Framework))
            {
                globalProperties.Add("TargetFramework", Framework);
            }

            if (!string.IsNullOrWhiteSpace(Runtime))
            {
                globalProperties.Add("RuntimeIdentifier", Runtime);
            }

            var project = new ProjectInstance(Project, globalProperties, null);

            string runProgram = project.GetPropertyValue("RunCommand");

            if (string.IsNullOrEmpty(runProgram))
            {
                ThrowUnableToRunError(project);
            }

            string runArguments        = project.GetPropertyValue("RunArguments");
            string runWorkingDirectory = project.GetPropertyValue("RunWorkingDirectory");

            if (Args.Any())
            {
                runArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(Args);
            }

            CommandSpec commandSpec = new CommandSpec(runProgram, runArguments);

            var command = CommandFactoryUsingResolver.Create(commandSpec)
                          .WorkingDirectory(runWorkingDirectory);

            var rootVariableName = Environment.Is64BitProcess ? "DOTNET_ROOT" : "DOTNET_ROOT(x86)";

            if (Environment.GetEnvironmentVariable(rootVariableName) == null)
            {
                command.EnvironmentVariable(rootVariableName, Path.GetDirectoryName(new Muxer().MuxerPath));
            }

            return(command);
        }
コード例 #7
0
ファイル: TargetsTest.cs プロジェクト: ILMTitan/FibDotNet
        public void TestSetFibBaseImage(string registry, string repository, string tag, string digest, string expectedFibBaseImage)
        {
            _projectInstance.SetProperty("FibBaseRegistry", registry);
            _projectInstance.SetProperty("FibBaseRepository", repository);
            _projectInstance.SetProperty("FibBaseTag", tag);
            _projectInstance.SetProperty("FibBaseDigest", digest);

            Assert.IsTrue(_projectInstance.Build("SetFibBaseImage", Loggers));

            Assert.AreEqual(expectedFibBaseImage, _projectInstance.GetPropertyValue("FibBaseImage"));
        }
コード例 #8
0
        private ICommand GetRunCommand()
        {
            var globalProperties = new Dictionary <string, string>
            {
                { Constants.MSBuildExtensionsPath, AppContext.BaseDirectory }
            };

            if (!string.IsNullOrWhiteSpace(Configuration))
            {
                globalProperties.Add("Configuration", Configuration);
            }

            if (!string.IsNullOrWhiteSpace(Framework))
            {
                globalProperties.Add("TargetFramework", Framework);
            }

            ProjectInstance projectInstance = new ProjectInstance(Project, globalProperties, null);

            string runProgram = projectInstance.GetPropertyValue("RunCommand");

            if (string.IsNullOrEmpty(runProgram))
            {
                string outputType = projectInstance.GetPropertyValue("OutputType");

                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.RunCommandExceptionUnableToRun,
                              "dotnet run",
                              "OutputType",
                              outputType));
            }

            string runArguments        = projectInstance.GetPropertyValue("RunArguments");
            string runWorkingDirectory = projectInstance.GetPropertyValue("RunWorkingDirectory");

            string fullArguments = runArguments;

            if (_args.Any())
            {
                fullArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_args);
            }

            CommandSpec commandSpec = new CommandSpec(runProgram, fullArguments, CommandResolutionStrategy.None);

            return(Command.Create(commandSpec)
                   .WorkingDirectory(runWorkingDirectory));
        }
コード例 #9
0
        [Category("NotWorking")]          // until we figure out why it fails on wrench.
        public void ItemsInTargets()
        {
            string project_xml = @"<Project DefaultTargets='Default' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
	<Target Name='Default'>
		<PropertyGroup>
			<_ExplicitMSCorlibPath>$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToStandardLibraries ('$(TargetFrameworkIdentifier)', '$(TargetFrameworkVersion)', '$(TargetFrameworkProfile)'))\mscorlib.dll</_ExplicitMSCorlibPath>
		</PropertyGroup>
		<ItemGroup>
			<_ExplicitReference
				Include='$(_ExplicitMSCorlibPath)'
				Condition='Exists($(_ExplicitMSCorlibPath))'>
				<Private>false</Private>
			</_ExplicitReference>
		</ItemGroup>
	</Target>
	<Import Project='$(MSBuildBinPath)\\Microsoft.CSharp.targets' />
</Project>";
            var    xml         = XmlReader.Create(new StringReader(project_xml));
            var    root        = ProjectRootElement.Create(xml);

            root.FullPath = "ProjectInstanceTest.ConditionalExpression.proj";
            var proj = new ProjectInstance(root, null, "4.0", ProjectCollection.GlobalProjectCollection);

            proj.Build();
            // make sure the property value expansion is done successfully.
            Assert.IsTrue(!string.IsNullOrEmpty(proj.GetPropertyValue("_ExplicitMSCorlibPath")), "premise: propertyValue by ToolLocationHelper func call");
            var items = proj.GetItems("_ExplicitReference");

            // make sure items are stored after build.
            Assert.IsTrue(items.Any(), "items.Any");
            Assert.IsTrue(!string.IsNullOrEmpty(items.First().EvaluatedInclude), "item.EvaluatedInclude");
        }
コード例 #10
0
        /// <summary>
        /// Initialize 'resolvedInfo' by having MSBuild resolve the assembly in the context of the current project
        /// </summary>
        /// <param name="assemblyInclude">Either a full path to a file on disk, or a simple name or fusion name</param>
        /// <param name="isAlreadyInProjectFile">Pass true for this parameter, as well as the evaluated include for the other parameter, if you are trying to discover the MSBuild resolution of an existing ProjectElement</param>
        private void AddToProjectFileAndTryResolve(string assemblyInclude)
        {
            Action <string> Trace = (s) => FSharpTrace.PrintLine("ProjectSystemReferenceResolution", () => "ResolveAssemblyReferenceCore: " + s);

            Trace("starting: \"" + assemblyInclude + "\"");
            ProjectInstance instance = null;

            instance = this.ProjectMgr.BuildProject.CreateProjectInstance();   // use a fresh instance...
            instance.AddItem(ProjectFileConstants.Reference, assemblyInclude); // ...and mutate it as through there were another <Reference Include="blah"> there
            Trace("instance[Configuration]=" + instance.GetPropertyValue("Configuration"));
            Trace("instance[Platform]=" + instance.GetPropertyValue("Platform"));
            var result = BuildInstance(this.ProjectMgr, ref instance, MsBuildTarget.ResolveAssemblyReferences);

            this.ResolveFromBuiltProject(assemblyInclude, result);
            Trace("finished without finding original item: \"" + assemblyInclude + "\"");
        }
コード例 #11
0
        /// <inheritdoc />
        public void PredictInputsAndOutputs(ProjectInstance project, ProjectPredictionReporter reporter)
        {
            // This is based on $(VCTargetsPath)\BuildCustomizations\masm.targets, if the before targets
            // property isn't set then the masm.targets haven't been imported, and no @(MASM) items will
            // be processed by the MASM targets.
            if (string.IsNullOrWhiteSpace(project.GetPropertyValue(MasmBeforeTargetsPropertyName)))
            {
                return;
            }

            ICollection <ProjectItemInstance> masmItems = project.GetItems(MasmItemName);

            if (masmItems.Count == 0)
            {
                return;
            }

            var reportedIncludes = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (ProjectItemInstance masmItem in masmItems)
            {
                if (IsExcludedFromBuild(masmItem))
                {
                    continue;
                }

                ReportInputs(reporter, masmItem, reportedIncludes);
                ReportOutputs(reporter, masmItem);
            }
        }
コード例 #12
0
        public void TaskNodesDieAfterBuild()
        {
            using (TestEnvironment env = TestEnvironment.Create())
            {
                string            pidTaskProject  = $@"
<Project>
    <UsingTask TaskName=""ProcessIdTask"" AssemblyName=""net.r_eg.IeXod.Engine.UnitTests"" TaskFactory=""TaskHostFactory"" />
    <Target Name='AccessPID'>
        <ProcessIdTask>
            <Output PropertyName=""PID"" TaskParameter=""Pid"" />
        </ProcessIdTask>
    </Target>
</Project>";
                TransientTestFile project         = env.CreateFile("testProject.csproj", pidTaskProject);
                ProjectInstance   projectInstance = new ProjectInstance(project.Path);
                projectInstance.Build().ShouldBeTrue();
                string processId = projectInstance.GetPropertyValue("PID");
                string.IsNullOrEmpty(processId).ShouldBeFalse();
                Int32.TryParse(processId, out int pid).ShouldBeTrue();
                Process.GetCurrentProcess().Id.ShouldNotBe <int>(pid);
                try
                {
                    Process taskHostNode = Process.GetProcessById(pid);
                    taskHostNode.WaitForExit(2000).ShouldBeTrue();
                }
                // We expect the TaskHostNode to exit quickly. If it exits before Process.GetProcessById, it will throw an ArgumentException.
                catch (ArgumentException e)
                {
                    e.Message.ShouldBe($"Process with an Id of {pid} is not running.");
                }
            }
        }
コード例 #13
0
ファイル: ProjectInstance_Tests.cs プロジェクト: xen2/msbuild
        public void CreateProjectInstancePassesEnvironment()
        {
            Project         p = new Project();
            ProjectInstance i = p.CreateProjectInstance();

            Assert.True(i.GetPropertyValue("username") != null);
        }
コード例 #14
0
        public void GetSubToolsetVersion_FromConstructor()
        {
            string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");

            try
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", "ABC");

                string projectContent = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                        <Target Name='t'>
                            <Message Text='Hello'/>
                        </Target>
                    </Project>";

                ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectContent)));

                IDictionary <string, string> globalProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                globalProperties.Add("VisualStudioVersion", "ABCD");

                IDictionary <string, string> projectCollectionGlobalProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                projectCollectionGlobalProperties.Add("VisualStudioVersion", "ABCDE");

                ProjectInstance p = new ProjectInstance(xml, globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, "ABCDEF", new ProjectCollection(projectCollectionGlobalProperties));

                Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
                Assert.Equal("ABCDEF", p.SubToolsetVersion);
                Assert.Equal("ABCDEF", p.GetPropertyValue("VisualStudioVersion"));
            }
            finally
            {
                Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
            }
        }
コード例 #15
0
        private static void AddCustomOutputs(ISet <string> outputs, ProjectInstance projectInstance)
        {
            foreach (ProjectItemInstance customOutput in projectInstance.GetItems("UpToDateCheckOutput"))
            {
                outputs.Add(customOutput.GetMetadataValue("FullPath"));
            }

            foreach (ProjectItemInstance buildOutput in projectInstance.GetItems("UpToDateCheckBuilt").Where(i => string.IsNullOrEmpty(i.GetMetadataValue("Original"))))
            {
                outputs.Add(buildOutput.GetMetadataValue("FullPath"));
            }

            // See if this is a NoTarget SDK project. If so, skip the outputs.
            string usingNoTargets     = projectInstance.GetPropertyValue("UsingMicrosoftNoTargetsSdk");
            bool   isNoTargetsProject = !string.IsNullOrEmpty(usingNoTargets) && usingNoTargets.Trim().Equals("true", StringComparison.OrdinalIgnoreCase);

            if (!isNoTargetsProject)
            {
                return;
            }

            // This IS a NoTarget SDK project, so we have to do some further adjusting. Because of:
            // Target "CollectUpToDateCheckBuiltDesignTime" in file "C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Microsoft\VisualStudio\Managed\Microsoft.Managed.DesignTime.targets"
            RemoveNoTargetsOutputs(outputs, projectInstance);
        }
コード例 #16
0
        public IEnumerable <FilePath> EnumerateRazorToolAssemblies()
        {
            HashSet <string> seen = new HashSet <string>();

            var globalProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                // This property disables default item globbing to improve performance
                // This should be safe because we are not evaluating items, only properties
                { Constants.EnableDefaultItems, "false" }
            };

            foreach (var projectFile in _directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.*proj"))
            {
                var project = new ProjectInstance(projectFile, globalProperties, null);
                var path    = project.GetPropertyValue("_RazorToolAssembly");
                if (string.IsNullOrEmpty(path))
                {
                    continue;
                }

                if (!seen.Add(path))
                {
                    continue;
                }

                yield return(new FilePath(path));
            }
        }
コード例 #17
0
        private ICommand GetTargetCommand()
        {
            var globalProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                // This property disables default item globbing to improve performance
                // This should be safe because we are not evaluating items, only properties
                { Constants.EnableDefaultItems, "false" },
                { Constants.MSBuildExtensionsPath, AppContext.BaseDirectory }
            };

            if (!string.IsNullOrWhiteSpace(Configuration))
            {
                globalProperties.Add("Configuration", Configuration);
            }

            if (!string.IsNullOrWhiteSpace(Framework))
            {
                globalProperties.Add("TargetFramework", Framework);
            }

            if (!string.IsNullOrWhiteSpace(Runtime))
            {
                globalProperties.Add("RuntimeIdentifier", Runtime);
            }

            var project = new ProjectInstance(Project, globalProperties, null);

            string runProgram = project.GetPropertyValue("RunCommand");

            if (string.IsNullOrEmpty(runProgram))
            {
                ThrowUnableToRunError(project);
            }

            string runArguments        = project.GetPropertyValue("RunArguments");
            string runWorkingDirectory = project.GetPropertyValue("RunWorkingDirectory");

            if (Args.Any())
            {
                runArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(Args);
            }

            CommandSpec commandSpec = new CommandSpec(runProgram, runArguments, CommandResolutionStrategy.None);

            return(Command.Create(commandSpec)
                   .WorkingDirectory(runWorkingDirectory));
        }
コード例 #18
0
            static bool IsDesignTimeBuild(ProjectInstance project)
            {
                var designTimeBuild = project.GetPropertyValue(DesignTimeProperties.DesignTimeBuild);
                var buildingProject = project.GlobalPropertiesDictionary[DesignTimeProperties.BuildingProject]?.EvaluatedValue;

                return(MSBuildStringIsTrue(designTimeBuild) ||
                       buildingProject != null && !MSBuildStringIsTrue(buildingProject));
            }
コード例 #19
0
        private ICommand GetRunCommand()
        {
            Dictionary <string, string> globalProperties = new Dictionary <string, string>()
            {
                { LocalizableStrings.RunCommandMSBuildExtensionsPath, AppContext.BaseDirectory }
            };

            if (!string.IsNullOrWhiteSpace(Configuration))
            {
                globalProperties.Add(LocalizableStrings.RunCommandConfiguration, Configuration);
            }

            if (!string.IsNullOrWhiteSpace(Framework))
            {
                globalProperties.Add(LocalizableStrings.RunCommandTargetFramework, Framework);
            }

            ProjectInstance projectInstance = new ProjectInstance(Project, globalProperties, null);

            string runProgram = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandProjectInstance);

            if (string.IsNullOrEmpty(runProgram))
            {
                string outputType = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandOutputType);

                throw new GracefulException(string.Join(Environment.NewLine,
                                                        LocalizableStrings.RunCommandExceptionUnableToRun1,
                                                        LocalizableStrings.RunCommandExceptionUnableToRun2,
                                                        $"{LocalizableStrings.RunCommandExceptionUnableToRun3} '{outputType}'."));
            }

            string runArguments        = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandRunArguments);
            string runWorkingDirectory = projectInstance.GetPropertyValue(LocalizableStrings.RunCommandRunWorkingDirectory);

            string fullArguments = runArguments;

            if (_args.Any())
            {
                fullArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_args);
            }

            CommandSpec commandSpec = new CommandSpec(runProgram, fullArguments, CommandResolutionStrategy.None);

            return(Command.Create(commandSpec)
                   .WorkingDirectory(runWorkingDirectory));
        }
コード例 #20
0
        /// <inheritdoc/>
        public void PredictInputsAndOutputs(ProjectInstance projectInstance, ProjectPredictionReporter predictionReporter)
        {
            // This predictor only applies when StyleCop exists and is enabled.
            if (!projectInstance.Targets.ContainsKey(StyleCopTargetName) ||
                projectInstance.GetPropertyValue(StyleCopEnabledPropertyName).Equals("false", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            // Find the StyleCop settings file as an input. If the override settings file is specified and valid,
            // it's used. Else fall back to finding the project settings file. Note that the validation or lack thereof
            // mimics what StyleCop actually does.
            string styleCopSettingsFile = TryGetOverrideSettingsFile(projectInstance, out string styleCopOverrideSettingsFile)
                ? styleCopOverrideSettingsFile
                : GetProjectSettingsFile(projectInstance.Directory);

            if (!string.IsNullOrEmpty(styleCopSettingsFile))
            {
                predictionReporter.ReportInputFile(styleCopSettingsFile);
            }

            // For Completeness we should consider Compile items as well since they're passed to StyleCop, but in practice another predictor will take care of that.

            // StyleCop addins as input directories
            foreach (ProjectItemInstance item in projectInstance.GetItems(StyleCopAdditionalAddinPathsItemName))
            {
                string addinPath         = item.GetMetadataValue("FullPath");
                string expandedAddinPath = Environment.ExpandEnvironmentVariables(addinPath);
                if (Directory.Exists(expandedAddinPath))
                {
                    predictionReporter.ReportInputDirectory(expandedAddinPath);
                }
            }

            // StyleCop violations file as an output
            string styleCopOutputFile = projectInstance.GetPropertyValue(StyleCopOutputFilePropertyName);

            if (!string.IsNullOrEmpty(styleCopOutputFile))
            {
                predictionReporter.ReportOutputFile(styleCopOutputFile);
            }

            // When StyleCopCacheResults is true, a StyleCop.Cache file is written adjacent to the project.
            // Currently we want to avoid predicting this as predicting outputs to non-output directories generally leads to problems in the consumers of this library.
            // If the need for absolute completeness arises, it should be added and those consumers will just need to deal.
        }
コード例 #21
0
ファイル: RunCommand.cs プロジェクト: vkargov/cli
        private ICommand GetRunCommand()
        {
            Dictionary <string, string> globalProperties = new Dictionary <string, string>()
            {
                { "MSBuildExtensionsPath", AppContext.BaseDirectory }
            };

            if (!string.IsNullOrWhiteSpace(Configuration))
            {
                globalProperties.Add("Configuration", Configuration);
            }

            if (!string.IsNullOrWhiteSpace(Framework))
            {
                globalProperties.Add("TargetFramework", Framework);
            }

            ProjectInstance projectInstance = new ProjectInstance(Project, globalProperties, null);

            string runProgram = projectInstance.GetPropertyValue("RunCommand");

            if (string.IsNullOrEmpty(runProgram))
            {
                string outputType = projectInstance.GetPropertyValue("OutputType");

                throw new GracefulException(string.Join(Environment.NewLine,
                                                        "Unable to run your project.",
                                                        "Please ensure you have a runnable project type and ensure 'dotnet run' supports this project.",
                                                        $"The current OutputType is '{outputType}'."));
            }

            string runArguments        = projectInstance.GetPropertyValue("RunArguments");
            string runWorkingDirectory = projectInstance.GetPropertyValue("RunWorkingDirectory");

            string fullArguments = runArguments;

            if (_args.Any())
            {
                fullArguments += " " + ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(_args);
            }

            CommandSpec commandSpec = new CommandSpec(runProgram, fullArguments, CommandResolutionStrategy.None);

            return(Command.Create(commandSpec)
                   .WorkingDirectory(runWorkingDirectory));
        }
コード例 #22
0
            private static string[] GetFullTargetFrameworkSubsetNames(ProjectInstance projectInstance)
            {
                string val = projectInstance.GetPropertyValue(FullReferenceAssemblyNames).Trim();

                string[] fullTargetFrameworkSubsetNames = val.Split(';').Select(s => s.Trim()).ToArray();

                return(fullTargetFrameworkSubsetNames);
            }
コード例 #23
0
            private static string[] GetPdtarSearchPaths(ProjectInstance projectInstance)
            {
                string val = projectInstance.GetPropertyValue(ProjectDesignTimeAssemblyResolutionSearchPaths).Trim();

                string[] _pdtarSearchPaths = val.Split(';').Select(s => s.Trim()).ToArray();

                return(_pdtarSearchPaths);
            }
コード例 #24
0
            private static string[] GetFullFrameworkFolders(ProjectInstance projectInstance)
            {
                string val = projectInstance.GetPropertyValue(FullFrameworkReferenceAssemblyPaths).Trim();

                string[] _fullFrameworkFolders = val.Split(';').Select(s => s.Trim()).ToArray();

                return(_fullFrameworkFolders);
            }
コード例 #25
0
 public static IEnumerable <string> GetPlatforms(this ProjectInstance projectInstance)
 {
     return((projectInstance.GetPropertyValue("Platforms") ?? "")
            .Split(
                new char[] { ';' },
                StringSplitOptions.RemoveEmptyEntries)
            .Where(p => !string.IsNullOrWhiteSpace(p))
            .DefaultIfEmpty("AnyCPU"));
 }
コード例 #26
0
        public static string GetProjectId(this ProjectInstance projectInstance)
        {
            var projectGuidProperty = projectInstance.GetPropertyValue("ProjectGuid");
            var projectGuid         = string.IsNullOrEmpty(projectGuidProperty)
                ? Guid.NewGuid()
                : new Guid(projectGuidProperty);

            return(projectGuid.ToString("B").ToUpper());
        }
コード例 #27
0
 public static IEnumerable <string> GetConfigurations(this ProjectInstance projectInstance)
 {
     return((projectInstance.GetPropertyValue("Configurations") ?? "Debug;Release")
            .Split(
                new char[] { ';' },
                StringSplitOptions.RemoveEmptyEntries)
            .Where(c => !string.IsNullOrWhiteSpace(c))
            .DefaultIfEmpty("Debug"));
 }
コード例 #28
0
ファイル: ProjectInstance_Tests.cs プロジェクト: xen2/msbuild
        public void SetGlobalPropertyOnInstance()
        {
            Dictionary <string, string> globals = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "p", "p1" }
            };
            Project         p        = new Project(ProjectRootElement.Create(), globals, null);
            ProjectInstance instance = p.CreateProjectInstance();

            instance.SetProperty("p", "p2");

            Assert.Equal("p2", instance.GetPropertyValue("p"));

            // And clearing it should not expose the original global property value
            instance.SetProperty("p", "");

            Assert.Equal("", instance.GetPropertyValue("p"));
        }
コード例 #29
0
            private static string GetStateFile(ProjectInstance projectInstance)
            {
                string intermediatePath = projectInstance.GetPropertyValue(IntermediateOutputPath).Trim();

                intermediatePath = GetFullPathInProjectContext(projectInstance, intermediatePath);

                string stateFile = Path.Combine(intermediatePath, "DesignTimeResolveAssemblyReferences.cache");

                return(stateFile);
            }
コード例 #30
0
            private static string[] GetAllowedAssemblyExtensions(ProjectInstance projectInstance)
            {
                string[] allowedAssemblyExtensions;

                string val = projectInstance.GetPropertyValue(AllowedReferenceAssemblyFileExtensions).Trim();

                allowedAssemblyExtensions = val.Split(';').Select(s => s.Trim()).ToArray();

                return(allowedAssemblyExtensions);
            }