示例#1
0
        public void PropertyDictionarySerialization()
        {
            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            ProjectPropertyInstance p1 = GetPropertyInstance("p1", "v1");
            ProjectPropertyInstance p2 = GetPropertyInstance("p2", "v2");
            ProjectPropertyInstance p3 = GetPropertyInstance("p1", "v1");
            ProjectPropertyInstance p4 = GetPropertyInstance("p2", "v3");

            properties.Set(p1);
            properties.Set(p2);
            properties.Set(p3);
            properties.Set(p1);
            properties.Set(p4);

            TranslationHelpers.GetWriteTranslator().TranslateDictionary <PropertyDictionary <ProjectPropertyInstance>, ProjectPropertyInstance>(ref properties, ProjectPropertyInstance.FactoryForDeserialization);
            PropertyDictionary <ProjectPropertyInstance> deserializedProperties = null;

            TranslationHelpers.GetReadTranslator().TranslateDictionary <PropertyDictionary <ProjectPropertyInstance>, ProjectPropertyInstance>(ref deserializedProperties, ProjectPropertyInstance.FactoryForDeserialization);

            Assert.Equal(properties.PropertyNames.Count, deserializedProperties.PropertyNames.Count);
            foreach (string propertyName in properties.PropertyNames)
            {
                Assert.Equal(properties[propertyName].EvaluatedValue, deserializedProperties[propertyName].EvaluatedValue);
            }
        }
示例#2
0
        public void BasicPropertyDictionary()
        {
            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            ProjectPropertyInstance p1 = GetPropertyInstance("p1", "v1");
            ProjectPropertyInstance p2 = GetPropertyInstance("p2", "v2");
            ProjectPropertyInstance p3 = GetPropertyInstance("p1", "v1");
            ProjectPropertyInstance p4 = GetPropertyInstance("p2", "v3");

            properties.Set(p1);
            properties.Set(p2);
            properties.Set(p3);
            properties.Set(p1);
            properties.Set(p4);

            Assert.Equal(2, properties.Count);
            Assert.Equal("v1", properties["p1"].EvaluatedValue);
            Assert.Equal("v3", properties["p2"].EvaluatedValue);

            Assert.True(properties.Remove("p1"));
            Assert.Null(properties["p1"]);

            Assert.False(properties.Remove("x"));

            properties.Clear();

            Assert.Empty(properties);
        }
示例#3
0
        public void OldSyntaxTests()
        {
            Parser          p             = new Parser();
            ProjectInstance parentProject = new ProjectInstance(ProjectRootElement.Create());
            ItemDictionary <ProjectItemInstance> itemBag = new ItemDictionary <ProjectItemInstance>();

            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "foo.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "bar.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "baz.cs", parentProject.FullPath));

            PropertyDictionary <ProjectPropertyInstance> propertyBag = new PropertyDictionary <ProjectPropertyInstance>();

            propertyBag.Set(ProjectPropertyInstance.Create("foo", "true"));
            propertyBag.Set(ProjectPropertyInstance.Create("bar", "yes"));
            propertyBag.Set(ProjectPropertyInstance.Create("one", "1"));
            propertyBag.Set(ProjectPropertyInstance.Create("onepointzero", "1.0"));
            propertyBag.Set(ProjectPropertyInstance.Create("two", "2"));
            propertyBag.Set(ProjectPropertyInstance.Create("simple", "simplestring"));
            propertyBag.Set(ProjectPropertyInstance.Create("complex", "This is a complex string"));
            propertyBag.Set(ProjectPropertyInstance.Create("c1", "Another (complex) one."));
            propertyBag.Set(ProjectPropertyInstance.Create("c2", "Another (complex) one."));

            Expander <ProjectPropertyInstance, ProjectItemInstance> expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(propertyBag, itemBag, FileSystems.Default);

            AssertParseEvaluate(p, "(($(foo) != 'two' and $(bar)) and 5 >= 1) or $(one) == 1", expander, true);
        }
示例#4
0
        public void EqualsSameStartEnd1()
        {
            PropertyDictionary <ProjectPropertyInstance> dictionary = new PropertyDictionary <ProjectPropertyInstance>();

            ProjectPropertyInstance p1 = ProjectPropertyInstance.Create("A", "value1");
            ProjectPropertyInstance p2 = ProjectPropertyInstance.Create("B", "value2");

            dictionary.Set(p1);
            dictionary.Set(p2);

            ProjectPropertyInstance value = MSBuildNameIgnoreCaseComparer.Mutable.GetValueWithConstraints <ProjectPropertyInstance>(dictionary, "babbbb", 1, 1);

            Assert.IsTrue(Object.ReferenceEquals(p1, value), "Should have returned the 'A' value");
        }
        public void EqualsStartZero()
        {
            PropertyDictionary <ProjectPropertyInstance> dictionary = new PropertyDictionary <ProjectPropertyInstance>();

            ProjectPropertyInstance p1 = ProjectPropertyInstance.Create("aab", "value1");
            ProjectPropertyInstance p2 = ProjectPropertyInstance.Create("aba", "value2");

            dictionary.Set(p1);
            dictionary.Set(p2);

            ProjectPropertyInstance value = MSBuildNameIgnoreCaseComparer.Mutable.GetValueWithConstraints <ProjectPropertyInstance>(dictionary, "aabaa", 0, 2);

            Assert.True(Object.ReferenceEquals(p1, value)); // "Should have returned the 'aab' value"
        }
        public void EqualsSameStartEnd2()
        {
            MSBuildNameIgnoreCaseComparer comparer = MSBuildNameIgnoreCaseComparer.Mutable;
            PropertyDictionary <ProjectPropertyInstance> dictionary = new PropertyDictionary <ProjectPropertyInstance>(comparer);

            ProjectPropertyInstance p1 = ProjectPropertyInstance.Create("a", "value1");
            ProjectPropertyInstance p2 = ProjectPropertyInstance.Create("b", "value2");

            dictionary.Set(p1);
            dictionary.Set(p2);

            ProjectPropertyInstance value = comparer.GetValueWithConstraints <ProjectPropertyInstance>(dictionary, "aabaa", 2, 2);

            Assert.True(Object.ReferenceEquals(p2, value)); // "Should have returned the 'b' value"
        }
示例#7
0
        /// <summary>
        /// Creates a standard ProjectCollection and adds a fake toolset with the following contents to it:
        ///
        /// ToolsVersion = Fake
        /// Base Properties:
        /// a = a1
        /// b = b1
        ///
        /// SubToolset "12.0":
        /// d = d4
        /// e = e5
        ///
        /// SubToolset "v11.0":
        /// b = b2
        /// c = c2
        ///
        /// SubToolset "FakeSubToolset":
        /// a = a3
        /// c = c3
        ///
        /// SubToolset "v13.0":
        /// f = f6
        /// g = g7
        /// </summary>
        private Toolset GetFakeToolset(IDictionary <string, string> globalPropertiesForProjectCollection)
        {
            ProjectCollection projectCollection = new ProjectCollection(globalPropertiesForProjectCollection);

            IDictionary <string, string> properties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            properties.Add("a", "a1");
            properties.Add("b", "b1");

            Dictionary <string, SubToolset> subToolsets = new Dictionary <string, SubToolset>(StringComparer.OrdinalIgnoreCase);

            // SubToolset 12.0 properties
            PropertyDictionary <ProjectPropertyInstance> subToolset12Properties = new PropertyDictionary <ProjectPropertyInstance>();

            subToolset12Properties.Set(ProjectPropertyInstance.Create("d", "d4"));
            subToolset12Properties.Set(ProjectPropertyInstance.Create("e", "e5"));

            // SubToolset v11.0 properties
            PropertyDictionary <ProjectPropertyInstance> subToolset11Properties = new PropertyDictionary <ProjectPropertyInstance>();

            subToolset11Properties.Set(ProjectPropertyInstance.Create("b", "b2"));
            subToolset11Properties.Set(ProjectPropertyInstance.Create("c", "c2"));

            // FakeSubToolset properties
            PropertyDictionary <ProjectPropertyInstance> fakeSubToolsetProperties = new PropertyDictionary <ProjectPropertyInstance>();

            fakeSubToolsetProperties.Set(ProjectPropertyInstance.Create("a", "a3"));
            fakeSubToolsetProperties.Set(ProjectPropertyInstance.Create("c", "c3"));

            // SubToolset v13.0 properties
            PropertyDictionary <ProjectPropertyInstance> subToolset13Properties = new PropertyDictionary <ProjectPropertyInstance>();

            subToolset13Properties.Set(ProjectPropertyInstance.Create("f", "f6"));
            subToolset13Properties.Set(ProjectPropertyInstance.Create("g", "g7"));

            subToolsets.Add("12.0", new SubToolset("12.0", subToolset12Properties));
            subToolsets.Add("v11.0", new SubToolset("v11.0", subToolset11Properties));
            subToolsets.Add("FakeSubToolset", new SubToolset("FakeSubToolset", fakeSubToolsetProperties));
            subToolsets.Add("v13.0", new SubToolset("v13.0", subToolset13Properties));

            Toolset parentToolset = projectCollection.GetToolset("4.0");

            Toolset fakeToolset = new Toolset("Fake", parentToolset.ToolsPath, properties, projectCollection, subToolsets, parentToolset.OverrideTasksPath);

            projectCollection.AddToolset(fakeToolset);

            return(fakeToolset);
        }
