/// <summary>
 /// Constructor taking a delegate for unit test purposes only
 /// </summary>
 internal ToolsetConfigurationReader(PropertyDictionary<ProjectPropertyInstance> environmentProperties, PropertyDictionary<ProjectPropertyInstance> globalProperties, Func<Configuration> readApplicationConfiguration)
     : base(environmentProperties, globalProperties)
 {
     ErrorUtilities.VerifyThrowArgumentNull(readApplicationConfiguration, "readApplicationConfiguration");
     _readApplicationConfiguration = readApplicationConfiguration;
     _projectImportSearchPathsCache = new Dictionary<string, Dictionary<string, List<string>>>(StringComparer.OrdinalIgnoreCase);
 }
        /// <summary>
        /// Translates a PropertyDictionary of ProjectPropertyInstances.
        /// </summary>
        /// <param name="translator">The tranlator doing the translating</param>
        /// <param name="value">The dictionary to translate.</param>
        public static void TranslateProjectPropertyInstanceDictionary(this INodePacketTranslator translator, ref PropertyDictionary<ProjectPropertyInstance> value)
        {
            if (!translator.TranslateNullable(value))
            {
                return;
            }

            if (translator.Mode == TranslationDirection.ReadFromStream)
            {
                int count = 0;
                translator.Translate(ref count);

                value = new PropertyDictionary<ProjectPropertyInstance>(count);
                for (int i = 0; i < count; i++)
                {
                    ProjectPropertyInstance instance = null;
                    translator.Translate(ref instance, ProjectPropertyInstance.FactoryForDeserialization);
                    value[instance.Name] = instance;
                }
            }
            else // TranslationDirection.WriteToStream
            {
                int count = value.Count;
                translator.Translate(ref count);

                foreach (ProjectPropertyInstance instance in value)
                {
                    ProjectPropertyInstance instanceForSerialization = instance;
                    translator.Translate(ref instanceForSerialization, ProjectPropertyInstance.FactoryForDeserialization);
                }
            }
        }
示例#3
0
        public void ExpandAllIntoTaskItems3()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

            List<ProjectItemInstance> ig = new List<ProjectItemInstance>();
            ig.Add(new ProjectItemInstance(project, "Compile", "foo.cs", project.FullPath));
            ig.Add(new ProjectItemInstance(project, "Compile", "bar.cs", project.FullPath));

            List<ProjectItemInstance> ig2 = new List<ProjectItemInstance>();
            ig2.Add(new ProjectItemInstance(project, "Resource", "bing.resx", project.FullPath));

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

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

            IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo;bar;@(compile);@(resource)", ExpanderOptions.ExpandPropertiesAndItems, MockElementLocation.Instance);

            ObjectModelHelpers.AssertItemsMatch(@"
                foo
                bar
                foo.cs
                bar.cs
                bing.resx
                ", GetTaskArrayFromItemList(itemsOut));
        }
示例#4
0
		internal ExpressionOptions(ExpressionContext owner)
		{
			MyOwner = owner;
			MyProperties = new PropertyDictionary();

			this.InitializeProperties();
		}
示例#5
0
        /// <summary>
        /// Constructor that associates a set of properties with a sub-toolset version.  
        /// </summary>
        internal SubToolset(string subToolsetVersion, PropertyDictionary<ProjectPropertyInstance> properties)
        {
            ErrorUtilities.VerifyThrowArgumentLength(subToolsetVersion, "subToolsetVersion");

            _subToolsetVersion = subToolsetVersion;
            _properties = properties;
        }
示例#6
0
        /// <summary>
        /// Constructor overload accepting a registry wrapper for unit testing purposes only
        /// </summary>
        internal ToolsetRegistryReader(PropertyDictionary<ProjectPropertyInstance> environmentProperties, PropertyDictionary<ProjectPropertyInstance> globalProperties, RegistryKeyWrapper msbuildRegistryWrapper)
            : base(environmentProperties, globalProperties)
        {
            error.VerifyThrowArgumentNull(msbuildRegistryWrapper, "msbuildRegistryWrapper");

            _msbuildRegistryWrapper = msbuildRegistryWrapper;
        }
示例#7
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);
        }
		internal ExpressionParserOptions(ExpressionContext owner)
		{
			MyOwner = owner;
			MyProperties = new PropertyDictionary();
			MyParseCulture = CultureInfo.InvariantCulture;

			this.InitializeProperties();
		}
示例#9
0
        public void ExpandAllIntoTaskItems1()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

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

            ObjectModelHelpers.AssertItemsMatch(@"foo", GetTaskArrayFromItemList(itemsOut));
        }
示例#10
0
    public PropertyDefinition(String systemName, String humanName, Type type, PropertyDictionary owner)
    {
      SystemName = systemName;
      HumanName = humanName;
      ValueType = type;
      Owner = owner;

      Rules = new List<Rule>();

    }
示例#11
0
        public ElementNode(ElementNode parent, int openAngleBracketPosition, NameToken nameToken, int maxEnd) {
            Parent = parent;

            if (nameToken.HasColon)
                StartTag = new TagNodeWithPrefix(this, openAngleBracketPosition, nameToken, maxEnd);
            else
                StartTag = new TagNode(this, openAngleBracketPosition, nameToken, maxEnd);

            VirtualEnd = maxEnd;
            Properties = new PropertyDictionary();
        }
