public void GetMetadataValuesFromDefinition()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <ItemDefinitionGroup>
                            <i>
                                <m0>v0</m0>
                                <m1>v1</m1>
                            </i>
                        </ItemDefinitionGroup>
                        <ItemGroup>
                            <i Include='i1'>
                                <m1>v1b</m1>
                                <m2>v2</m2>
                            </i>
                        </ItemGroup>
                    </Project>
                ";

            ProjectItemInstance item = GetOneItem(content);

            Assert.Equal("v0", item.GetMetadataValue("m0"));
            Assert.Equal("v1b", item.GetMetadataValue("m1"));
            Assert.Equal("v2", item.GetMetadataValue("m2"));

            Assert.Equal(3, Helpers.MakeList(item.Metadata).Count);
            Assert.Equal(3 + BuiltInMetadataCount, Helpers.MakeList(item.MetadataNames).Count);
            Assert.Equal(3 + BuiltInMetadataCount, item.MetadataCount);
        }
        /// <summary>
        ///     Gets the effective global properties for a project reference item.
        /// </summary>
        /// <remarks>
        ///     The behavior of this method should match the logic in the SDK
        /// </remarks>
        private static GlobalPropertyPartsForMSBuildTask ProjectReferenceGlobalPropertiesModifier(
            GlobalPropertyPartsForMSBuildTask defaultParts,
            ProjectItemInstance projectReference
            )
        {
            // ProjectReference defines yet another metadata name containing properties to undefine. Merge it in if non empty.
            var globalPropertiesToRemove = SplitPropertyNames(projectReference.GetMetadataValue(GlobalPropertiesToRemoveMetadataName));

            var newUndefineProperties = defaultParts.UndefineProperties;

            newUndefineProperties = newUndefineProperties.AddRange(defaultParts.UndefineProperties);
            newUndefineProperties = newUndefineProperties.AddRange(globalPropertiesToRemove);

            newUndefineProperties.Add("InnerBuildProperty");

            var newProperties = defaultParts.Properties;

            // The properties on the project reference supersede the ones from the MSBuild task instead of appending.
            if (newProperties.Count == 0)
            {
                // TODO: Mimic AssignProjectConfiguration's behavior for determining the values for these.
                var setConfigurationString   = projectReference.GetMetadataValue(SetConfigurationMetadataName);
                var setPlatformString        = projectReference.GetMetadataValue(SetPlatformMetadataName);
                var setTargetFrameworkString = projectReference.GetMetadataValue(SetTargetFrameworkMetadataName);

                if (!String.IsNullOrEmpty(setConfigurationString) || !String.IsNullOrEmpty(setPlatformString) || !String.IsNullOrEmpty(setTargetFrameworkString))
                {
                    newProperties = SplitPropertyNameValuePairs(
                        ItemMetadataNames.PropertiesMetadataName,
                        $"{setConfigurationString};{setPlatformString};{setTargetFrameworkString}").ToImmutableDictionary();
                }
            }

            return(new GlobalPropertyPartsForMSBuildTask(newProperties, defaultParts.AdditionalProperties, newUndefineProperties));
        }
            public Matcher(ProjectItemInstance item, string source)
            {
                _sourceFolder = source;

                ParsePatterns(
                    item.GetMetadataValue(FileMatchMetadata),
                    out _doMatchAll,
                    out _fileMatches,
                    out _fileRegexMatches,
                    out string fileWildcardMatch);
                ParsePatterns(
                    item.GetMetadataValue(FileExcludeMetadata),
                    out _,
                    out _fileExcludes,
                    out _fileRegexExcludes,
                    out _);
                ParsePatterns(
                    item.GetMetadataValue(DirExcludeMetadata),
                    out _,
                    out _dirExcludes,
                    out _dirRegexExcludes,
                    out _);

                // Optimization to only enumerate files which match the pattern.
                // This can only be done if there's exactly one pattern though.
                SearchPattern = _fileMatches.Count + _fileRegexMatches.Count == 1
                    ? _fileMatches.Count == 1
                        ? _fileMatches[0]
                        : fileWildcardMatch
                    : "*";
            }
        public void AccessorsWithMetadata()
        {
            ProjectItemInstance item = GetItemInstance();

            item.SetMetadata("m1", "v0");
            item.SetMetadata("m1", "v1");
            item.SetMetadata("m2", "v2");

            Assert.Equal("m1", item.GetMetadata("m1").Name);
            Assert.Equal("m2", item.GetMetadata("m2").Name);
            Assert.Equal("v1", item.GetMetadataValue("m1"));
            Assert.Equal("v2", item.GetMetadataValue("m2"));
        }
