示例#1
0
        public void SimpleAddAndRetrieveProject()
        {
            // Initialize engine.
            Engine engine = new Engine(@"c:\");

            // Instantiate new project manager.
            ProjectManager projectManager = new ProjectManager();

            // Set up variables that represent the information we would be getting from 
            // the "MSBuild" task.
            string fullPath = @"c:\rajeev\temp\myapp.proj";
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("Configuration", "Debug");

            // Create a new project that matches the information that we're pretending
            // to receive from the MSBuild task.
            Project project1 = new Project(engine);
            project1.FullFileName = fullPath;
            project1.GlobalProperties = globalProperties;

            // Add the new project to the ProjectManager.
            projectManager.AddProject(project1);

            // Try and retrieve the project from the ProjectManager based on the fullpath + globalprops,
            // and make sure we get back the same project we added.
            Assertion.AssertEquals(project1, projectManager.GetProject(fullPath, globalProperties, null));
        }
示例#2
0
        /// <summary>
        /// Called either on the main or child node. This is the routing method for getting cache entries.
        /// </summary>
        public CacheEntry[] GetCacheEntries
        (
            int handleId, string[] names,
            string cacheScope, string cacheKey, string cacheVersion,
            CacheContentType cacheContentType, bool localNodeOnly
        )
        {
            TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId);
            BuildPropertyGroup   scopeProperties;

            if (cacheKey == null)
            {
                Project parentProject = executionContext.ParentProject;
                scopeProperties = parentProject.GlobalProperties;
            }
            else
            {
                // Property values are compared using case sensitive comparisons because the case of property values do have meaning.
                // In this case we are using properties in a manner where we do not want case sensitive comparisons.
                // There is not enough benefit for this one special case to add case insensitive
                // comparisons to build properties. We instead uppercase all of the keys for both get and set CachedEntries.
                scopeProperties = new BuildPropertyGroup();
                scopeProperties.SetProperty("CacheKey", cacheKey.ToUpper(CultureInfo.InvariantCulture));
            }

            if (cacheScope == null)
            {
                cacheScope = executionContext.ParentProject.FullFileName;
            }

            if (cacheVersion == null)
            {
                cacheVersion = executionContext.ParentProject.ToolsVersion;
            }

            CacheEntry[] result = parentEngine.CacheManager.GetCacheEntries(names, cacheScope, scopeProperties, cacheVersion, cacheContentType);

            bool haveCompleteResult = (result.Length == names.Length);

            if (haveCompleteResult)
            {
                for (int i = 0; i < result.Length; i++)
                {
                    if (result[i] == null)
                    {
                        haveCompleteResult = false;
                        break;
                    }
                }
            }

            // If we didn't have the complete result locally, check with the parent if allowed.
            if (!haveCompleteResult && parentEngine.Router.ChildMode && !localNodeOnly)
            {
                result = parentEngine.Router.ParentNode.GetCachedEntriesFromHost(names, cacheScope, scopeProperties, cacheVersion, cacheContentType);
                parentEngine.CacheManager.SetCacheEntries(result, cacheScope, scopeProperties, cacheVersion, cacheContentType);
            }

            return(result);
        }
示例#3
0
        public void Metadata()
        {
            string content = @"
            <i Include='i1' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
               <m>$(p)</m>
               <n>n1</n>
            </i>";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(content);
            BuildItem item = CreateBuildItemFromXmlDocument(doc);
            Assertion.AssertEquals("i", item.Name);
            BuildPropertyGroup properties = new BuildPropertyGroup();
            properties.SetProperty("p", "p1");

            // Evaluated
            Expander expander = new Expander(properties, null, ExpanderOptions.ExpandAll);
            item.EvaluateAllItemMetadata(expander, ParserOptions.AllowPropertiesAndItemLists, null, null);
            Assertion.AssertEquals("p1", item.GetEvaluatedMetadata("m"));

            // Unevaluated
            Assertion.AssertEquals("$(p)", item.GetMetadata("m"));
            Assertion.AssertEquals("n1", item.GetMetadata("n"));

            // All custom metadata
            ArrayList metadataNames = new ArrayList(item.CustomMetadataNames);
            Assertion.Assert(metadataNames.Contains("n"));
            Assertion.Assert(metadataNames.Contains("m"));

            // Custom metadata count only
            Assertion.AssertEquals(2, item.CustomMetadataCount);
            
            // All metadata count
            Assertion.AssertEquals(2 + FileUtilities.ItemSpecModifiers.All.Length, item.MetadataCount);
        }