示例#12
0
        public void PropertyGroupEmpty()
        {
            string content = ObjectModelHelpers.CleanupFileContents(@"
            <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
            <Target Name='t' >
                <PropertyGroup/>
            </Target>
            </Project>");
            IntrinsicTask task = CreateIntrinsicTask(content);
            PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>();
            ExecuteTask(task, LookupHelpers.CreateLookup(properties));

            Assert.AreEqual(0, properties.Count);
        }
 /// <summary>
 /// Set a boolean switch only if its value exists.
 /// </summary>
 internal void AppendPlusOrMinusSwitch
     (
     string switchName,
     PropertyDictionary bag,
     string parameterName
     )
 {
     object obj = bag[parameterName];
     // If the switch isn't set, don't add it to the command line.
     if (obj != null)
     {
         bool value = (bool)obj;
         // Do not quote - or + as they are part of the switch
         AppendSwitchUnquotedIfNotNull(switchName, (value ? "+" : "-"));
     }
 }
示例#14
0
        public void PropertyGroupWithComments()
        {
            string content = ObjectModelHelpers.CleanupFileContents(@"
            <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
            <Target Name='t' >
                <PropertyGroup><!-- c -->
                    <p1>v1</p1><!-- c -->
                </PropertyGroup>
            </Target>
            </Project>");
            IntrinsicTask task = CreateIntrinsicTask(content);
            PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>();
            ExecuteTask(task, LookupHelpers.CreateLookup(properties));

            Assert.AreEqual(1, properties.Count);
            Assert.AreEqual("v1", properties["p1"].EvaluatedValue);
        }
 /// <summary>
 /// Set a switch if its value exists by choosing from the input choices
 /// </summary>
 internal void AppendByChoiceSwitch
     (
     string switchName,
     PropertyDictionary bag,
     string parameterName,
     string choice1,
     string choice2
     )
 {
     object obj = bag[parameterName];
     // If the switch isn't set, don't add it to the command line.
     if (obj != null)
     {
         bool value = (bool)obj;
         AppendSwitchUnquotedIfNotNull(switchName, (value ? choice1 : choice2));
     }
 }
        /// <summary>
        /// Set a boolean switch iff its value exists and its value is 'true'.
        /// </summary>
        internal void AppendWhenTrue
            (
            string switchName,
            PropertyDictionary bag,
            string parameterName
            )
        {
            object obj = bag[parameterName];
            // If the switch isn't set, don't add it to the command line.
            if (obj != null)
            {
                bool value = (bool)obj;

                if (value)
                {
                    AppendSwitch(switchName);
                }
            }
        }
        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();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MachineSpecificationsFunctions"/> class.
 /// </summary>
 /// <param name="project">The project.</param>
 /// <param name="properties">The properties.</param>
 public MachineSpecificationsFunctions(Project project, PropertyDictionary properties) : base(project, properties)
 {
 }
示例#19
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public BaseVM() : base()
 {
     _vmInstance        = this;
     PropertyChanged   += OnPropertyChanged;
     _changedProperties = _propertyDictionaries.Dequeue();
 }
示例#20
0
 /// <summary>
 /// Constructor which will load toolsets from the specified locations.
 /// </summary>
 public ToolsetProvider(string defaultToolsVersion, PropertyDictionary <ProjectPropertyInstance> environmentProperties, PropertyDictionary <ProjectPropertyInstance> globalProperties, ToolsetDefinitionLocations toolsetDefinitionLocations)
 {
     InitializeToolsetCollection(environmentProperties, globalProperties, toolsetDefinitionLocations);
 }
示例#21
0
        /// <summary>
        /// Helper method to create the request definition and setting the request definition will have an actual project instance or not
        /// </summary>
        private RequestDefinition InternalCreateNewRequest(string projectFile, string toolsversion, string[] targetsToBuild, PropertyDictionary <ProjectPropertyInstance> globalProperties)
        {
            // Make sure that the path is rooted. This is particularly important when testing implementation of RequestBuilder. The RequestBuild adds default path if the project file path
            // is not rooted. This will cause us to not be able to locate the approprate RequestDefinition as the file name is also used as a comparing mechinasim
            projectFile = System.IO.Path.Combine(_tempPath, projectFile);
            RequestDefinition p1 = new RequestDefinition(projectFile, toolsversion, targetsToBuild, globalProperties, 0, null, (IBuildComponentHost)_host);

            // If a project object is to be created then we will need to add all targets that we will be building to the project XML
            if (_createMSBuildProject)
            {
                p1.CreateMSBuildProject = true;
                ProjectDefinition p = p1.ProjectDefinition;
                foreach (string target in targetsToBuild)
                {
                    TargetDefinition t = new TargetDefinition(target, p.ProjectXmlDocument);
                    p1.ProjectDefinition.AddTarget(t);
                }
            }

            return(p1);
        }
示例#22
0
 /// <summary>
 /// Default constructor
 /// </summary>
 internal ToolsetConfigurationReader(PropertyDictionary <ProjectPropertyInstance> environmentProperties, PropertyDictionary <ProjectPropertyInstance> globalProperties)
     : this(environmentProperties, globalProperties, ReadApplicationConfiguration)
 {
 }
示例#23
0
 /// <exclude/>
 public MSBuildFunctions(Project project, PropertyDictionary properties) : base(project, properties)
 {
 }
示例#24
0
        public void PropertyFunctionStaticMethodFileAttributes()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

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

            string tempFile = FileUtilities.GetTemporaryFile();
            try
            {
                File.SetAttributes(tempFile, FileAttributes.ReadOnly | FileAttributes.Archive);

                string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseAnd(32,$([System.IO.File]::GetAttributes(" + tempFile + "))))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                Assert.Equal("32", result);
            }
            finally
            {
                File.SetAttributes(tempFile, FileAttributes.Normal);
                File.Delete(tempFile);
            }
        }
示例#25
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);
        }
示例#26
0
        /// <summary>
        /// Gets the effective global properties for a project reference.
        /// </summary>
        /// <remarks>
        /// The behavior of this method should match the logic in Microsoft.Common.CurrentVersion.targets and the MSBuild task.
        /// </remarks>
        private static PropertyDictionary <ProjectPropertyInstance> GetProjectReferenceGlobalProperties(ProjectItemInstance projectReference, PropertyDictionary <ProjectPropertyInstance> requesterGlobalProperties)
        {
            string propertiesString               = projectReference.GetMetadataValue(PropertiesMetadataName);
            string additionalPropertiesString     = projectReference.GetMetadataValue(AdditionalPropertiesMetadataName);
            string undefinePropertiesString       = projectReference.GetMetadataValue(UndefinePropertiesMetadataName);
            string globalPropertiesToRemoveString = projectReference.GetMetadataValue(GlobalPropertiesToRemoveMetadataName);

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

                if (!string.IsNullOrEmpty(setConfigurationString) || !string.IsNullOrEmpty(setPlatformString) || !string.IsNullOrEmpty(setTargetFrameworkString))
                {
                    propertiesString = $"{setConfigurationString};{setPlatformString};{setTargetFrameworkString}";
                }
            }

            // If none of these are set, we can just reuse the requestor's global properties directly.
            if (string.IsNullOrEmpty(propertiesString) &&
                string.IsNullOrEmpty(additionalPropertiesString) &&
                string.IsNullOrEmpty(undefinePropertiesString) &&
                string.IsNullOrEmpty(globalPropertiesToRemoveString))
            {
                return(requesterGlobalProperties);
            }

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

            // Append and remove properties as specified by the various metadata
            MergeIntoPropertyDictionary(globalProperties, propertiesString, PropertiesMetadataName);
            MergeIntoPropertyDictionary(globalProperties, additionalPropertiesString, AdditionalPropertiesMetadataName);
            RemoveFromPropertyDictionary(globalProperties, globalPropertiesToRemoveString);
            RemoveFromPropertyDictionary(globalProperties, undefinePropertiesString);

            return(globalProperties);
        }