Esempio n. 5
0
        public int get_CanonicalName(out string pbstrCanonicalName)
        {
            // Get the output assembly path (including the name)
            pbstrCanonicalName = output.GetMetadataValue("FullPath");
            Debug.Assert(!String.IsNullOrEmpty(pbstrCanonicalName), "Output Assembly not defined");

            // Make sure we have a full path
            if (!System.IO.Path.IsPathRooted(pbstrCanonicalName))
            {
                pbstrCanonicalName = new Url(project.BaseURI, pbstrCanonicalName).AbsoluteUrl;
            }
            return(VSConstants.S_OK);
        }
Esempio n. 6
0
        private bool IsValidItem(ProjectItemInstance outputItem)
        {
            Version version  = null;
            Version version1 = null;

            if (Version.TryParse(outputItem.GetMetadataValue("Version"), out version) && Version.TryParse(outputItem.GetMetadataValue("HighestVersionInRedist"), out version1) && version > version1)
            {
                return(false);
            }
            if (!string.IsNullOrEmpty(outputItem.GetMetadataValue("OutOfRangeDependencies")))
            {
                return(false);
            }
            return(true);
        }
Esempio n. 7
0
        /// <summary>
        /// Determins what the TargetPath metadata would be set to after calling the AssignTargetPath task.
        /// </summary>
        /// <remarks>
        /// See: https://github.com/microsoft/msbuild/blob/master/src/Tasks/AssignTargetPath.cs.
        /// </remarks>
        public static string GetTargetPath(this ProjectItemInstance item)
        {
            string link = item.GetMetadataValue("Link");

            // If file has a link, use that.
            if (!string.IsNullOrEmpty(link))
            {
                return(link);
            }

            var evaluatedInclude = item.EvaluatedInclude;

            // If the file path is relative and doesn't contain any relative specifiers then just use the file path as-is
            if (!Path.IsPathRooted(evaluatedInclude) && !evaluatedInclude.Contains(RelativeSpecifier, StringComparison.Ordinal))
            {
                return(evaluatedInclude);
            }

            // Normalize the path
            string evaluatedIncludeFullPath = Path.GetFullPath(evaluatedInclude);

            string projectDir = item.Project.Directory;
            bool   projectDirHasTrailingSlash = projectDir[projectDir.Length - 1] == Path.DirectorySeparatorChar;

            // If the item is under the project dir, return the relative path from the project dir.
            if (evaluatedIncludeFullPath.StartsWith(projectDir, StringComparison.OrdinalIgnoreCase) &&
                (projectDirHasTrailingSlash ||
                 (evaluatedIncludeFullPath.Length > projectDir.Length && evaluatedIncludeFullPath[projectDir.Length] == Path.DirectorySeparatorChar)))
            {
                return(evaluatedIncludeFullPath.Substring(projectDir.Length + (projectDirHasTrailingSlash ? 0 : 1)));
            }

            // The item is not under the project dir. Return the filename only.
            return(Path.GetFileName(evaluatedInclude));
        }
        public void GetMissingMetadata()
        {
            ProjectItemInstance item = GetItemInstance();

            Assert.Equal(null, item.GetMetadata("X"));
            Assert.Equal(String.Empty, item.GetMetadataValue("X"));
        }
