Beispiel #1
0
        public void TestExecution1()
        {
            Engine  engine;
            Project project;
            string  path = Path.Combine(Path.Combine("Test", "resources"), "MakeDir");

            string documentString = @"
                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<ItemGroup>
						<Dir Include='Test\resources\MakeDir\A' />
						<Dir Include='Test\resources\MakeDir\B' />
						<Dir Include='Test\resources\MakeDir\C' />
					</ItemGroup>
					<Target Name='1'>
						<MakeDir Directories='@(Dir)'>
							<Output
								TaskParameter='DirectoriesCreated'
								ItemName='Out'
							/>
						</MakeDir>
					</Target>
				</Project>
			"            ;

            engine  = new Engine(Consts.BinPath);
            project = engine.CreateNewProject();
            project.LoadXml(documentString);
            project.Build("1");

            Assert.AreEqual(3, Directory.GetDirectories(path).Length, "A1");

            BuildItemGroup output = project.GetEvaluatedItemsByName("Out");

            Assert.AreEqual(Path.Combine(path, "A"), output [0].FinalItemSpec, "A5");
            Assert.AreEqual(Path.Combine(path, "B"), output [1].FinalItemSpec, "A6");
            Assert.AreEqual(Path.Combine(path, "C"), output [2].FinalItemSpec, "A7");
        }
Beispiel #2
0
        public void InvalidUnqualifiedMetadataReference()
        {
            List <string> parameters = new List <string>();

            parameters.Add("@(File)");
            parameters.Add("%(Culture)");

            Hashtable itemsByType = new Hashtable(StringComparer.OrdinalIgnoreCase);

            BuildItemGroup items = new BuildItemGroup();

            itemsByType["FILE"] = items;

            BuildItem a = items.AddNewItem("File", "a.foo");
            BuildItem b = items.AddNewItem("File", "b.foo");

            a.SetMetadata("Culture", "fr-fr");

            BuildPropertyGroup properties = new BuildPropertyGroup();

            // This is expected to throw because not all items contain a value for metadata "Culture".
            // Only a.foo has a Culture metadata.  b.foo does not.
            ArrayList buckets = BatchingEngine.PrepareBatchingBuckets(new XmlDocument().CreateElement("Foo"), parameters, CreateLookup(itemsByType, properties));
        }
        public void ConditionSaveProjectAfterSet()
        {
            project.LoadXml(ProjectContentWithOneBuildItemGroupThreeBuildItems);
            BuildItemGroup group = GetBuildItemGroupFromProject(project, false);

            group.Condition = "'t' == 'true'";

            string expectedProjectContents = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                        <ItemGroup Condition=""'t' == 'true'"">
                            <n1 Include='i1' Exclude='e1'>
                                <n1Meta1>n1value1</n1Meta1>
                                <n1Meta2>n1value2</n1Meta2>
                            </n1>
                            <n2 Include='i2' Condition=""'a2' == 'b2'"" />
                            <n3 Include='i3'>
                                <n3Meta1>n3value1</n3Meta1>
                            </n3>
                        </ItemGroup>
                    </Project>
                    ";

            SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
        }
        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();
        }
Beispiel #5
0
        string GetItems(Project proj, string name)
        {
            BuildItemGroup big = proj.GetEvaluatedItemsByName(name);
            string         str = String.Empty;

            if (big == null)
            {
                return(str);
            }

            foreach (BuildItem bi in big)
            {
                if (str == String.Empty)
                {
                    str = bi.FinalItemSpec;
                }
                else
                {
                    str += ";" + bi.FinalItemSpec;
                }
            }

            return(str);
        }
Beispiel #6
0
            public BuildItem AddGeneratedFileItem(BuildItemGroup buildItemGroup, string sourceFileName, string outputFileName)
            {
                if (outputFileName == null || outputFileName.Length == 0)
                {
                    outputFileName = GetOutputFileDefaultName(sourceFileName);
                }
                bool      compilable = this._compilable;
                BuildItem buildItem  = buildItemGroup.AddNewItem(compilable ? "Compile" : "None", outputFileName);

                buildItem.SetMetadata(ITEMMETADATA_AUTOGEN, "True");
                if (compilable)
                {
                    buildItem.SetMetadata(ITEMMETADATA_DESIGNTIME, "True");
                }
                string customTool = this._customTool;

                if (!string.IsNullOrEmpty(customTool))
                {
                    buildItem.SetMetadata(ITEMMETADATA_GENERATOR, customTool);
                }
                buildItem.SetMetadata(ITEMMETADATA_DEPENDENTUPON, sourceFileName);
                buildItem.SetMetadata(ITEMMETADATA_ORMGENERATOR, this.OfficialName);
                return(buildItem);
            }
Beispiel #7
0
        public void RemoveItemPreviouslyModifiedAndGottenThroughGetItem()
        {
            Hashtable table1 = new Hashtable(StringComparer.OrdinalIgnoreCase);
            Lookup    lookup = LookupHelpers.CreateLookup(table1);

            // Add an item with m=m1 and n=n1
            BuildItem item1 = new BuildItem("i1", "a2");

            item1.SetMetadata("m", "m1");
            lookup.PopulateWithItem(item1);

            lookup.EnterScope();

            // Make a modification to the item to be m=m2
            Dictionary <string, string> newMetadata = new Dictionary <string, string>();

            newMetadata.Add("m", "m2");
            BuildItemGroup group = new BuildItemGroup();

            group.AddItem(item1);
            lookup.ModifyItems(item1.Name, group, newMetadata);

            // Get the item (under the covers, it cloned it in order to apply the modification)
            BuildItemGroup group2 = lookup.GetItems(item1.Name);

            Assertion.AssertEquals(1, group2.Count);
            BuildItem item1b = group2[0];

            // Remove the item
            lookup.RemoveItem(item1b);

            // There's now no items at all
            BuildItemGroup group3 = lookup.GetItems(item1.Name);

            Assertion.AssertEquals(0, group3.Count);
        }