示例#4
0
        public static bool Build(Project pProj, OutputWindowPane pPane, string pTarget, NameValueCollection pParams)
        {
            Microsoft.Build.BuildEngine.Engine buildEngine = new Microsoft.Build.BuildEngine.Engine();
              BuildExecutor executor = new BuildExecutor(pPane);

              RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework", false);
              if (key == null) {
            throw new Exception("Failed to determine .NET Framework install root - no .NETFramework key");
              }
              string installRoot = key.GetValue("InstallRoot") as string;
              if (installRoot == null) {
            throw new Exception("Failed to determine .NET Framework install root - no InstallRoot value");
              }
              key.Close();

              buildEngine.BinPath = Path.Combine(installRoot, string.Format("v{0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build));
              buildEngine.RegisterLogger(executor);

              executor.Verbosity = LoggerVerbosity.Normal;

              BuildPropertyGroup properties = new BuildPropertyGroup();
              foreach (string propKey in pParams.Keys) {
            string val = pParams[propKey];

            properties.SetProperty(propKey, val, true);
              }

              return buildEngine.BuildProjectFile(pProj.FileName, new string[]{pTarget}, properties);
        }
        public void CantModifyThroughEnumerator()
        {
            BuildPropertyGroup pg = new BuildPropertyGroup();
            // Only NormalProperties are modifiable anyway
            BuildProperty p1 = new BuildProperty("name1", "value1", PropertyType.NormalProperty);
            pg.SetProperty(p1);

            BuildPropertyGroupProxy proxy = new BuildPropertyGroupProxy(pg);

            Hashtable list = new Hashtable(StringComparer.OrdinalIgnoreCase);

            // Get the one property
            foreach (DictionaryEntry prop in proxy)
            {
                list.Add(prop.Key, prop.Value);
            }

            // Change the property
            Assertion.Assert((string)list["name1"] == "value1");
            list["name1"] = "newValue";
            Assertion.Assert((string)list["name1"] == "newValue");

            // Get the property again
            list = new Hashtable(StringComparer.OrdinalIgnoreCase);
            foreach (DictionaryEntry prop in proxy)
            {
                list.Add(prop.Key, prop.Value);
            }

            // Property value hasn't changed
            Assertion.Assert((string)list["name1"] == "value1");
        }
        public void BasicProxying()
        {
            BuildPropertyGroup pg = new BuildPropertyGroup();
            BuildProperty p1 = new BuildProperty("name1", "value1", PropertyType.EnvironmentProperty);
            BuildProperty p2 = new BuildProperty("name2", "value2", PropertyType.GlobalProperty);
            pg.SetProperty(p1);
            pg.SetProperty(p2);

            BuildPropertyGroupProxy proxy = new BuildPropertyGroupProxy(pg);

            Hashtable list = new Hashtable(StringComparer.OrdinalIgnoreCase);

            foreach (DictionaryEntry prop in proxy)
            {
                list.Add(prop.Key, prop.Value);
            }

            Assertion.Assert(list.Count == 2);
            Assertion.Assert((string)list["name1"] == "value1");
            Assertion.Assert((string)list["name2"] == "value2");
        }
示例#7
0
        /// <summary>
        /// Called either on the main or child node. This is the routing method for setting cache entries.
        /// </summary>
        public void SetCacheEntries
        (
            int handleId, CacheEntry[] entries,
            string cacheScope, string cacheKey, string cacheVersion,
            CacheContentType cacheContentType, bool localNodeOnly
        )
        {
            TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId);
            BuildPropertyGroup   scopeProperties;

            if (cacheKey == null)
            {
                Project parentProject = executionContext.ParentProject;
                scopeProperties = parentProject.GlobalProperties;
            }
            else
            {
                // Property values are compared using case sensitive comparisons because the case of property values do have meaning.
                // In this case we are using properties in a manner where we do not want case sensitive comparisons.
                // There is not enough benefit for this one special case to add case insensitive
                // comparisons to build properties. We instead uppercase all of the keys for both get and set CachedEntries.
                scopeProperties = new BuildPropertyGroup();
                scopeProperties.SetProperty("CacheKey", cacheKey.ToUpper(CultureInfo.InvariantCulture));
            }

            if (cacheScope == null)
            {
                cacheScope = executionContext.ParentProject.FullFileName;
            }

            if (cacheVersion == null)
            {
                cacheVersion = executionContext.ParentProject.ToolsVersion;
            }

            parentEngine.CacheManager.SetCacheEntries(entries, cacheScope, scopeProperties, cacheVersion, cacheContentType);

            // Also send these to the parent if we're allowed to
            if (parentEngine.Router.ChildMode && !localNodeOnly)
            {
                Exception exception = parentEngine.Router.ParentNode.PostCacheEntriesToHost(entries, cacheScope, scopeProperties, cacheVersion, cacheContentType);

                // If we had problems on the parent node, rethrow the exception here
                if (exception != null)
                {
                    throw exception;
                }
            }
        }
        private void SetupMembers()
        {
            pg1 = new BuildPropertyGroup();
            pg1.SetProperty("foo", "bar");
            pg1.SetProperty("abc", "true");
            pg1.SetProperty("Unit", "inches");

            pg2 = new BuildPropertyGroup();
            pg2.SetProperty("foo", "bar");
            pg2.SetProperty("abc", "true");

            pg3 = new BuildPropertyGroup();

            // These Choose objects are only suitable for
            // holding a place in the GroupingCollection.
            choose1 = new Choose();
            choose2 = new Choose();
            choose3 = new Choose();

            ig1 = new BuildItemGroup();
            ig1.AddNewItem("x", "x1");
            ig1.AddNewItem("x", "x2");
            ig1.AddNewItem("y", "y1");
            ig1.AddNewItem("y", "y2");
            ig1.AddNewItem("y", "y3");
            ig1.AddNewItem("y", "y4");

            ig2 = new BuildItemGroup();
            ig2.AddNewItem("jacksonfive", "germaine");
            ig2.AddNewItem("jacksonfive", "tito");
            ig2.AddNewItem("jacksonfive", "michael");
            ig2.AddNewItem("jacksonfive", "latoya");
            ig2.AddNewItem("jacksonfive", "janet");

            ig3 = new BuildItemGroup();
        }
 /// <summary>
 /// Sets the given property in the given property group.
 /// </summary>
 /// <param name="property"></param>
 /// <param name="propertyGroup"></param>
 /// <param name="globalProperties"></param>
 private void SetProperty(PropertyDefinition property, BuildPropertyGroup propertyGroup, BuildPropertyGroup globalProperties)
 {
     try
     {
         // Global properties cannot be overwritten
         if (globalProperties[property.Name] == null)
         {
             propertyGroup.SetProperty(property.Name, property.Value);
         }
     }
     catch (ArgumentException ex)
     {
         InvalidToolsetDefinitionException.Throw(ex, "InvalidPropertyNameInToolset", property.Name, property.Source, ex.Message);
     }
 }
示例#10
0
		public bool DoBuild(BuildJob job, ILogger logger)
		{
			engine.RegisterLogger(logger);
			
			Program.Log("Building target '" + job.Target + "' in " + job.ProjectFileName);
			string[] targets = job.Target.Split(';');
			
			BuildPropertyGroup globalProperties = new BuildPropertyGroup();
			foreach (var pair in job.Properties) {
				globalProperties.SetProperty(pair.Key, pair.Value, true);
			}
			
			try {
				return engine.BuildProjectFile(job.ProjectFileName, targets, globalProperties);
			} finally {
				engine.UnregisterAllLoggers();
			}
		}
示例#11
0
            public void ImportOutputProperties()
            {
                BuildPropertyGroup pg = new BuildPropertyGroup();
                pg.SetProperty("foo", "fooval");
                pg.SetProperty(new BuildProperty("bar", "barval", PropertyType.EnvironmentProperty));
                pg.SetProperty(new BuildProperty("baz", "bazval", PropertyType.GlobalProperty));
                pg.SetProperty(new BuildProperty("caz", "cazval", PropertyType.ImportedProperty));
                pg.SetProperty(new BuildProperty("barb", "barbval", PropertyType.OutputProperty));

                BuildPropertyGroup pgo = new BuildPropertyGroup();
                pgo.SetProperty(new BuildProperty("foo", "fooout", PropertyType.OutputProperty));
                pgo.SetProperty(new BuildProperty("bar", "barout", PropertyType.OutputProperty));
                pgo.SetProperty(new BuildProperty("baz", "bazout", PropertyType.OutputProperty));
                pgo.SetProperty(new BuildProperty("caz", "cazout", PropertyType.OutputProperty));
                pgo.SetProperty(new BuildProperty("barb", "barbout", PropertyType.OutputProperty));
                pgo.SetProperty(new BuildProperty("gaz", "gazout", PropertyType.OutputProperty));

                pg.ImportProperties(pgo);

                Assertion.AssertEquals(6, pg.Count);
                Assertion.AssertEquals("fooout", pg["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barout", pg["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazout", pg["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazout", pg["caz"].FinalValueEscaped);
                Assertion.AssertEquals("barbout", pg["barb"].FinalValueEscaped);
                Assertion.AssertEquals("gazout", pg["gaz"].FinalValueEscaped);

                pg.SetProperty(new BuildProperty("foo", "fooout2", PropertyType.OutputProperty));
                pg.SetProperty(new BuildProperty("gaz", "gazout2", PropertyType.OutputProperty));

                Assertion.AssertEquals("fooout2", pg["foo"].FinalValueEscaped);
                Assertion.AssertEquals("gazout2", pg["gaz"].FinalValueEscaped);

                pg.RemoveProperty("baz");
                pg.RevertAllOutputProperties();

                Assertion.AssertEquals(3, pg.Count);
                Assertion.AssertEquals("fooval", pg["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pg["bar"].FinalValueEscaped);
                Assertion.AssertNull(pg["baz"]);
                Assertion.AssertEquals("cazval", pg["caz"].FinalValueEscaped);
                Assertion.AssertNull(pg["barb"]);
            }
示例#12
0
        public void TestConstructor1andProperties()
        {

            int nodeProxyId = 1;
            string projectFileName = "ProjectFileName";
            string[] targetNames = new string[] { "Build" };
            BuildPropertyGroup globalProperties = null;
            int requestId = 1;

            BuildRequest firstConstructorRequest = new BuildRequest(nodeProxyId, projectFileName, targetNames, globalProperties, null, requestId, false, false);
            Assert.AreEqual(1, firstConstructorRequest.HandleId, "Expected firstConstructorRequest.NodeProxyId to be 1");
            firstConstructorRequest.HandleId = 2;
            Assert.AreEqual(2, firstConstructorRequest.HandleId, "Expected firstConstructorRequest.NodeProxyId to be 2");
            Assert.AreEqual(1, firstConstructorRequest.RequestId, "Expected firstConstructorRequest.RequestId to be 1");
            firstConstructorRequest.RequestId = 2;
            Assert.AreEqual(2, firstConstructorRequest.RequestId, "Expected firstConstructorRequest.RequestId to be 2");
            Assert.IsNull(firstConstructorRequest.GlobalProperties, "Expected firstConstructorRequest.GlobalProperties to be null");
            firstConstructorRequest.GlobalProperties = new BuildPropertyGroup();
            Assert.IsNotNull(firstConstructorRequest.GlobalProperties, "Expected firstConstructorRequest.GlobalProperties to not be null");
            Assert.IsTrue((firstConstructorRequest.TargetNames.Length == 1) && (string.Compare("Build", firstConstructorRequest.TargetNames[0], StringComparison.OrdinalIgnoreCase) == 0), "Expected to have one target with a value of Build in firstConstructorRequest.TargetNames");
            Assert.IsTrue(string.Compare("ProjectFileName", firstConstructorRequest.ProjectFileName, StringComparison.OrdinalIgnoreCase) == 0, "Expected firstConstructorRequest.ProjectFileName to be called ProjecFileName");

            globalProperties = new BuildPropertyGroup();
            BuildProperty propertyToAdd = new BuildProperty("PropertyName", "Value");
            globalProperties.SetProperty(propertyToAdd);

            firstConstructorRequest = new BuildRequest(nodeProxyId, projectFileName, targetNames, globalProperties, null, requestId, false, false);
            Assert.IsNotNull(firstConstructorRequest.GlobalPropertiesPassedByTask, "Expected GlobalPropertiesPassedByTask to not be null");
            Assert.IsNotNull(firstConstructorRequest.GlobalProperties, "Expected GlobalPropertiesPassedByTask to not be null");
            Assert.IsTrue(string.Compare(firstConstructorRequest.GlobalProperties["PropertyName"].Value, "Value", StringComparison.OrdinalIgnoreCase) == 0, "Expected GlobalProperties, propertyname to be equal to value");

            string buildProperty = ((Hashtable)firstConstructorRequest.GlobalPropertiesPassedByTask)["PropertyName"] as string;
            Assert.IsTrue(string.Compare(buildProperty, "Value", StringComparison.OrdinalIgnoreCase) == 0, "Expected hashtable to contain a property group with a value of value");
            Assert.IsTrue((firstConstructorRequest.TargetNames.Length == 1) && (string.Compare("Build", firstConstructorRequest.TargetNames[0], StringComparison.OrdinalIgnoreCase) == 0), "Expected to have one target with a value of Build");
            Assert.IsTrue(string.Compare("ProjectFileName", firstConstructorRequest.ProjectFileName, StringComparison.OrdinalIgnoreCase) == 0, "Expected project file to be called ProjecFileName");
      
        
        }
示例#13
0
        public void TestForDuplicatesInProjectTable()
        {
            ProjectManager projectManager = new ProjectManager();

            string fullPath = @"c:\foo\bar.proj";
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("p1", "v1");

            Project p = new Project(new Engine());
            p.FullFileName = fullPath;
            p.GlobalProperties = globalProperties;
            p.ToolsVersion = "4.0";

            // Add the new project to the ProjectManager, twice
            Hashtable table = new Hashtable(StringComparer.OrdinalIgnoreCase);
            ProjectManager.AddProject(table, p);
            ProjectManager.AddProject(table, p);

            Assertion.AssertEquals(1, ((ArrayList)table[fullPath]).Count); // Didn't add a duplicate

            // Add a second, slightly different project, and ensure it DOES get added
            Project p2 = new Project(new Engine());
            p2.FullFileName = fullPath;
            p2.GlobalProperties = globalProperties;
            p2.ToolsVersion = "2.0";

            ProjectManager.AddProject(table, p2);

            Project p3 = new Project(new Engine());
            p3.FullFileName = fullPath;
            p3.GlobalProperties = new BuildPropertyGroup();
            p3.ToolsVersion = "2.0";

            ProjectManager.AddProject(table, p3);

            Assertion.AssertEquals(3, ((ArrayList)table[fullPath]).Count);
        }
示例#14
0
        public void RemoveProjectsByFullPath()
        {
            // Initialize engine.  Need two separate engines because we don't allow two
            // projects with the same full path to be loaded in the same Engine.
            Engine engine1 = new Engine(@"c:\");
            Engine engine2 = new Engine(@"c:\");

            // Instantiate new project manager.
            ProjectManager projectManager = new ProjectManager();

            // Set up a global property group.
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("Configuration", "Release");

            // Create a few new projects.
            Project project1 = new Project(engine1);
            project1.FullFileName = @"c:\rajeev\temp\myapp.proj";
            project1.GlobalProperties = globalProperties;

            Project project2 = new Project(engine1);
            project2.FullFileName = @"c:\blah\foo.proj";
            project2.GlobalProperties = globalProperties;

            Project project3 = new Project(engine2);
            project3.FullFileName = @"c:\blah\foo.proj";
            globalProperties.SetProperty("Configuration", "Debug");
            project3.GlobalProperties = globalProperties;

            // Add the new projects to the ProjectManager.
            projectManager.AddProject(project1);
            projectManager.AddProject(project2);
            projectManager.AddProject(project3);

            // Remove all projects with the full path "c:\blah\foo.proj" (case insenstively).
            projectManager.RemoveProjects(@"c:\BLAH\FOO.Proj");

            // Make sure project 1 is still there.
            Assertion.AssertEquals(project1, projectManager.GetProject(project1.FullFileName, project1.GlobalProperties, null));

            // Make sure projects 2 and 3 are gone.
            Assertion.AssertNull(projectManager.GetProject(project2.FullFileName, project2.GlobalProperties, null));
            Assertion.AssertNull(projectManager.GetProject(project3.FullFileName, project3.GlobalProperties, null));
        }
示例#15
0
        public void ResetBuildStatusForAllProjects()
        {
            // Initialize engine.  Need two separate engines because we don't allow two
            // projects with the same full path to be loaded in the same Engine.
            Engine engine1 = new Engine(@"c:\");
            Engine engine2 = new Engine(@"c:\");

            // Instantiate new project manager.
            ProjectManager projectManager = new ProjectManager();

            // Set up a global property group.
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("Configuration", "Release");

            // Create a few new projects.
            Project project1 = new Project(engine1);
            project1.FullFileName = @"c:\rajeev\temp\myapp.proj";
            project1.GlobalProperties = globalProperties;

            Project project2 = new Project(engine1);
            project2.FullFileName = @"c:\blah\foo.proj";
            project2.GlobalProperties = globalProperties;

            Project project3 = new Project(engine2);
            project3.FullFileName = @"c:\blah\foo.proj";
            globalProperties.SetProperty("Configuration", "Debug");
            project3.GlobalProperties = globalProperties;

            // Add the new projects to the ProjectManager.
            projectManager.AddProject(project1);
            projectManager.AddProject(project2);
            projectManager.AddProject(project3);

            // Put all the projects in a non-reset state.
            project1.IsReset = false;
            project2.IsReset = false;
            project3.IsReset = false;

            // Call ResetAllProjects.
            projectManager.ResetBuildStatusForAllProjects();

            // Make sure they all got reset.
            Assertion.Assert(project1.IsReset);
            Assertion.Assert(project2.IsReset);
            Assertion.Assert(project3.IsReset);
        }
示例#16
0
        public void SimpleAddAndRetrieveProjectWithDifferentFullPath()
        {
            // Initialize engine.
            Engine engine = new Engine(@"c:\");

            // Instantiate new project manager.
            ProjectManager projectManager = new ProjectManager();

            // Set up variables that represent the information we would be getting from 
            // the "MSBuild" task.
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("Configuration", "Release");

            // Create a new project that matches the information that we're pretending
            // to receive from the MSBuild task.
            Project project1 = new Project(engine);
            project1.FullFileName = @"c:\rajeev\temp\myapp.proj";
            project1.GlobalProperties = globalProperties;

            // Add the new project to the ProjectManager.
            projectManager.AddProject(project1);

            // Now search for a project with a different full path but same set of global
            // properties.  We expect to get back null, because no such project exists.
            Assertion.AssertNull(projectManager.GetProject(@"c:\blah\wrong.proj", globalProperties, null));
        }
示例#17
0
        public void TestForDuplicatesInProjectEntryTable()
        {
            ProjectManager projectManager = new ProjectManager();

            string fullPath = @"c:\foo\bar.proj";
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("p1", "v1");
            string toolsVersion = "3.5";

            // Add the new project entry to the ProjectManager, twice
            Hashtable table = new Hashtable(StringComparer.OrdinalIgnoreCase);
            ProjectManager.AddProjectEntry(table, fullPath, globalProperties, toolsVersion, 0);

            ProjectManager.AddProjectEntry(table, fullPath, globalProperties, toolsVersion, 0);

            Assertion.AssertEquals(1, ((ArrayList)table[fullPath]).Count); // Didn't add a duplicate

            // Add a second, slightly different project entry, and ensure it DOES get added
            ProjectManager.AddProjectEntry(table, fullPath, globalProperties, "2.0", 0);
            ProjectManager.AddProjectEntry(table, fullPath, new BuildPropertyGroup(), "2.0", 0);

            Assertion.AssertEquals(3, ((ArrayList)table[fullPath]).Count);
        }
示例#18
0
        public static ProjectFileInfo Create(MSBuildOptions options, ILogger logger, string solutionDirectory, string projectFilePath, ICollection<MSBuildDiagnosticsMessage> diagnostics)
        {
            var projectFileInfo = new ProjectFileInfo();
            projectFileInfo.ProjectFilePath = projectFilePath;

#if DNX451
            if (!PlatformHelper.IsMono)
            {
                var properties = new Dictionary<string, string>
                {
                    { "DesignTimeBuild", "true" },
                    { "BuildProjectReferences", "false" },
                    { "_ResolveReferenceDependencies", "true" },
                    { "SolutionDir", solutionDirectory + Path.DirectorySeparatorChar }
                };

                if (!string.IsNullOrWhiteSpace(options.VisualStudioVersion))
                {
                    properties.Add("VisualStudioVersion", options.VisualStudioVersion);
                }

                var collection = new ProjectCollection(properties);

                logger.LogInformation("Using toolset {0} for {1}", options.ToolsVersion ?? collection.DefaultToolsVersion, projectFilePath);

                var project = string.IsNullOrEmpty(options.ToolsVersion) ?
                        collection.LoadProject(projectFilePath) :
                        collection.LoadProject(projectFilePath, options.ToolsVersion);

                var projectInstance = project.CreateProjectInstance();
                var buildResult = projectInstance.Build("ResolveReferences", new Microsoft.Build.Framework.ILogger[] { new MSBuildLogForwarder(logger, diagnostics) });

                if (!buildResult)
                {
                    return null;
                }

                projectFileInfo.AssemblyName = projectInstance.GetPropertyValue("AssemblyName");
                projectFileInfo.Name = projectInstance.GetPropertyValue("ProjectName");
                projectFileInfo.TargetFramework = new FrameworkName(projectInstance.GetPropertyValue("TargetFrameworkMoniker"));
                projectFileInfo.SpecifiedLanguageVersion = ToLanguageVersion(projectInstance.GetPropertyValue("LangVersion"));
                projectFileInfo.ProjectId = new Guid(projectInstance.GetPropertyValue("ProjectGuid").TrimStart('{').TrimEnd('}'));
                projectFileInfo.TargetPath = projectInstance.GetPropertyValue("TargetPath");
                var outputType = projectInstance.GetPropertyValue("OutputType");
                switch(outputType)
                {
                    case "Library": projectFileInfo.OutputKind = OutputKind.DynamicallyLinkedLibrary;
                        break;
                    case "WinExe": projectFileInfo.OutputKind = OutputKind.WindowsApplication;
                        break;
                    default:
                    case "Exe": projectFileInfo.OutputKind = OutputKind.ConsoleApplication;
                        break;
                }

                projectFileInfo.SourceFiles =
                    projectInstance.GetItems("Compile")
                                   .Select(p => p.GetMetadataValue("FullPath"))
                                   .ToList();

                projectFileInfo.References =
                    projectInstance.GetItems("ReferencePath")
                                   .Where(p => !string.Equals("ProjectReference", p.GetMetadataValue("ReferenceSourceTarget"), StringComparison.OrdinalIgnoreCase))
                                   .Select(p => p.GetMetadataValue("FullPath"))
                                   .ToList();

                projectFileInfo.ProjectReferences =
                    projectInstance.GetItems("ProjectReference")
                                   .Select(p => p.GetMetadataValue("FullPath"))
                                   .ToList();

                projectFileInfo.Analyzers =
                    projectInstance.GetItems("Analyzer")
                                   .Select(p => p.GetMetadataValue("FullPath"))
                                   .ToList();

                var allowUnsafe = projectInstance.GetPropertyValue("AllowUnsafeBlocks");
                if (!string.IsNullOrWhiteSpace(allowUnsafe))
                {
                    projectFileInfo.AllowUnsafe = Convert.ToBoolean(allowUnsafe);
                }

                var defineConstants = projectInstance.GetPropertyValue("DefineConstants");
                if (!string.IsNullOrWhiteSpace(defineConstants))
                {
                    projectFileInfo.DefineConstants = defineConstants.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
                }
            }
            else
            {
                // On mono we need to use this API since the ProjectCollection
                // isn't fully implemented
#pragma warning disable CS0618
                var engine = Engine.GlobalEngine;
                engine.DefaultToolsVersion = "4.0";
#pragma warning restore CS0618
                // engine.RegisterLogger(new ConsoleLogger());
                engine.RegisterLogger(new MSBuildLogForwarder(logger, diagnostics));

                var propertyGroup = new BuildPropertyGroup();
                propertyGroup.SetProperty("DesignTimeBuild", "true");
                propertyGroup.SetProperty("BuildProjectReferences", "false");
                // Dump entire assembly reference closure
                propertyGroup.SetProperty("_ResolveReferenceDependencies", "true");
                propertyGroup.SetProperty("SolutionDir", solutionDirectory + Path.DirectorySeparatorChar);

                // propertyGroup.SetProperty("MSBUILDENABLEALLPROPERTYFUNCTIONS", "1");

                engine.GlobalProperties = propertyGroup;

                var project = engine.CreateNewProject();
                project.Load(projectFilePath);
                var buildResult = engine.BuildProjectFile(projectFilePath, new[] { "ResolveReferences" }, propertyGroup, null, BuildSettings.None, null);

                if (!buildResult)
                {
                    return null;
                }

                var itemsLookup = project.EvaluatedItems.OfType<BuildItem>()
                                                        .ToLookup(g => g.Name);

                var properties = project.EvaluatedProperties.OfType<BuildProperty>()
                                                            .ToDictionary(p => p.Name);

                projectFileInfo.AssemblyName = properties["AssemblyName"].FinalValue;
                projectFileInfo.Name = Path.GetFileNameWithoutExtension(projectFilePath);
                projectFileInfo.TargetFramework = new FrameworkName(properties["TargetFrameworkMoniker"].FinalValue);
                if (properties.ContainsKey("LangVersion"))
                {
                    projectFileInfo.SpecifiedLanguageVersion = ToLanguageVersion(properties["LangVersion"].FinalValue);
                }
                projectFileInfo.ProjectId = new Guid(properties["ProjectGuid"].FinalValue.TrimStart('{').TrimEnd('}'));
                projectFileInfo.TargetPath = properties["TargetPath"].FinalValue;

                // REVIEW: FullPath here returns the wrong physical path, we need to figure out
                // why. We must be setting up something incorrectly
                projectFileInfo.SourceFiles = itemsLookup["Compile"]
                    .Select(b => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, b.FinalItemSpec)))
                    .ToList();

                projectFileInfo.References = itemsLookup["ReferencePath"]
                    .Where(p => !p.HasMetadata("Project"))
                    .Select(p => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, p.FinalItemSpec)))
                    .ToList();

                projectFileInfo.ProjectReferences = itemsLookup["ProjectReference"]
                    .Select(p => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, p.FinalItemSpec)))
                    .ToList();

                projectFileInfo.Analyzers = itemsLookup["Analyzer"]
                    .Select(p => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, p.FinalItemSpec)))
                    .ToList();

                var allowUnsafe = properties["AllowUnsafeBlocks"].FinalValue;
                if (!string.IsNullOrWhiteSpace(allowUnsafe))
                {
                    projectFileInfo.AllowUnsafe = Convert.ToBoolean(allowUnsafe);
                }

                var defineConstants = properties["DefineConstants"].FinalValue;
                if (!string.IsNullOrWhiteSpace(defineConstants))
                {
                    projectFileInfo.DefineConstants = defineConstants.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
                }
            }
#else
            // TODO: Shell out to msbuild/xbuild here?
#endif
            return projectFileInfo;
        }
示例#19
0
		public void TestSetProperty3 ()
		{
			BuildPropertyGroup bpg = new BuildPropertyGroup ();
			
			bpg.SetProperty ("name", "$(A)");

			BuildProperty bp = bpg ["name"];

			Assert.AreEqual ("name", bp.Name, "A1");
			Assert.AreEqual ("$(A)", bp.Value, "A2");
			Assert.AreEqual ("$(A)", bp.FinalValue, "A3");
		}
        public void TestTargetFrameworkPaths0()
        {
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("TargetFrameworkVersion", "v2.0");

            Project msbuildProject = CreateVenusSolutionProject(globalProperties, "4.0");

            // ToolsVersion is 2.0, TargetFrameworkVersion is v2.0 --> one item pointing to v2.0
            msbuildProject.ToolsVersion = "4.0";

            bool success = msbuildProject.Build("GetFrameworkPathAndRedistList");
            Assertion.AssertEquals(true, success);

            AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV20);
            AssertProjectItemNameCount(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", 1);
        }
示例#21
0
        /// <summary>
        /// Called either on the main or child node. This is the routing method for setting cache entries.
        /// </summary>
        public void SetCacheEntries
        (
            int handleId, CacheEntry[] entries, 
            string cacheScope, string cacheKey, string cacheVersion,
            CacheContentType cacheContentType, bool localNodeOnly
        )
        {
            TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId);
            BuildPropertyGroup scopeProperties;

            if (cacheKey == null)
            {
                Project parentProject = executionContext.ParentProject;
                scopeProperties = parentProject.GlobalProperties;
            }
            else
            {
                // Property values are compared using case sensitive comparisons because the case of property values do have meaning.
                // In this case we are using properties in a manner where we do not want case sensitive comparisons.
                // There is not enough benefit for this one special case to add case insensitive 
                // comparisons to build properties. We instead uppercase all of the keys for both get and set CachedEntries.
                scopeProperties = new BuildPropertyGroup();
                scopeProperties.SetProperty("CacheKey", cacheKey.ToUpper(CultureInfo.InvariantCulture));
            }

            if (cacheScope == null)
            {
                cacheScope = executionContext.ParentProject.FullFileName;
            }

            if (cacheVersion == null)
            {
                cacheVersion = executionContext.ParentProject.ToolsVersion;
            }

            parentEngine.CacheManager.SetCacheEntries(entries, cacheScope, scopeProperties, cacheVersion, cacheContentType);

            // Also send these to the parent if we're allowed to
            if (parentEngine.Router.ChildMode && !localNodeOnly)
            {
                Exception exception = parentEngine.Router.ParentNode.PostCacheEntriesToHost(entries, cacheScope, scopeProperties, cacheVersion, cacheContentType);

                // If we had problems on the parent node, rethrow the exception here
                if (exception != null)
                {
                    throw exception;
                }
            }
        }
示例#22
0
            public void ClonePropertyGroup()
            {
                BuildPropertyGroup pg = new BuildPropertyGroup();
                pg.SetProperty("foo", "fooval");
                pg.SetProperty(new BuildProperty("bar", "barval", PropertyType.EnvironmentProperty));
                pg.SetProperty(new BuildProperty("baz", "bazval", PropertyType.GlobalProperty));
                pg.SetProperty(new BuildProperty("caz", "cazval", PropertyType.ImportedProperty));
                pg.SetProperty(new BuildProperty("barb", "barbval", PropertyType.OutputProperty));

                pg.SetProperty(new BuildProperty("foo", "fooout", PropertyType.OutputProperty));
                pg.SetProperty(new BuildProperty("barb", "barbout", PropertyType.OutputProperty));
                pg.SetProperty(new BuildProperty("gaz", "gazout", PropertyType.OutputProperty));
                pg.SetProperty(new BuildProperty("foo", "fooout2", PropertyType.OutputProperty));

                BuildPropertyGroup pgsc = pg.Clone(false /* shallow clone */);
                BuildPropertyGroup pgdc = pg.Clone(true /* deep clone */);

                Assertion.AssertEquals(6, pg.Count);
                Assertion.AssertEquals("fooout2", pg["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pg["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pg["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pg["caz"].FinalValueEscaped);
                Assertion.AssertEquals("barbout", pg["barb"].FinalValueEscaped);
                Assertion.AssertEquals("gazout", pg["gaz"].FinalValueEscaped);

                Assertion.AssertEquals(6, pgsc.Count);
                Assertion.AssertEquals("fooout2", pgsc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgsc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgsc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgsc["caz"].FinalValueEscaped);
                Assertion.AssertEquals("barbout", pgsc["barb"].FinalValueEscaped);
                Assertion.AssertEquals("gazout", pgsc["gaz"].FinalValueEscaped);

                Assertion.AssertEquals(6, pgdc.Count);
                Assertion.AssertEquals("fooout2", pgdc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgdc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgdc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgdc["caz"].FinalValueEscaped);
                Assertion.AssertEquals("barbout", pgdc["barb"].FinalValueEscaped);
                Assertion.AssertEquals("gazout", pgdc["gaz"].FinalValueEscaped);

                pg.RevertAllOutputProperties();

                Assertion.AssertEquals(4, pg.Count);
                Assertion.AssertEquals("fooval", pg["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pg["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pg["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pg["caz"].FinalValueEscaped);
                Assertion.AssertNull(pg["barb"]);
                Assertion.AssertNull(pg["gaz"]);

                Assertion.AssertEquals(6, pgsc.Count);
                Assertion.AssertEquals("fooout2", pgsc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgsc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgsc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgsc["caz"].FinalValueEscaped);
                Assertion.AssertEquals("barbout", pgsc["barb"].FinalValueEscaped);
                Assertion.AssertEquals("gazout", pgsc["gaz"].FinalValueEscaped);

                Assertion.AssertEquals(6, pgdc.Count);
                Assertion.AssertEquals("fooout2", pgdc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgdc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgdc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgdc["caz"].FinalValueEscaped);
                Assertion.AssertEquals("barbout", pgdc["barb"].FinalValueEscaped);
                Assertion.AssertEquals("gazout", pgdc["gaz"].FinalValueEscaped);

                pgsc.RevertAllOutputProperties();

                Assertion.AssertEquals(4, pg.Count);
                Assertion.AssertEquals("fooval", pg["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pg["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pg["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pg["caz"].FinalValueEscaped);
                Assertion.AssertNull(pg["barb"]);
                Assertion.AssertNull(pg["gaz"]);

                Assertion.AssertEquals(4, pgsc.Count);
                Assertion.AssertEquals("fooval", pgsc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgsc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgsc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgsc["caz"].FinalValueEscaped);
                Assertion.AssertNull(pgsc["barb"]);
                Assertion.AssertNull(pgsc["gaz"]);

                Assertion.AssertEquals(6, pgdc.Count);
                Assertion.AssertEquals("fooout2", pgdc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgdc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgdc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgdc["caz"].FinalValueEscaped);
                Assertion.AssertEquals("barbout", pgdc["barb"].FinalValueEscaped);
                Assertion.AssertEquals("gazout", pgdc["gaz"].FinalValueEscaped);

                pgdc.RevertAllOutputProperties();

                Assertion.AssertEquals(4, pg.Count);
                Assertion.AssertEquals("fooval", pg["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pg["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pg["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pg["caz"].FinalValueEscaped);
                Assertion.AssertNull(pg["barb"]);
                Assertion.AssertNull(pg["gaz"]);

                Assertion.AssertEquals(4, pgsc.Count);
                Assertion.AssertEquals("fooval", pgsc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgsc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgsc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgsc["caz"].FinalValueEscaped);
                Assertion.AssertNull(pgsc["barb"]);
                Assertion.AssertNull(pgsc["gaz"]);

                Assertion.AssertEquals(4, pgdc.Count);
                Assertion.AssertEquals("fooval", pgdc["foo"].FinalValueEscaped);
                Assertion.AssertEquals("barval", pgdc["bar"].FinalValueEscaped);
                Assertion.AssertEquals("bazval", pgdc["baz"].FinalValueEscaped);
                Assertion.AssertEquals("cazval", pgdc["caz"].FinalValueEscaped);
                Assertion.AssertNull(pgdc["barb"]);
                Assertion.AssertNull(pgdc["gaz"]);
            }
示例#23
0
            public void PropertyGroupCustomSerialization()
            {
                BuildPropertyGroup pg = new BuildPropertyGroup();
                pg.SetProperty(new BuildProperty("bar", "barval", PropertyType.EnvironmentProperty));
                pg.SetProperty(new BuildProperty("baz", "bazval", PropertyType.GlobalProperty));
                pg.SetProperty(new BuildProperty("caz", "cazval", PropertyType.ImportedProperty));
                pg.SetProperty(new BuildProperty("barb", "barbout", PropertyType.OutputProperty));
                pg.SetProperty(new BuildProperty("gaz", "gazout", PropertyType.OutputProperty));
                pg.SetProperty(new BuildProperty("foo", "fooout2", PropertyType.OutputProperty));

                MemoryStream stream = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(stream);
                BinaryReader reader = new BinaryReader(stream);
                try
                {
                    stream.Position = 0;
                    pg.WriteToStream(writer);
                    long streamWriteEndPosition = stream.Position;

                    stream.Position = 0;
                    BuildPropertyGroup pg2 = new BuildPropertyGroup();
                    pg2.CreateFromStream(reader);
                    long streamReadEndPosition = stream.Position;
                    Assert.IsTrue(streamWriteEndPosition == streamReadEndPosition, "Stream end positions should be equal");
                    Assert.AreEqual(6, pg.Count);
                    Assert.AreEqual("fooout2", pg2["foo"].FinalValueEscaped);
                    Assert.AreEqual("barval", pg2["bar"].FinalValueEscaped);
                    Assert.AreEqual("bazval", pg2["baz"].FinalValueEscaped);
                    Assert.AreEqual("cazval", pg2["caz"].FinalValueEscaped);
                    Assert.AreEqual("barbout", pg2["barb"].FinalValueEscaped);
                    Assert.AreEqual("gazout", pg2["gaz"].FinalValueEscaped);
                }
                finally
                {
                    reader.Close();
                    writer = null;
                    stream = null;
                }
            }
示例#24
0
		public void TestSetProperty4 ()
		{
			BuildPropertyGroup bpg = new BuildPropertyGroup ();

			bpg.SetProperty ("P1", "$(A)", true);
			bpg.SetProperty ("P2", "$(A)", false);

			BuildProperty b1 = bpg ["P1"];
			BuildProperty b2 = bpg ["P2"];

			Assert.AreEqual ("P1", b1.Name, "A1");
			Assert.AreEqual (Utilities.Escape ("$(A)"), b1.Value, "A2");
			Assert.AreEqual ("$(A)", b1.FinalValue, "A3");
			Assert.AreEqual ("P2", b2.Name, "A4");
			Assert.AreEqual ("$(A)", b2.Value, "A5");
			Assert.AreEqual ("$(A)", b2.FinalValue, "A6");
		}
示例#25
0
        public void GetBuckets()
        {
            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

            Hashtable itemsByType = new Hashtable(StringComparer.OrdinalIgnoreCase);

            BuildItemGroup items = new BuildItemGroup();
            items.AddNewItem("File", "a.foo");
            items.AddNewItem("File", "b.foo");
            items.AddNewItem("File", "c.foo");
            items.AddNewItem("File", "d.foo");
            items.AddNewItem("File", "e.foo");
            itemsByType["FILE"] = items;

            items = new BuildItemGroup();
            items.AddNewItem("Doc", "a.doc");
            items.AddNewItem("Doc", "b.doc");
            items.AddNewItem("Doc", "c.doc");
            items.AddNewItem("Doc", "d.doc");
            items.AddNewItem("Doc", "e.doc");
            itemsByType["DOC"] = items;

            BuildPropertyGroup properties = new BuildPropertyGroup();
            properties.SetProperty("UnitTests", "unittests.foo");
            properties.SetProperty("OBJ", "obj");

            ArrayList buckets = BatchingEngine.PrepareBatchingBuckets(new XmlDocument().CreateElement("Foo"), parameters, CreateLookup(itemsByType, properties));

            Assertion.AssertEquals(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'";

                Assertion.Assert(BuildEngine.Utilities.EvaluateCondition(tempXmlAttribute.Value,
                    tempXmlAttribute, bucket.Expander, null, ParserOptions.AllowAll, null, null));
                Assertion.AssertEquals("a.doc;b.doc;c.doc;d.doc;e.doc", ExpandItemsIntoString(bucket, "@(doc)"));
                Assertion.AssertEquals("unittests.foo", ExpandMetadataAndProperties(bucket, "$(bogus)$(UNITTESTS)"));
            }

            Assertion.AssertEquals("a.foo", ExpandItemsIntoString((ItemBucket)buckets[0], "@(File)"));
            Assertion.AssertEquals(".foo", ExpandItemsIntoString((ItemBucket)buckets[0], "@(File->'%(Extension)')"));
            Assertion.AssertEquals("obj\\a.ext", ExpandMetadataAndProperties((ItemBucket)buckets[0], "$(obj)\\%(Filename).ext"));

            // we weren't batching on this attribute, so it has no value
            Assertion.AssertEquals(String.Empty, ExpandMetadataAndProperties((ItemBucket)buckets[0], "%(Extension)"));

            items = ((ItemBucket)buckets[0]).Expander.ExpandSingleItemListExpressionIntoItemsLeaveEscaped("@(file)", null);
            Assertion.AssertNotNull(items);
            Assertion.AssertEquals(1, items.Count);

            int invalidProjectFileExceptions = 0;
            try
            {
                // This should throw because we don't allow item lists to be concatenated
                // with other strings.
                items = ((ItemBucket)buckets[0]).Expander.ExpandSingleItemListExpressionIntoItemsLeaveEscaped("@(file);$(unitests)", null);
            }
            catch (InvalidProjectFileException)
            {
                invalidProjectFileExceptions++;
            }

            // We do allow separators in item vectors, this results in an item group with a single flattened item
            items = ((ItemBucket)buckets[0]).Expander.ExpandSingleItemListExpressionIntoItemsLeaveEscaped("@(file, ',')", null);
            Assertion.AssertNotNull(items);
            Assertion.AssertEquals(1, items.Count);
            Assertion.AssertEquals("a.foo", items[0].FinalItemSpec);

            Assertion.AssertEquals(1, invalidProjectFileExceptions);
        }
示例#26
0
        public void GetToolsetSettings()
        {
            Engine e = new Engine(@"C:\binpath");

            e.Toolsets.Add(new Toolset("Whidbey", @"C:\WhidbeyPath"));
            BuildPropertyGroup properties = new BuildPropertyGroup();
            properties.SetProperty("foo", "bar");
            e.Toolsets.Add(new Toolset("orcas", @"C:\OrcasBinPath", properties));

            Toolset ts1 = e.Toolsets["Whidbey"];
            Toolset ts2 = e.Toolsets["Orcas"];

            Assertion.AssertEquals(@"C:\WhidbeyPath", ts1.ToolsPath);
            Assertion.AssertEquals(@"C:\OrcasBinPath", ts2.ToolsPath);
            Assertion.AssertEquals(0, ts1.BuildProperties.Count);
            Assertion.AssertEquals(1, ts2.BuildProperties.Count);
            Assertion.AssertEquals("bar", ts2.BuildProperties["foo"].Value);
        }
示例#27
0
            public void PropertyGroupIsEquivalent_DifferentCaseOnName()
            {
                BuildPropertyGroup pg1 = new BuildPropertyGroup();
                BuildPropertyGroup pg2 = new BuildPropertyGroup();

                pg1.SetProperty("oscarthegrouch", "Green");
                pg1.SetProperty("bigbird", "Yellow");
                pg1.SetProperty("elmo", "Red");

                pg2.SetProperty("Elmo", "Red");
                pg2.SetProperty("BigBird", "Yellow");
                pg2.SetProperty("OscartheGrouch", "Green");

                // The two property bags are not equivalent.
                Assertion.Assert(pg1.IsEquivalent(pg2));
            }
示例#28
0
		public void TestSetProperty2 ()
		{
			BuildPropertyGroup bpg = new BuildPropertyGroup ();
			bpg.SetProperty ("name", null);
		}
示例#29
0
        /// <summary>
        /// Called either on the main or child node. This is the routing method for getting cache entries.
        /// </summary>
        public CacheEntry[] GetCacheEntries
        (
            int handleId, string[] names, 
            string cacheScope, string cacheKey, string cacheVersion,
            CacheContentType cacheContentType, bool localNodeOnly
        )
        {
            TaskExecutionContext executionContext = GetTaskContextFromHandleId(handleId);
            BuildPropertyGroup scopeProperties;

            if (cacheKey == null)
            {
                Project parentProject = executionContext.ParentProject;
                scopeProperties = parentProject.GlobalProperties;
            }
            else
            {
                // Property values are compared using case sensitive comparisons because the case of property values do have meaning.
                // In this case we are using properties in a manner where we do not want case sensitive comparisons.
                // There is not enough benefit for this one special case to add case insensitive 
                // comparisons to build properties. We instead uppercase all of the keys for both get and set CachedEntries.
                scopeProperties = new BuildPropertyGroup();
                scopeProperties.SetProperty("CacheKey", cacheKey.ToUpper(CultureInfo.InvariantCulture));
            }

            if (cacheScope == null)
            {
                cacheScope = executionContext.ParentProject.FullFileName;
            }

            if (cacheVersion == null)
            {
                cacheVersion = executionContext.ParentProject.ToolsVersion;
            }

            CacheEntry[] result = parentEngine.CacheManager.GetCacheEntries(names, cacheScope, scopeProperties, cacheVersion, cacheContentType);

            bool haveCompleteResult = (result.Length == names.Length);

            if (haveCompleteResult)
            {
                for (int i = 0; i < result.Length; i++)
                {
                    if (result[i] == null)
                    {
                        haveCompleteResult = false;
                        break;
                    }
                }
            }

            // If we didn't have the complete result locally, check with the parent if allowed.
            if (!haveCompleteResult && parentEngine.Router.ChildMode && !localNodeOnly)
            {
                result = parentEngine.Router.ParentNode.GetCachedEntriesFromHost(names, cacheScope, scopeProperties, cacheVersion, cacheContentType);
                parentEngine.CacheManager.SetCacheEntries(result, cacheScope, scopeProperties, cacheVersion, cacheContentType);
            }

            return result;
        }
示例#30
0
		public void TestSetProperty5 ()
		{
			BuildPropertyGroup bpg = new BuildPropertyGroup ();

			bpg.SetProperty ("1", "$(A)");
		}
示例#31
0
        public void GetToolsetProxiesToolset()
        {
            Engine e = new Engine(@"C:\binpath");

            e.Toolsets.Add(new Toolset("Whidbey", @"C:\WhidbeyPath"));

            BuildPropertyGroup properties = new BuildPropertyGroup();
            properties.SetProperty("foo", "bar");
            e.Toolsets.Add(new Toolset("orcas", @"C:\OrcasBinPath", properties));

            Toolset ts1 = e.Toolsets["orcas"];
            ts1.BuildProperties["foo"].Value = "bar2";
            ts1.BuildProperties.SetProperty("foo2", "bar3");
            Assertion.AssertEquals("bar2", ts1.BuildProperties["foo"].Value);
            Assertion.AssertEquals("bar3", ts1.BuildProperties["foo2"].Value);

            // Get it again, should be unchanged
            Toolset ts1b = e.Toolsets["orcas"];
            Assertion.AssertEquals("bar", ts1b.BuildProperties["foo"].Value);
            Assertion.AssertNull(ts1b.BuildProperties["foo2"]);
        }
示例#32
0
            public void PropertyGroupIsEquivalent_BlankPropertyValue()
            {
                BuildPropertyGroup pg1 = new BuildPropertyGroup();
                BuildPropertyGroup pg2 = new BuildPropertyGroup();

                pg1.SetProperty("Elmo", "Red");
                pg1.SetProperty("BigBird", "Yellow");
                pg1.SetProperty("OscartheGrouch", "Green");

                pg2.SetProperty("Elmo", "Red");
                pg2.SetProperty("BigBird", "");
                pg2.SetProperty("OscartheGrouch", "Green");

                // The two property bags are not equivalent.
                Assertion.Assert(!pg1.IsEquivalent(pg2));
            }
示例#33
0
        /// <summary>
        /// Used to load information about default MSBuild tasks i.e. tasks that do not need to be explicitly declared in projects
        /// with the &lt;UsingTask&gt; element. Default task information is read from special files, which are located in the same
        /// directory as the MSBuild binaries.
        /// </summary>
        /// <remarks>
        /// 1) a default tasks file needs the &lt;Project&gt; root tag in order to be well-formed
        /// 2) the XML declaration tag &lt;?xml ...&gt; is ignored
        /// 3) comment tags are always ignored regardless of their placement
        /// 4) the rest of the tags are expected to be &lt;UsingTask&gt; tags
        /// </remarks>
        private void RegisterDefaultTasks(BuildEventContext buildEventContext)
        {
            if (!defaultTasksRegistrationAttempted)
            {
                try
                {
                    this.defaultTaskRegistry = new TaskRegistry();

                    string[] defaultTasksFiles = { };

                    try
                    {
                        defaultTasksFiles = getFiles(toolset.ToolsPath, defaultTasksFilePattern);

                        if (defaultTasksFiles.Length == 0)
                        {
                            loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty),
                                                       "DefaultTasksFileLoadFailureWarning",
                                                       defaultTasksFilePattern, toolset.ToolsPath, String.Empty);
                        }
                    }
                    // handle security problems when finding the default tasks files
                    catch (UnauthorizedAccessException e)
                    {
                        loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty),
                                                   "DefaultTasksFileLoadFailureWarning",
                                                   defaultTasksFilePattern, toolset.ToolsPath, e.Message);
                    }
                    // handle problems when reading the default tasks files
                    catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception.
                    {
                        if (ExceptionHandling.NotExpectedException(e))
                        {
                            throw;
                        }

                        loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty),
                                                   "DefaultTasksFileLoadFailureWarning",
                                                   defaultTasksFilePattern, toolset.ToolsPath, e.Message);
                    }

                    BuildPropertyGroup propertyBag = null;

                    foreach (string defaultTasksFile in defaultTasksFiles)
                    {
                        try
                        {
                            XmlDocument defaultTasks = loadXmlFromPath(defaultTasksFile);

                            // look for the first root tag that is not a comment or an XML declaration -- this should be the <Project> tag
                            // NOTE: the XML parser will guarantee there is only one real root element in the file
                            // but we need to find it amongst the other types of XmlNode at the root.
                            foreach (XmlNode topLevelNode in defaultTasks.ChildNodes)
                            {
                                if (XmlUtilities.IsXmlRootElement(topLevelNode))
                                {
                                    ProjectErrorUtilities.VerifyThrowInvalidProject(topLevelNode.LocalName == XMakeElements.project,
                                                                                    topLevelNode, "UnrecognizedElement", topLevelNode.Name);

                                    ProjectErrorUtilities.VerifyThrowInvalidProject((topLevelNode.Prefix.Length == 0) && (String.Equals(topLevelNode.NamespaceURI, XMakeAttributes.defaultXmlNamespace, StringComparison.OrdinalIgnoreCase)),
                                                                                    topLevelNode, "ProjectMustBeInMSBuildXmlNamespace", XMakeAttributes.defaultXmlNamespace);

                                    // the <Project> tag can only the XML namespace -- no other attributes
                                    foreach (XmlAttribute projectAttribute in topLevelNode.Attributes)
                                    {
                                        ProjectXmlUtilities.VerifyThrowProjectInvalidAttribute(projectAttribute.Name == XMakeAttributes.xmlns, projectAttribute);
                                    }

                                    // look at all the child tags of the <Project> root tag we found
                                    foreach (XmlNode usingTaskNode in topLevelNode.ChildNodes)
                                    {
                                        if (usingTaskNode.NodeType != XmlNodeType.Comment)
                                        {
                                            ProjectErrorUtilities.VerifyThrowInvalidProject(usingTaskNode.Name == XMakeElements.usingTask,
                                                                                            usingTaskNode, "UnrecognizedElement", usingTaskNode.Name);

                                            // Initialize the property bag if it hasn't been already.
                                            if (propertyBag == null)
                                            {
                                                // Set the value of the MSBuildBinPath/ToolsPath properties.
                                                BuildPropertyGroup reservedPropertyBag = new BuildPropertyGroup();

                                                reservedPropertyBag.SetProperty(
                                                    new BuildProperty(ReservedPropertyNames.binPath, EscapingUtilities.Escape(toolset.ToolsPath),
                                                                      PropertyType.ReservedProperty));

                                                reservedPropertyBag.SetProperty(
                                                    new BuildProperty(ReservedPropertyNames.toolsPath, EscapingUtilities.Escape(toolset.ToolsPath),
                                                                      PropertyType.ReservedProperty));

                                                // Also set MSBuildAssemblyVersion so that the tasks file can tell between v4 and v12 MSBuild
                                                reservedPropertyBag.SetProperty(
                                                    new BuildProperty(ReservedPropertyNames.assemblyVersion, Constants.AssemblyVersion,
                                                                      PropertyType.ReservedProperty));

                                                propertyBag = new BuildPropertyGroup();
                                                propertyBag.ImportInitialProperties(parentEngine.EnvironmentProperties, reservedPropertyBag, BuildProperties, parentEngine.GlobalProperties);
                                            }

                                            defaultTaskRegistry.RegisterTask(new UsingTask((XmlElement)usingTaskNode, true), new Expander(propertyBag), loggingServices, buildEventContext);
                                        }
                                    }

                                    break;
                                }
                            }
                        }
                        // handle security problems when loading the default tasks file
                        catch (UnauthorizedAccessException e)
                        {
                            loggingServices.LogError(buildEventContext, new BuildEventFileInfo(defaultTasksFile), "DefaultTasksFileFailure", e.Message);
                            break;
                        }
                        // handle problems when loading the default tasks file
                        catch (IOException e)
                        {
                            loggingServices.LogError(buildEventContext, new BuildEventFileInfo(defaultTasksFile), "DefaultTasksFileFailure", e.Message);
                            break;
                        }
                        // handle XML errors in the default tasks file
                        catch (XmlException e)
                        {
                            ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, new BuildEventFileInfo(e),
                                                                                    "DefaultTasksFileFailure", e.Message);
                        }
                    }
                }
                finally
                {
                    defaultTasksRegistrationAttempted = true;
                }
            }
        }
示例#34
0
            public void ImportInitialPropertiesHasCorrectPrecedence()
            {
                BuildPropertyGroup environmentProperties = new BuildPropertyGroup();
                environmentProperties.SetProperty("Property1", "Value1");
                environmentProperties.SetProperty("Property2", "Value2");
                environmentProperties.SetProperty("Property3", "Value3");
                environmentProperties.SetProperty("Property4", "Value4");
                BuildPropertyGroup reservedProperties = new BuildPropertyGroup();
                reservedProperties.SetProperty("Property2", "Value5");
                reservedProperties.SetProperty("Property3", "Value6");
                reservedProperties.SetProperty("Property4", "Value7");
                BuildPropertyGroup toolsVersionDependentProperties = new BuildPropertyGroup();
                toolsVersionDependentProperties.SetProperty("Property3", "Value8");
                toolsVersionDependentProperties.SetProperty("Property4", "Value9");
                BuildPropertyGroup globalProperties = new BuildPropertyGroup();
                globalProperties.SetProperty("Property4", "Value10");

                BuildPropertyGroup evaluatedProperties = new BuildPropertyGroup();
                evaluatedProperties.ImportInitialProperties(environmentProperties, reservedProperties, toolsVersionDependentProperties, globalProperties);

                Assertion.AssertEquals("Value10", evaluatedProperties["Property4"].Value);
                Assertion.AssertEquals("Value8",  evaluatedProperties["Property3"].Value);
                Assertion.AssertEquals("Value5",  evaluatedProperties["Property2"].Value);
                Assertion.AssertEquals("Value1",  evaluatedProperties["Property1"].Value);
            }