Esempio n. 9
0
        internal void SetHintPathAndPrivateValue(ProjectInstance instance, ProjectItemInstance iteminstance)
        {
            // Private means local copy; we want to know if it is already set to not override the default
            string privateValue     = this.ItemNode.GetMetadata(ProjectFileConstants.Private);
            string originalHintPath = this.ItemNode.GetMetadata(ProjectFileConstants.HintPath);


            this.ResolvedAssembly = AssemblyName.GetAssemblyName(this.AssemblyPath);
            resolvedProperties    = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            foreach (var str in iteminstance.MetadataNames)
            {
                resolvedProperties.Add(str);
            }
            prjitem = iteminstance;

            string hintPath = iteminstance.GetMetadataValue(ProjectFileConstants.HintPath);

            if (hintPath != originalHintPath)
            {
                if (Path.IsPathRooted(hintPath))
                {
                    hintPath = PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, new Uri(hintPath));
                }
                if (hintPath != originalHintPath)
                {
                    this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, hintPath);
                }
                // If this is not already set, we default to true
                if (String.IsNullOrEmpty(privateValue))
                {
                    this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString());
                }
            }
        }
        public void SetMetadata()
        {
            ProjectItemInstance item = GetItemInstance();

            item.SetMetadata("m", "m1");
            Assert.Equal("m1", item.GetMetadataValue("m"));
        }
        public void SetMetadataEmptyString()
        {
            ProjectItemInstance item = GetItemInstance();

            item.SetMetadata("m", String.Empty);
            Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
        }
Esempio n. 12
0
        /// <summary>
        ///     Gets the effective global properties for an item that will get passed to <see cref="MSBuild.Projects"/>.
        /// </summary>
        /// <remarks>
        ///     The behavior of this method matches the hardcoded behaviour of the msbuild task
        ///     and the <paramref name="globalPropertyModifiers"/> parameter can contain other mutations done at build time in targets / tasks
        /// </remarks>
        private static PropertyDictionary <ProjectPropertyInstance> GetGlobalPropertiesForItem(
            ProjectItemInstance projectReference,
            PropertyDictionary <ProjectPropertyInstance> requesterGlobalProperties,
            IEnumerable <GlobalPropertiesModifier> globalPropertyModifiers = null)
        {
            ErrorUtilities.VerifyThrowInternalNull(projectReference, nameof(projectReference));
            ErrorUtilities.VerifyThrowArgumentNull(requesterGlobalProperties, nameof(requesterGlobalProperties));

            var properties           = SplitPropertyNameValuePairs(ItemMetadataNames.PropertiesMetadataName, projectReference.GetMetadataValue(ItemMetadataNames.PropertiesMetadataName));
            var additionalProperties = SplitPropertyNameValuePairs(ItemMetadataNames.AdditionalPropertiesMetadataName, projectReference.GetMetadataValue(ItemMetadataNames.AdditionalPropertiesMetadataName));
            var undefineProperties   = SplitPropertyNames(projectReference.GetMetadataValue(ItemMetadataNames.UndefinePropertiesMetadataName));

            var defaultParts = new GlobalPropertyPartsForMSBuildTask(properties.ToImmutableDictionary(), additionalProperties.ToImmutableDictionary(), undefineProperties.ToImmutableList());

            var globalPropertyParts = globalPropertyModifiers?.Aggregate(defaultParts, (currentProperties, modifier) => modifier(currentProperties, projectReference)) ?? defaultParts;

            if (globalPropertyParts.AllEmpty())
            {
                return(requesterGlobalProperties);
            }

            // Make a copy to avoid mutating the requester
            var globalProperties = new PropertyDictionary <ProjectPropertyInstance>(requesterGlobalProperties);

            // Append and remove properties as specified by the various metadata
            MergeIntoPropertyDictionary(globalProperties, globalPropertyParts.Properties);
            MergeIntoPropertyDictionary(globalProperties, globalPropertyParts.AdditionalProperties);
            RemoveFromPropertyDictionary(globalProperties, globalPropertyParts.UndefineProperties);

            return(globalProperties);
        }
Esempio n. 13
0
        public int get_CanonicalName(out string pbstrCanonicalName)
        {
            if (output == null)
            {
                pbstrCanonicalName = project.Url;
                return(VSConstants.S_OK);
            }

            // Get the output assembly path (including the name)
            pbstrCanonicalName = output.GetMetadataValue("FullPath");
            Debug.Assert(!String.IsNullOrEmpty(pbstrCanonicalName), "Output Assembly not defined");

            // Make sure we have a full path
            pbstrCanonicalName = CommonUtils.GetAbsoluteFilePath(project.ProjectHome, pbstrCanonicalName);
            return(VSConstants.S_OK);
        }
        public void SetNullMetadataValue()
        {
            ProjectItemInstance item = GetItemInstance();

            item.SetMetadata("m", null);
            Assert.Equal(String.Empty, item.GetMetadataValue("m"));
        }