示例#8
0
        /// <summary>
        /// Submit 3 build request where first one has multiple references and last has multiple references. Some of the references are built with different global properties
        /// </summary>
        public void BuildMultipleProjectsWithReferencesAndDifferentGlobalProperties()
        {
            ProjectPropertyInstance prop1 = ProjectPropertyInstance.Create("prop1", "Value1");
            ProjectPropertyInstance prop2 = ProjectPropertyInstance.Create("prop2", "Value2");
            PropertyDictionary <ProjectPropertyInstance> group1 = new PropertyDictionary <ProjectPropertyInstance>();

            group1.Set(prop1);
            PropertyDictionary <ProjectPropertyInstance> group2 = new PropertyDictionary <ProjectPropertyInstance>();

            group2.Set(prop2);

            RequestDefinition p1 = CreateNewRequest("1.proj");
            RequestDefinition p2 = CreateNewRequest("2.proj");
            RequestDefinition p3 = CreateNewRequest("3.proj");
            RequestDefinition p4 = CreateNewRequest("4.proj");
            RequestDefinition p5 = CreateNewRequest("2.proj", group1);
            RequestDefinition p6 = CreateNewRequest("6.proj");
            RequestDefinition p7 = CreateNewRequest("2.proj", group2);

            p1.AddChildDefinition(p4);
            p1.AddChildDefinition(p5);
            p3.AddChildDefinition(p6);
            p3.AddChildDefinition(p7);

            p1.SubmitBuildRequest();
            p1.ValidateBuildResult();

            p2.SubmitBuildRequest();
            p2.ValidateBuildResult();

            p3.SubmitBuildRequest();
            p3.ValidateBuildResult();
        }
        public void TestEquals()
        {
            BuildRequestConfiguration config1 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary <string, string>(), "toolsVersion", new string[0], null), "2.0");

            Assert.Equal(config1, config1);
            BuildRequestConfiguration config2 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary <string, string>(), "toolsVersion", new string[0], null), "2.0");

            Assert.Equal(config1, config2);

            BuildRequestConfiguration config3 = new BuildRequestConfiguration(new BuildRequestData("file2", new Dictionary <string, string>(), "toolsVersion", new string[0], null), "2.0");

            Assert.NotEqual(config1, config3);

            BuildRequestConfiguration config4 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary <string, string>(), "toolsVersion2", new string[0], null), "2.0");

            Assert.NotEqual(config1, config4);

            PropertyDictionary <ProjectPropertyInstance> props = new PropertyDictionary <ProjectPropertyInstance>();

            props.Set(ProjectPropertyInstance.Create("prop1", "value1"));
            BuildRequestData          data    = new BuildRequestData("file", props.ToDictionary(), "toolsVersion", new string[0], null);
            BuildRequestConfiguration config5 = new BuildRequestConfiguration(data, "2.0");

            Assert.NotEqual(config1, config5);

            Assert.Equal(config1, config2);
            Assert.NotEqual(config1, config3);
        }
示例#10
0
        /// <summary>
        /// A new build request from the node for a project which was already previously built in that node but for a different global properties
        /// </summary>
        public void ReferenceAProjectAlreadyBuiltInTheNodeButWithDifferentGlobalProperties()
        {
            ProjectPropertyInstance prop1 = ProjectPropertyInstance.Create("prop1", "Value1");
            ProjectPropertyInstance prop2 = ProjectPropertyInstance.Create("prop2", "Value2");
            PropertyDictionary <ProjectPropertyInstance> group1 = new PropertyDictionary <ProjectPropertyInstance>();

            group1.Set(prop1);
            PropertyDictionary <ProjectPropertyInstance> group2 = new PropertyDictionary <ProjectPropertyInstance>();

            group2.Set(prop2);

            RequestDefinition p1 = CreateNewRequest("1.proj", "2.0", new string[1] {
                "t1"
            }, group1);
            RequestDefinition p2 = CreateNewRequest("2.proj");
            RequestDefinition p3 = CreateNewRequest("1.proj", "2.0", new string[1] {
                "t1"
            }, group2);

            p2.AddChildDefinition(p3);

            p1.SubmitBuildRequest();
            p1.ValidateBuildResult();

            p2.SubmitBuildRequest();
            p2.ValidateBuildResult();
        }