Beispiel #8
0
        public void InitiallyNoItemsInBucketOfTypesInItemNames()
        {
            // This bucket is for items of type "i"
            string[] itemNames = new string[] { "i" };

            // There are items of type "i" and "j" available in the project, though
            BuildItemGroup group1 = new BuildItemGroup();
            BuildItemGroup group2 = new BuildItemGroup();

            group1.AddNewItem("i", "i1");
            group2.AddNewItem("j", "j1");
            Hashtable items = new Hashtable(StringComparer.OrdinalIgnoreCase);

            items.Add("i", group1);
            items.Add("j", group2);
            Lookup lookup = LookupHelpers.CreateLookup(items);

            ItemBucket bucket = new ItemBucket(itemNames, new Dictionary <string, string>(), lookup, 0);

            // No items of type i
            Assertion.AssertEquals(0, bucket.Lookup.GetItems("i1").Count);
            // Items of type j, however, are visible
            Assertion.AssertEquals(1, bucket.Lookup.GetItems("j").Count);
        }
        void CheckResourceNames(string [,] files, string [] names, string rootNamespace)
        {
            Assert.AreEqual(files.GetUpperBound(0) + 1, names.Length, "Number of files and names must match");
            string projectText = CreateProject(files, rootNamespace);

            Engine            engine  = new Engine(Consts.BinPath);
            Project           project = engine.CreateNewProject();
            TestMessageLogger logger  = new TestMessageLogger();

            engine.RegisterLogger(logger);
            Console.WriteLine(projectText);
            project.LoadXml(projectText);
            if (!project.Build("1"))
            {
                logger.DumpMessages();
                Assert.Fail("Build failed");
            }

            BuildItemGroup group = project.GetEvaluatedItemsByName("ResourceNames");

            Assert.AreEqual(names.Length, group.Count, "A2");
            for (int i = 0; i <= files.GetUpperBound(0); i++)
            {
                Assert.AreEqual(names [i], group [i].FinalItemSpec, "A3 #" + (i + 1));
                Assert.AreEqual(files [i, 1] != null, group [i].HasMetadata("LogicalName"), "A4 #" + (i + 1));
                if (files [i, 1] != null)
                {
                    Assert.AreEqual(files [i, 1], group [i].GetMetadata("LogicalName"), "A5 #" + (i + 1));
                }
                Assert.AreEqual(files [i, 2] != null, group [i].HasMetadata("DependentUpon"), "A6 #" + (i + 1));
                if (files [i, 2] != null)
                {
                    Assert.AreEqual(files [i, 2], group [i].GetMetadata("DependentUpon"), "A7 #" + (i + 1));
                }
            }
        }
        /// <summary>
        /// Returns the list of all project references found in the given <paramref name="projectPath"/>
        /// </summary>
        /// <remarks>
        /// This method unconditionally opens an MSBuild object model on the given project
        /// to extract the set of project references.  It does not cache.  Use with care.
        /// </remarks>
        /// <param name="projectPath">Full path to the project to open.</param>
        /// <returns>The list of full project file names referred by by the given project.</returns>
        internal IEnumerable <string> LoadProjectReferences(string projectPath)
        {
            IEnumerable <string> projects = new string[0];

            Project project = this.LoadProject(projectPath);

            if (project == null)
            {
                return(projects);
            }

            this._logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.Analyzing_Project_References, Path.GetFileName(projectPath)));

#if NET40
            projects = project.GetItems("ProjectReference").Select(i => ConvertToFullPath(i.EvaluatedInclude, projectPath));
#else
            BuildItemGroup buildItemGroup = project.GetEvaluatedItemsByName("ProjectReference");
            if (buildItemGroup != null)
            {
                projects = buildItemGroup.OfType <BuildItem>().Select(b => ConvertToFullPath(b.FinalItemSpec, projectPath));
            }
#endif
            // Tell the user what project references we found
            if (projects.Any())
            {
                StringBuilder sb = new StringBuilder(string.Format(CultureInfo.CurrentCulture, Resource.Project_References_Found, Path.GetFileName(projectPath)));
                foreach (string p in projects)
                {
                    sb.AppendLine();
                    sb.Append("    " + p);
                }
                this._logger.LogMessage(sb.ToString());
            }

            return(projects);
        }
        /// <summary>
        /// Retrieves the list of source file names from the specified project.
        /// </summary>
        /// <param name="projectPath">Full path to the project file.</param>
        /// <returns>A non-null (but possibly empty) list of full paths to files.</returns>
        internal IEnumerable <string> LoadSourceFilesFromProject(string projectPath)
        {
            IEnumerable <string> sources = new string[0];
            Project project = this.LoadProject(projectPath);

            if (project == null)
            {
                return(sources);
            }

            // Tell the user.  This helps us see when we use the cache and when we don't
            this._logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.Analyzing_Project_Files, Path.GetFileName(projectPath)));

#if NET40
            sources = project.GetItems("Compile").Select(i => ConvertToFullPath(i.EvaluatedInclude, projectPath));
#else
            BuildItemGroup buildItemGroup = project.GetEvaluatedItemsByName("Compile");
            if (buildItemGroup != null)
            {
                sources = buildItemGroup.OfType <BuildItem>().Select(b => ConvertToFullPath(b.FinalItemSpec, projectPath));
            }
#endif
            return(sources);
        }
Beispiel #12
0
        public void TestMissingConditionWhen()
        {
            Engine  engine;
            Project project;

            BuildItemGroup[] groups = new BuildItemGroup[1];

            // a <When> requires a Condition
            string documentString = @"
				<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                    <Choose>
                        <When>
					        <ItemGroup>
						        <A Include='a' />
					        </ItemGroup>
                        </When>
                    </Choose>
				</Project>
			"            ;

            engine  = new Engine(Consts.BinPath);
            project = engine.CreateNewProject();
            project.LoadXml(documentString);
        }