Esempio n. 15
0
        private void ReportOutputs(ProjectPredictionReporter reporter, ProjectItemInstance masmItem)
        {
            reporter.ReportOutputFile(masmItem.GetMetadataValue(ObjectFileNameMetadata));

            string assembledCodeListingFile = masmItem.GetMetadataValue(AssembledCodeListingFileMetadata);

            if (!string.IsNullOrWhiteSpace(assembledCodeListingFile))
            {
                reporter.ReportOutputFile(assembledCodeListingFile);
            }

            string browseFile = masmItem.GetMetadataValue(BrowseFileMetadata);

            if (!string.IsNullOrWhiteSpace(browseFile))
            {
                reporter.ReportOutputFile(browseFile);
            }
        }
Esempio n. 16
0
        public void BuiltInMetadataInMetadataCondition()
        {
            string content = @"
                    <Project>
                        <ItemGroup>
                            <i Include='i1'>
                                <m Condition=""'%(Identity)'=='i1'"">m1</m>
                                <n Condition=""'%(Identity)'=='i2'"">n1</n>
                            </i>
                        </ItemGroup>
                    </Project>
                ";

            ProjectItemInstance item = GetOneItem(content);

            Assert.Equal("m1", item.GetMetadataValue("m"));
            Assert.Equal(String.Empty, item.GetMetadataValue("n"));
        }
Esempio n. 17
0
        /// <summary>
        /// Get the file location as seen in the IDE, used for ResourceDictionary.Source resolution.
        /// </summary>
        private string GetSourceLink(ProjectItemInstance projectItemInstance)
        {
            if (projectItemInstance.HasMetadata("Link"))
            {
                return(projectItemInstance.GetMetadataValue("Link"));
            }

            return(projectItemInstance.EvaluatedInclude);
        }
Esempio n. 18
0
        private static void AssertItemHasMetadata(Dictionary <string, string> expected, ProjectItemInstance item)
        {
            Assert.Equal(expected.Keys.Count, item.DirectMetadataCount);

            foreach (var key in expected.Keys)
            {
                Assert.Equal(expected[key], item.GetMetadataValue(key));
            }
        }
Esempio n. 19
0
        /// <summary>
        ///     Returns a value indicating if the specified <see cref="ProjectItemInstance"/>
        ///     originated in an imported file.
        /// </summary>
        /// <returns>
        ///     <see langword="true"/> if <paramref name="item"/> originated in an imported file;
        ///     otherwise, <see langword="false"/> if it was defined in the project being built.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="item"/> is <see langword="null"/>.
        /// </exception>
        public static bool IsImported(this ProjectItemInstance item)
        {
            Requires.NotNull(item, nameof(item));

            string definingProjectFullPath = item.GetMetadataValue("DefiningProjectFullPath");
            string projectFullPath         = item.Project.FullPath; // NOTE: This returns project being built, not owning target

            return(!StringComparers.Paths.Equals(definingProjectFullPath, projectFullPath));
        }
        public void BuiltInMetadataInMetadataCondition()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <ItemGroup>
                            <i Include='i1'>
                                <m Condition=""'%(Identity)'=='i1'"">m1</m>
                                <n Condition=""'%(Identity)'=='i2'"">n1</n>
                            </i>
                        </ItemGroup>
                    </Project>
                ";

            ProjectItemInstance item = GetOneItem(content);

            Assert.Equal("m1", item.GetMetadataValue("m"));
            Assert.Equal(String.Empty, item.GetMetadataValue("n"));
        }
Esempio n. 21
0
        public static string SafeGetMetadataValue(this ProjectItemInstance item, string name)
        {
            string result = null;

            try {
                result = item.GetMetadataValue(name);
            }
            catch (Exception) { }
            return(result);
        }
Esempio n. 22
0
 internal string GetMsBuildProperty(string propName)
 {
     if (resolvedProperties != null && prjitem != null)
     {
         if (resolvedProperties.Contains(propName))
         {
             return(prjitem.GetMetadataValue(propName));
         }
     }
     return("");
 }