示例#11
0
        public void NotTests()
        {
            Console.WriteLine("NegationParseTest()");
            Parser p = new Parser();

            PropertyDictionary<ProjectPropertyInstance> propertyBag = new PropertyDictionary<ProjectPropertyInstance>();
            propertyBag.Set(ProjectPropertyInstance.Create("foo", "4"));
            propertyBag.Set(ProjectPropertyInstance.Create("bar", "32"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(propertyBag, new ItemDictionary<ProjectItemInstance>());

            AssertParseEvaluate(p, "!true", expander, false);
            AssertParseEvaluate(p, "!(true)", expander, false);
            AssertParseEvaluate(p, "!($(foo) <= 5)", expander, false);
            AssertParseEvaluate(p, "!($(foo) <= 5 and $(bar) >= 15)", expander, false);
        }
示例#12
0
        public void ValidateToolsetTranslation()
        {
            PropertyDictionary<ProjectPropertyInstance> buildProperties = new PropertyDictionary<ProjectPropertyInstance>();
            buildProperties.Set(ProjectPropertyInstance.Create("a", "a1"));

            PropertyDictionary<ProjectPropertyInstance> environmentProperties = new PropertyDictionary<ProjectPropertyInstance>();
            environmentProperties.Set(ProjectPropertyInstance.Create("b", "b1"));

            PropertyDictionary<ProjectPropertyInstance> globalProperties = new PropertyDictionary<ProjectPropertyInstance>();
            globalProperties.Set(ProjectPropertyInstance.Create("c", "c1"));

            PropertyDictionary<ProjectPropertyInstance> subToolsetProperties = new PropertyDictionary<ProjectPropertyInstance>();
            subToolsetProperties.Set(ProjectPropertyInstance.Create("d", "d1"));

            Dictionary<string, SubToolset> subToolsets = new Dictionary<string, SubToolset>(StringComparer.OrdinalIgnoreCase);
            subToolsets.Add("dogfood", new SubToolset("dogfood", subToolsetProperties));

            Toolset t = new Toolset("4.0", "c:\\bar", buildProperties, environmentProperties, globalProperties, subToolsets, "c:\\foo", "4.0");

            ((INodePacketTranslatable)t).Translate(TranslationHelpers.GetWriteTranslator());
            Toolset t2 = Toolset.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());

            Assert.Equal(t.ToolsVersion, t2.ToolsVersion);
            Assert.Equal(t.ToolsPath, t2.ToolsPath);
            Assert.Equal(t.OverrideTasksPath, t2.OverrideTasksPath);
            Assert.Equal(t.Properties.Count, t2.Properties.Count);

            foreach (string key in t.Properties.Keys)
            {
                Assert.Equal(t.Properties[key].Name, t2.Properties[key].Name);
                Assert.Equal(t.Properties[key].EvaluatedValue, t2.Properties[key].EvaluatedValue);
            }

            Assert.Equal(t.SubToolsets.Count, t2.SubToolsets.Count);

            foreach (string key in t.SubToolsets.Keys)
            {
                SubToolset subToolset1 = t.SubToolsets[key];
                SubToolset subToolset2 = null;

                if (t2.SubToolsets.TryGetValue(key, out subToolset2))
                {
                    Assert.Equal(subToolset1.SubToolsetVersion, subToolset2.SubToolsetVersion);
                    Assert.Equal(subToolset1.Properties.Count, subToolset2.Properties.Count);

                    foreach (string subToolsetPropertyKey in subToolset1.Properties.Keys)
                    {
                        Assert.Equal(subToolset1.Properties[subToolsetPropertyKey].Name, subToolset2.Properties[subToolsetPropertyKey].Name);
                        Assert.Equal(subToolset1.Properties[subToolsetPropertyKey].EvaluatedValue, subToolset2.Properties[subToolsetPropertyKey].EvaluatedValue);
                    }
                }
                else
                {
                    Assert.True(false, string.Format("Sub-toolset {0} was lost in translation.", key));
                }
            }

            Assert.Equal(t.DefaultOverrideToolsVersion, t2.DefaultOverrideToolsVersion);
        }
        public void EqualsEndEnd()
        {
            MSBuildNameIgnoreCaseComparer comparer = MSBuildNameIgnoreCaseComparer.Mutable;
            PropertyDictionary <ProjectPropertyInstance> dictionary = new PropertyDictionary <ProjectPropertyInstance>(comparer);

            ProjectPropertyInstance p1 = ProjectPropertyInstance.Create("aabaaaa", "value1");
            ProjectPropertyInstance p2 = ProjectPropertyInstance.Create("baaaa", "value2");

            dictionary.Set(p1);
            dictionary.Set(p2);

            string constraint = "aabaaa";

            ProjectPropertyInstance p3 = ProjectPropertyInstance.Create("abaaa", "value3");

            dictionary.Set(p3);

            // Should match o3
            ProjectPropertyInstance value1 = comparer.GetValueWithConstraints <ProjectPropertyInstance>(dictionary, constraint, 1, 5);

            Assert.True(Object.ReferenceEquals(p3, value1)); // "Should have returned the 'abaaa' value"

            dictionary.Remove("abaaa");                      // get rid of o3

            ProjectPropertyInstance value2 = comparer.GetValueWithConstraints <ProjectPropertyInstance>(dictionary, constraint, 1, 5);

            Assert.Null(value2); // "Should not have been a match in the dictionary"

            // Even if the string is exactly the same, if only a substring is being compared, then although it
            // will be judged equal, the hash codes will NOT be the same, and for that reason, a lookup in the
            // dictionary will fail.
            int originalHashCode = comparer.GetHashCode("aabaaa");

            try
            {
                comparer.SetConstraintsForUnitTestingOnly(constraint, 1, 5);

                Assert.True(comparer.Equals("aabaaa", constraint)); // same on both sides
                Assert.NotEqual(originalHashCode, comparer.GetHashCode(constraint));
            }
            finally
            {
                comparer.RemoveConstraintsForUnitTestingOnly();
            }
        }
示例#14
0
        /// <summary>
        /// Sets a new metadata value on the ItemDefinition.
        /// This is ONLY called during evaluation and does not affect the XML.
        /// </summary>
        ProjectMetadata IItemDefinition <ProjectMetadata> .SetMetadata(ProjectMetadataElement metadataElement, string evaluatedValue, ProjectMetadata predecessor)
        {
            _metadata = _metadata ?? new PropertyDictionary <ProjectMetadata>();

            ProjectMetadata metadatum = new ProjectMetadata(this, metadataElement, evaluatedValue, predecessor);

            _metadata.Set(metadatum);

            return(metadatum);
        }
        public void TestTranslation()
        {
            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            properties.Set(ProjectPropertyInstance.Create("this", "that"));
            properties.Set(ProjectPropertyInstance.Create("foo", "bar"));

            BuildRequestData          data   = new BuildRequestData("file", properties.ToDictionary(), "4.0", new string[0], null);
            BuildRequestConfiguration config = new BuildRequestConfiguration(data, "2.0");

            Assert.Equal(NodePacketType.BuildRequestConfiguration, config.Type);

            ((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator());
            INodePacket packet = BuildRequestConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());

            BuildRequestConfiguration deserializedConfig = packet as BuildRequestConfiguration;

            Assert.Equal(config, deserializedConfig);
        }
示例#16
0
        /// <summary>
        /// Sets a new metadata value on the ItemDefinition.
        /// </summary>
        /// <remarks>Unevaluated value is assumed to be escaped as necessary</remarks>
        public ProjectMetadata SetMetadataValue(string name, string unevaluatedValue)
        {
            if (Link != null)
            {
                return(Link.SetMetadataValue(name, unevaluatedValue));
            }

            XmlUtilities.VerifyThrowArgumentValidElementName(name);
            ErrorUtilities.VerifyThrowArgument(!FileUtilities.ItemSpecModifiers.IsItemSpecModifier(name), "ItemSpecModifierCannotBeCustomMetadata", name);
            ErrorUtilities.VerifyThrowInvalidOperation(!XMakeElements.ReservedItemNames.Contains(name), "CannotModifyReservedItemMetadata", name);

            ProjectMetadata metadatum;

            if (_metadata != null)
            {
                metadatum = _metadata[name];

                if (metadatum != null)
                {
                    Project.VerifyThrowInvalidOperationNotImported(metadatum.Xml.ContainingProject);
                    metadatum.UnevaluatedValue = unevaluatedValue;
                    return(metadatum);
                }
            }

            // We can't use the item definition that this object came from as a root, as it doesn't map directly
            // to a single XML element. Instead, add a new one to the project. Best we can do.
            ProjectItemDefinitionElement itemDefinition = _project.Xml.AddItemDefinition(_itemType);

            ProjectMetadataElement metadatumXml = itemDefinition.AddMetadata(name, unevaluatedValue);

            _metadata ??= new PropertyDictionary <ProjectMetadata>();

            string evaluatedValueEscaped = _project.ExpandMetadataValueBestEffortLeaveEscaped(this, unevaluatedValue, metadatumXml.Location);

            metadatum = new ProjectMetadata(this, metadatumXml, evaluatedValueEscaped, null /* predecessor unknown */);

            _metadata.Set(metadatum);

            return(metadatum);
        }
示例#17
0
        /// <summary>
        /// Adds a ProjectMetadata to the item.
        /// This is ONLY called during evaluation and does not affect the XML.
        /// </summary>
        ProjectMetadata IItem <ProjectMetadata> .SetMetadata(ProjectMetadataElement metadataElement, string evaluatedInclude)
        {
            _directMetadata = _directMetadata ?? new PropertyDictionary <ProjectMetadata>();

            ProjectMetadata predecessor = GetMetadata(metadataElement.Name);

            ProjectMetadata metadatum = new ProjectMetadata(this, metadataElement, evaluatedInclude, predecessor);

            _directMetadata.Set(metadatum);

            return(metadatum);
        }
        public void EqualsEndPastEnd1()
        {
            PropertyDictionary <ProjectPropertyInstance> dictionary = new PropertyDictionary <ProjectPropertyInstance>();

            ProjectPropertyInstance p = ProjectPropertyInstance.Create("bbb", "value");

            dictionary.Set(p);

            ProjectPropertyInstance value = MSBuildNameIgnoreCaseComparer.Mutable.GetValueWithConstraints <ProjectPropertyInstance>(dictionary, "abbbaaa", 1, 3);

            Assert.True(Object.ReferenceEquals(p, value)); // "Should have returned the same object as was inserted"
        }
示例#19
0
        public void PropertyDictionarySerialization()
        {
            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            ProjectPropertyInstance p1 = GetPropertyInstance("p1", "v1");
            ProjectPropertyInstance p2 = GetPropertyInstance("p2", "v2");
            ProjectPropertyInstance p3 = GetPropertyInstance("p1", "v1");
            ProjectPropertyInstance p4 = GetPropertyInstance("p2", "v3");

            properties.Set(p1);
            properties.Set(p2);
            properties.Set(p3);
            properties.Set(p1);
            properties.Set(p4);

            TranslationHelpers.GetWriteTranslator().TranslateDictionary <PropertyDictionary <ProjectPropertyInstance>, ProjectPropertyInstance>(ref properties, ProjectPropertyInstance.FactoryForDeserialization);
            PropertyDictionary <ProjectPropertyInstance> deserializedProperties = null;

            TranslationHelpers.GetReadTranslator().TranslateDictionary <PropertyDictionary <ProjectPropertyInstance>, ProjectPropertyInstance>(ref deserializedProperties, ProjectPropertyInstance.FactoryForDeserialization);

            Assert.Equal(properties, deserializedProperties);
        }
 /// <summary>
 /// Sets the given property in the given property group.
 /// </summary>
 private void SetProperty(ToolsetPropertyDefinition property, PropertyDictionary <ProjectPropertyInstance> propertyGroup, PropertyDictionary <ProjectPropertyInstance> globalProperties)
 {
     try
     {
         // Global properties cannot be overwritten
         if (globalProperties[property.Name] == null)
         {
             propertyGroup.Set(ProjectPropertyInstance.Create(property.Name, EscapingUtilities.UnescapeAll(property.Value), true /* may be reserved */, false /* not immutable */));
         }
     }
     catch (ArgumentException ex)
     {
         InvalidToolsetDefinitionException.Throw(ex, "InvalidPropertyNameInToolset", property.Name, property.Source.LocationString, ex.Message);
     }
 }
示例#21
0
        public BuildRequestData(string projectFullPath, IDictionary <string, string> globalProperties, string toolsVersion, string[] targetsToBuild, HostServices hostServices, BuildRequestDataFlags flags)
            : this(targetsToBuild, hostServices, flags)
        {
            ErrorUtilities.VerifyThrowArgumentLength(projectFullPath, nameof(projectFullPath));
            ErrorUtilities.VerifyThrowArgumentNull(globalProperties, nameof(globalProperties));

            ProjectFullPath            = FileUtilities.NormalizePath(projectFullPath);
            GlobalPropertiesDictionary = new PropertyDictionary <ProjectPropertyInstance>(globalProperties.Count);
            foreach (KeyValuePair <string, string> propertyPair in globalProperties)
            {
                GlobalPropertiesDictionary.Set(ProjectPropertyInstance.Create(propertyPair.Key, propertyPair.Value));
            }

            ExplicitlySpecifiedToolsVersion = toolsVersion;
        }
示例#22
0
        private ProjectMetadata SetMetadataOperation(string name, string unevaluatedValue, bool propagateMetadataToSiblingItems)
        {
            Project.VerifyThrowInvalidOperationNotImported(_xml.ContainingProject);

            XmlUtilities.VerifyThrowArgumentValidElementName(name);
            ErrorUtilities.VerifyThrowArgument(!FileUtilities.ItemSpecModifiers.IsItemSpecModifier(name), "ItemSpecModifierCannotBeCustomMetadata", name);
            ErrorUtilities.VerifyThrowInvalidOperation(!XMakeElements.ReservedItemNames.Contains(name), "CannotModifyReservedItemMetadata", name);
            ErrorUtilities.VerifyThrowInvalidOperation(_xml.Parent != null && _xml.Parent.Parent != null, "OM_ObjectIsNoLongerActive");

            if (!propagateMetadataToSiblingItems)
            {
                _project.SplitItemElementIfNecessary(_xml);
            }

            ProjectMetadata metadatum;

            if (_directMetadata != null && _directMetadata.Contains(name))
            {
                metadatum = _directMetadata[name];
                metadatum.UnevaluatedValue = unevaluatedValue;
            }
            else
            {
                ProjectMetadataElement metadatumXml = _xml.AddMetadata(name, unevaluatedValue);

                string evaluatedValueEscaped = _project.ExpandMetadataValueBestEffortLeaveEscaped(this, unevaluatedValue, metadatumXml.Location);

                metadatum = new ProjectMetadata(this, metadatumXml, evaluatedValueEscaped, null /* predecessor unknown */);
            }

            if (!propagateMetadataToSiblingItems)
            {
                _directMetadata = _directMetadata ?? new PropertyDictionary <ProjectMetadata>();
                _directMetadata.Set(metadatum);
            }
            else
            {
                var siblingItems = _project.Items.Where(i => i._xml == _xml);

                foreach (var siblingItem in siblingItems)
                {
                    siblingItem._directMetadata = siblingItem._directMetadata ?? new PropertyDictionary <ProjectMetadata>();
                    siblingItem._directMetadata.Set(metadatum.DeepClone());
                }
            }

            return(metadatum);
        }
        public void MatchProperty()
        {
            MSBuildNameIgnoreCaseComparer comparer = MSBuildNameIgnoreCaseComparer.Default;
            PropertyDictionary <ProjectPropertyInstance> dictionary = new PropertyDictionary <ProjectPropertyInstance>(comparer);

            ProjectPropertyInstance p = ProjectPropertyInstance.Create("foo", "bar");

            dictionary.Set(p);

            string s = "$(foo)";
            ProjectPropertyInstance value = dictionary.GetProperty(s, 2, 4);

            Assert.True(Object.ReferenceEquals(p, value)); // "Should have returned the same object as was inserted"

            Assert.Equal(MSBuildNameIgnoreCaseComparer.Default.GetHashCode("foo"), comparer.GetHashCode(s, 2, 3));
        }
示例#24
0
            /// <summary>
            /// Creates an item based on the provided item, with the specified include and item type.
            /// </summary>
            private ProjectItem CreateItem(string evaluatedIncludeEscaped, string evaluatedIncludeBeforeWildcardExpansionEscaped, ProjectItem source)
            {
                ErrorUtilities.VerifyThrowInternalNull(_xml, "xml");

                // The new item inherits any metadata originating in item definitions, which
                // takes precedence over its own item definition metadata.
                //
                // Order of precedence:
                // (1) any directly defined metadata on the source item
                // (2) any inherited item definition metadata the source item had accumulated, in order of accumulation
                // (3) any item definition metadata associated with the source item's item type
                // (4) any item definition metadata associated with the destination item's item type; none yet.

                // Clone for (1)
                PropertyDictionary <ProjectMetadata> directMetadataClone = null;

                if (source.DirectMetadataCount > 0)
                {
                    directMetadataClone = new PropertyDictionary <ProjectMetadata>(source.DirectMetadataCount);

                    foreach (ProjectMetadata metadatum in source._directMetadata)
                    {
                        directMetadataClone.Set(metadatum.DeepClone());
                    }
                }

                // Combine (2) and (3) into a list, (2) on top.
                int inheritedItemDefinitionsCount = (source._inheritedItemDefinitions == null) ? 0 : source._inheritedItemDefinitions.Count;

                List <ProjectItemDefinition> inheritedItemDefinitionsClone = null;

                if (source._inheritedItemDefinitions != null)
                {
                    inheritedItemDefinitionsClone = inheritedItemDefinitionsClone ?? new List <ProjectItemDefinition>(inheritedItemDefinitionsCount + 1);
                    inheritedItemDefinitionsClone.AddRange(source._inheritedItemDefinitions);
                }

                ProjectItemDefinition sourceItemDefinition;

                if (_project.ItemDefinitions.TryGetValue(source.ItemType, out sourceItemDefinition))
                {
                    inheritedItemDefinitionsClone = inheritedItemDefinitionsClone ?? new List <ProjectItemDefinition>(inheritedItemDefinitionsCount + 1);
                    inheritedItemDefinitionsClone.Add(sourceItemDefinition);
                }

                return(new ProjectItem(_project, _xml, evaluatedIncludeEscaped, evaluatedIncludeBeforeWildcardExpansionEscaped, directMetadataClone, inheritedItemDefinitionsClone));
            }
示例#25
0
        /// <summary>
        /// Build the same project twice with different global properties
        /// </summary>
        public void BuildingTheSameProjectTwiceWithDifferentGlobalProperties()
        {
            ProjectPropertyInstance prop1 = ProjectPropertyInstance.Create("prop1", "Value1");
            ProjectPropertyInstance prop2 = ProjectPropertyInstance.Create("prop2", "Value2");
            PropertyDictionary <ProjectPropertyInstance> group1 = new PropertyDictionary <ProjectPropertyInstance>();

            group1.Set(prop1);
            PropertyDictionary <ProjectPropertyInstance> group2 = new PropertyDictionary <ProjectPropertyInstance>();

            group2.Set(prop2);

            RequestDefinition p1 = CreateNewRequest("1.proj", "2.0", null, group1);
            RequestDefinition p2 = CreateNewRequest("1.proj", "3.0", null, group2);

            p1.SubmitBuildRequest();
            p1.ValidateBuildResult();

            p2.SubmitBuildRequest();
            p2.ValidateBuildResult();
        }
        public void MatchProperty()
        {
            PropertyDictionary<ProjectPropertyInstance> dictionary = new PropertyDictionary<ProjectPropertyInstance>();

            ProjectPropertyInstance p = ProjectPropertyInstance.Create("foo", "bar");

            dictionary.Set(p);

            string s = "$(foo)";
            ProjectPropertyInstance value = MSBuildNameIgnoreCaseComparer.Mutable.GetValueWithConstraints<ProjectPropertyInstance>(dictionary, s, 2, 4);

            Assert.IsTrue(Object.ReferenceEquals(p, value), "Should have returned the same object as was inserted");

            try
            {
                MSBuildNameIgnoreCaseComparer.Mutable.SetConstraintsForUnitTestingOnly(s, 2, 4);
                Assert.AreEqual(MSBuildNameIgnoreCaseComparer.Default.GetHashCode("foo"), MSBuildNameIgnoreCaseComparer.Mutable.GetHashCode(s));
            }
            finally
            {
                MSBuildNameIgnoreCaseComparer.Mutable.RemoveConstraintsForUnitTestingOnly();
            }
        }
        public void MatchProperty()
        {
            PropertyDictionary <ProjectPropertyInstance> dictionary = new PropertyDictionary <ProjectPropertyInstance>();

            ProjectPropertyInstance p = ProjectPropertyInstance.Create("foo", "bar");

            dictionary.Set(p);

            string s = "$(foo)";
            ProjectPropertyInstance value = MSBuildNameIgnoreCaseComparer.Mutable.GetValueWithConstraints <ProjectPropertyInstance>(dictionary, s, 2, 4);

            Assert.True(Object.ReferenceEquals(p, value)); // "Should have returned the same object as was inserted"

            try
            {
                MSBuildNameIgnoreCaseComparer.Mutable.SetConstraintsForUnitTestingOnly(s, 2, 4);
                Assert.Equal(MSBuildNameIgnoreCaseComparer.Default.GetHashCode("foo"), MSBuildNameIgnoreCaseComparer.Mutable.GetHashCode(s));
            }
            finally
            {
                MSBuildNameIgnoreCaseComparer.Mutable.RemoveConstraintsForUnitTestingOnly();
            }
        }
示例#28
0
        /// <summary>
        /// Adds metadata with the specified name and value to the item.
        /// Updates an existing metadata if one already exists with the same name on the item directly, as opposed to inherited from an item definition.
        /// Updates the evaluated project, but does not affect anything else in the project until reevaluation. For example,
        /// if a piece of metadata named "m" is added on item of type "i", it does not affect "j" which is evaluated from "@(j->'%(m)')" until reevaluation.
        /// Also if the unevaluated value of "m" is set to something that is modified by evaluation, such as "$(p)", the evaluated value will be set to literally "$(p)" until reevaluation.
        /// This is a convenience that it is understood does not necessarily leave the project in a perfectly self consistent state.
        /// Returns the new or existing metadatum.
        /// </summary>
        /// <remarks>Unevaluated value is assumed to be escaped as necessary</remarks>
        public ProjectMetadata SetMetadataValue(string name, string unevaluatedValue)
        {
            Project.VerifyThrowInvalidOperationNotImported(_xml.ContainingProject);

            XmlUtilities.VerifyThrowArgumentValidElementName(name);
            ErrorUtilities.VerifyThrowArgument(!FileUtilities.ItemSpecModifiers.IsItemSpecModifier(name), "ItemSpecModifierCannotBeCustomMetadata", name);
            ErrorUtilities.VerifyThrowInvalidOperation(XMakeElements.IllegalItemPropertyNames[name] == null, "CannotModifyReservedItemMetadata", name);
            ErrorUtilities.VerifyThrowInvalidOperation(_xml.Parent != null && _xml.Parent.Parent != null, "OM_ObjectIsNoLongerActive");

            _project.SplitItemElementIfNecessary(_xml);

            ProjectMetadata metadatum;

            if (_directMetadata != null)
            {
                metadatum = _directMetadata[name];

                if (metadatum != null)
                {
                    metadatum.UnevaluatedValue = unevaluatedValue;
                    return(metadatum);
                }
            }

            ProjectMetadataElement metadatumXml = _xml.AddMetadata(name, unevaluatedValue);

            _directMetadata = _directMetadata ?? new PropertyDictionary <ProjectMetadata>();

            string evaluatedValueEscaped = _project.ExpandMetadataValueBestEffortLeaveEscaped(this, unevaluatedValue, metadatumXml.Location);

            metadatum = new ProjectMetadata(this, metadatumXml, evaluatedValueEscaped, null /* predecessor unknown */);

            _directMetadata.Set(metadatum);

            return(metadatum);
        }
示例#29
0
        public void ModifiedProperty()
        {
            PropertyDictionary<ProjectPropertyInstance> group = new PropertyDictionary<ProjectPropertyInstance>();
            group.Set(ProjectPropertyInstance.Create("p1", "v1"));
            Lookup lookup = LookupHelpers.CreateLookup(group);
            // Enter scope so that property sets are allowed on it
            Lookup.Scope enteredScope = lookup.EnterScope("x");

            // Change the property value
            lookup.SetProperty(ProjectPropertyInstance.Create("p1", "v2"));

            // Lookup is updated, but not original item group
            Assert.Equal("v2", lookup.GetProperty("p1").EvaluatedValue);
            Assert.Equal("v1", group["p1"].EvaluatedValue);

            Lookup.Scope enteredScope2 = lookup.EnterScope("x");

            // Change the value again in the new scope 
            lookup.SetProperty(ProjectPropertyInstance.Create("p1", "v3"));

            // Lookup is updated, but not the original item group
            Assert.Equal("v3", lookup.GetProperty("p1").EvaluatedValue);
            Assert.Equal("v1", group["p1"].EvaluatedValue);

            Lookup.Scope enteredScope3 = lookup.EnterScope("x");

            // Change the value again in the new scope 
            lookup.SetProperty(ProjectPropertyInstance.Create("p1", "v4"));

            Assert.Equal("v4", lookup.GetProperty("p1").EvaluatedValue);

            enteredScope3.LeaveScope();

            Assert.Equal("v4", lookup.GetProperty("p1").EvaluatedValue);

            // Leave to the outer scope
            enteredScope2.LeaveScope();
            enteredScope.LeaveScope();

            // Now the lookup and original group are updated
            Assert.Equal("v4", lookup.GetProperty("p1").EvaluatedValue);
            Assert.Equal("v4", group["p1"].EvaluatedValue);
        }
示例#30
0
        public void PropertyFunctionConsumingItemMetadata()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            itemMetadataTable["Compile.Identity"] = "fOo.Cs";
            StringMetadataTable itemMetadata = new StringMetadataTable(itemMetadataTable);

            List<ProjectItemInstance> ig = new List<ProjectItemInstance>();
            pg.Set(ProjectPropertyInstance.Create("SomePath", @"c:\some\path"));
            ig.Add(new ProjectItemInstance(project, "Compile", "fOo.Cs", project.FullPath));

            ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>();
            itemsByType.ImportItems(ig);

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, itemsByType, itemMetadata);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine($(SomePath),%(Compile.Identity)))", ExpanderOptions.ExpandAll, MockElementLocation.Instance);

            Assert.Equal(@"c:\some\path\fOo.Cs", result);
        }