Beispiel #13
0
        void CheckTargetPath(string[] files, string[] assignedFiles, string rootFolder, string id)
        {
            Engine  engine  = new Engine(Consts.BinPath);
            Project project = engine.CreateNewProject();

            string projectText = CreateProjectString(files, rootFolder);

            project.LoadXml(projectText);

            Assert.IsTrue(project.Build("1"), id + "1 : Error in building");

            BuildItemGroup include = project.GetEvaluatedItemsByName("FooPath");

            Assert.AreEqual(files.Length, include.Count, id + "2");

            for (int i = 0; i < files.Length; i++)
            {
                Assert.AreEqual(files [i], include [i].FinalItemSpec, id + "3, file #" + i);
                Assert.IsTrue(include[i].HasMetadata("TargetPath"), id + "4, file #" + i + ", TargetPath metadata missing");
                Assert.AreEqual(assignedFiles [i], include[i].GetMetadata("TargetPath"), id + "5, file #" + i);
                Assert.IsTrue(include [i].HasMetadata("Child"), id + "6, file #" + i + ", Child metadata missing");
                Assert.AreEqual("C" + files [i], include [i].GetMetadata("Child"), id + "7, file #" + i + ", Child metadata value incorrect");
            }
        }
Beispiel #14
0
        public void TestCondition3()
        {
            Engine  engine;
            Project project;

            BuildItemGroup [] groups = new BuildItemGroup [1];

            string documentString = @"
				<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
					<ItemGroup>
						<A Include='a;b' />
					</ItemGroup>
				</Project>
			"            ;

            engine  = new Engine(Consts.BinPath);
            project = engine.CreateNewProject();
            project.LoadXml(documentString);

            project.ItemGroups.CopyTo(groups, 0);
            groups [0] [0].Condition = "true";
            Assert.AreEqual("true", groups [0] [0].Condition, "A1");
            Assert.AreEqual("true", project.EvaluatedItems [0].Condition, "A2");
        }
Beispiel #15
0
        private void OnResetCsproj()
        {
            String sourceRoot = ConfigurationManager.AppSettings["source_root"];
            String csprojName = ConfigurationManager.AppSettings["csproj_name"];

            String csprojFile = sourceRoot + csprojName;

            Project project = new Project();

            project.Load(csprojFile);

            BuildItemGroup itemGroup = project.AddNewItemGroup();

            itemGroup.AddNewItem("Content", "_static\\data\\okr.me");
            itemGroup.AddNewItem("Content", "_static\\data\\cover.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okr-bg.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okr-icon.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okr-splash.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okrapp.config");

            String[] appFiles = Directory.GetFileSystemEntries(sourceRoot + "_static\\data\\app\\");

            foreach (var file in appFiles)
            {
                itemGroup.AddNewItem("Content", "_static\\data\\app\\" + Path.GetFileName(file));
            }

            String[] bookFiles = Directory.GetFileSystemEntries(sourceRoot + "_static\\data\\book\\");

            foreach (var file in bookFiles)
            {
                itemGroup.AddNewItem("Content", "_static\\data\\book\\" + Path.GetFileName(file));
            }

            project.Save(csprojFile);
        }
Beispiel #16
0
        public void TestNullFields()
        {
            Engine  engine;
            Project project;

            string documentString = @"
				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<ItemGroup>
						<A Include='1;2;5'>
							<Sub>fooA</Sub>
						</A>
					</ItemGroup>
					<Target Name='1'>
						<CreateItem Include='@(A)' >
							<Output
								TaskParameter='Include'
								ItemName='NewItem'
							/>
						</CreateItem>
					</Target>
				</Project>"                ;

            engine  = new Engine(Consts.BinPath);
            project = engine.CreateNewProject();
            project.LoadXml(documentString);
            Assert.IsTrue(project.Build("1"), "A1, Build failed");

            BuildItemGroup include = project.GetEvaluatedItemsByName("NewItem");

            Assert.AreEqual(3, include.Count, "A2");

            string [,] additional_metadata = new string [0, 0];
            CheckBuildItem(include [0], "NewItem", additional_metadata, "1", "A");
            CheckBuildItem(include [1], "NewItem", additional_metadata, "2", "B");
            CheckBuildItem(include [2], "NewItem", additional_metadata, "5", "C");
        }