示例#27
0
        /// <summary>
        /// Async version of BuildProjectFilesInParallel.
        /// </summary>
        /// <param name="projectFileNames">The list of projects to build</param>
        /// <param name="targetNames">The set of targets to build</param>
        /// <param name="globalProperties">The global properties to use for each project</param>
        /// <param name="undefineProperties">The list of global properties to undefine</param>
        /// <param name="toolsVersion">The tools versions to use</param>
        /// <param name="returnTargetOutputs">Should the target outputs be returned in the BuildEngineResult</param>
        /// <param name="skipNonexistentTargets">If set, skip targets that are not defined in the projects to be built.</param>
        /// <returns>A Task returning a structure containing the result of the build, success or failure and the list of target outputs per project</returns>
        private async Task <BuildEngineResult> BuildProjectFilesInParallelAsync(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList <String>[] undefineProperties, string[] toolsVersion, bool returnTargetOutputs, bool skipNonexistentTargets = false)
        {
            ErrorUtilities.VerifyThrowArgumentNull(projectFileNames, nameof(projectFileNames));
            ErrorUtilities.VerifyThrowArgumentNull(globalProperties, nameof(globalProperties));
            VerifyActiveProxy();

            List <IDictionary <string, ITaskItem[]> > targetOutputsPerProject = null;

#if FEATURE_FILE_TRACKER
            using (FullTracking.Suspend())
#endif
            {
                bool overallSuccess = true;

                if (projectFileNames.Length == 1 && projectFileNames[0] == null && globalProperties[0] == null && (undefineProperties == null || undefineProperties[0] == null) && toolsVersion[0] == null)
                {
                    // This is really a legacy CallTarget invocation
                    ITargetResult[] results = await _targetBuilderCallback.LegacyCallTarget(targetNames, ContinueOnError, _taskLocation);

                    if (returnTargetOutputs)
                    {
                        targetOutputsPerProject = new List <IDictionary <string, ITaskItem[]> >(1)
                        {
                            new Dictionary <string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase)
                        };
                    }

                    for (int i = 0; i < targetNames.Length; i++)
                    {
                        targetOutputsPerProject[0][targetNames[i]] = results[i].Items;
                        if (results[i].ResultCode == TargetResultCode.Failure)
                        {
                            overallSuccess = false;
                        }
                    }
                }
                else
                {
                    // UNDONE: (Refactor) Investigate making this a ReadOnly collection of some sort.
                    PropertyDictionary <ProjectPropertyInstance>[] propertyDictionaries = new PropertyDictionary <ProjectPropertyInstance> [projectFileNames.Length];

                    for (int i = 0; i < projectFileNames.Length; i++)
                    {
                        // Copy in the original project's global properties
                        propertyDictionaries[i] = new PropertyDictionary <ProjectPropertyInstance>(_requestEntry.RequestConfiguration.Project.GlobalPropertiesDictionary);

                        // Now add/replace any which may have been specified.
                        if (globalProperties[i] != null)
                        {
                            foreach (DictionaryEntry entry in globalProperties[i])
                            {
                                propertyDictionaries[i].Set(ProjectPropertyInstance.Create(entry.Key as string, entry.Value as string, _taskLocation));
                            }
                        }

                        // Finally, remove any which were requested to be removed.
                        if (undefineProperties?[i] != null)
                        {
                            foreach (string property in undefineProperties[i])
                            {
                                propertyDictionaries[i].Remove(property);
                            }
                        }
                    }

                    IRequestBuilderCallback builderCallback = _requestEntry.Builder as IRequestBuilderCallback;
                    BuildResult[]           results         = await builderCallback.BuildProjects(
                        projectFileNames,
                        propertyDictionaries,
                        toolsVersion ?? Array.Empty <string>(),
                        targetNames ?? Array.Empty <string>(),
                        waitForResults : true,
                        skipNonexistentTargets : skipNonexistentTargets);

                    // Even if one of the projects fails to build and therefore has no outputs, it should still have an entry in the results array (albeit with an empty list in it)
                    ErrorUtilities.VerifyThrow(results.Length == projectFileNames.Length, "{0}!={1}.", results.Length, projectFileNames.Length);

                    if (returnTargetOutputs)
                    {
                        targetOutputsPerProject = new List <IDictionary <string, ITaskItem[]> >(results.Length);
                    }

                    // Now walk through the results, and report that subset which was asked for.
                    for (int i = 0; i < results.Length; i++)
                    {
                        targetOutputsPerProject?.Add(new Dictionary <string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase));

                        foreach (KeyValuePair <string, TargetResult> resultEntry in results[i].ResultsByTarget)
                        {
                            if (targetOutputsPerProject != null)
                            {
                                // We need to clone the task items because if we did not then we would be passing live references
                                // out to the caller of the msbuild callback and any modifications they make to those items
                                // would appear in the results cache.
                                ITaskItem[] clonedTaskItem = new ITaskItem[resultEntry.Value.Items.Length];
                                for (int j = 0; j < resultEntry.Value.Items.Length; j++)
                                {
                                    clonedTaskItem[j] = ((TaskItem)resultEntry.Value.Items[j]).DeepClone();
                                }

                                targetOutputsPerProject[i][resultEntry.Key] = clonedTaskItem;
                            }
                        }

                        if (results[i].OverallResult == BuildResultCode.Failure)
                        {
                            overallSuccess = false;
                        }

                        if (!string.IsNullOrEmpty(results[i].SchedulerInducedError))
                        {
                            LoggingContext.LogErrorFromText(
                                subcategoryResourceName: null,
                                errorCode: null,
                                helpKeyword: null,
                                file: new BuildEventFileInfo(ProjectFileOfTaskNode, LineNumberOfTaskNode, ColumnNumberOfTaskNode),
                                message: results[i].SchedulerInducedError);
                        }
                    }

                    ErrorUtilities.VerifyThrow(results.Length == projectFileNames.Length || !overallSuccess, "The number of results returned {0} cannot be less than the number of project files {1} unless one of the results indicated failure.", results.Length, projectFileNames.Length);
                }

                BuildRequestsSucceeded = overallSuccess;

                return(new BuildEngineResult(overallSuccess, targetOutputsPerProject));
            }
        }