示例#31
0
        /// <summary>
        /// Creates an expander populated with some ProjectPropertyInstances and ProjectPropertyItems.
        /// </summary>
        /// <returns></returns>
        private Expander<ProjectPropertyInstance, ProjectItemInstance> CreateItemFunctionExpander()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("p", "v0"));
            pg.Set(ProjectPropertyInstance.Create("p", "v1"));
            pg.Set(ProjectPropertyInstance.Create("Val", "2"));
            pg.Set(ProjectPropertyInstance.Create("a", "filename"));

            ItemDictionary<ProjectItemInstance> ig = new ItemDictionary<ProjectItemInstance>();

            for (int n = 0; n < 10; n++)
            {
                ProjectItemInstance pi = new ProjectItemInstance(project, "i", "i" + n.ToString(), project.FullPath);
                for (int m = 0; m < 5; m++)
                {
                    pi.SetMetadata("Meta" + m.ToString(), @"c:\firstdirectory\seconddirectory\file" + m.ToString() + ".ext");
                }
                pi.SetMetadata("Meta9", @"seconddirectory\file.ext");
                pi.SetMetadata("Meta10", @";someo%3bherplace\foo.txt;secondd%3brectory\file.ext;");
                pi.SetMetadata("MetaBlank", @"");

                if (n % 2 > 0)
                {
                    pi.SetMetadata("Even", "true");
                    pi.SetMetadata("Odd", "false");
                }
                else
                {
                    pi.SetMetadata("Even", "false");
                    pi.SetMetadata("Odd", "true");
                }
                ig.Add(pi);
            }

            Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            itemMetadataTable["Culture"] = "abc%253bdef;$(Gee_Aych_Ayee)";
            itemMetadataTable["Language"] = "english";
            IMetadataTable itemMetadata = new StringMetadataTable(itemMetadataTable);

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, ig, itemMetadata);

            return expander;
        }