Beispiel #17
0
        public void ItemListTests()
        {
            Parser    p = new Parser();
            Hashtable conditionedProperties = null;

            BuildItemGroup myCompileItemGroup = new BuildItemGroup();

            myCompileItemGroup.AddItem(new BuildItem("Compile", "foo.cs"));
            myCompileItemGroup.AddItem(new BuildItem("Compile", "bar.cs"));
            myCompileItemGroup.AddItem(new BuildItem("Compile", "baz.cs"));

            BuildItemGroup myBooleanItemGroup = new BuildItemGroup();

            myBooleanItemGroup.AddItem(new BuildItem("Boolean", "true"));

            Hashtable itemsByType = new Hashtable(StringComparer.OrdinalIgnoreCase);

            itemsByType["Compile"] = myCompileItemGroup;
            itemsByType["Boolean"] = myBooleanItemGroup;

            Expander expander = new Expander(LookupHelpers.CreateLookup(itemsByType).ReadOnlyLookup);
            ConditionEvaluationState state = new ConditionEvaluationState(DummyAttribute, expander, conditionedProperties, string.Empty);

            AssertParseEvaluate(p, "@(Compile) == 'foo.cs;bar.cs;baz.cs'", state, true);
            AssertParseEvaluate(p, "@(Compile,' ') == 'foo.cs bar.cs baz.cs'", state, true);
            AssertParseEvaluate(p, "@(Compile,'') == 'foo.csbar.csbaz.cs'", state, true);
            AssertParseEvaluate(p, "@(Compile->'%(Filename)') == 'foo;bar;baz'", state, true);
            AssertParseEvaluate(p, "@(Compile -> 'temp\\%(Filename).xml', ' ') == 'temp\\foo.xml temp\\bar.xml temp\\baz.xml'", state, true);
            AssertParseEvaluate(p, "@(Compile->'', '') == ''", state, true);
            AssertParseEvaluate(p, "@(Compile->'') == ';;'", state, true);
            AssertParseEvaluate(p, "@(Compile->'%(Nonexistent)', '') == ''", state, true);
            AssertParseEvaluate(p, "@(Compile->'%(Nonexistent)') == ';;'", state, true);
            AssertParseEvaluate(p, "@(Boolean)", state, true);
            AssertParseEvaluate(p, "@(Boolean) == true", state, true);
            AssertParseEvaluate(p, "'@(Empty, ';')' == ''", state, true);
        }
        private void CreateAssemblyReferenceProjectFile(IDictionary <string, ProjectInfo> projects)
        {
            foreach (ProjectInfo projectInfo in projects.Values)
            {
                if (m_AssemblyRefProjectFilesHandled.Contains(projectInfo))
                {
                    continue;
                }

                Debug.Assert(projectInfo.MSBuildProject != null);

                List <BuildItem> projectReferencesToMove          = new List <BuildItem>();
                BuildItemGroup   assemblyReferencesBuildItemGroup = null;
                BuildItemGroup   projectReferencesBuildItemGroup  = null;

                foreach (BuildItemGroup buildItemGroup in projectInfo.MSBuildProject.ItemGroups)
                {
                    foreach (BuildItem buildItem in buildItemGroup)
                    {
                        if (buildItem.Name == Reference)
                        {
                            // Keep a bookmark on the BuildItemGroup that holds assembly references
                            assemblyReferencesBuildItemGroup = buildItemGroup;
                        }

                        if (buildItem.Name == ProjectReference)
                        {
                            // Keep a bookmark on the BuildItemGroup that holds project references
                            projectReferencesBuildItemGroup = buildItemGroup;

                            // Take a look at all project references to identify those to convert to assembly references
                            ProjectInfo referencedProjectInfo;
                            string      projectGuid = buildItem.GetMetadata(Project);
                            m_ProjectsByGuid.TryGetValue(projectGuid, out referencedProjectInfo);
                            if (referencedProjectInfo != null)
                            {
                                projectReferencesToMove.Add(buildItem);
                            }
                        }
                    }
                }

                // If no project references found or none to move, nothing to change; save file as-is
                if (projectReferencesBuildItemGroup == null || projectReferencesToMove.Count == 0)
                {
                    //Console.WriteLine("Nothing to do.");
                }
                else
                {
                    if (assemblyReferencesBuildItemGroup == null)
                    {
                        assemblyReferencesBuildItemGroup = projectInfo.MSBuildProject.AddNewItemGroup();
                    }

                    foreach (BuildItem buildItem in projectReferencesToMove)
                    {
                        projectReferencesBuildItemGroup.RemoveItem(buildItem);

                        // Get the assembly name corresponding to the project GUID
                        foreach (ProjectInfo pinfo in projects.Values)
                        {
                            if (pinfo.ProjectGuid == buildItem.GetMetadata(Project))
                            {
                                BuildItem newBuildItem =
                                    assemblyReferencesBuildItemGroup.AddNewItem(Reference, pinfo.AssemblyName);
                                newBuildItem.SetMetadata("Private", bool.FalseString);
                                newBuildItem.SetMetadata("SpecificVersion", bool.FalseString);
                                if (m_Arguments.HintPath != string.Empty)
                                {
                                    string relative =
                                        GetRelativePath(Path.GetDirectoryName(projectInfo.Filename), m_Arguments.HintPath);
                                    newBuildItem.SetMetadata("HintPath", Path.Combine(relative, pinfo.AssemblyName) + ".dll");
                                }
                                break;
                            }
                        }
                    }
                }
                StringBuilder sb = new StringBuilder(Path.ChangeExtension(projectInfo.Filename, null));
                if (m_Arguments.Overwrite == false)
                {
                    sb.Append(AssemblyRefs);
                }
                sb.Append(CSProjFileExtension);
                string projectFileName = sb.ToString();
                projectInfo.MSBuildProject.Save(projectFileName);
                m_AssemblyRefProjectFilesHandled.Add(projectInfo);
            }
        }
        private void CreateProjectReferenceProjectFile(IDictionary <string, ProjectInfo> projects)
        {
            foreach (ProjectInfo projectInfo in projects.Values)
            {
                if (m_ProjectRefProjectFilesHandled.Contains(projectInfo))
                {
                    continue;
                }
                Debug.Assert(projectInfo.MSBuildProject != null);

                List <BuildItem> assemblyReferencesToMove         = new List <BuildItem>();
                BuildItemGroup   assemblyReferencesBuildItemGroup = null;
                BuildItemGroup   projectReferencesBuildItemGroup  = null;

                foreach (BuildItemGroup buildItemGroup in projectInfo.MSBuildProject.ItemGroups)
                {
                    foreach (BuildItem buildItem in buildItemGroup)
                    {
                        // Find all assembly references to convert to project references
                        if (buildItem.Name == Reference)
                        {
                            // Keep a bookmark on the BuildItemGroup that holds assembly references
                            assemblyReferencesBuildItemGroup = buildItemGroup;

                            // Take a look at all assembly references to identify those to convert to project references
                            ProjectInfo referencedProjectInfo;
                            string      projectName = GetAssemblyNameFromFullyQualifiedName(buildItem.Include);
                            projects.TryGetValue(projectName, out referencedProjectInfo);
                            if (referencedProjectInfo != null)
                            {
                                assemblyReferencesToMove.Add(buildItem);
                            }
                        }

                        if (buildItem.Name == ProjectReference)
                        {
                            // Keep a bookmark on the BuildItemGroup that holds project references
                            projectReferencesBuildItemGroup = buildItemGroup;
                        }
                    }
                }

                // If no assembly references found or none to move, nothing to change; save file as-is
                if (assemblyReferencesBuildItemGroup == null || assemblyReferencesToMove.Count == 0)
                {
                    //Console.WriteLine("Nothing to do.");
                }
                else
                {
                    // If no project reference group exists, create one.
                    if (projectReferencesBuildItemGroup == null)
                    {
                        projectReferencesBuildItemGroup = projectInfo.MSBuildProject.AddNewItemGroup();
                    }

                    // Remove assembly reference and replace by corresponding project reference.
                    foreach (BuildItem buildItem in assemblyReferencesToMove)
                    {
                        assemblyReferencesBuildItemGroup.RemoveItem(buildItem);
                        string    replacementAssemblyName = GetAssemblyNameFromFullyQualifiedName(buildItem.Include);
                        var       replacementProjectInfo  = m_ProjectsByName[replacementAssemblyName.ToUpperInvariant()];
                        string    remplacementInclude     = GetRelativePath(Path.GetDirectoryName(projectInfo.Filename), replacementProjectInfo.Filename);
                        BuildItem newBuildItem            = projectReferencesBuildItemGroup.AddNewItem(ProjectReference, remplacementInclude);
                        newBuildItem.SetMetadata("Project", replacementProjectInfo.ProjectGuid);
                        newBuildItem.SetMetadata("Name", replacementProjectInfo.ProjectName);
                        newBuildItem.SetMetadata("Private", bool.FalseString);
                    }
                }

                StringBuilder sb = new StringBuilder(Path.ChangeExtension(projectInfo.Filename, null));
                if (m_Arguments.Overwrite == false)
                {
                    sb.Append(ProjectRefs);
                }
                sb.Append(CSProjFileExtension);
                string projectFileName = sb.ToString();
                projectInfo.MSBuildProject.Save(projectFileName);
                m_ProjectRefProjectFilesHandled.Add(projectInfo);
            }
        }