Esempio n. 23
0
        public static bool ShouldCopyToOutputDirectory(this ProjectItemInstance item)
        {
            var copyToOutputDirectoryValue = item.GetMetadataValue("CopyToOutputDirectory");

            if (copyToOutputDirectoryValue.Equals("Always", StringComparison.OrdinalIgnoreCase) ||
                copyToOutputDirectoryValue.Equals("PreserveNewest", StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            return(false);
        }
Esempio n. 24
0
        // Internal for testing
        internal static string[] GetConfiguredExtensionNames(ProjectItemInstance configurationItem)
        {
            var extensionNamesValue = configurationItem.GetMetadataValue(RazorConfigurationItemTypeExtensionsProperty);

            if (string.IsNullOrEmpty(extensionNamesValue))
            {
                return(Array.Empty <string>());
            }

            var configuredExtensionNames = extensionNamesValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            return(configuredExtensionNames);
        }
        public void CreateItemWithNullMetadataValue()
        {
            Project         project         = new Project();
            ProjectInstance projectInstance = project.CreateProjectInstance();

            IDictionary <string, string> metadata = new Dictionary <string, string>();

            metadata.Add("m", null);

            ProjectItemInstance item = projectInstance.AddItem("i", "i1", metadata);

            Assert.Equal(String.Empty, item.GetMetadataValue("m"));
        }
        private static void AssertExpectedStyleCopSetting(string expectedValue, BuildResult actualResult)
        {
            Assert.IsNotNull(actualResult.ProjectStateAfterBuild, "Test error: ProjectStateAfterBuild should not be null");

            IEnumerable <ProjectItemInstance> matches = actualResult.ProjectStateAfterBuild.GetItemsByItemTypeAndEvaluatedInclude(BuildTaskConstants.SettingItemName, TargetConstants.StyleCopProjectPathItemName);

            Assert.AreNotEqual(0, matches.Count(), "Expected SonarQubeSetting with include value of '{0}' does not exist", TargetConstants.StyleCopProjectPathItemName);
            Assert.AreEqual(1, matches.Count(), "Only expecting one SonarQubeSetting with include value of '{0}' to exist", TargetConstants.StyleCopProjectPathItemName);

            ProjectItemInstance item = matches.Single();
            string value             = item.GetMetadataValue(BuildTaskConstants.SettingValueMetadataName);

            Assert.AreEqual(expectedValue, value, "SonarQubeSetting with include value '{0}' does not have the expected value");
        }
        public void CastToITaskItem()
        {
            ProjectItemInstance item = GetItemInstance();

            item.SetMetadata("m", "m1");

            ITaskItem taskItem = (ITaskItem)item;

            Assert.Equal(item.EvaluatedInclude, taskItem.ItemSpec);
            Assert.Equal(1 + BuiltInMetadataCount, taskItem.MetadataCount);
            Assert.Equal(1 + BuiltInMetadataCount, taskItem.MetadataNames.Count);
            Assert.Equal("m1", taskItem.GetMetadata("m"));
            taskItem.SetMetadata("m", "m2");
            Assert.Equal("m2", item.GetMetadataValue("m"));
        }
Esempio n. 28
0
        public void BuiltInMisqualifiedMetadataExpression()
        {
            string content = @"
                    <Project>
                        <ItemGroup>
                            <i Include='i1'>
                                <m>%(j.Identity)</m>
                            </i>
                        </ItemGroup>
                    </Project>
                ";

            ProjectItemInstance item = GetOneItem(content);

            Assert.Equal(String.Empty, item.GetMetadataValue("m"));
        }
        public void BuiltInMisqualifiedMetadataExpression()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <ItemGroup>
                            <i Include='i1'>
                                <m>%(j.Identity)</m>
                            </i>
                        </ItemGroup>
                    </Project>
                ";

            ProjectItemInstance item = GetOneItem(content);

            Assert.Equal(String.Empty, item.GetMetadataValue("m"));
        }
Esempio n. 30
0
        private void ReportInputs(ProjectPredictionReporter reporter, ProjectItemInstance masmItem, HashSet <string> reportedIncludes)
        {
            reporter.ReportInputFile(masmItem.EvaluatedInclude);

            string[] includePaths = masmItem.GetMetadataValue(IncludePathsMetadata)
                                    .Split(IncludePathsSeparator, StringSplitOptions.RemoveEmptyEntries);

            // Avoid reporting paths that we've already reported for this project.
            foreach (string includePath in includePaths)
            {
                string trimmedPath = includePath.Trim();
                if (!string.IsNullOrEmpty(trimmedPath) && reportedIncludes.Add(trimmedPath))
                {
                    reporter.ReportInputDirectory(trimmedPath);
                }
            }
        }