示例#32
0
        public void PropertyFunctionStaticMethodRegex1()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("File", @"foo\file.txt"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            // Support enum combines as Enum.Parse expects them
            string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Text.RegularExpressions.Regex]::IsMatch(`-42`, `^-?\d+(\.\d{2})?$`, `RegexOptions.IgnoreCase,RegexOptions.Singleline`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(@"True", result);

            // We support the C# style enum combining syntax too
            result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Text.RegularExpressions.Regex]::IsMatch(`-42`, `^-?\d+(\.\d{2})?$`, System.Text.RegularExpressions.RegexOptions.IgnoreCase|RegexOptions.Singleline))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(@"True", result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Text.RegularExpressions.Regex]::IsMatch(`100 GBP`, `^-?\d+(\.\d{2})?$`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(@"False", result);
        }
示例#33
0
        public void PropertySimpleSpaced()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$( SomeStuff )", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(String.Empty, result);
        }
示例#34
0
        public void PropertyFunctionPropertyPathRootSubtraction()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("RootPath", @"c:\this\is\the\root"));
            pg.Set(ProjectPropertyInstance.Create("MyPath", @"c:\this\is\the\root\my\project\is\here.proj"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$(MyPath.SubString($(RootPath.Length)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(@"\my\project\is\here.proj", result);
        }
示例#35
0
        public void PropertyFunctionConstructor2()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("ver1", @"1.2.3.4"));
            pg.Set(ProjectPropertyInstance.Create("ver2", @"2.2.3.4"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Version]::new($(ver1)).CompareTo($([System.Version]::new($(ver2)))))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(@"-1", result);
        }
示例#36
0
        public void PropertyFunctionNoArgumentsTrim()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("FileName", "    foo.ext   "));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$(FileName.Trim())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal("foo.ext", result);
        }
示例#37
0
        public void PropertyFunctionPropertyWithArgumentWithSpaces()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.SubString(8))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal("SOME STUff", result);
        }
示例#38
0
        public void PropertyFunctionNullReturn()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$([System.Convert]::ChangeType(,$(SomeStuff.GetType())))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal("", result);
        }