示例#28
0
        /// <remarks>
        /// Traverse an evaluated graph
        /// Maintain the state of each node (InProcess and Processed) to detect cycles
        /// returns false if loading the graph is not successful
        /// </remarks>
        private (bool success, List <string> projectsInCycle) DetectCycles(ProjectGraphNode node,
                                                                           Dictionary <ProjectGraphNode, NodeState> nodeState,
                                                                           ProjectCollection projectCollection,
                                                                           PropertyDictionary <ProjectPropertyInstance> globalProperties)
        {
            nodeState[node] = NodeState.InProcess;
            IEnumerable <ProjectItemInstance> projectReferenceItems = node.ProjectInstance.GetItems(ProjectReferenceItemName);

            foreach (var projectReferenceToParse in projectReferenceItems)
            {
                string projectReferenceFullPath = projectReferenceToParse.GetMetadataValue(FullPathMetadataName);
                PropertyDictionary <ProjectPropertyInstance> projectReferenceGlobalProperties = GetProjectReferenceGlobalProperties(projectReferenceToParse, globalProperties);
                var projectReferenceConfigurationMetadata = new ConfigurationMetadata(projectReferenceFullPath, projectReferenceGlobalProperties);
                ProjectGraphNode projectReference         = _allParsedProjects[projectReferenceConfigurationMetadata];
                if (nodeState.TryGetValue(projectReference, out NodeState projectReferenceNodeState))
                {
                    // Because this is a depth-first search, we should only encounter new nodes or nodes whose subgraph has been completely processed.
                    // If we encounter a node that is currently being processed(InProcess state), it must be one of the ancestors in a circular dependency.
                    if (projectReferenceNodeState == NodeState.InProcess)
                    {
                        if (node.Equals(projectReference))
                        {
                            // the project being evaluated has a reference to itself
                            var selfReferencingProjectString = FormatCircularDependencyError(new List <string> {
                                node.ProjectInstance.FullPath, node.ProjectInstance.FullPath
                            });
                            throw new CircularDependencyException(string.Format(
                                                                      ResourceUtilities.GetResourceString("CircularDependencyInProjectGraph"),
                                                                      selfReferencingProjectString));
                        }
                        else
                        {
                            // the project being evaluated has a circular dependency involving multiple projects
                            // add this project to the list of projects involved in cycle
                            var projectsInCycle = new List <string> {
                                projectReferenceConfigurationMetadata.ProjectFullPath
                            };
                            return(false, projectsInCycle);
                        }
                    }
                }
                else
                {
                    // recursively process newly discovered references
                    var loadReference = DetectCycles(projectReference, nodeState, projectCollection,
                                                     projectReferenceGlobalProperties);
                    if (!loadReference.success)
                    {
                        if (loadReference.projectsInCycle[0].Equals(node.ProjectInstance.FullPath))
                        {
                            // we have reached the nth project in the cycle, form error message and throw
                            loadReference.projectsInCycle.Add(projectReferenceConfigurationMetadata.ProjectFullPath);
                            loadReference.projectsInCycle.Add(node.ProjectInstance.FullPath);
                            var errorMessage = FormatCircularDependencyError(loadReference.projectsInCycle);
                            throw new CircularDependencyException(string.Format(
                                                                      ResourceUtilities.GetResourceString("CircularDependencyInProjectGraph"),
                                                                      errorMessage));
                        }
                        else
                        {
                            // this is one of the projects in the circular dependency
                            // update the list of projects in cycle and return the list to the caller
                            loadReference.projectsInCycle.Add(projectReferenceConfigurationMetadata.ProjectFullPath);
                            return(false, loadReference.projectsInCycle);
                        }
                    }
                }
                ProjectGraphNode parsedProjectReference = _allParsedProjects[projectReferenceConfigurationMetadata];
                node.AddProjectReference(parsedProjectReference);
                parsedProjectReference.AddReferencingProject(node);
            }
            nodeState[node] = NodeState.Processed;
            return(true, null);
        }
示例#29
0
        /// <summary>
        /// Load a graph with root node at entryProjectFile
        /// Maintain a queue of projects to be processed and evaluate projects in parallel
        /// Returns false if loading the graph is not successful
        /// </summary>
        private bool LoadGraph(
            ConcurrentQueue <ConfigurationMetadata> projectsToEvaluate,
            ProjectCollection projectCollection,
            ConcurrentDictionary <ConfigurationMetadata, object> tasksInProgress,
            ProjectInstanceFactoryFunc projectInstanceFactory,
            out List <Exception> exceptions)
        {
            var exceptionsInTasks    = new ConcurrentBag <Exception>();
            var evaluationWaitHandle = new AutoResetEvent(false);

            while (projectsToEvaluate.Count != 0 || tasksInProgress.Count != 0)
            {
                ConfigurationMetadata projectToEvaluate;
                if (projectsToEvaluate.Count != 0)
                {
                    projectToEvaluate = projectsToEvaluate.Dequeue();
                    var task = new Task(() =>
                    {
                        ProjectGraphNode parsedProject = CreateNewNode(projectToEvaluate, projectCollection, projectInstanceFactory);
                        IEnumerable <ProjectItemInstance> projectReferenceItems = parsedProject.ProjectInstance.GetItems(ProjectReferenceItemName);
                        foreach (var projectReferenceToParse in projectReferenceItems)
                        {
                            if (!string.IsNullOrEmpty(projectReferenceToParse.GetMetadataValue(ToolsVersionMetadataName)))
                            {
                                throw new InvalidOperationException(string.Format(
                                                                        CultureInfo.InvariantCulture,
                                                                        ResourceUtilities.GetResourceString(
                                                                            "ProjectGraphDoesNotSupportProjectReferenceWithToolset"),
                                                                        projectReferenceToParse.EvaluatedInclude,
                                                                        parsedProject.ProjectInstance.FullPath));
                            }

                            string projectReferenceFullPath = projectReferenceToParse.GetMetadataValue(FullPathMetadataName);
                            PropertyDictionary <ProjectPropertyInstance> projectReferenceGlobalProperties = GetProjectReferenceGlobalProperties(projectReferenceToParse, projectToEvaluate.GlobalProperties);
                            var projectReferenceConfigurationMetadata = new ConfigurationMetadata(projectReferenceFullPath, projectReferenceGlobalProperties);
                            if (!tasksInProgress.ContainsKey(projectReferenceConfigurationMetadata))
                            {
                                if (!_allParsedProjects.ContainsKey(projectReferenceConfigurationMetadata))
                                {
                                    projectsToEvaluate.Enqueue(projectReferenceConfigurationMetadata);
                                    evaluationWaitHandle.Set();
                                }
                            }
                        }
                    });

                    if (tasksInProgress.TryAdd(projectToEvaluate, null))
                    {
                        // once the task completes, remove it from tasksInProgress using a chained task
                        // signal the wait handle to process new projects that have been discovered by this task or exit if all projects have been evaluated
                        task.ContinueWith(_ =>
                        {
                            if (task.IsFaulted)
                            {
                                exceptionsInTasks.Add(task.Exception.InnerException);
                            }
                            tasksInProgress.TryRemove(projectToEvaluate, out var _);
                            evaluationWaitHandle.Set();
                        });
                        task.Start();
                    }
                }
                else
                {
                    // if projectsToEvaluate is empty but there are tasks in progress, there is nothing to do till a task completes and discovers new projects
                    // wait till a task completes and sends a signal
                    evaluationWaitHandle.WaitOne();
                }
            }

            if (exceptionsInTasks.Count != 0)
            {
                exceptions = exceptionsInTasks.ToList();
                return(false);
            }

            exceptions = null;
            return(true);
        }
示例#30
0
        private static void SetUpProperties(ArrayList attributeList, Task task, XmlNode xml, PropertyDictionary oldPropertyValues)
        {
            var projectProperties = task.Project.Properties;
            var logMessage        = new StringBuilder();

            foreach (MacroAttribute macroAttribute in attributeList)
            {
                var    attributeName = macroAttribute.AttributeName;
                var    xmlAttribute  = xml.Attributes[attributeName];
                string value         = null;

                if (xmlAttribute != null)
                {
                    value = projectProperties.ExpandProperties(xmlAttribute.Value, null);
                }
                else if (macroAttribute.DefaultValue != null)
                {
                    value = macroAttribute.DefaultValue;
                }

                var localPropertyName = macroAttribute.LocalPropertyName;

                task.Log(Level.Debug, "Setting property {0} to {1}", localPropertyName, value);

                if (logMessage.Length > 0)
                {
                    logMessage.Append(", ");
                }

                logMessage.AppendFormat("{0} = '{1}'", localPropertyName, value);

                if (projectProperties.Contains(localPropertyName))
                {
                    oldPropertyValues.Add(localPropertyName, projectProperties[localPropertyName]);
                    projectProperties.Remove(localPropertyName);
                }

                if (value != null)
                {
                    projectProperties.Add(localPropertyName, value);
                }
            }

            task.Log(Level.Info, logMessage.ToString());
        }