Beispiel #20
0
        public void IncludeAndExcludeUnescaping()
        {
            string       tempFolder = Path.Combine(Path.GetTempPath(), "IncludeAndExcludeUnescaping");
            string       matchesFoo = Path.Combine(tempFolder, "*");
            string       foo        = Path.Combine(tempFolder, "foo");
            StreamWriter sw         = null;

            try
            {
                Directory.CreateDirectory(tempFolder);
                sw = File.CreateText(foo);

                string projectContents = String.Format(@"
                    <Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
                        <ItemGroup>
                            <i1 Include=`)` Exclude=`)`/>
                            <i2 Include=`%29` Exclude=`%29`/>
                            <i3 Include=`%29` Exclude=`)`/>
                            <i4 Include=`)` Exclude=`%29`/>
                            <i5 Include=`);x` Exclude=`%29`/>
                            <i6 Include=`x` Exclude=`y`/>
                            <i7 Include=` ` Exclude=`y`/>
                            <i8 Include=`x` Exclude=``/>
                            <i9 Include=`);%29` Exclude=`)`/>
                            <i10 Include=`%2a` Exclude=`%2a`/>
                            <i11 Include=`{0}` Exclude=`{1}`/>
                            <i12 Include=`{1}` Exclude=`{1}`/>
                        </ItemGroup>
                    </Project>
                    ", foo, matchesFoo);

                Project project = ObjectModelHelpers.CreateInMemoryProject(projectContents);

                BuildItemGroup i1Items  = project.GetEvaluatedItemsByName("i1");
                BuildItemGroup i2Items  = project.GetEvaluatedItemsByName("i2");
                BuildItemGroup i3Items  = project.GetEvaluatedItemsByName("i3");
                BuildItemGroup i4Items  = project.GetEvaluatedItemsByName("i4");
                BuildItemGroup i5Items  = project.GetEvaluatedItemsByName("i5");
                BuildItemGroup i6Items  = project.GetEvaluatedItemsByName("i6");
                BuildItemGroup i7Items  = project.GetEvaluatedItemsByName("i7");
                BuildItemGroup i8Items  = project.GetEvaluatedItemsByName("i8");
                BuildItemGroup i9Items  = project.GetEvaluatedItemsByName("i9");
                BuildItemGroup i10Items = project.GetEvaluatedItemsByName("i10");
                BuildItemGroup i11Items = project.GetEvaluatedItemsByName("i11");
                BuildItemGroup i12Items = project.GetEvaluatedItemsByName("i12");
                Assertion.Assert(") should exclude )", i1Items.Count == 0);
                Assertion.Assert("%29 should exclude %29", i2Items.Count == 0);
                Assertion.Assert(") should exclude %29", i3Items.Count == 0);
                Assertion.Assert("%29 should exclude )", i4Items.Count == 0);
                Assertion.Assert("%29 should exclude ) from );x", i5Items.Count == 1 && i5Items[0].FinalItemSpecEscaped == "x");
                Assertion.Assert("y should not exclude x", i6Items.Count == 1 && i6Items[0].FinalItemSpecEscaped == "x");
                Assertion.Assert("empty include, y exclude", i7Items.Count == 0);
                Assertion.Assert("x include, empty exclude", i8Items.Count == 1 && i8Items[0].FinalItemSpecEscaped == "x");
                Assertion.Assert(") should exclude both from );%29", i9Items.Count == 0);
                Assertion.Assert("%2a should exclude %2a", i10Items.Count == 0);
                Assertion.Assert("* matching foo should exclude foo", i11Items.Count == 0);
                Assertion.Assert("* should exclude *", i12Items.Count == 0);
            }
            finally
            {
                if (null != sw)
                {
                    sw.Close();
                }
                File.Delete(foo);
                Directory.Delete(tempFolder);
            }
        }
        public MSBuildResult Run(
            ProjectConfigurationInfo[] configurations, IEngineLogWriter logWriter, MSBuildVerbosity verbosity,
            string[] runTargets, string[] evaluateItems, string[] evaluateProperties, Dictionary <string, string> globalProperties, int taskId)
        {
            MSBuildResult result = null;

            BuildEngine.RunSTA(taskId, delegate {
                try {
                    var project = SetupProject(configurations);
                    InitLogger(logWriter);

                    buildEngine.Engine.UnregisterAllLoggers();

                    var logger = new LocalLogger(file);
                    buildEngine.Engine.RegisterLogger(logger);
                    if (logWriter != null)
                    {
                        buildEngine.Engine.RegisterLogger(consoleLogger);
                        consoleLogger.Verbosity = GetVerbosity(verbosity);
                        buildEngine.Engine.RegisterLogger(new TargetLogger(logWriter.RequiredEvents, LogEvent));
                    }

                    if (runTargets != null && runTargets.Length > 0)
                    {
                        if (globalProperties != null)
                        {
                            foreach (var p in globalProperties)
                            {
                                project.GlobalProperties.SetProperty(p.Key, p.Value);
                            }
                        }

                        // We are using this BuildProject overload and the BuildSettings.None argument as a workaround to
                        // an xbuild bug which causes references to not be resolved after the project has been built once.
                        buildEngine.Engine.BuildProject(project, runTargets, new Hashtable(), BuildSettings.None);

                        if (globalProperties != null)
                        {
                            foreach (var p in globalProperties.Keys)
                            {
                                project.GlobalProperties.RemoveProperty(p);
                                buildEngine.Engine.GlobalProperties.RemoveProperty(p);
                            }
                        }
                    }

                    result = new MSBuildResult(logger.BuildResult.ToArray());

                    if (evaluateProperties != null)
                    {
                        foreach (var name in evaluateProperties)
                        {
                            result.Properties [name] = project.GetEvaluatedProperty(name);
                        }
                    }

                    if (evaluateItems != null)
                    {
                        foreach (var name in evaluateItems)
                        {
                            BuildItemGroup grp = project.GetEvaluatedItemsByName(name);
                            var list           = new List <MSBuildEvaluatedItem> ();
                            foreach (BuildItem item in grp)
                            {
                                var evItem = new MSBuildEvaluatedItem(name, UnescapeString(item.FinalItemSpec));
                                foreach (DictionaryEntry de in (IDictionary)evaluatedMetadataField.GetValue(item))
                                {
                                    evItem.Metadata [(string)de.Key] = UnescapeString((string)de.Value);
                                }
                                list.Add(evItem);
                            }
                            result.Items[name] = list.ToArray();
                        }
                    }
                } catch (InvalidProjectFileException ex) {
                    var r = new MSBuildTargetResult(
                        file, false, ex.ErrorSubcategory, ex.ErrorCode, ex.ProjectFile,
                        ex.LineNumber, ex.ColumnNumber, ex.EndLineNumber, ex.EndColumnNumber,
                        ex.BaseMessage, ex.HelpKeyword);
                    LogWriteLine(r.ToString());
                    result = new MSBuildResult(new [] { r });
                } finally {
                    DisposeLogger();
                }
            });
            return(result);
        }
Beispiel #22
0
        public void TestIndexer3()
        {
            BuildItemGroup big = new BuildItemGroup();

            Assert.IsNotNull(big [-1], "A1");
        }
 public void RemoveItemGroup(BuildItemGroup itemGroupToRemove)
 {
 }
Beispiel #24
0
        public void TestSetMetadata5a()
        {
            Engine  engine;
            Project project;

            BuildItemGroup[] groups = new BuildItemGroup[1];

            string documentString = @"
				<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
					<PropertyGroup>
						<A>A</A>
						<C>@(D)</C>
					</PropertyGroup>
					<ItemGroup>
						<D Include='D'/>
						<C Include='$(C)'/>
						<A Include='a;b'>
							<Md>@(C)</Md>
						</A>
						<B Include='$(A)'/>
					</ItemGroup>
					<Target Name='main'>
						<Message Text=""a.md: %(A.Md)""/>
						<Message Text=""a.md: %(A.Meta)""/>
					</Target>
				</Project>
			"            ;

            engine  = new Engine(Consts.BinPath);
            project = engine.CreateNewProject();
            MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger();
            engine.RegisterLogger(logger);
            project.LoadXml(documentString);

            CheckMetadata(project, "A", "Md", new string [] { "@(C)", "@(C)" }, "G1");
            CheckEvaluatedMetadata(project, "A", "Md", new string[] { "D", "D" }, "G2");

            //@(B)
            Assert.AreEqual("A", project.GetEvaluatedItemsByName("B")[0].FinalItemSpec, "B2");

            project.ItemGroups.CopyTo(groups, 0);

            /*Broken right now:
             * CheckBuildItemGroup (groups[0], new string[] {
             *      "D", "D",
             *      "C", "$(C)",
             *      "A", "a;b",
             *      "B", "$(A)"
             * }, "H1");*/

            CheckBuildItemGroup(project.GetEvaluatedItemsByName("C"), new string[] {
                "C", "D"
            }, "H2");

            CheckBuildItemGroup(project.GetEvaluatedItemsByName("C"), new string[] {
                "C", "D"
            }, "I");

            project.GetEvaluatedItemsByName("A")[0].SetMetadata("Meta", "@(B)");

            Assert.AreEqual(5, project.EvaluatedItems.Count, "A0");
            Assert.AreEqual(2, project.GetEvaluatedItemsByName("A").Count, "A7");

            CheckMetadata(project, "A", "Meta", new string[] { "@(B)", "" }, "J");

            if (!project.Build())
            {
                logger.DumpMessages();
                Assert.Fail("Build failed");
            }

            CheckMetadata(project, "A", "Meta", new string[] { "@(B)", "" }, "K1");
            CheckEvaluatedMetadata(project, "A", "Meta", new string[] { "", "" }, "K2");

            logger.CheckLoggedMessageHead("a.md: D", "E10");
            logger.CheckLoggedMessageHead("a.md: ", "E11");
            Assert.AreEqual(0, logger.NormalMessageCount, "Unexpected messages left");
        }
Beispiel #25
0
        internal static void ReadAllFilesInSCProjAndCopyProcessThem(
            string csProjFilePath,
            string tempFolder,
            ReflectionOnSeparateAppDomainHandler reflectionOnSeparateAppDomain,
            List <string> coreAssembliesForUseByXamlToCSharpConverter,
            List <string> coreAssembliesForUseByCSharpToExeOrDllCompiler,
            ILogger logger)
        {
            // Load CSProj:
            Project project = new Project(new Engine());

            project.Load(csProjFilePath);

            // Process files:
            //foreach (BuildItem buildItem in Enumerable.SelectMany<BuildItemGroup, BuildItem, BuildItem>(Enumerable.Cast<BuildItemGroup>((IEnumerable)project.ItemGroups), (Func<BuildItemGroup, IEnumerable<BuildItem>>)(grp => Enumerable.Cast<BuildItem>((IEnumerable)grp)), (Func<BuildItemGroup, BuildItem, BuildItem>)((grp, item) => item)))
            foreach (BuildItemGroup buildItemGroup in project.ItemGroups)
            {
                List <BuildItem> buildItemsToRemove = new List <BuildItem>();

                foreach (BuildItem buildItem in buildItemGroup)
                {
                    if ((buildItem.Name == "Compile" || buildItem.Name == "Content") &&
                        !string.IsNullOrEmpty(buildItem.Include) &&
                        (buildItem.Include.ToLower().EndsWith(".cs") || buildItem.Include.ToLower().EndsWith(".xaml")))
                    {
                        ProcessFile(buildItem.Include, csProjFilePath, tempFolder, reflectionOnSeparateAppDomain, logger);

                        // In the CSPROJ, rename ".xaml" files to ".xaml.g.cs", and change their BuildAction from "Content" to "Compile"
                        if (buildItem.Include.ToLower().EndsWith(".xaml"))
                        {
                            buildItem.Include = buildItem.Include + ".g.cs";
                            buildItem.Name    = "Compile";
                        }
                    }
                    else if (buildItem.Name == "ProjectReference")
                    {
                        foreach (string coreAssemblyFilePath in coreAssembliesForUseByCSharpToExeOrDllCompiler)
                        {
                            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(coreAssemblyFilePath);
                            if (buildItem.Include.EndsWith(fileNameWithoutExtension + ".csproj"))
                            {
                                buildItemsToRemove.Add(buildItem);
                            }
                        }
                    }
                }

                // Remove build items marked for removal:
                foreach (BuildItem buildItemToRemove in buildItemsToRemove)
                {
                    buildItemGroup.RemoveItem(buildItemToRemove);
                }
            }

            // Add reference to the core assemblies:
            if (coreAssembliesForUseByXamlToCSharpConverter.Count > 0)
            {
                BuildItemGroup newBuildItemGroup = project.AddNewItemGroup();
                foreach (string coreAssemblyFilePath in coreAssembliesForUseByCSharpToExeOrDllCompiler)
                {
                    string    fileNameWithoutExtension = Path.GetFileNameWithoutExtension(coreAssemblyFilePath);
                    BuildItem newBuildItem             = newBuildItemGroup.AddNewItem("Reference", fileNameWithoutExtension);
                    newBuildItem.SetMetadata("HintPath", coreAssemblyFilePath);
                }
            }

            // Remove the build target, since we are handling the compilation manually:
            Import importToRemove = null;

            foreach (Import import in project.Imports)
            {
                if (import.ProjectPath.EndsWith("Build.targets"))
                {
                    importToRemove = import;
                }
            }
            if (importToRemove != null)
            {
                project.Imports.RemoveImport(importToRemove);
            }

            //todo: copy other file types to temp folder (images, etc.) ?

            // Save the modified CSProj to the temp folder:
            project.Save(Path.Combine(tempFolder, Path.GetFileName(csProjFilePath)));
        }
Beispiel #26
0
        /// <summary>
        /// Asserts that there are no items in the project of the specified type
        /// </summary>
        static internal void AssertNoItem(Project p, string type)
        {
            BuildItemGroup items = p.GetEvaluatedItemsByName(type);

            Assertion.AssertEquals(0, items.Count);
        }
Beispiel #27
0
        public void TestVariableExpansion()
        {
            Engine  engine;
            Project project;

            string documentString = @"
                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
				<PropertyGroup>
					<P1>FooP1</P1>
					<P2>FooP2</P2>
					<C>@(IG)</C>
					<P3>@(Nine->'%(Identity)')</P3>
				</PropertyGroup>
				<ItemGroup>
					<Nine Include=""Nine""/>
					<Eight Include=""Eight""/>
					<Seven Include=""@(Eight)""/>
					<Six Include=""@(Seven);$(P3)""/>
					<Third Include=""Abc""/>
					<Fourth Include=""$(P2)""/>
					<Second Include=""@(Third);$(P1);@(Fourth);@(Six)""/>
					<IG Include=""@(Second)""/>
				</ItemGroup>

					<Target Name='1'>
						<CreateItem Include='$(C)' >
							<Output
								TaskParameter='Include'
								ItemName='Items'
							/>
						</CreateItem>

						<Message Text=""C: $(C)""/>
						<Message Text=""items: @(items)""/>
					</Target>
				</Project>
			"            ;

            engine = new Engine(Consts.BinPath);

            TestMessageLogger testLogger = new TestMessageLogger();

            engine.RegisterLogger(testLogger);

            project = engine.CreateNewProject();
            project.LoadXml(documentString);
            if (!project.Build("1"))
            {
                testLogger.DumpMessages();
                Assert.Fail("Build failed");
            }

            BuildItemGroup include = project.GetEvaluatedItemsByName("Items");

            Assert.AreEqual(5, include.Count, "A2");

            Assert.AreEqual("Abc", include [0].FinalItemSpec, "A#3");
            Assert.AreEqual("FooP1", include[1].FinalItemSpec, "A#4");
            Assert.AreEqual("FooP2", include[2].FinalItemSpec, "A#5");
            Assert.AreEqual("Eight", include[3].FinalItemSpec, "A#6");
            Assert.AreEqual("Nine", include[4].FinalItemSpec, "A#7");

            testLogger.CheckLoggedMessageHead("C: Abc;FooP1;FooP2;Eight;Nine", "A#9");
            testLogger.CheckLoggedMessageHead("items: Abc;FooP1;FooP2;Eight;Nine", "A#10");
        }
 public void RemoveItemGroup(BuildItemGroup itemGroupToRemove)
 {
 }
Beispiel #29
0
        public void TestCondition2()
        {
            BuildItemGroup big = new BuildItemGroup();

            big.Condition = "true";
        }
Beispiel #30
0
        // NOTE: maybe it should throw an exception?
        // at the moment it probably doesn't find a "null" element
        public void TestRemoveItem2()
        {
            BuildItemGroup big = new BuildItemGroup();

            big.RemoveItem(null);
        }
Beispiel #31
0
        public void TestCopy1()
        {
            Engine  engine;
            Project project;
            string  file_path   = Path.Combine(source_path, "copy.txt");
            string  target_file = Path.Combine(target_path, "copy.txt");

            using (File.CreateText(file_path)) { }

            string documentString = @"
				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<PropertyGroup><DestFile>"                     + target_file + @"</DestFile></PropertyGroup>
					<ItemGroup>
						<SFiles Include='"                         + file_path + @"'><Md>1</Md></SFiles>
						<DFiles Include='$(DestFile)'><Mde>2</Mde></DFiles>
					</ItemGroup>
					<Target Name='1'>
						<Copy SourceFiles='@(SFiles)' DestinationFiles='@(DFiles)' SkipUnchangedFiles='true' >
							<Output TaskParameter='CopiedFiles' ItemName='I0'/>
							<Output TaskParameter='DestinationFiles' ItemName='I1'/>
						</Copy>
						<Message Text=""I0 : @(I0), I1: @(I1)""/>
					</Target>
				</Project>
			"            ;

            engine  = new Engine(Consts.BinPath);
            project = engine.CreateNewProject();

            TestMessageLogger testLogger = new TestMessageLogger();

            engine.RegisterLogger(testLogger);

            project.LoadXml(documentString);

            if (!project.Build("1"))
            {
                var sb = new StringBuilder();
                testLogger.DumpMessages(sb);
                Assert.Fail("Build failed " + sb.ToString());
            }
            Assert.IsTrue(File.Exists(target_file), "A2");

            BuildItemGroup big = project.GetEvaluatedItemsByName("I0");

            Assert.AreEqual(1, big.Count, "A3");
            BuildItem bi = big [0];

            Assert.AreEqual(target_file, bi.FinalItemSpec, "A4");
            Assert.AreEqual("1", bi.GetMetadata("Md"), "A4");
            Assert.AreEqual("2", bi.GetMetadata("Mde"), "A5");

            big = project.GetEvaluatedItemsByName("I1");
            Assert.AreEqual(1, big.Count, "A10");
            bi = big [0];
            Assert.AreEqual(target_file, bi.FinalItemSpec, "A11");
            Assert.AreEqual("1", bi.GetMetadata("Md"), "A12");
            Assert.AreEqual("2", bi.GetMetadata("Mde"), "A13");

            // build again, this time files won't get copied because
            // of SkipUnchangedFiles=true
            if (!project.Build("1"))
            {
                testLogger.DumpMessages();
                Assert.Fail("Build failed #2");
            }
            Assert.IsTrue(File.Exists(target_file), "A20");

            big = project.GetEvaluatedItemsByName("I0");
            Assert.AreEqual(1, big.Count, "A21");
            bi = big [0];
            Assert.AreEqual(target_file, bi.FinalItemSpec, "A22");
            Assert.AreEqual("1", bi.GetMetadata("Md"), "A23");
            Assert.AreEqual("2", bi.GetMetadata("Mde"), "A24");

            big = project.GetEvaluatedItemsByName("I1");
            Assert.AreEqual(1, big.Count, "A25");
            bi = big [0];
            Assert.AreEqual(target_file, bi.FinalItemSpec, "A26");
            Assert.AreEqual("1", bi.GetMetadata("Md"), "A27");
            Assert.AreEqual("2", bi.GetMetadata("Mde"), "A28");
        }
Beispiel #32
0
	public BuildItem AddGeneratedFileBuildItem(BuildItemGroup buildItemGroup, string sourceFileName, string outputFileName)
	{
		if (outputFileName == null || outputFileName.Length == 0)
		{
			outputFileName = GetOutputFileDefaultName(sourceFileName);
		}
		BuildItem buildItem = buildItemGroup.AddNewItem("None", outputFileName);
		buildItem.SetMetadata(ITEMMETADATA_AUTOGEN, "True");
		buildItem.SetMetadata(ITEMMETADATA_DEPENDENTUPON, sourceFileName);
		buildItem.SetMetadata(ITEMMETADATA_ORMGENERATOR, this.OfficialName);
		return buildItem;
	}