示例#39
0
        public void GetBuckets()
        {
            ProjectInstance project    = ProjectHelpers.CreateEmptyProjectInstance();
            List <string>   parameters = new List <string>();

            parameters.Add("@(File);$(unittests)");
            parameters.Add("$(obj)\\%(Filename).ext");
            parameters.Add("@(File->'%(extension)')");  // attributes in transforms don't affect batching

            ItemDictionary <ProjectItemInstance> itemsByType = new ItemDictionary <ProjectItemInstance>();

            IList <ProjectItemInstance> items = new List <ProjectItemInstance>();

            items.Add(new ProjectItemInstance(project, "File", "a.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "b.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "c.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "d.foo", project.FullPath));
            items.Add(new ProjectItemInstance(project, "File", "e.foo", project.FullPath));
            itemsByType.ImportItems(items);

            items = new List <ProjectItemInstance>();
            items.Add(new ProjectItemInstance(project, "Doc", "a.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "b.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "c.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "d.doc", project.FullPath));
            items.Add(new ProjectItemInstance(project, "Doc", "e.doc", project.FullPath));
            itemsByType.ImportItems(items);

            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            properties.Set(ProjectPropertyInstance.Create("UnitTests", "unittests.foo"));
            properties.Set(ProjectPropertyInstance.Create("OBJ", "obj"));

            List <ItemBucket> buckets = BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), MockElementLocation.Instance);

            Assert.Equal(5, buckets.Count);

            foreach (ItemBucket bucket in buckets)
            {
                // non-batching data -- same for all buckets
                XmlAttribute tempXmlAttribute = (new XmlDocument()).CreateAttribute("attrib");
                tempXmlAttribute.Value = "'$(Obj)'=='obj'";

                Assert.True(ConditionEvaluator.EvaluateCondition(tempXmlAttribute.Value, ParserOptions.AllowAll, bucket.Expander, ExpanderOptions.ExpandAll, Directory.GetCurrentDirectory(), MockElementLocation.Instance, null, new BuildEventContext(1, 2, 3, 4)));
                Assert.Equal("a.doc;b.doc;c.doc;d.doc;e.doc", bucket.Expander.ExpandIntoStringAndUnescape("@(doc)", ExpanderOptions.ExpandItems, MockElementLocation.Instance));
                Assert.Equal("unittests.foo", bucket.Expander.ExpandIntoStringAndUnescape("$(bogus)$(UNITTESTS)", ExpanderOptions.ExpandPropertiesAndMetadata, MockElementLocation.Instance));
            }

            Assert.Equal("a.foo", buckets[0].Expander.ExpandIntoStringAndUnescape("@(File)", ExpanderOptions.ExpandItems, MockElementLocation.Instance));
            Assert.Equal(".foo", buckets[0].Expander.ExpandIntoStringAndUnescape("@(File->'%(Extension)')", ExpanderOptions.ExpandItems, MockElementLocation.Instance));
            Assert.Equal("obj\\a.ext", buckets[0].Expander.ExpandIntoStringAndUnescape("$(obj)\\%(Filename).ext", ExpanderOptions.ExpandPropertiesAndMetadata, MockElementLocation.Instance));

            // we weren't batching on this attribute, so it has no value
            Assert.Equal(String.Empty, buckets[0].Expander.ExpandIntoStringAndUnescape("%(Extension)", ExpanderOptions.ExpandAll, MockElementLocation.Instance));

            ProjectItemInstanceFactory factory = new ProjectItemInstanceFactory(project, "i");

            items = buckets[0].Expander.ExpandIntoItemsLeaveEscaped("@(file)", factory, ExpanderOptions.ExpandItems, MockElementLocation.Instance);
            Assert.NotNull(items);
            Assert.Equal(1, items.Count);

            int invalidProjectFileExceptions = 0;

            try
            {
                // This should throw because we don't allow item lists to be concatenated
                // with other strings.
                bool throwAway;
                items = buckets[0].Expander.ExpandSingleItemVectorExpressionIntoItems("@(file)$(unitests)", factory, ExpanderOptions.ExpandItems, false /* no nulls */, out throwAway, MockElementLocation.Instance);
            }
            catch (InvalidProjectFileException ex)
            {
                // check we don't lose error codes from IPFE's during build
                Assert.Equal(ex.ErrorCode, "MSB4012");
                invalidProjectFileExceptions++;
            }

            // We do allow separators in item vectors, this results in an item group with a single flattened item
            items = buckets[0].Expander.ExpandIntoItemsLeaveEscaped("@(file, ',')", factory, ExpanderOptions.ExpandItems, MockElementLocation.Instance);
            Assert.NotNull(items);
            Assert.Equal(1, items.Count);
            Assert.Equal("a.foo", items[0].EvaluatedInclude);

            Assert.Equal(1, invalidProjectFileExceptions);
        }
示例#40
0
        public void PropertyTests()
        {
            Parser p = new Parser();

            var propertyBag = new PropertyDictionary <ProjectPropertyInstance>();

            propertyBag.Set(ProjectPropertyInstance.Create("foo", "true"));
            propertyBag.Set(ProjectPropertyInstance.Create("bar", "yes"));
            propertyBag.Set(ProjectPropertyInstance.Create("one", "1"));
            propertyBag.Set(ProjectPropertyInstance.Create("onepointzero", "1.0"));
            propertyBag.Set(ProjectPropertyInstance.Create("two", "2"));
            propertyBag.Set(ProjectPropertyInstance.Create("simple", "simplestring"));
            propertyBag.Set(ProjectPropertyInstance.Create("complex", "This is a complex string"));
            propertyBag.Set(ProjectPropertyInstance.Create("c1", "Another (complex) one."));
            propertyBag.Set(ProjectPropertyInstance.Create("c2", "Another (complex) one."));
            propertyBag.Set(ProjectPropertyInstance.Create("x86", "x86"));
            propertyBag.Set(ProjectPropertyInstance.Create("no", "no"));

            Expander <ProjectPropertyInstance, ProjectItemInstance> expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(propertyBag, new ItemDictionary <ProjectItemInstance>(), FileSystems.Default);

            AssertParseEvaluate(p, "$(foo)", expander, true);
            AssertParseEvaluate(p, "!$(foo)", expander, false);
            // Test properties with strings
            AssertParseEvaluate(p, "$(simple) == 'simplestring'", expander, true);
            AssertParseEvaluate(p, "'simplestring' == $(simple)", expander, true);
            AssertParseEvaluate(p, "'foo' != $(simple)", expander, true);
            AssertParseEvaluate(p, "'simplestring' == '$(simple)'", expander, true);
            AssertParseEvaluate(p, "$(simple) == simplestring", expander, true);
            AssertParseEvaluate(p, "$(x86) == x86", expander, true);
            AssertParseEvaluate(p, "$(x86)==x86", expander, true);
            AssertParseEvaluate(p, "x86==$(x86)", expander, true);
            AssertParseEvaluate(p, "$(c1) == $(c2)", expander, true);
            AssertParseEvaluate(p, "'$(c1)' == $(c2)", expander, true);
            AssertParseEvaluate(p, "$(c1) != $(simple)", expander, true);
            AssertParseEvaluate(p, "$(c1) == $(c2)", expander, true);
            // Test properties with numbers
            AssertParseEvaluate(p, "$(one) == $(onepointzero)", expander, true);
            AssertParseEvaluate(p, "$(one) <= $(two)", expander, true);
            AssertParseEvaluate(p, "$(two) > $(onepointzero)", expander, true);
            AssertParseEvaluate(p, "$(one) != $(two)", expander, true);
            AssertParseEvaluate(p, "'$(no)'==false", expander, true);
        }
示例#41
0
        public void ExpandAllIntoTaskItems4()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("a", "aaa"));
            pg.Set(ProjectPropertyInstance.Create("b", "bbb"));
            pg.Set(ProjectPropertyInstance.Create("c", "cc;dd"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo$(a);$(b);$(c)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            ObjectModelHelpers.AssertItemsMatch(@"
                fooaaa
                bbb
                cc
                dd
                ", GetTaskArrayFromItemList(itemsOut));
        }
示例#42
0
        public void PropertyFunctionPropertyWithArgumentBooleanReturn()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("PathRoot", @"c:\goo"));
            pg.Set(ProjectPropertyInstance.Create("PathRoot2", @"c:\goop\"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$(PathRoot2.Endswith(\))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);
            Assert.Equal("True", result);
            result = expander.ExpandIntoStringLeaveEscaped(@"$(PathRoot.Endswith(\))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);
            Assert.Equal("False", result);
        }
示例#43
0
        public void PropertyFunctionConstructor1()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("ver1", @"1.2.3.4"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            object result = expander.ExpandPropertiesLeaveTypedAndEscaped(@"$([System.Version]::new($(ver1)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Version v = result as Version;
            Assert.NotNull(v);

            Assert.Equal(1, v.Major);
            Assert.Equal(2, v.Minor);
            Assert.Equal(3, v.Build);
            Assert.Equal(4, v.Revision);
        }
示例#44
0
        public void PropertyFunctionPropertyWithArgumentChained()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("Value", "3"));
            pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToUpperInvariant().ToLowerInvariant())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);
            Assert.Equal("this is some stuff", result);
        }
示例#45
0
        public void PropertyFunctionStaticMethodNested()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("File", @"foo\file.txt"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine(`c:\`, $([System.IO.Path]::Combine(`foo`,`file.txt`))))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(@"c:\foo\file.txt", result);
        }
示例#46
0
        public void PropertyFunctionPropertyWithArgumentNested()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("Value", "12345"));
            pg.Set(ProjectPropertyInstance.Create("SomeStuff", "1234567890"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.SubString($(Value.get_Length())))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal("67890", result);
        }
示例#47
0
        public void PropertyFunctionStaticMethodDirectoryNameOfFileAbove()
        {
            string tempPath = Path.GetTempPath();
            string tempFile = Path.GetFileName(FileUtilities.GetTemporaryFile());

            try
            {
                string directoryStart = Path.Combine(tempPath, "one\\two\\three\\four\\five");

                PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
                pg.Set(ProjectPropertyInstance.Create("StartingDirectory", directoryStart));
                pg.Set(ProjectPropertyInstance.Create("FileToFind", tempFile));

                Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

                string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetDirectoryNameOfFileAbove($(StartingDirectory), $(FileToFind)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                Assert.Equal(Microsoft.Build.Shared.FileUtilities.EnsureTrailingSlash(tempPath), Microsoft.Build.Shared.FileUtilities.EnsureTrailingSlash(result));

                result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetDirectoryNameOfFileAbove($(StartingDirectory), Hobbits))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                Assert.Equal(String.Empty, result);
            }
            finally
            {
                File.Delete(tempFile);
            }
        }
示例#48
0
        public void PropertyFunctionArrayReturnManualSplitter()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("List", "A-B-C-D"));
            pg.Set(ProjectPropertyInstance.Create("Splitter", "-"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$(List.Split($(Splitter.ToCharArray())))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal("A;B;C;D", result);
        }
示例#49
0
        public void PropertyFunctionGetRegistryValueFromView2()
        {
            try
            {
                PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
                pg.Set(ProjectPropertyInstance.Create("SomeProperty", "Value"));

                Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);
                RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test");

                key.SetValue(String.Empty, "%TEMP%", RegistryValueKind.ExpandString);
                string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetRegistryValueFromView('HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test', null, null, Microsoft.Win32.RegistryView.Default))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                Assert.Equal(Environment.GetEnvironmentVariable("TEMP"), result);
            }
            finally
            {
                Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test");
            }
        }        /// <summary>
示例#50
0
        public void PropertyFunctionInCondition()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("PathRoot", @"c:\goo"));
            pg.Set(ProjectPropertyInstance.Create("PathRoot2", @"c:\goop\"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            Assert.True(ConditionEvaluator.EvaluateCondition(@"'$(PathRoot2.Endswith(`\`))' == 'true'", ParserOptions.AllowAll, expander, ExpanderOptions.ExpandProperties, Directory.GetCurrentDirectory(), MockElementLocation.Instance, null, new BuildEventContext(1, 2, 3, 4)));
            Assert.True(ConditionEvaluator.EvaluateCondition(@"'$(PathRoot.Endswith(\))' == 'false'", ParserOptions.AllowAll, expander, ExpanderOptions.ExpandProperties, Directory.GetCurrentDirectory(), MockElementLocation.Instance, null, new BuildEventContext(1, 2, 3, 4)));
        }
示例#51
0
        public void Medley()
        {
            // Make absolutely sure that the static method cache hasn't been polluted by the other tests.  
            AvailableStaticMethods.Reset_ForUnitTestsOnly();

            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("File", @"foo\file.txt"));

            pg.Set(ProjectPropertyInstance.Create("a", "no"));
            pg.Set(ProjectPropertyInstance.Create("b", "true"));
            pg.Set(ProjectPropertyInstance.Create("c", "1"));
            pg.Set(ProjectPropertyInstance.Create("position", "4"));
            pg.Set(ProjectPropertyInstance.Create("d", "xxx"));
            pg.Set(ProjectPropertyInstance.Create("e", "xxx"));
            pg.Set(ProjectPropertyInstance.Create("and", "and"));
            pg.Set(ProjectPropertyInstance.Create("a_semi_b", "a;b"));
            pg.Set(ProjectPropertyInstance.Create("a_apos_b", "a'b"));
            pg.Set(ProjectPropertyInstance.Create("foo_apos_foo", "foo'foo"));
            pg.Set(ProjectPropertyInstance.Create("a_escapedsemi_b", "a%3bb"));
            pg.Set(ProjectPropertyInstance.Create("a_escapedapos_b", "a%27b"));
            pg.Set(ProjectPropertyInstance.Create("has_trailing_slash", @"foo\"));
            pg.Set(ProjectPropertyInstance.Create("emptystring", @""));
            pg.Set(ProjectPropertyInstance.Create("space", @" "));
            pg.Set(ProjectPropertyInstance.Create("listofthings", @"a;b;c;d;e;f;g;h;i;j;k;l"));
            pg.Set(ProjectPropertyInstance.Create("input", @"EXPORT a"));
            pg.Set(ProjectPropertyInstance.Create("propertycontainingnullasastring", @"null"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string[,] validTests = {
                {"$(input.ToString()[1])", "X"},
                {"$(input[1])", "X"},
                {"$(listofthings.Split(';')[$(position)])","e"},
                {@"$([System.Text.RegularExpressions.Regex]::Match($(Input), `EXPORT\s+(.+)`).Groups[1].Value)","a"},
                {"$([MSBuild]::Add(1,2).CompareTo(3))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo(3))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo(3.0))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo('3'))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo(3.1))", "-1"},
                {"$([MSBuild]::Add(1,2).CompareTo(2))", "1"},
                {"$([MSBuild]::Add(1,2).Equals(3))", "True"},
                {"$([MSBuild]::Add(1,2).Equals(3.0))", "True"},
                {"$([MSBuild]::Add(1,2).Equals('3'))", "True"},
                {"$([MSBuild]::Add(1,2).Equals(3.1))", "False"},
                {"$(a.Insert(0,'%28'))", "%28no"},
                {"$(a.Insert(0,'\"'))", "\"no"},
                {"$(a.Insert(0,'(('))", "%28%28no"},
                {"$(a.Insert(0,'))'))", "%29%29no"},
                {"A$(Reg:A)A", "AA"},
                {"A$(Reg:AA)", "A"},
                {"$(Reg:AA)", ""},
                {"$(Reg:AAAA)", ""},
                {"$(Reg:AAA)", ""},
                {"$([MSBuild]::Add(2,$([System.Convert]::ToInt64('28', 16))))", "42"},
                {"$([MSBuild]::Add(2,$([System.Convert]::ToInt64('28', $([System.Convert]::ToInt32(16))))))", "42"},
                {"$(e.Length.ToString())", "3"},
                {"$(e.get_Length().ToString())", "3"},
                {"$(emptystring.Length)", "0" },
                {"$(space.Length)", "1" },
                {"$([System.TimeSpan]::Equals(null, null))", "True"}, // constant, unquoted null is a special value
                {"$([MSBuild]::Add(40,null))", "40"},
                {"$([MSBuild]::Add( 40 , null ))", "40"},
                {"$([MSBuild]::Add(null,40))", "40"},
                {"$([MSBuild]::Escape(';'))", "%3b"},
                {"$([MSBuild]::UnEscape('%3b'))", ";"},
                {"$(e.Substring($(e.Length)))", ""},
                {"$([System.Int32]::MaxValue)", System.Int32.MaxValue.ToString()},
                {"x$()", "x"},
                {"A$(Reg:A)A", "AA"},
                {"A$(Reg:AA)", "A"},
                {"$(Reg:AA)", ""},
                {"$(Reg:AAAA)", ""},
                {"$(Reg:AAA)", ""}
                                   };

            string[] errorTests = {
            "$(input[)",
            "$(input.ToString()])",
            "$(input.ToString()[)",
            "$(input.ToString()[12])",
            "$(input[])",
            "$(input[-1])",
            "$(listofthings.Split(';')[)",
            "$(listofthings.Split(';')['goo'])",
            "$(listofthings.Split(';')[])",
            "$(listofthings.Split(';')[-1])",
            "$([]::())",
                                                      @"
 
$(
 
$(
 
[System.IO]::Path.GetDirectory('c:\foo\bar\baz.txt')
 
).Substring(
 
'$([System.IO]::Path.GetPathRoot(
 
'$([System.IO]::Path.GetDirectory('c:\foo\bar\baz.txt'))'
 
).Length)'
 
 
 
)
 
",
                "$([Microsoft.VisualBasic.FileIO.FileSystem]::CurrentDirectory)", // not allowed
                "$(e.Length..ToString())",
                "$(SomeStuff.get_Length(null))",
                "$(SomeStuff.Substring((1)))",
                "$(b.Substring(-10, $(c)))",
                "$(b.Substring(-10, $(emptystring)))",
                "$(b.Substring(-10, $(space)))",
                "$([MSBuild]::Add.Sub(null,40))",
                "$([MSBuild]::Add( ,40))", // empty parameter is empty string
                "$([MSBuild]::Add('',40))", // empty quoted parameter is empty string
                "$([MSBuild]::Add(40,,,))",
                "$([MSBuild]::Add(40, ,,))",
                "$([MSBuild]::Add(40,)",
                "$([MSBuild]::Add(40,X)",
                "$([MSBuild]::Add(40,",
                "$([MSBuild]::Add(40",
                "$([MSBuild]::Add(,))", // gives "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."
                "$([System.TimeSpan]::Equals(,))", // empty parameter is interpreted as empty string
                "$([System.TimeSpan]::Equals($(space),$(emptystring)))", // empty parameter is interpreted as empty string
                "$([System.TimeSpan]::Equals($(emptystring),$(emptystring)))", // empty parameter is interpreted as empty string
                "$([MSBuild]::Add($(PropertyContainingNullAsAString),40))", // a property containing the word null is a string "null"
                "$([MSBuild]::Add('null',40))", // the word null is a string "null"
                "$(SomeStuff.Substring(-10))",
                "$(.Length)",
                "$(.Substring(1))",
                "$(.get_Length())",
                "$(e.)",
                "$(e..)",
                "$(e..Length)",
                "$(e$(d).Length)",
                "$($(d).Length)",
                "$(e`.Length)",
                "$([System.IO.Path]Combine::Combine(`a`,`b`))",
                "$([System.IO.Path]::Combine((`a`,`b`))",
                "$([System.IO.Path]::Combine(`|`,`b`))",
                "$([System.IO.Path]Combine(::Combine(`a`,`b`))",
                "$([System.IO.Path]Combine(`::Combine(`a`,`b`)`, `b`)`)",
                "$([System.IO.Path]::`Combine(`a`, `b`)`)",
                "$([System.IO.Path]::(`Combine(`a`, `b`)`))",
                "$([System.DateTime]foofoo::Now)",
                "$([System.DateTime].Now)",
                "$([].Now)",
                "$([ ].Now)",
                "$([ .Now)",
                "$([])",
                "$([ )",
                "$([ ])",
                "$([System.Diagnostics.Process]::Start(`NOTEPAD.EXE`))",
                "$([[]]::Start(`NOTEPAD.EXE`))",
                "$([(::Start(`NOTEPAD.EXE`))",
                "$([Goop]::Start(`NOTEPAD.EXE`))",
                "$([System.Threading.Thread]::CurrentThread)",
                "$",
                "$(",
                "$((",
                "@",
                "@(",
                "@()",
                "%",
                "%(",
                "%()",
                "exists",
                "exists(",
                "exists()",
                "exists( )",
                "exists(,)",
                "@(x->'",
                "@(x->''",
                "@(x-",
                "@(x->'x','",
                "@(x->'x',''",
                "@(x->'x','')",
                "-1>x",
                "\n",
                "\t",
                "+-1",
                "$(SomeStuff.)",
                "$(SomeStuff.!)",
                "$(SomeStuff.`)",
                "$(SomeStuff.GetType)",
                "$(goop.baz`)",
                "$(SomeStuff.Substring(HELLO!))",
                "$(SomeStuff.ToLowerInvariant()_goop)",
                "$(SomeStuff($(System.DateTime.Now)))",
                "$(System.Foo.Bar.Lgg)",
                "$(SomeStuff.Lgg)",
                "$(SomeStuff($(Value)))",
                "$(e.$(e.Length))",
                "$(e.Substring($(e.Substring(,)))",
                "$(e.Substring($(e.Substring(a)))",
                "$(e.Substring($([System.IO.Path]::Combine(`a`, `b`))))",
                "$([]::())",
                "$((((",
                "$(Registry:X)",
                "$($())",
                "$",
                "()"
            };

            string result;
            for (int i = 0; i < validTests.GetLength(0); i++)
            {
                result = expander.ExpandIntoStringLeaveEscaped(validTests[i, 0], ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                if (!String.Equals(result, validTests[i, 1]))
                {
                    string message = "FAILURE: " + validTests[i, 0] + " expanded to '" + result + "' instead of '" + validTests[i, 1] + "'";
                    Console.WriteLine(message);
                    Assert.True(false, message);
                }
                else
                {
                    Console.WriteLine(validTests[i, 0] + " expanded to '" + result + "'");
                }
            }

            for (int i = 0; i < errorTests.GetLength(0); i++)
            {
                // If an expression is invalid,
                //      - Expansion may throw InvalidProjectFileException, or
                //      - return the original unexpanded expression
                bool success = true;
                bool caughtException = false;
                result = String.Empty;
                try
                {
                    result = expander.ExpandIntoStringLeaveEscaped(errorTests[i], ExpanderOptions.ExpandProperties, MockElementLocation.Instance);
                    if (String.Compare(result, errorTests[i]) == 0)
                    {
                        Console.WriteLine(errorTests[i] + " did not expand.");
                        success = false;
                    }
                }
                catch (InvalidProjectFileException ex)
                {
                    Console.WriteLine(errorTests[i] + " caused '" + ex.Message + "'");
                    caughtException = true;
                }
                Assert.True(
                        (success == false || caughtException == true),
                        "FAILURE: Expected '" + errorTests[i] + "' to not parse or not be evaluated but it evaluated to '" + result + "'"
                    );
            }
        }
示例#52
0
        public void PropertyFunctionInvalid7()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
                pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff"));

                Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

                string result = expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff.Substring(-10))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);
            }
           );
        }