示例#31
0
 public FilterChainConfigurator(Element element, XmlNode elementNode, PropertyDictionary properties, FrameworkInfo targetFramework)
     : base(element, elementNode, properties, targetFramework)
 {
 }
示例#32
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);
        }
示例#33
0
 internal ToolsetLocalReader(PropertyDictionary <ProjectPropertyInstance> environmentProperties, PropertyDictionary <ProjectPropertyInstance> globalProperties)
     : base(environmentProperties, globalProperties)
 {
 }
示例#34
0
 public EnvironmentFunctions(Project project, Location location, PropertyDictionary properties)
     : base(project, location, properties)
 {
 }
示例#35
0
 public EnvVarFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
示例#36
0
 public StringFunctions(Project project, PropertyDictionary propDict) : base(project, propDict)
 {
 }
示例#37
0
 /// <summary>
 /// Constructor taking a delegate for unit test purposes only
 /// </summary>
 internal ToolsetConfigurationReader(PropertyDictionary <ProjectPropertyInstance> environmentProperties, PropertyDictionary <ProjectPropertyInstance> globalProperties, Func <Configuration> readApplicationConfiguration)
     : base(environmentProperties, globalProperties)
 {
     ErrorUtilities.VerifyThrowArgumentNull(readApplicationConfiguration, nameof(readApplicationConfiguration));
     _readApplicationConfiguration  = readApplicationConfiguration;
     _projectImportSearchPathsCache = new Dictionary <string, Dictionary <string, ProjectImportPathMatch> >(StringComparer.OrdinalIgnoreCase);
 }
 /// <summary>
 /// Default constructor
 /// </summary>
 internal ToolsetConfigurationReader(PropertyDictionary<ProjectPropertyInstance> environmentProperties, PropertyDictionary<ProjectPropertyInstance> globalProperties)
     : this(environmentProperties, globalProperties, ReadApplicationConfiguration)
 {
 }
示例#39
0
 public Int32ConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties)
 {
 }
示例#40
0
        /// <summary>
        /// Helper method to create a new request definition given a filename, tools version, targets and global properties
        /// </summary>
        private RequestDefinition CreateNewRequest(string projectFile, string toolsversion, string[] targetsToBuild, PropertyDictionary <ProjectPropertyInstance> globalProperties)
        {
            if (targetsToBuild == null)
            {
                targetsToBuild = new string[1] {
                    RequestDefinition.defaultTargetName
                };
            }

            return(InternalCreateNewRequest(projectFile, toolsversion, targetsToBuild, globalProperties));
        }
示例#41
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);
        }
示例#42
0
        /// <summary>
        /// Populate Toolsets with a dictionary of (toolset version, Toolset)
        /// using information from the registry and config file, if any.
        /// </summary>
        private void InitializeToolsetCollection(PropertyDictionary <ProjectPropertyInstance> environmentProperties, PropertyDictionary <ProjectPropertyInstance> globalProperties, ToolsetDefinitionLocations toolsetDefinitionLocations)
        {
            _toolsets = new Dictionary <string, Toolset>(StringComparer.OrdinalIgnoreCase);

            ToolsetReader.ReadAllToolsets(_toolsets, environmentProperties, globalProperties, toolsetDefinitionLocations);
        }
示例#43
0
 private static Lookup CreateLookup(ItemDictionary <ProjectItemInstance> itemsByType, PropertyDictionary <ProjectPropertyInstance> properties)
 {
     return(new Lookup(itemsByType, properties, null));
 }
示例#44
0
        /// <summary>
        /// Reads the settings for a specified tools version
        /// </summary>
        private Toolset ReadToolset
        (
            ToolsetPropertyDefinition toolsVersion,
            PropertyDictionary <ProjectPropertyInstance> globalProperties,
            PropertyDictionary <ProjectPropertyInstance> initialProperties,
            bool accumulateProperties
        )
        {
            // Initial properties is the set of properties we're going to use to expand property expressions like $(foo)
            // in the values we read out of the registry or config file. We'll add to it as we pick up properties (including binpath)
            // from the registry or config file, so that properties there can be referenced in values below them.
            // After processing all the properties, we don't need initialProperties anymore.
            string toolsPath = null;
            string binPath   = null;
            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            IEnumerable <ToolsetPropertyDefinition> rawProperties = GetPropertyDefinitions(toolsVersion.Name);

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

            foreach (ToolsetPropertyDefinition property in rawProperties)
            {
                EvaluateAndSetProperty(property, properties, globalProperties, initialProperties, accumulateProperties, ref toolsPath, ref binPath, ref expander);
            }

            Dictionary <string, SubToolset> subToolsets        = new Dictionary <string, SubToolset>(StringComparer.OrdinalIgnoreCase);
            IEnumerable <string>            subToolsetVersions = GetSubToolsetVersions(toolsVersion.Name);

            foreach (string subToolsetVersion in subToolsetVersions)
            {
                string subToolsetToolsPath = null;
                string subToolsetBinPath   = null;
                IEnumerable <ToolsetPropertyDefinition>      rawSubToolsetProperties = GetSubToolsetPropertyDefinitions(toolsVersion.Name, subToolsetVersion);
                PropertyDictionary <ProjectPropertyInstance> subToolsetProperties    = new PropertyDictionary <ProjectPropertyInstance>();

                // If we have a sub-toolset, any values defined here will override the toolset properties.
                foreach (ToolsetPropertyDefinition property in rawSubToolsetProperties)
                {
                    EvaluateAndSetProperty(property, subToolsetProperties, globalProperties, initialProperties, false /* do not ever accumulate sub-toolset properties */, ref subToolsetToolsPath, ref subToolsetBinPath, ref expander);
                }

                if (subToolsetToolsPath != null || subToolsetBinPath != null)
                {
                    InvalidToolsetDefinitionException.Throw("MSBuildToolsPathNotSupportedInSubToolsets", toolsVersion.Name, toolsVersion.Source.LocationString, subToolsetVersion);
                }

                subToolsets[subToolsetVersion] = new SubToolset(subToolsetVersion, subToolsetProperties);
            }

            // All tools versions must specify a value for MSBuildToolsPath (or MSBuildBinPath)
            if (String.IsNullOrEmpty(toolsPath) && String.IsNullOrEmpty(binPath))
            {
                return(null);
            }

            // If both MSBuildBinPath and MSBuildToolsPath are present, they must be the same
            if (toolsPath != null && binPath != null && !toolsPath.Equals(binPath, StringComparison.OrdinalIgnoreCase))
            {
                InvalidToolsetDefinitionException.Throw("ConflictingValuesOfMSBuildToolsPath", toolsVersion.Name, toolsVersion.Source.LocationString);
            }

            AppendStandardProperties(properties, globalProperties, toolsVersion.Name, null, toolsPath);
            Toolset toolset = null;

            try
            {
                var importSearchPathsTable = GetProjectImportSearchPathsTable(toolsVersion.Name, NativeMethodsShared.GetOSNameForExtensionsPath());
                toolset = new Toolset(toolsVersion.Name, toolsPath ?? binPath, properties, _environmentProperties, globalProperties, subToolsets, MSBuildOverrideTasksPath, DefaultOverrideToolsVersion, importSearchPathsTable);
            }
            catch (ArgumentException e)
            {
                InvalidToolsetDefinitionException.Throw("ErrorCreatingToolset", toolsVersion.Name, e.Message);
            }

            return(toolset);
        }