示例#53
0
        /// <summary>
        /// Creates an expander populated with some ProjectPropertyInstances and ProjectPropertyItems.
        /// </summary>
        /// <returns></returns>
        private Expander<ProjectPropertyInstance, ProjectItemInstance> CreateExpander()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("p", "v0"));
            pg.Set(ProjectPropertyInstance.Create("p", "v1"));

            ItemDictionary<ProjectItemInstance> ig = new ItemDictionary<ProjectItemInstance>();
            ProjectItemInstance i0 = new ProjectItemInstance(project, "i", "i0", project.FullPath);
            ProjectItemInstance i1 = new ProjectItemInstance(project, "i", "i1", project.FullPath);
            ig.Add(i0);
            ig.Add(i1);

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, ig);

            return expander;
        }
示例#54
0
        public void PropertyFunctionNoCollisionsOnType()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("System", "The System Namespace"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped("$(System)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal("The System Namespace", result);
        }
示例#55
0
        public void UnmodifiedProperty()
        {
            PropertyDictionary<ProjectPropertyInstance> group = new PropertyDictionary<ProjectPropertyInstance>();
            ProjectPropertyInstance property = ProjectPropertyInstance.Create("p1", "v1");
            group.Set(property);
            Lookup lookup = LookupHelpers.CreateLookup(group);

            Assert.Equal(property, lookup.GetProperty("p1"));

            Lookup.Scope enteredScope = lookup.EnterScope("x");

            Assert.Equal(property, lookup.GetProperty("p1"));
        }
示例#56
0
        public void PropertyFunctionStaticMethodMakeRelative()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("ParentPath", @"c:\abc\def"));
            pg.Set(ProjectPropertyInstance.Create("FilePath", @"c:\abc\def\foo.cpp"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::MakeRelative($(ParentPath), `$(FilePath)`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(@"foo.cpp", result);
        }
示例#57
0
        /// <summary>
        /// Creates a set of complicated item metadata and properties, and items to exercise
        /// the Expander class.  The data here contains escaped characters, metadata that
        /// references properties, properties that reference items, and other complex scenarios.
        /// </summary>
        /// <param name="pg"></param>
        /// <param name="primaryItemsByName"></param>
        /// <param name="secondaryItemsByName"></param>
        /// <param name="itemMetadata"></param>
        private void CreateComplexPropertiesItemsMetadata
            (
            out ReadOnlyLookup readOnlyLookup,
            out StringMetadataTable itemMetadata
            )
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            itemMetadataTable["Culture"] = "abc%253bdef;$(Gee_Aych_Ayee)";
            itemMetadataTable["Language"] = "english";
            itemMetadata = new StringMetadataTable(itemMetadataTable);

            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("Gee_Aych_Ayee", "ghi"));
            pg.Set(ProjectPropertyInstance.Create("OutputPath", @"\jk ; l\mno%253bpqr\stu"));
            pg.Set(ProjectPropertyInstance.Create("TargetPath", "@(IntermediateAssembly->'%(RelativeDir)')"));

            List<ProjectItemInstance> intermediateAssemblyItemGroup = new List<ProjectItemInstance>();
            ProjectItemInstance i1 = new ProjectItemInstance(project, "IntermediateAssembly", @"subdir1\engine.dll", project.FullPath);
            intermediateAssemblyItemGroup.Add(i1);
            i1.SetMetadata("aaa", "111");
            ProjectItemInstance i2 = new ProjectItemInstance(project, "IntermediateAssembly", @"subdir2\tasks.dll", project.FullPath);
            intermediateAssemblyItemGroup.Add(i2);
            i2.SetMetadata("bbb", "222");

            List<ProjectItemInstance> contentItemGroup = new List<ProjectItemInstance>();
            ProjectItemInstance i3 = new ProjectItemInstance(project, "Content", "splash.bmp", project.FullPath);
            contentItemGroup.Add(i3);
            i3.SetMetadata("ccc", "333");

            List<ProjectItemInstance> resourceItemGroup = new List<ProjectItemInstance>();
            ProjectItemInstance i4 = new ProjectItemInstance(project, "Resource", "string$(p).resx", project.FullPath);
            resourceItemGroup.Add(i4);
            i4.SetMetadata("ddd", "444");
            ProjectItemInstance i5 = new ProjectItemInstance(project, "Resource", "dialogs%253b.resx", project.FullPath);
            resourceItemGroup.Add(i5);
            i5.SetMetadata("eee", "555");

            List<ProjectItemInstance> contentItemGroup2 = new List<ProjectItemInstance>();
            ProjectItemInstance i6 = new ProjectItemInstance(project, "Content", "about.bmp", project.FullPath);
            contentItemGroup2.Add(i6);
            i6.SetMetadata("fff", "666");

            ItemDictionary<ProjectItemInstance> secondaryItemsByName = new ItemDictionary<ProjectItemInstance>();
            secondaryItemsByName.ImportItems(resourceItemGroup);
            secondaryItemsByName.ImportItems(contentItemGroup2);

            Lookup lookup = new Lookup(secondaryItemsByName, pg, null);

            // Add primary items
            lookup.EnterScope("x");
            lookup.PopulateWithItems("IntermediateAssembly", intermediateAssemblyItemGroup);
            lookup.PopulateWithItems("Content", contentItemGroup);

            readOnlyLookup = new ReadOnlyLookup(lookup);
        }
示例#58
0
        public void StringExpansionTests()
        {
            Parser p = new Parser();

            ProjectInstance parentProject = new ProjectInstance(ProjectRootElement.Create());
            ItemDictionary <ProjectItemInstance> itemBag = new ItemDictionary <ProjectItemInstance>();

            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "foo.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "bar.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "baz.cs", parentProject.FullPath));

            PropertyDictionary <ProjectPropertyInstance> propertyBag = new PropertyDictionary <ProjectPropertyInstance>();

            propertyBag.Set(ProjectPropertyInstance.Create("foo", "true"));
            propertyBag.Set(ProjectPropertyInstance.Create("bar", "yes"));
            propertyBag.Set(ProjectPropertyInstance.Create("one", "1"));
            propertyBag.Set(ProjectPropertyInstance.Create("onepointzero", "1.0"));
            propertyBag.Set(ProjectPropertyInstance.Create("two", "2"));
            propertyBag.Set(ProjectPropertyInstance.Create("simple", "simplestring"));
            propertyBag.Set(ProjectPropertyInstance.Create("complex", "This is a complex string"));
            propertyBag.Set(ProjectPropertyInstance.Create("c1", "Another (complex) one."));
            propertyBag.Set(ProjectPropertyInstance.Create("c2", "Another (complex) one."));
            propertyBag.Set(ProjectPropertyInstance.Create("TestQuote", "Contains'Quote'"));
            propertyBag.Set(ProjectPropertyInstance.Create("AnotherTestQuote", "Here's Johnny!"));
            propertyBag.Set(ProjectPropertyInstance.Create("Atsign", "Test the @ replacement"));

            Expander <ProjectPropertyInstance, ProjectItemInstance> expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(propertyBag, itemBag, FileSystems.Default);

            AssertParseEvaluate(p, "'simplestring: true foo.cs;bar.cs;baz.cs' == '$(simple): $(foo) @(compile)'", expander, true);
            AssertParseEvaluate(p, "'$(c1) $(c2)' == 'Another (complex) one. Another (complex) one.'", expander, true);
            AssertParseEvaluate(p, "'CONTAINS%27QUOTE%27' == '$(TestQuote)'", expander, true);
            AssertParseEvaluate(p, "'Here%27s Johnny!' == '$(AnotherTestQuote)'", expander, true);
            AssertParseEvaluate(p, "'Test the %40 replacement' == $(Atsign)", expander, true);
        }
示例#59
0
        public void ValidateToolsetTranslation()
        {
            PropertyDictionary <ProjectPropertyInstance> buildProperties = new PropertyDictionary <ProjectPropertyInstance>();

            buildProperties.Set(ProjectPropertyInstance.Create("a", "a1"));

            PropertyDictionary <ProjectPropertyInstance> environmentProperties = new PropertyDictionary <ProjectPropertyInstance>();

            environmentProperties.Set(ProjectPropertyInstance.Create("b", "b1"));

            PropertyDictionary <ProjectPropertyInstance> globalProperties = new PropertyDictionary <ProjectPropertyInstance>();

            globalProperties.Set(ProjectPropertyInstance.Create("c", "c1"));

            PropertyDictionary <ProjectPropertyInstance> subToolsetProperties = new PropertyDictionary <ProjectPropertyInstance>();

            subToolsetProperties.Set(ProjectPropertyInstance.Create("d", "d1"));

            Dictionary <string, SubToolset> subToolsets = new Dictionary <string, SubToolset>(StringComparer.OrdinalIgnoreCase);

            subToolsets.Add("dogfood", new SubToolset("dogfood", subToolsetProperties));

            Toolset t = new Toolset("4.0", "c:\\bar", buildProperties, environmentProperties, globalProperties,
                                    subToolsets, "c:\\foo", "4.0", new Dictionary <string, List <string> >
            {
                ["MSBuildExtensionsPath"] = new List <string> {
                    @"c:\foo"
                }
            });

            ((INodePacketTranslatable)t).Translate(TranslationHelpers.GetWriteTranslator());
            Toolset t2 = Toolset.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());

            Assert.Equal(t.ToolsVersion, t2.ToolsVersion);
            Assert.Equal(t.ToolsPath, t2.ToolsPath);
            Assert.Equal(t.OverrideTasksPath, t2.OverrideTasksPath);
            Assert.Equal(t.Properties.Count, t2.Properties.Count);

            foreach (string key in t.Properties.Keys)
            {
                Assert.Equal(t.Properties[key].Name, t2.Properties[key].Name);
                Assert.Equal(t.Properties[key].EvaluatedValue, t2.Properties[key].EvaluatedValue);
            }

            Assert.Equal(t.SubToolsets.Count, t2.SubToolsets.Count);

            foreach (string key in t.SubToolsets.Keys)
            {
                SubToolset subToolset1 = t.SubToolsets[key];
                SubToolset subToolset2 = null;

                if (t2.SubToolsets.TryGetValue(key, out subToolset2))
                {
                    Assert.Equal(subToolset1.SubToolsetVersion, subToolset2.SubToolsetVersion);
                    Assert.Equal(subToolset1.Properties.Count, subToolset2.Properties.Count);

                    foreach (string subToolsetPropertyKey in subToolset1.Properties.Keys)
                    {
                        Assert.Equal(subToolset1.Properties[subToolsetPropertyKey].Name, subToolset2.Properties[subToolsetPropertyKey].Name);
                        Assert.Equal(subToolset1.Properties[subToolsetPropertyKey].EvaluatedValue, subToolset2.Properties[subToolsetPropertyKey].EvaluatedValue);
                    }
                }
                else
                {
                    Assert.True(false, $"Sub-toolset {key} was lost in translation.");
                }
            }

            Assert.Equal(t.DefaultOverrideToolsVersion, t2.DefaultOverrideToolsVersion);

            Assert.NotNull(t2.ImportPropertySearchPathsTable);
            Assert.Equal(1, t2.ImportPropertySearchPathsTable.Count);
            Assert.Equal(@"c:\foo", t2.ImportPropertySearchPathsTable["MSBuildExtensionsPath"][0]);
        }
示例#60
0
        public void ExpandPropertiesIntoProjectPropertyInstances()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("a", "aaa"));
            pg.Set(ProjectPropertyInstance.Create("b", "bbb"));
            pg.Set(ProjectPropertyInstance.Create("c", "cc;dd"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i");
            IList<ProjectItemInstance> itemsOut = expander.ExpandIntoItemsLeaveEscaped("foo$(a);$(b);$(c);$(d", itemFactory, ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(5, itemsOut.Count);
        }