示例#45
0
        public void PropertyFunctionStaticMethodIntrinsicMaths()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

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

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(39.9, 2.1))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((39.9 + 2.1).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(40, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((40 + 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Subtract(44, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((44 - 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Subtract(42.9, 0.9))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((42.9 - 0.9).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Multiply(21, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((21 * 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Multiply(84.0, 0.5))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((84.0 * 0.5).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Divide(84, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((84 / 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Divide(84.4, 2.0))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((84.4 / 2.0).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Modulo(85, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((85 % 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Modulo(2345.5, 43))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((2345.5 % 43).ToString(), result);

            // test for overflow wrapping
            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(9223372036854775807, 20))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            double expectedResult = 9223372036854775807D + 20D;
            Assert.Equal(expectedResult.ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseOr(40, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((40 | 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseAnd(42, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((42 & 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseXor(213, 255))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((213 ^ 255).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseNot(-43))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((~-43).ToString(), result);
        }
示例#46
0
        /// <summary>
        /// Appends standard properties to a dictionary. These properties are read from
        /// the registry under Windows (they are a part of a toolset definition).
        /// </summary>
        private static void AppendStandardProperties(
            PropertyDictionary <ProjectPropertyInstance> properties,
            PropertyDictionary <ProjectPropertyInstance> globalProperties,
            string version,
            string root,
            string toolsPath)
        {
            if (NativeMethodsShared.IsMono)
            {
                var v4Dir = FrameworkLocationHelper.GetPathToDotNetFrameworkV40(DotNetFrameworkArchitecture.Current)
                            + Path.DirectorySeparatorChar;
                var v35Dir = FrameworkLocationHelper.GetPathToDotNetFrameworkV35(DotNetFrameworkArchitecture.Current)
                             + Path.DirectorySeparatorChar;

                if (root == null)
                {
                    var libraryPath = NativeMethodsShared.FrameworkBasePath;
                    if (toolsPath.StartsWith(libraryPath))
                    {
                        root = Path.GetDirectoryName(toolsPath);
                        if (toolsPath.EndsWith("bin"))
                        {
                            root = Path.GetDirectoryName(root);
                        }
                    }
                    else
                    {
                        root = libraryPath;
                    }
                }

                root += Path.DirectorySeparatorChar;

                // Global properties cannot be overwritten
                if (globalProperties["FrameworkSDKRoot"] == null && properties["FrameworkSDKRoot"] == null)
                {
                    properties.Set(ProjectPropertyInstance.Create("FrameworkSDKRoot", root, true, false));
                }
                if (globalProperties["MSBuildToolsRoot"] == null && properties["MSBuildToolsRoot"] == null)
                {
                    properties.Set(ProjectPropertyInstance.Create("MSBuildToolsRoot", root, true, false));
                }
                if (globalProperties["MSBuildFrameworkToolsPath"] == null &&
                    properties["MSBuildFrameworkToolsPath"] == null)
                {
                    properties.Set(ProjectPropertyInstance.Create("MSBuildFrameworkToolsPath", toolsPath, true, false));
                }
                if (globalProperties["MSBuildFrameworkToolsPath32"] == null &&
                    properties["MSBuildFrameworkToolsPath32"] == null)
                {
                    properties.Set(
                        ProjectPropertyInstance.Create("MSBuildFrameworkToolsPath32", toolsPath, true, false));
                }
                if (globalProperties["MSBuildRuntimeVersion"] == null && properties["MSBuildRuntimeVersion"] == null)
                {
                    properties.Set(ProjectPropertyInstance.Create("MSBuildRuntimeVersion", version, true, false));
                }
                if (!string.IsNullOrEmpty(v35Dir) && globalProperties["SDK35ToolsPath"] == null &&
                    properties["SDK35ToolsPath"] == null)
                {
                    properties.Set(ProjectPropertyInstance.Create("SDK35ToolsPath", v35Dir, true, false));
                }
                if (!string.IsNullOrEmpty(v4Dir) && globalProperties["SDK40ToolsPath"] == null &&
                    properties["SDK40ToolsPath"] == null)
                {
                    properties.Set(ProjectPropertyInstance.Create("SDK40ToolsPath", v4Dir, true, false));
                }
            }
        }
示例#47
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>
示例#48
0
        /// <summary>
        /// Processes a particular ToolsetPropertyDefinition into the correct value and location in the initial and/or final property set.
        /// </summary>
        /// <param name="property">The ToolsetPropertyDefinition being analyzed.</param>
        /// <param name="properties">The final set of properties that we wish this toolset property to be added to. </param>
        /// <param name="globalProperties">The global properties, used for expansion and to make sure none are overridden.</param>
        /// <param name="initialProperties">The initial properties, used for expansion and added to if "accumulateProperties" is true.</param>
        /// <param name="accumulateProperties">If "true", we add this property to the initialProperties dictionary, as well, so that properties later in the toolset can use this value.</param>
        /// <param name="toolsPath">If this toolset property is the "MSBuildToolsPath" property, we will return the value in this parameter.</param>
        /// <param name="binPath">If this toolset property is the "MSBuildBinPath" property, we will return the value in this parameter.</param>
        /// <param name="expander">The expander used to expand the value of the properties.  Ref because if we are accumulating the properties, we need to re-create the expander to account for the new property value.</param>
        private void EvaluateAndSetProperty(ToolsetPropertyDefinition property, PropertyDictionary <ProjectPropertyInstance> properties, PropertyDictionary <ProjectPropertyInstance> globalProperties, PropertyDictionary <ProjectPropertyInstance> initialProperties, bool accumulateProperties, ref string toolsPath, ref string binPath, ref Expander <ProjectPropertyInstance, ProjectItemInstance> expander)
        {
            if (String.Equals(property.Name, ReservedPropertyNames.toolsPath, StringComparison.OrdinalIgnoreCase))
            {
                toolsPath = ExpandPropertyUnescaped(property, expander);
                toolsPath = ExpandRelativePathsRelativeToExeLocation(toolsPath);

                if (accumulateProperties)
                {
                    SetProperty
                    (
                        new ToolsetPropertyDefinition(ReservedPropertyNames.toolsPath, toolsPath, property.Source),
                        initialProperties,
                        globalProperties
                    );
                }
            }
            else if (String.Equals(property.Name, ReservedPropertyNames.binPath, StringComparison.OrdinalIgnoreCase))
            {
                binPath = ExpandPropertyUnescaped(property, expander);
                binPath = ExpandRelativePathsRelativeToExeLocation(binPath);

                if (accumulateProperties)
                {
                    SetProperty
                    (
                        new ToolsetPropertyDefinition(ReservedPropertyNames.binPath, binPath, property.Source),
                        initialProperties,
                        globalProperties
                    );
                }
            }
            else if (ReservedPropertyNames.IsReservedProperty(property.Name))
            {
                // We don't allow toolsets to define reserved properties
                string baseMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("CannotModifyReservedProperty", property.Name);
                InvalidToolsetDefinitionException.Throw("InvalidPropertyNameInToolset", property.Name, property.Source.LocationString, baseMessage);
            }
            else
            {
                // It's an arbitrary property
                property.Value = ExpandPropertyUnescaped(property, expander);

                SetProperty(property, properties, globalProperties);

                if (accumulateProperties)
                {
                    SetProperty(property, initialProperties, globalProperties);
                }
            }

            if (accumulateProperties)
            {
                expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(initialProperties, FileSystems.Default);
            }
        }
示例#49
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 + "'"
                    );
            }
        }
示例#50
0
 /// <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);
     }
 }
示例#51
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;
        }
示例#52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PkgConfigFunctions"/> class.
 /// </summary>
 /// <param name="project">The current project.</param>
 /// <param name="properties">The projects properties.</param>
 public PkgConfigFunctions(Project project, PropertyDictionary properties) : base(project, properties) {
 }
示例#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
 /// <summary>
 /// Empty impl
 /// </summary>
 Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults)
 {
     throw new NotImplementedException();
 }
示例#55
0
        /// <summary>
        /// Gathers toolset data from the registry and configuration file, if any:
        /// allows you to specify which of the registry and configuration file to
        /// read from by providing ToolsetInitialization
        /// </summary>
        internal static string ReadAllToolsets(Dictionary <string, Toolset> toolsets, PropertyDictionary <ProjectPropertyInstance> environmentProperties, PropertyDictionary <ProjectPropertyInstance> globalProperties, ToolsetDefinitionLocations locations)
        {
            return(ReadAllToolsets(toolsets,
#if FEATURE_WIN32_REGISTRY
                                   null,
#endif
                                   null,
                                   environmentProperties, globalProperties, locations));
        }
示例#56
0
 /// <summary>
 /// Helper method to create a new request definition given a filename and global properties
 /// </summary>
 private RequestDefinition CreateNewRequest(string projectFile, PropertyDictionary <ProjectPropertyInstance> globalProperties)
 {
     return(CreateNewRequest(projectFile, null, null, globalProperties));
 }
示例#57
0
 internal ToolsetLocalReader(PropertyDictionary<ProjectPropertyInstance> environmentProperties, PropertyDictionary<ProjectPropertyInstance> globalProperties)
    : base(environmentProperties, globalProperties)
 {
 }
示例#58
0
        /// <summary>
        /// Gathers toolset data from the registry and configuration file, if any.
        /// NOTE:  this method is internal for unit testing purposes only.
        /// </summary>
        internal static string ReadAllToolsets
        (
            Dictionary <string, Toolset> toolsets,
#if FEATURE_WIN32_REGISTRY
            ToolsetRegistryReader registryReader,
#endif
            ToolsetConfigurationReader configurationReader,
            PropertyDictionary <ProjectPropertyInstance> environmentProperties,
            PropertyDictionary <ProjectPropertyInstance> globalProperties,
            ToolsetDefinitionLocations locations
        )
        {
            var initialProperties =
                new PropertyDictionary <ProjectPropertyInstance>(environmentProperties);

            initialProperties.ImportProperties(globalProperties);

            // The ordering here is important because the configuration file should have greater precedence
            // than the registry, and we do a check and don't read in the new toolset if there's already one.
            string defaultToolsVersionFromConfiguration         = null;
            string overrideTasksPathFromConfiguration           = null;
            string defaultOverrideToolsVersionFromConfiguration = null;

            if ((locations & ToolsetDefinitionLocations.ConfigurationFile) == ToolsetDefinitionLocations.ConfigurationFile)
            {
                if (configurationReader == null)
                {
                    configurationReader = new ToolsetConfigurationReader(environmentProperties, globalProperties);
                }

                // Accumulation of properties is okay in the config file because it's deterministically ordered
                defaultToolsVersionFromConfiguration = configurationReader.ReadToolsets(toolsets, globalProperties,
                                                                                        initialProperties, true /* accumulate properties */, out overrideTasksPathFromConfiguration,
                                                                                        out defaultOverrideToolsVersionFromConfiguration);
            }

            string defaultToolsVersionFromRegistry         = null;
            string overrideTasksPathFromRegistry           = null;
            string defaultOverrideToolsVersionFromRegistry = null;

            if ((locations & ToolsetDefinitionLocations.Registry) == ToolsetDefinitionLocations.Registry)
            {
#if FEATURE_WIN32_REGISTRY
                if (NativeMethodsShared.IsWindows || registryReader != null)
                {
                    // If we haven't been provided a registry reader (i.e. unit tests), create one
                    registryReader ??= new ToolsetRegistryReader(environmentProperties, globalProperties);

                    // We do not accumulate properties when reading them from the registry, because the order
                    // in which values are returned to us is essentially random: so we disallow one property
                    // in the registry to refer to another also in the registry
                    defaultToolsVersionFromRegistry = registryReader.ReadToolsets(toolsets, globalProperties,
                                                                                  initialProperties, false /* do not accumulate properties */, out overrideTasksPathFromRegistry,
                                                                                  out defaultOverrideToolsVersionFromRegistry);
                }
                else
#endif
                {
                    var currentDir = BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory.TrimEnd(Path.DirectorySeparatorChar);
                    var props      = new PropertyDictionary <ProjectPropertyInstance>();

                    var libraryPath = NativeMethodsShared.FrameworkBasePath;

                    if (!string.IsNullOrEmpty(libraryPath))
                    {
                        // The 4.0 toolset is installed in the framework directory
                        var v4Dir =
                            FrameworkLocationHelper.GetPathToDotNetFrameworkV40(DotNetFrameworkArchitecture.Current);
                        if (v4Dir != null && !toolsets.ContainsKey("4.0"))
                        {
                            // Create standard properties. On Mono they are well known
                            var buildProperties =
                                CreateStandardProperties(globalProperties, "4.0", libraryPath, v4Dir);

                            toolsets.Add(
                                "4.0",
                                new Toolset(
                                    "4.0",
                                    v4Dir,
                                    buildProperties,
                                    environmentProperties,
                                    globalProperties,
                                    null,
                                    currentDir,
                                    string.Empty));
                        }

                        // Other toolsets are installed in the xbuild directory
                        var xbuildToolsetsDir = Path.Combine(libraryPath, $"xbuild{Path.DirectorySeparatorChar}");
                        if (FileSystems.Default.DirectoryExists(xbuildToolsetsDir))
                        {
                            var r = new Regex(Regex.Escape(xbuildToolsetsDir) + @"\d+\.\d+");
                            foreach (var d in Directory.GetDirectories(xbuildToolsetsDir).Where(d => r.IsMatch(d)))
                            {
                                var version = Path.GetFileName(d);
                                var binPath = Path.Combine(d, "bin");
                                if (toolsets.ContainsKey(version))
                                {
                                    continue;
                                }

                                if (NativeMethodsShared.IsMono && Version.TryParse(version, out Version parsedVersion) && parsedVersion.Major > 14)
                                {
                                    continue;
                                }

                                // Create standard properties. On Mono they are well known
                                var buildProperties =
                                    CreateStandardProperties(globalProperties, version, xbuildToolsetsDir, binPath);

                                toolsets.Add(
                                    version,
                                    new Toolset(
                                        version,
                                        binPath,
                                        buildProperties,
                                        environmentProperties,
                                        globalProperties,
                                        null,
                                        currentDir,
                                        string.Empty));
                            }
                        }
                    }
                    if (!toolsets.ContainsKey(MSBuildConstants.CurrentToolsVersion))
                    {
                        toolsets.Add(
                            MSBuildConstants.CurrentToolsVersion,
                            new Toolset(
                                MSBuildConstants.CurrentToolsVersion,
                                currentDir,
                                props,
                                new PropertyDictionary <ProjectPropertyInstance>(),
                                currentDir,
                                string.Empty));
                    }
                }
            }

            // The 2.0 .NET Framework installer did not write a ToolsVersion key for itself in the registry.
            // The 3.5 installer writes one for 2.0, but 3.5 might not be installed.
            // The 4.0 and subsequent installers can't keep writing the 2.0 one, because (a) it causes SxS issues and (b) we
            // don't want it unless 2.0 is installed.
            // So if the 2.0 framework is actually installed, we're reading the registry, and either the registry or the config
            // file have not already created the 2.0 toolset, mock up a fake one.
            if (((locations & ToolsetDefinitionLocations.Registry) != 0) && !toolsets.ContainsKey("2.0") &&
                FrameworkLocationHelper.PathToDotNetFrameworkV20 != null)
            {
                var synthetic20Toolset = new Toolset(
                    "2.0",
                    FrameworkLocationHelper.PathToDotNetFrameworkV20,
                    environmentProperties,
                    globalProperties,
                    null /* 2.0 did not have override tasks */,
                    null /* 2.0 did not have a default override toolsversion */);
                toolsets.Add("2.0", synthetic20Toolset);
            }

            string defaultToolsVersionFromLocal         = null;
            string overrideTasksPathFromLocal           = null;
            string defaultOverrideToolsVersionFromLocal = null;

            if ((locations & ToolsetDefinitionLocations.Local) == ToolsetDefinitionLocations.Local)
            {
                var localReader = new ToolsetLocalReader(environmentProperties, globalProperties);

                defaultToolsVersionFromLocal = localReader.ReadToolsets(
                    toolsets,
                    globalProperties,
                    initialProperties,
                    false /* accumulate properties */,
                    out overrideTasksPathFromLocal,
                    out defaultOverrideToolsVersionFromLocal);
            }

            // We'll use the path from the configuration file if it was specified, otherwise we'll try
            // the one from the registry.  It's possible (and valid) that neither the configuration file
            // nor the registry specify a override in which case we'll just return null.
            var overrideTasksPath = overrideTasksPathFromConfiguration ?? overrideTasksPathFromRegistry ?? overrideTasksPathFromLocal;

            // We'll use the path from the configuration file if it was specified, otherwise we'll try
            // the one from the registry.  It's possible (and valid) that neither the configuration file
            // nor the registry specify a override in which case we'll just return null.
            var defaultOverrideToolsVersion = defaultOverrideToolsVersionFromConfiguration
                                              ?? defaultOverrideToolsVersionFromRegistry
                                              ?? defaultOverrideToolsVersionFromLocal;

            // We'll use the default from the configuration file if it was specified, otherwise we'll try
            // the one from the registry.  It's possible (and valid) that neither the configuration file
            // nor the registry specify a default, in which case we'll just return null.
            var defaultToolsVersion = defaultToolsVersionFromConfiguration ?? defaultToolsVersionFromRegistry ?? defaultToolsVersionFromLocal;

            // If we got a default version from the registry or config file, and it
            // actually exists, fine.
            // Otherwise we have to come up with one.
            if (defaultToolsVersion != null && toolsets.ContainsKey(defaultToolsVersion))
            {
                return(defaultToolsVersion);
            }
            // We're going to choose a hard coded default tools version of 2.0.
            defaultToolsVersion = Constants.defaultToolsVersion;

            // But don't overwrite any existing tools path for this default we're choosing.
            if (toolsets.ContainsKey(Constants.defaultToolsVersion))
            {
                return(defaultToolsVersion);
            }
            // There's no tools path already for 2.0, so use the path to the v2.0 .NET Framework.
            // If an old-fashioned caller sets BinPath property, or passed a BinPath to the constructor,
            // that will overwrite what we're setting here.
            ErrorUtilities.VerifyThrow(
                Constants.defaultToolsVersion == "2.0",
                "Getting 2.0 FX path so default should be 2.0");
            var pathToFramework = FrameworkLocationHelper.PathToDotNetFrameworkV20;

            // We could not find the default toolsversion because it was not installed on the machine. Fallback to the
            // one we expect to always be there when running msbuild 4.0.
            if (pathToFramework == null)
            {
                pathToFramework     = FrameworkLocationHelper.PathToDotNetFrameworkV40;
                defaultToolsVersion = Constants.defaultFallbackToolsVersion;
            }

            // Again don't overwrite any existing tools path for this default we're choosing.
            if (toolsets.ContainsKey(defaultToolsVersion))
            {
                return(defaultToolsVersion);
            }
            var defaultToolset = new Toolset(
                defaultToolsVersion,
                pathToFramework,
                environmentProperties,
                globalProperties,
                overrideTasksPath,
                defaultOverrideToolsVersion);
            toolsets.Add(defaultToolsVersion, defaultToolset);

            return(defaultToolsVersion);
        }
示例#59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AssemblyFunctions"/> class.
 /// </summary>
 /// <param name="project">The current project.</param>
 /// <param name="properties">The projects properties.</param>
 public AssemblyFunctions(Project project, PropertyDictionary properties) : base(project, properties) {}
示例#60
0
 public CCNetFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }